WebOrbiton
v2.0.0.8

Publisium

627 lines · 23.6 KB
  1. <?php
  2. ​
  3. declare(strict_types=1);
  4. ​
  5. require_once __DIR__ . '/language.php';
  6. ​
  7. final class BlockEditor
  8. {
  9. private const ALLOWED_TYPES = [
  10. 'paragraph',
  11. 'heading2',
  12. 'heading3',
  13. 'image',
  14. 'video',
  15. 'quote',
  16. 'list',
  17. 'code',
  18. 'table',
  19. 'checklist',
  20. 'callout',
  21. 'separator',
  22. 'embed',
  23. 'contact_form',
  24. ];
  25. ​
  26. public const HOME_SYSTEM_TYPES = [
  27. 'home_featured',
  28. 'home_articles',
  29. ];
  30. ​
  31. public static function sanitize(string $rawJson, bool $allowContactForm = false): string
  32. {
  33. return json_encode(['blocks' => self::cleanBlocks($rawJson, $allowContactForm, [])], JSON_UNESCAPED_UNICODE);
  34. }
  35. ​
  36. public static function sanitizeHomepage(string $rawJson): string
  37. {
  38. $blocks = self::cleanBlocks($rawJson, true, self::HOME_SYSTEM_TYPES);
  39. $presentTypes = array_column($blocks, 'type');
  40. ​
  41. foreach (self::HOME_SYSTEM_TYPES as $systemType) {
  42. if (!in_array($systemType, $presentTypes, true)) {
  43. $blocks[] = ['id' => 'sys_' . $systemType, 'type' => $systemType, 'data' => []];
  44. }
  45. }
  46. ​
  47. return json_encode(['blocks' => $blocks], JSON_UNESCAPED_UNICODE);
  48. }
  49. ​
  50. public static function homepageBlocks(array $settings): array
  51. {
  52. $decoded = json_decode(self::sanitizeHomepage((string) ($settings['homepage_blocks'] ?? '')), true);
  53. ​
  54. return is_array($decoded['blocks'] ?? null) ? $decoded['blocks'] : [];
  55. }
  56. ​
  57. private static function cleanBlocks(string $rawJson, bool $allowContactForm, array $systemTypes): array
  58. {
  59. $decoded = json_decode($rawJson, true);
  60. ​
  61. if (!is_array($decoded) || !isset($decoded['blocks']) || !is_array($decoded['blocks'])) {
  62. return [];
  63. }
  64. ​
  65. $cleanBlocks = [];
  66. $hasContactForm = false;
  67. $seenSystemTypes = [];
  68. ​
  69. foreach ($decoded['blocks'] as $block) {
  70. if (!is_array($block) || !isset($block['type']) || !is_string($block['type'])) {
  71. continue;
  72. }
  73. ​
  74. if (in_array($block['type'], $systemTypes, true)) {
  75. if (isset($seenSystemTypes[$block['type']])) {
  76. continue;
  77. }
  78. $seenSystemTypes[$block['type']] = true;
  79. $cleanBlocks[] = ['id' => 'sys_' . $block['type'], 'type' => $block['type'], 'data' => []];
  80. continue;
  81. }
  82. ​
  83. if (!in_array($block['type'], self::ALLOWED_TYPES, true)) {
  84. continue;
  85. }
  86. ​
  87. if ($block['type'] === 'contact_form') {
  88. if (!$allowContactForm || $hasContactForm) {
  89. continue;
  90. }
  91. $hasContactForm = true;
  92. }
  93. ​
  94. $data = is_array($block['data'] ?? null) ? $block['data'] : [];
  95. ​
  96. $cleanBlocks[] = [
  97. 'id' => is_string($block['id'] ?? null) ? substr($block['id'], 0, 40) : bin2hex(random_bytes(8)),
  98. 'type' => $block['type'],
  99. 'data' => self::sanitizeBlockData($block['type'], $data),
  100. ];
  101. }
  102. ​
  103. return $cleanBlocks;
  104. }
  105. ​
  106. private static function sanitizeBlockData(string $type, array $data): array
  107. {
  108. return match ($type) {
  109. 'paragraph', 'quote' => [
  110. 'text' => self::cleanHtml((string) ($data['text'] ?? '')),
  111. ],
  112. 'heading2', 'heading3' => [
  113. 'text' => strip_tags((string) ($data['text'] ?? '')),
  114. ],
  115. 'image' => [
  116. 'src' => self::cleanUrl((string) ($data['src'] ?? '')),
  117. 'alt' => strip_tags((string) ($data['alt'] ?? '')),
  118. 'caption' => strip_tags((string) ($data['caption'] ?? '')),
  119. ],
  120. 'video' => [
  121. 'src' => self::cleanUrl((string) ($data['src'] ?? '')),
  122. 'caption' => strip_tags((string) ($data['caption'] ?? '')),
  123. ],
  124. 'list' => [
  125. 'style' => in_array($data['style'] ?? 'unordered', ['ordered', 'unordered'], true) ? $data['style'] : 'unordered',
  126. 'items' => array_map(
  127. static fn($item) => strip_tags((string) $item),
  128. is_array($data['items'] ?? null) ? $data['items'] : []
  129. ),
  130. ],
  131. 'code' => [
  132. 'language' => preg_replace('/[^a-zA-Z0-9_+-]/', '', (string) ($data['language'] ?? 'text')),
  133. 'code' => (string) ($data['code'] ?? ''),
  134. ],
  135. 'table' => [
  136. 'rows' => self::sanitizeTableRows(is_array($data['rows'] ?? null) ? $data['rows'] : []),
  137. ],
  138. 'checklist' => [
  139. 'items' => self::sanitizeChecklistItems(is_array($data['items'] ?? null) ? $data['items'] : []),
  140. ],
  141. 'callout' => [
  142. 'style' => in_array($data['style'] ?? 'info', ['info', 'warning', 'success', 'danger'], true) ? $data['style'] : 'info',
  143. 'text' => strip_tags((string) ($data['text'] ?? '')),
  144. ],
  145. 'embed' => [
  146. 'url' => self::cleanUrl((string) ($data['url'] ?? '')),
  147. ],
  148. 'separator', 'contact_form' => [],
  149. default => [],
  150. };
  151. }
  152. ​
  153. private static function sanitizeTableRows(array $rows): array
  154. {
  155. $clean = [];
  156. foreach ($rows as $row) {
  157. if (!is_array($row)) {
  158. continue;
  159. }
  160. $clean[] = array_map(static fn($cell) => strip_tags((string) $cell), $row);
  161. }
  162. ​
  163. return $clean;
  164. }
  165. ​
  166. private static function sanitizeChecklistItems(array $items): array
  167. {
  168. $clean = [];
  169. foreach ($items as $item) {
  170. if (!is_array($item)) {
  171. continue;
  172. }
  173. $clean[] = [
  174. 'text' => strip_tags((string) ($item['text'] ?? '')),
  175. 'checked' => (bool) ($item['checked'] ?? false),
  176. ];
  177. }
  178. ​
  179. return $clean;
  180. }
  181. ​
  182. private static function cleanUrl(string $url): string
  183. {
  184. $url = trim($url);
  185. if ($url === '') {
  186. return '';
  187. }
  188. ​
  189. if (str_starts_with($url, 'https://') || str_starts_with($url, 'http://')) {
  190. return filter_var($url, FILTER_SANITIZE_URL) ?: '';
  191. }
  192. ​
  193. if (preg_match('#^[a-zA-Z][a-zA-Z0-9+.-]*:#', $url) === 1) {
  194. return '';
  195. }
  196. ​
  197. if (str_starts_with($url, '//')) {
  198. return '';
  199. }
  200. ​
  201. $url = ltrim($url, '/');
  202. ​
  203. return filter_var($url, FILTER_SANITIZE_URL) ?: '';
  204. }
  205. ​
  206. private static function cleanHtml(string $text): string
  207. {
  208. if (trim($text) === '') {
  209. return '';
  210. }
  211. ​
  212. if (!class_exists(\DOMDocument::class)) {
  213. return strip_tags($text, '<b><strong><i><em><a><br><u><s><code><ul><ol><li>');
  214. }
  215. ​
  216. $allowedTags = ['b', 'strong', 'i', 'em', 'u', 's', 'code', 'a', 'span', 'br', 'ul', 'ol', 'li'];
  217. $allowedColors = '/^#[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/';
  218. ​
  219. $wrapped = '<?xml encoding="utf-8"?><div>' . $text . '</div>';
  220. ​
  221. $previous = libxml_use_internal_errors(true);
  222. $dom = new \DOMDocument();
  223. $dom->loadHTML($wrapped, LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NOBLANKS);
  224. libxml_clear_errors();
  225. libxml_use_internal_errors($previous);
  226. ​
  227. $root = $dom->getElementsByTagName('div')->item(0);
  228. if ($root === null) {
  229. return '';
  230. }
  231. ​
  232. self::sanitizeNode($dom, $root, $allowedTags, $allowedColors);
  233. ​
  234. $html = '';
  235. foreach (iterator_to_array($root->childNodes) as $child) {
  236. $html .= $dom->saveHTML($child);
  237. }
  238. ​
  239. return self::decodeTextEntities($html);
  240. }
  241. ​
  242. private static function decodeTextEntities(string $html): string
  243. {
  244. return (string) preg_replace_callback('/&(#[0-9]+|#x[0-9a-fA-F]+|[a-zA-Z][a-zA-Z0-9]*);/', static function (array $match): string {
  245. $char = html_entity_decode($match[0], ENT_QUOTES | ENT_HTML5, 'UTF-8');
  246. if ($char === $match[0] || $char === "\u{00A0}" || mb_strlen($char, 'UTF-8') !== 1 || ord($char[0]) < 128) {
  247. return $match[0];
  248. }
  249. ​
  250. return $char;
  251. }, $html);
  252. }
  253. ​
  254. private static function sanitizeNode(\DOMDocument $dom, \DOMNode $node, array $allowedTags, string $allowedColors): void
  255. {
  256. $children = iterator_to_array($node->childNodes);
  257. ​
  258. foreach ($children as $child) {
  259. if ($child instanceof \DOMText) {
  260. continue;
  261. }
  262. ​
  263. if (!$child instanceof \DOMElement) {
  264. $node->removeChild($child);
  265. continue;
  266. }
  267. ​
  268. $tag = strtolower($child->tagName);
  269. $parentTag = $node instanceof \DOMElement ? strtolower($node->tagName) : '';
  270. $misplacedItem = $tag === 'li' && !in_array($parentTag, ['ul', 'ol'], true);
  271. ​
  272. if ($misplacedItem || !in_array($tag, $allowedTags, true)) {
  273. $previousSibling = $child->previousSibling;
  274. if (in_array($tag, ['div', 'p', 'li'], true) && $previousSibling !== null
  275. && !($previousSibling instanceof \DOMElement && in_array(strtolower($previousSibling->tagName), ['br', 'ul', 'ol'], true))) {
  276. $node->insertBefore($dom->createElement('br'), $child);
  277. }
  278. while ($child->firstChild) {
  279. $node->insertBefore($child->firstChild, $child);
  280. }
  281. $node->removeChild($child);
  282. self::sanitizeNode($dom, $node, $allowedTags, $allowedColors);
  283. return;
  284. }
  285. ​
  286. self::sanitizeAttributes($child, $tag, $allowedColors);
  287. self::sanitizeNode($dom, $child, $allowedTags, $allowedColors);
  288. }
  289. }
  290. ​
  291. private static function sanitizeAttributes(\DOMElement $element, string $tag, string $allowedColors): void
  292. {
  293. $keep = [];
  294. ​
  295. if ($tag === 'a') {
  296. $href = self::cleanUrl((string) $element->getAttribute('href'));
  297. if ($href !== '') {
  298. $keep['href'] = $href;
  299. if ($element->getAttribute('target') === '_blank') {
  300. $keep['target'] = '_blank';
  301. $keep['rel'] = 'noopener noreferrer';
  302. }
  303. }
  304. }
  305. ​
  306. if ($tag === 'span') {
  307. $color = self::extractColor((string) $element->getAttribute('style'), $allowedColors);
  308. if ($color !== '') {
  309. $keep['style'] = 'color:' . $color;
  310. }
  311. }
  312. ​
  313. foreach (iterator_to_array($element->attributes ?? []) as $attribute) {
  314. $element->removeAttribute($attribute->name);
  315. }
  316. ​
  317. foreach ($keep as $name => $value) {
  318. $element->setAttribute($name, $value);
  319. }
  320. }
  321. ​
  322. private static function extractColor(string $style, string $allowedColors): string
  323. {
  324. if (preg_match('/color\s*:\s*(#[0-9a-fA-F]{3,6})/', $style, $matches) !== 1) {
  325. return '';
  326. }
  327. ​
  328. $color = $matches[1];
  329. ​
  330. return preg_match($allowedColors, $color) === 1 ? $color : '';
  331. }
  332. ​
  333. public static function readingTimeMinutes(string $blocksJson): int
  334. {
  335. $decoded = json_decode($blocksJson, true);
  336. if (!is_array($decoded) || !isset($decoded['blocks'])) {
  337. return 1;
  338. }
  339. ​
  340. $wordCount = 0;
  341. foreach ($decoded['blocks'] as $block) {
  342. $wordCount += self::blockWordCount(is_array($block) ? $block : []);
  343. }
  344. ​
  345. return max(1, (int) ceil($wordCount / 200));
  346. }
  347. ​
  348. private static function blockWordCount(array $block): int
  349. {
  350. $type = $block['type'] ?? '';
  351. $data = is_array($block['data'] ?? null) ? $block['data'] : [];
  352. ​
  353. if ($type === 'table') {
  354. $cells = [];
  355. foreach ($data['rows'] ?? [] as $row) {
  356. foreach (is_array($row) ? $row : [] as $cell) {
  357. $cells[] = (string) $cell;
  358. }
  359. }
  360. $text = implode(' ', $cells);
  361. } else {
  362. $text = match ($type) {
  363. 'paragraph', 'quote', 'heading2', 'heading3', 'callout' => strip_tags((string) ($data['text'] ?? '')),
  364. 'list' => implode(' ', array_map('strval', $data['items'] ?? [])),
  365. 'checklist' => implode(' ', array_map(static fn($item) => (string) ($item['text'] ?? ''), $data['items'] ?? [])),
  366. default => '',
  367. };
  368. }
  369. ​
  370. $text = trim($text);
  371. if ($text === '') {
  372. return 0;
  373. }
  374. ​
  375. return count(preg_split('/\s+/', $text));
  376. }
  377. ​
  378. public static function render(string $blocksJson): string
  379. {
  380. $decoded = json_decode($blocksJson, true);
  381. if (!is_array($decoded) || !isset($decoded['blocks'])) {
  382. return '';
  383. }
  384. ​
  385. $html = '';
  386. foreach ($decoded['blocks'] as $block) {
  387. $html .= self::renderBlock($block);
  388. }
  389. ​
  390. return $html;
  391. }
  392. ​
  393. // Renders the blocks and puts $insertHtml halfway through (only when there are at least 3 blocks).
  394. public static function renderWithMiddle(string $blocksJson, string $insertHtml): string
  395. {
  396. $decoded = json_decode($blocksJson, true);
  397. if (!is_array($decoded) || !isset($decoded['blocks']) || !is_array($decoded['blocks'])) {
  398. return '';
  399. }
  400. ​
  401. $parts = [];
  402. foreach ($decoded['blocks'] as $block) {
  403. $blockHtml = self::renderBlock(is_array($block) ? $block : []);
  404. if ($blockHtml !== '') {
  405. $parts[] = $blockHtml;
  406. }
  407. }
  408. ​
  409. if ($insertHtml !== '' && count($parts) >= 3) {
  410. array_splice($parts, intdiv(count($parts), 2), 0, [$insertHtml]);
  411. }
  412. ​
  413. return implode('', $parts);
  414. }
  415. ​
  416. private static function renderBlock(array $block): string
  417. {
  418. $type = $block['type'] ?? '';
  419. $data = $block['data'] ?? [];
  420. ​
  421. return match ($type) {
  422. 'paragraph' => self::renderParagraph((string) ($data['text'] ?? '')),
  423. 'quote' => '<blockquote>' . ($data['text'] ?? '') . '</blockquote>',
  424. 'heading2' => '<h2>' . htmlspecialchars((string) ($data['text'] ?? '')) . '</h2>',
  425. 'heading3' => '<h3>' . htmlspecialchars((string) ($data['text'] ?? '')) . '</h3>',
  426. 'image' => '<figure><img src="' . htmlspecialchars((string) ($data['src'] ?? '')) . '" alt="' . htmlspecialchars((string) ($data['alt'] ?? '')) . '">' .
  427. (($data['caption'] ?? '') !== '' ? '<figcaption>' . htmlspecialchars((string) $data['caption']) . '</figcaption>' : '') . '</figure>',
  428. 'video' => '<figure>' . self::renderVideo((string) ($data['src'] ?? '')) .
  429. (($data['caption'] ?? '') !== '' ? '<figcaption>' . htmlspecialchars((string) $data['caption']) . '</figcaption>' : '') . '</figure>',
  430. 'list' => self::renderList($data),
  431. 'code' => self::renderCode($data),
  432. 'table' => self::renderTable($data),
  433. 'checklist' => self::renderChecklist($data),
  434. 'callout' => '<div class="callout callout-' . htmlspecialchars((string) ($data['style'] ?? 'info')) . '">' .
  435. htmlspecialchars((string) ($data['text'] ?? '')) . '</div>',
  436. 'embed' => self::renderEmbed((string) ($data['url'] ?? '')),
  437. 'separator' => '<hr>',
  438. 'contact_form' => self::renderContactForm(),
  439. default => '',
  440. };
  441. }
  442. ​
  443. private static function renderVideo(string $src): string
  444. {
  445. $embed = self::embedInfo($src);
  446. if ($embed !== null) {
  447. return self::embedFrame($embed);
  448. }
  449. ​
  450. return '<video controls playsinline preload="metadata" src="' . htmlspecialchars($src) . '"></video>';
  451. }
  452. ​
  453. private static function renderEmbed(string $url): string
  454. {
  455. $embed = self::embedInfo($url) ?? ['src' => $url, 'kind' => 'wide'];
  456. ​
  457. return self::embedFrame($embed);
  458. }
  459. ​
  460. private static function embedFrame(array $embed): string
  461. {
  462. 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>';
  463. }
  464. ​
  465. public static function embedInfo(string $url): ?array
  466. {
  467. $url = trim($url);
  468. if (!preg_match('#^https?://#i', $url)) {
  469. return null;
  470. }
  471. $host = strtolower((string) parse_url($url, PHP_URL_HOST));
  472. $host = preg_replace('/^(www\.|m\.|mobile\.)/', '', $host);
  473. $path = (string) parse_url($url, PHP_URL_PATH);
  474. parse_str((string) parse_url($url, PHP_URL_QUERY), $query);
  475. ​
  476. if (in_array($host, ['youtube.com', 'youtube-nocookie.com', 'music.youtube.com'], true)) {
  477. $id = '';
  478. if (isset($query['v'])) {
  479. $id = (string) $query['v'];
  480. } elseif (preg_match('#^/(?:embed|shorts|live|v)/([\w-]{6,})#', $path, $m)) {
  481. $id = $m[1];
  482. }
  483. if ($id !== '' && preg_match('/^[\w-]+$/', $id)) {
  484. return ['src' => 'https://www.youtube-nocookie.com/embed/' . $id, 'kind' => str_contains($path, '/shorts/') ? 'tall' : 'wide'];
  485. }
  486. return null;
  487. }
  488. if ($host === 'youtu.be' && preg_match('#^/([\w-]{6,})#', $path, $m)) {
  489. return ['src' => 'https://www.youtube-nocookie.com/embed/' . $m[1], 'kind' => 'wide'];
  490. }
  491. if (in_array($host, ['vimeo.com', 'player.vimeo.com'], true) && preg_match('#/(\d+)#', $path, $m)) {
  492. return ['src' => 'https://player.vimeo.com/video/' . $m[1], 'kind' => 'wide'];
  493. }
  494. if (in_array($host, ['x.com', 'twitter.com'], true) && preg_match('#/status(?:es)?/(\d+)#', $path, $m)) {
  495. return ['src' => 'https://platform.twitter.com/embed/Tweet.html?id=' . $m[1] . '&dnt=true', 'kind' => 'post'];
  496. }
  497. if (in_array($host, ['facebook.com', 'fb.watch', 'web.facebook.com'], true)) {
  498. $isVideo = $host === 'fb.watch' || preg_match('#/(videos|watch|reel|share/v|share/r)#', $path . '?' . http_build_query($query));
  499. $plugin = $isVideo ? 'video.php' : 'post.php';
  500. return ['src' => 'https://www.facebook.com/plugins/' . $plugin . '?show_text=false&href=' . rawurlencode($url), 'kind' => $isVideo && !str_contains($path, '/reel') ? 'wide' : 'post'];
  501. }
  502. if ($host === 'instagram.com' && preg_match('#^/(p|reel|reels|tv)/([\w-]+)#', $path, $m)) {
  503. return ['src' => 'https://www.instagram.com/' . ($m[1] === 'reels' ? 'reel' : $m[1]) . '/' . $m[2] . '/embed', 'kind' => 'tall'];
  504. }
  505. if ($host === 'tiktok.com' && preg_match('#/video/(\d+)#', $path, $m)) {
  506. return ['src' => 'https://www.tiktok.com/embed/v2/' . $m[1], 'kind' => 'tall'];
  507. }
  508. if (in_array($host, ['dailymotion.com', 'dai.ly'], true) && preg_match('#^/(?:video/)?([a-zA-Z0-9]+)#', $path, $m)) {
  509. return ['src' => 'https://www.dailymotion.com/embed/video/' . $m[1], 'kind' => 'wide'];
  510. }
  511. if ($host === 'twitch.tv' && preg_match('#^/videos/(\d+)#', $path, $m)) {
  512. return ['src' => 'https://player.twitch.tv/?video=' . $m[1] . '&parent=' . rawurlencode((string) ($_SERVER['HTTP_HOST'] ?? 'localhost')), 'kind' => 'wide'];
  513. }
  514. if ($host === 'open.spotify.com' && preg_match('#^/(track|album|playlist|episode|show)/(\w+)#', $path, $m)) {
  515. return ['src' => 'https://open.spotify.com/embed/' . $m[1] . '/' . $m[2], 'kind' => 'audio'];
  516. }
  517. if ($host === 'soundcloud.com') {
  518. return ['src' => 'https://w.soundcloud.com/player/?url=' . rawurlencode($url), 'kind' => 'audio'];
  519. }
  520. if ($host === 'streamable.com' && preg_match('#^/(?:e/)?(\w+)#', $path, $m)) {
  521. return ['src' => 'https://streamable.com/e/' . $m[1], 'kind' => 'wide'];
  522. }
  523. ​
  524. return null;
  525. }
  526. ​
  527. private static function renderContactForm(): string
  528. {
  529. require_once __DIR__ . '/contact.php';
  530. ​
  531. return ContactForm::renderBlock();
  532. }
  533. ​
  534. private static function renderCode(array $data): string
  535. {
  536. $language = preg_replace('/[^a-z0-9+#-]/', '', strtolower((string) ($data['language'] ?? 'text'))) ?: 'text';
  537. $copyLabel = htmlspecialchars(Language::get('code_copy', 'Copy'), ENT_QUOTES);
  538. $copiedLabel = htmlspecialchars(Language::get('code_copied', 'Copied'), ENT_QUOTES);
  539. ​
  540. return '<div class="code-block">' .
  541. '<button type="button" class="code-copy" data-label="' . $copyLabel . '" data-copied="' . $copiedLabel . '">' . $copyLabel . '</button>' .
  542. '<pre><code class="language-' . $language . '">' . htmlspecialchars((string) ($data['code'] ?? '')) . '</code></pre>' .
  543. '</div>';
  544. }
  545. ​
  546. private static function renderParagraph(string $html): string
  547. {
  548. if (stripos($html, '<ul') === false && stripos($html, '<ol') === false) {
  549. return '<p>' . $html . '</p>';
  550. }
  551. ​
  552. if (!class_exists(\DOMDocument::class)) {
  553. return '<div class="paragraph-group">' . $html . '</div>';
  554. }
  555. ​
  556. $previous = libxml_use_internal_errors(true);
  557. $dom = new \DOMDocument();
  558. $dom->loadHTML('<?xml encoding="utf-8"?><div>' . $html . '</div>', LIBXML_NOERROR | LIBXML_NOWARNING);
  559. libxml_clear_errors();
  560. libxml_use_internal_errors($previous);
  561. ​
  562. $root = $dom->getElementsByTagName('div')->item(0);
  563. if ($root === null) {
  564. return '<p>' . $html . '</p>';
  565. }
  566. ​
  567. $parts = [];
  568. $buffer = '';
  569. $flush = static function () use (&$buffer, &$parts): void {
  570. $trimmed = preg_replace('#^(\s|<br\s*/?>)+|(\s|<br\s*/?>)+$#i', '', $buffer);
  571. if ($trimmed !== null && trim(strip_tags($trimmed)) !== '') {
  572. $parts[] = '<p>' . $trimmed . '</p>';
  573. }
  574. $buffer = '';
  575. };
  576. ​
  577. foreach (iterator_to_array($root->childNodes) as $child) {
  578. $outer = (string) $dom->saveHTML($child);
  579. if ($child instanceof \DOMElement && in_array(strtolower($child->tagName), ['ul', 'ol'], true)) {
  580. $flush();
  581. $parts[] = $outer;
  582. continue;
  583. }
  584. $buffer .= $outer;
  585. }
  586. $flush();
  587. ​
  588. return self::decodeTextEntities(implode('', $parts));
  589. }
  590. ​
  591. private static function renderList(array $data): string
  592. {
  593. $tag = ($data['style'] ?? 'unordered') === 'ordered' ? 'ol' : 'ul';
  594. $items = '';
  595. foreach ($data['items'] ?? [] as $item) {
  596. if (trim((string) $item) === '') {
  597. continue;
  598. }
  599. $items .= '<li>' . htmlspecialchars((string) $item) . '</li>';
  600. }
  601. return $items === '' ? '' : '<' . $tag . '>' . $items . '</' . $tag . '>';
  602. }
  603. ​
  604. private static function renderTable(array $data): string
  605. {
  606. $rows = '';
  607. foreach ($data['rows'] ?? [] as $row) {
  608. $cells = '';
  609. foreach ($row as $cell) {
  610. $cells .= '<td>' . htmlspecialchars((string) $cell) . '</td>';
  611. }
  612. $rows .= '<tr>' . $cells . '</tr>';
  613. }
  614. return '<table><tbody>' . $rows . '</tbody></table>';
  615. }
  616. ​
  617. private static function renderChecklist(array $data): string
  618. {
  619. $items = '';
  620. foreach ($data['items'] ?? [] as $item) {
  621. $checked = !empty($item['checked']) ? 'checked disabled' : 'disabled';
  622. $items .= '<li><input type="checkbox" ' . $checked . '> ' . htmlspecialchars((string) ($item['text'] ?? '')) . '</li>';
  623. }
  624. return '<ul class="checklist">' . $items . '</ul>';
  625. }
  626. }
  627. ​