3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Content\Text;
26 use Friendica\Model\Photo;
27 use Friendica\Model\Post;
30 * Tumblr Neue Post Format
31 * @see https://www.tumblr.com/docs/npf
35 static $heading_subtype = [];
38 * Convert BBCode into NPF (Tumblr Neue Post Format)
40 * @param string $bbcode
41 * @param integer $uri_id
44 static public function fromBBCode(string $bbcode, int $uri_id): array
46 $bbcode = self::prepareBody($bbcode);
48 $html = BBCode::convert($bbcode, false, BBCode::NPF);
53 $doc = new DOMDocument();
54 $doc->formatOutput = true;
55 if (!@$doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'))) {
59 self::setHeadingSubStyles($doc);
61 $element = $doc->getElementsByTagName('body')->item(0);
63 list($npf, $text, $formatting) = self::routeChildren($element, $uri_id, true, []);
65 return self::addLinkBlockForUriId($uri_id, 0, $npf);
69 * Fetch the heading types
71 * @param DOMDocument $doc
74 static function setHeadingSubStyles(DOMDocument $doc)
76 self::$heading_subtype = [];
77 foreach (['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] as $element) {
78 if ($doc->getElementsByTagName($element)->count() > 0) {
79 if (empty(self::$heading_subtype)) {
80 self::$heading_subtype[$element] = 'heading1';
82 self::$heading_subtype[$element] = 'heading2';
89 * Prepare the BBCode for the NPF conversion
91 * @param string $bbcode
94 static private function prepareBody(string $bbcode): string
96 $shared = BBCode::fetchShareAttributes($bbcode);
97 if (!empty($shared)) {
98 $bbcode = $shared['shared'];
101 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
103 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]\s*\[/url\]#ism", $bbcode, $pictures, PREG_SET_ORDER)) {
104 foreach ($pictures as $picture) {
105 if (preg_match('#/photo/.*-[01]\.#ism', $picture[2]) && (preg_match('#/photo/.*-0\.#ism', $picture[1]) || preg_match('#/photos/.*/image/#ism', $picture[1]))) {
106 $bbcode = str_replace($picture[0], "\n\n[img=" . str_replace('-1.', '-0.', $picture[2]) . "]" . $picture[3] . "[/img]\n\n", $bbcode);
111 $bbcode = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", "\n\n[img=$1]$2[/img]\n\n", $bbcode);
113 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img\]([^\[]+?)\[/img\]\s*\[/url\]#ism", $bbcode, $pictures, PREG_SET_ORDER)) {
114 foreach ($pictures as $picture) {
115 if (preg_match('#/photo/.*-[01]\.#ism', $picture[2]) && (preg_match('#/photo/.*-0\.#ism', $picture[1]) || preg_match('#/photos/.*/image/#ism', $picture[1]))) {
116 $bbcode = str_replace($picture[0], "\n\n[img]" . str_replace('-1.', '-0.', $picture[2]) . "[/img]\n\n", $bbcode);
121 $bbcode = preg_replace("/\[img\](.*?)\[\/img\]/ism", "\n\n[img]$1[/img]\n\n", $bbcode);
124 $oldbbcode = $bbcode;
125 $bbcode = str_replace(["\n\n\n"], ["\n\n"], $bbcode);
126 } while ($oldbbcode != $bbcode);
128 return trim($bbcode);
132 * Walk recursively through the HTML
134 * @param DOMElement $element
135 * @param integer $uri_id
136 * @param boolean $parse_structure
137 * @param array $callstack
139 * @param string $text
140 * @param array $formatting
143 static private function routeChildren(DOMElement $element, int $uri_id, bool $parse_structure, array $callstack, array $npf = [], string $text = '', array $formatting = []): array
145 if ($parse_structure && $text) {
146 list($npf, $text, $formatting) = self::addBlock($text, $formatting, $npf, $callstack);
149 $callstack[] = $element->nodeName;
150 $level = self::getLevelByCallstack($callstack);
152 foreach ($element->childNodes as $child) {
153 switch ($child->nodeName) {
156 list($npf, $text, $formatting) = self::addFormatting($child, $uri_id, 'bold', $callstack, $npf, $text, $formatting);
161 list($npf, $text, $formatting) = self::addFormatting($child, $uri_id, 'italic', $callstack, $npf, $text, $formatting);
165 list($npf, $text, $formatting) = self::addFormatting($child, $uri_id, 'strikethrough', $callstack, $npf, $text, $formatting);
170 list($npf, $text, $formatting) = self::addFormatting($child, $uri_id, '', $callstack, $npf, $text, $formatting);
181 $text .= $child->textContent;
186 // Ignore tables and spoilers
190 list($npf, $text, $formatting) = self::addInlineLink($child, $uri_id, $callstack, $npf, $text, $formatting);
194 $npf = self::addImageBlock($child, $uri_id, $level, $npf);
199 $npf = self::addMediaBlock($child, $uri_id, $level, $npf);
203 list($npf, $text, $formatting) = self::routeChildren($child, $uri_id, true, $callstack, $npf, $text, $formatting);
208 if ($parse_structure && $text) {
209 list($npf, $text, $formatting) = self::addBlock($text, $formatting, $npf, $callstack);
211 return [$npf, $text, $formatting];
215 * Return the correct indent level
217 * @param array $callstack
220 static private function getLevelByCallstack(array $callstack): int
223 foreach ($callstack as $entry) {
224 if (in_array($entry, ['ol', 'ul', 'blockquote'])) {
228 return max(0, $level - 1);
232 * Detect the subtype via the HTML element callstack
234 * @param array $callstack
235 * @param string $text
238 static private function getSubTypeByCallstack(array $callstack, string $text): string
241 foreach ($callstack as $entry) {
244 $subtype = 'ordered-list-item';
248 $subtype = 'unordered-list-item';
252 $subtype = self::$heading_subtype[$entry];
256 $subtype = self::$heading_subtype[$entry];
260 $subtype = self::$heading_subtype[$entry];
264 $subtype = self::$heading_subtype[$entry];
268 $subtype = self::$heading_subtype[$entry];
272 $subtype = self::$heading_subtype[$entry];
276 $subtype = mb_strlen($text) < 100 ? 'quote' : 'indented';
280 $subtype = 'indented';
292 * Add formatting for a text block
294 * @param DOMElement $element
295 * @param integer $uri_id
296 * @param string $type
297 * @param array $callstack
299 * @param string $text
300 * @param array $formatting
303 static private function addFormatting(DOMElement $element, int $uri_id, string $type, array $callstack, array $npf, string $text, array $formatting): array
305 $start = mb_strlen($text);
306 list($npf, $text, $formatting) = self::routeChildren($element, $uri_id, false, $callstack, $npf, $text, $formatting);
311 'end' => mb_strlen($text),
315 return [$npf, $text, $formatting];
319 * Add an inline link for a text block
321 * @param DOMElement $element
322 * @param integer $uri_id
323 * @param array $callstack
325 * @param string $text
326 * @param array $formatting
329 static private function addInlineLink(DOMElement $element, int $uri_id, array $callstack, array $npf, string $text, array $formatting): array
331 $start = mb_strlen($text);
332 list($npf, $text, $formatting) = self::routeChildren($element, $uri_id, false, $callstack, $npf, $text, $formatting);
335 foreach ($element->attributes as $key => $attribute) {
336 $attributes[$key] = trim($attribute->value);
338 if (!empty($attributes['href'])) {
341 'end' => mb_strlen($text),
343 'url' => $attributes['href']
346 return [$npf, $text, $formatting];
352 * @param string $text
353 * @param array $formatting
355 * @param array $callstack
358 static private function addBlock(string $text, array $formatting, array $npf, array $callstack): array
366 if (!empty($formatting)) {
367 $block['formatting'] = $formatting;
370 $level = self::getLevelByCallstack($callstack);
372 $block['indent_level'] = $level;
375 $subtype = self::getSubTypeByCallstack($callstack, $text);
377 $block['subtype'] = $subtype;
379 unset($block['subtype']);
385 return [$npf, $text, $formatting];
389 * Add a block for a preview picture
391 * @param array $media
392 * @param array $block
395 static private function addPoster(array $media, array $block): array
398 if (!empty($media['preview'])) {
399 $poster['url'] = $media['preview'];
401 if (!empty($media['preview-width'])) {
402 $poster['width'] = $media['preview-width'];
404 if (!empty($media['preview-height'])) {
405 $poster['height'] = $media['preview-height'];
407 if (!empty($poster)) {
408 $block['poster'] = [$poster];
414 * Add a link block from the HTML attachment of a given post uri-id
416 * @param integer $uri_id
417 * @param integer $level
421 static private function addLinkBlockForUriId(int $uri_id, int $level, array $npf): array
423 foreach (Post\Media::getByURIId($uri_id, [Post\Media::HTML]) as $link) {
424 $host = parse_url($link['url'], PHP_URL_HOST);
425 if (in_array($host, ['www.youtube.com', 'youtu.be'])) {
428 'provider' => 'youtube',
429 'url' => $link['url'],
431 } elseif (in_array($host, ['vimeo.com'])) {
434 'provider' => 'vimeo',
435 'url' => $link['url'],
437 } elseif (in_array($host, ['open.spotify.com'])) {
440 'provider' => 'spotify',
441 'url' => $link['url'],
446 'url' => $link['url'],
448 if (!empty($link['name'])) {
449 $block['title'] = $link['name'];
451 if (!empty($link['description'])) {
452 $block['description'] = $link['description'];
454 if (!empty($link['author-name'])) {
455 $block['author'] = $link['author-name'];
457 if (!empty($link['publisher-name'])) {
458 $block['site_name'] = $link['publisher-name'];
463 $block['indent_level'] = $level;
466 $npf[] = self::addPoster($link, $block);
474 * @param DOMElement $element
475 * @param integer $uri_id
476 * @param integer $level
480 static private function addImageBlock(DOMElement $element, int $uri_id, int $level, array $npf): array
483 foreach ($element->attributes as $key => $attribute) {
484 $attributes[$key] = trim($attribute->value);
486 if (empty($attributes['src'])) {
495 if (!empty($attributes['alt'])) {
496 $block['alt_text'] = $attributes['alt'];
499 if (!empty($attributes['title']) && (($attributes['alt'] ?? '') != $attributes['title'])) {
500 $block['caption'] = $attributes['title'];
503 $rid = Photo::ridFromURI($attributes['src']);
505 $photos = Photo::selectToArray([], ['resource-id' => $rid]);
506 foreach ($photos as $photo) {
507 $block['media'][] = [
508 'type' => $photo['type'],
509 'url' => str_replace('-0.', '-' . $photo['scale'] . '.', $attributes['src']),
510 'width' => $photo['width'],
511 'height' => $photo['height'],
514 if (empty($attributes['alt']) && !empty($photos[0]['desc'])) {
515 $block['alt_text'] = $photos[0]['desc'];
517 } elseif ($media = Post\Media::getByURL($uri_id, $attributes['src'], [Post\Media::IMAGE])) {
518 $block['media'][] = [
519 'type' => $media['mimetype'],
520 'url' => $media['url'],
521 'width' => $media['width'],
522 'height' => $media['height'],
524 if (empty($attributes['alt']) && !empty($media['description'])) {
525 $block['alt_text'] = $media['description'];
528 $block['media'][] = ['url' => $attributes['src']];
532 $block['indent_level'] = $level;
541 * Add an audio or video block
543 * @param DOMElement $element
544 * @param integer $uri_id
545 * @param integer $level
549 static private function addMediaBlock(DOMElement $element, int $uri_id, int $level, array $npf): array
552 foreach ($element->attributes as $key => $attribute) {
553 $attributes[$key] = trim($attribute->value);
555 if (empty($attributes['src'])) {
559 $media = Post\Media::getByURL($uri_id, $attributes['src'], [Post\Media::AUDIO, Post\Media::VIDEO]);
560 if (!empty($media)) {
561 switch ($media['type']) {
562 case Post\Media::AUDIO:
566 'type' => $media['mimetype'],
567 'url' => $media['url'],
571 if (!empty($media['name'])) {
572 $block['title'] = $media['name'];
573 } elseif (!empty($media['description'])) {
574 $block['title'] = $media['description'];
577 $block = self::addPoster($media, $block);
580 case Post\Media::VIDEO:
584 'type' => $media['mimetype'],
585 'url' => $media['url'],
589 $block = self::addPoster($media, $block);
595 'text' => $element->textContent,
599 'end' => mb_strlen($element->textContent),
601 'url' => $attributes['src']
608 $block['indent_level'] = $level;