3 * @copyright Copyright (C) 2010-2022, 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\Content\Widget\ContactBlock;
27 use Friendica\Core\Hook;
28 use Friendica\Core\Renderer;
29 use Friendica\Core\Search;
31 use Friendica\Model\Contact;
32 use Friendica\Util\Network;
33 use Friendica\Util\Strings;
34 use Friendica\Util\XML;
35 use League\HTMLToMarkdown\HtmlConverter;
40 * Search all instances of a specific HTML tag node in the provided DOM document and replaces them with BBCode text nodes.
42 * @see HTML::tagToBBCodeSub()
44 private static function tagToBBCode(DOMDocument $doc, string $tag, array $attributes, string $startbb, string $endbb, bool $ignoreChildren = false)
47 $done = self::tagToBBCodeSub($doc, $tag, $attributes, $startbb, $endbb, $ignoreChildren);
52 * Search the first specific HTML tag node in the provided DOM document and replaces it with BBCode text nodes.
54 * @param DOMDocument $doc
55 * @param string $tag HTML tag name
56 * @param array $attributes Array of attributes to match and optionally use the value from
57 * @param string $startbb BBCode tag opening
58 * @param string $endbb BBCode tag closing
59 * @param bool $ignoreChildren If set to false, the HTML tag children will be appended as text inside the BBCode tag
60 * Otherwise, they will be entirely ignored. Useful for simple BBCode that draw their
61 * inner value from an attribute value and disregard the tag children.
62 * @return bool Whether a replacement was done
64 private static function tagToBBCodeSub(DOMDocument $doc, string $tag, array $attributes, string $startbb, string $endbb, bool $ignoreChildren = false): bool
66 $savestart = str_replace('$', '\x01', $startbb);
69 $xpath = new DOMXPath($doc);
71 /** @var \DOMNode[] $list */
72 $list = $xpath->query("//" . $tag);
73 foreach ($list as $node) {
75 if ($node->attributes->length) {
76 foreach ($node->attributes as $attribute) {
77 $attr[$attribute->name] = $attribute->value;
83 $startbb = $savestart;
87 foreach ($attributes as $attribute => $value) {
88 $startbb = str_replace('\x01' . ++$i, '$1', $startbb);
89 if (strpos('*' . $startbb, '$1') > 0) {
90 if ($replace && (@$attr[$attribute] != '')) {
91 $startbb = preg_replace($value, $startbb, $attr[$attribute], -1, $count);
93 // If nothing could be changed
101 if (@$attr[$attribute] != $value) {
108 $StartCode = $doc->createTextNode($startbb);
109 $EndCode = $doc->createTextNode($endbb);
111 $node->parentNode->insertBefore($StartCode, $node);
113 if (!$ignoreChildren && $node->hasChildNodes()) {
114 /** @var \DOMNode $child */
115 foreach ($node->childNodes as $key => $child) {
116 /* Remove empty text nodes at the start or at the end of the children list */
117 if ($key > 0 && $key < $node->childNodes->length - 1 || $child->nodeName != '#text' || trim($child->nodeValue) !== '') {
118 $newNode = $child->cloneNode(true);
119 $node->parentNode->insertBefore($newNode, $node);
124 $node->parentNode->insertBefore($EndCode, $node);
125 $node->parentNode->removeChild($node);
133 * Converter for HTML to BBCode
135 * Made by: ike@piratenpartei.de
136 * Originally made for the syncom project: http://wiki.piratenpartei.de/Syncom
137 * https://github.com/annando/Syncom
139 * @param string $message
140 * @param string $basepath
142 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
144 public static function toBBCode(string $message, string $basepath = ''): string
147 * Check if message is empty to prevent a lot of code below from being executed
148 * for just an empty message.
150 if ($message === '') {
154 DI::profiler()->startRecording('rendering');
155 $message = str_replace("\r", "", $message);
157 $message = Strings::performWithEscapedBlocks($message, '#<pre><code.*</code></pre>#iUs', function ($message) {
158 $message = str_replace(
171 $message = preg_replace('=<(\w+):(.+?)>=', '<removeme>', $message);
172 $message = preg_replace('=</(\w+):(.+?)>=', '</removeme>', $message);
174 $doc = new DOMDocument();
175 $doc->preserveWhiteSpace = false;
177 $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8");
179 if (empty($message)) {
183 @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
185 XML::deleteNode($doc, 'style');
186 XML::deleteNode($doc, 'head');
187 XML::deleteNode($doc, 'title');
188 XML::deleteNode($doc, 'meta');
189 XML::deleteNode($doc, 'xml');
190 XML::deleteNode($doc, 'removeme');
192 $xpath = new DomXPath($doc);
193 $list = $xpath->query("//pre");
194 foreach ($list as $node) {
195 // Ensure to escape unescaped & - they will otherwise raise a warning
196 $safe_value = preg_replace('/&(?!\w+;)/', '&', $node->nodeValue);
197 $node->nodeValue = str_replace("\n", "\r", $safe_value);
200 $message = $doc->saveHTML();
201 $message = str_replace(["\n<", ">\n", "\r", "\n", "\xC3\x82\xC2\xA0"], ["<", ">", "<br />", " ", ""], $message);
202 $message = preg_replace('= [\s]*=i', " ", $message);
204 if (empty($message)) {
208 @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
210 self::tagToBBCode($doc, 'html', [], "", "");
211 self::tagToBBCode($doc, 'body', [], "", "");
213 // Outlook-Quote - Variant 1
214 self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal', 'style' => 'margin-left:35.4pt'], '[quote]', '[/quote]');
216 // Outlook-Quote - Variant 2
220 ['style' => 'border:none;border-left:solid blue 1.5pt;padding:0cm 0cm 0cm 4.0pt'],
226 self::tagToBBCode($doc, 'span', ['style' => 'text-decoration: underline;'], '[u]', '[/u]');
227 self::tagToBBCode($doc, 'span', ['style' => 'font-style: italic;'], '[i]', '[/i]');
228 self::tagToBBCode($doc, 'span', ['style' => 'font-weight: bold;'], '[b]', '[/b]');
230 /* self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[font=$1][size=$2][color=$3]', '[/color][/size][/font]');
231 self::node2BBCode($doc, 'font', array('size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[size=$1][color=$2]', '[/color][/size]');
232 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(.+)/'), '[font=$1][size=$2]', '[/size][/font]');
233 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'color'=>'/(.+)/'), '[font=$1][color=$3]', '[/color][/font]');
234 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/'), '[font=$1]', '[/font]');
235 self::node2BBCode($doc, 'font', array('size'=>'/(\d+)/'), '[size=$1]', '[/size]');
236 self::node2BBCode($doc, 'font', array('color'=>'/(.+)/'), '[color=$1]', '[/color]');
239 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*font-family:\s*(.+?)[,;].*color:\s*(.+?)[,;].*/'), '[size=$1][font=$2][color=$3]', '[/color][/font][/size]');
240 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(\d+)[,;].*/'), '[size=$1]', '[/size]');
241 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*/'), '[size=$1]', '[/size]');
243 self::tagToBBCode($doc, 'span', ['style' => '/.*color:\s*(.+?)[,;].*/'], '[color="$1"]', '[/color]');
245 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
246 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)pt.*/'), '[font=$1][size=$2]', '[/size][/font]');
247 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)px.*/'), '[font=$1][size=$2]', '[/size][/font]');
248 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
249 // Importing the classes - interesting for importing of posts from third party networks that were exported from friendica
251 //self::node2BBCode($doc, 'span', array('class'=>'/([\w ]+)/'), '[class=$1]', '[/class]');
252 self::tagToBBCode($doc, 'span', ['class' => 'type-link'], '[class=type-link]', '[/class]');
253 self::tagToBBCode($doc, 'span', ['class' => 'type-video'], '[class=type-video]', '[/class]');
255 self::tagToBBCode($doc, 'strong', [], '[b]', '[/b]');
256 self::tagToBBCode($doc, 'em', [], '[i]', '[/i]');
257 self::tagToBBCode($doc, 'b', [], '[b]', '[/b]');
258 self::tagToBBCode($doc, 'i', [], '[i]', '[/i]');
259 self::tagToBBCode($doc, 'u', [], '[u]', '[/u]');
260 self::tagToBBCode($doc, 's', [], '[s]', '[/s]');
261 self::tagToBBCode($doc, 'del', [], '[s]', '[/s]');
262 self::tagToBBCode($doc, 'strike', [], '[s]', '[/s]');
264 self::tagToBBCode($doc, 'big', [], "[size=large]", "[/size]");
265 self::tagToBBCode($doc, 'small', [], "[size=small]", "[/size]");
267 self::tagToBBCode($doc, 'blockquote', [], '[quote]', '[/quote]');
269 self::tagToBBCode($doc, 'br', [], "\n", '');
271 self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal'], "\n", "");
272 self::tagToBBCode($doc, 'div', ['class' => 'MsoNormal'], "\r", "");
274 self::tagToBBCode($doc, 'span', [], "", "");
276 self::tagToBBCode($doc, 'span', [], "", "");
277 self::tagToBBCode($doc, 'pre', [], "", "");
279 self::tagToBBCode($doc, 'div', [], "\r", "\r");
280 self::tagToBBCode($doc, 'p', [], "\n", "\n");
282 self::tagToBBCode($doc, 'ul', [], "[list]", "[/list]");
283 self::tagToBBCode($doc, 'ol', [], "[list=1]", "[/list]");
284 self::tagToBBCode($doc, 'li', [], "[*]", "");
286 self::tagToBBCode($doc, 'hr', [], "[hr]", "");
288 self::tagToBBCode($doc, 'table', [], "[table]", "[/table]");
289 self::tagToBBCode($doc, 'th', [], "[th]", "[/th]");
290 self::tagToBBCode($doc, 'tr', [], "[tr]", "[/tr]");
291 self::tagToBBCode($doc, 'td', [], "[td]", "[/td]");
293 self::tagToBBCode($doc, 'h1', [], "[h1]", "[/h1]");
294 self::tagToBBCode($doc, 'h2', [], "[h2]", "[/h2]");
295 self::tagToBBCode($doc, 'h3', [], "[h3]", "[/h3]");
296 self::tagToBBCode($doc, 'h4', [], "[h4]", "[/h4]");
297 self::tagToBBCode($doc, 'h5', [], "[h5]", "[/h5]");
298 self::tagToBBCode($doc, 'h6', [], "[h6]", "[/h6]");
300 self::tagToBBCode($doc, 'a', ['href' => '/mailto:(.+)/'], '[mail=$1]', '[/mail]');
301 self::tagToBBCode($doc, 'a', ['href' => '/(.+)/'], '[url=$1]', '[/url]');
303 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/', 'alt' => '/(.+)/'], '[img=$1]$2', '[/img]', true);
304 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/', 'width' => '/(\d+)/', 'height' => '/(\d+)/'], '[img=$2x$3]$1', '[/img]', true);
305 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], '[img]$1', '[/img]', true);
308 self::tagToBBCode($doc, 'video', ['src' => '/(.+)/'], '[video]$1', '[/video]', true);
309 self::tagToBBCode($doc, 'audio', ['src' => '/(.+)/'], '[audio]$1', '[/audio]', true);
310 // Backward compatibility, [iframe] support has been removed in version 2020.12
311 self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], '[url]$1', '[/url]', true);
313 self::tagToBBCode($doc, 'key', [], '[code]', '[/code]');
314 self::tagToBBCode($doc, 'code', [], '[code]', '[/code]');
316 $message = $doc->saveHTML();
318 // I'm removing something really disturbing
319 // Don't know exactly what it is
320 $message = str_replace(chr(194) . chr(160), ' ', $message);
322 $message = str_replace(" ", " ", $message);
324 // removing multiple DIVs
325 $message = preg_replace('=\r *\r=i', "\n", $message);
326 $message = str_replace("\r", "\n", $message);
328 Hook::callAll('html2bbcode', $message);
330 $message = strip_tags($message);
332 $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
334 // remove quotes if they don't make sense
335 $message = preg_replace('=\[/quote\][\s]*\[quote\]=i', "\n", $message);
337 $message = preg_replace('=\[quote\]\s*=i', "[quote]", $message);
338 $message = preg_replace('=\s*\[/quote\]=i', "[/quote]", $message);
341 $oldmessage = $message;
342 $message = str_replace("\n \n", "\n\n", $message);
343 } while ($oldmessage != $message);
346 $oldmessage = $message;
347 $message = str_replace("\n\n\n", "\n\n", $message);
348 } while ($oldmessage != $message);
351 $oldmessage = $message;
352 $message = str_replace(
375 } while ($message != $oldmessage);
377 $message = str_replace(
378 ['[b][b]', '[/b][/b]', '[i][i]', '[/i][/i]'],
379 ['[b]', '[/b]', '[i]', '[/i]'],
383 // Handling Yahoo style of mails
384 $message = str_replace('[hr][b]From:[/b]', '[quote][b]From:[/b]', $message);
389 $message = preg_replace_callback(
390 '#<pre><code(?: class="language-([^"]*)")?>(.*)</code></pre>#iUs',
391 function ($matches) {
393 if ($matches[1] != '') {
394 $prefix = '[code=' . $matches[1] . ']';
397 return $prefix . "\n" . html_entity_decode($matches[2]) . "\n" . '[/code]';
402 $message = trim($message);
404 if ($basepath != '') {
405 $message = self::qualifyURLs($message, $basepath);
408 DI::profiler()->stopRecording();
413 * Sub function to complete incomplete URL
415 * @param array $matches Result of preg_replace_callback
416 * @param string $basepath Basepath that is used to complete the URL
418 * @return string The expanded URL
420 private static function qualifyURLsSub(array $matches, string $basepath): string
422 $base = parse_url($basepath);
423 unset($base['query']);
424 unset($base['fragment']);
429 if (empty($url) || empty(parse_url($url))) {
433 $parts = array_merge($base, parse_url($url));
434 $url2 = Network::unparseURL($parts);
436 return str_replace($url, $url2, $link);
440 * Complete incomplete URLs in BBCode
442 * @param string $body Body with URLs
443 * @param string $basepath Base path that is used to complete the URL
445 * @return string Body with expanded URLs
447 private static function qualifyURLs(string $body, string $basepath): string
449 $URLSearchString = "^\[\]";
451 $matches = ["/\[url\=([$URLSearchString]*)\].*?\[\/url\]/ism",
452 "/\[url\]([$URLSearchString]*)\[\/url\]/ism",
453 "/\[img\=[0-9]*x[0-9]*\](.*?)\[\/img\]/ism",
454 "/\[img\](.*?)\[\/img\]/ism",
455 "/\[zmg\=[0-9]*x[0-9]*\](.*?)\[\/img\]/ism",
456 "/\[zmg\](.*?)\[\/zmg\]/ism",
457 "/\[video\](.*?)\[\/video\]/ism",
458 "/\[audio\](.*?)\[\/audio\]/ism",
461 foreach ($matches as $match) {
462 $body = preg_replace_callback(
464 function ($match) use ($basepath) {
465 return self::qualifyURLsSub($match, $basepath);
473 private static function breakLines(string $line, int $level, int $wraplength = 75): string
475 if ($wraplength == 0) {
476 $wraplength = 2000000;
479 $wraplen = $wraplength - $level;
486 $subline = substr($line, 0, $wraplen);
488 $pos = strrpos($subline, ' ');
491 $pos = strpos($line, ' ');
494 if (($pos > 0) && strlen($line) > $wraplen) {
495 $newline = trim(substr($line, 0, $pos));
497 $newline = str_repeat(">", $level) . ' ' . $newline;
500 $newlines[] = $newline . " ";
501 $line = substr($line, $pos + 1);
503 } while ((strlen($line) > $wraplen) && !($oldline == $line));
506 $line = str_repeat(">", $level) . ' ' . $line;
511 return implode("\n", $newlines);
514 private static function quoteLevel(string $message, int $wraplength = 75): string
516 $lines = explode("\n", $message);
520 foreach ($lines as $line) {
523 while (strpos("*" . $line, '[quote]') > 0) {
525 $pos = strpos($line, '[quote]');
526 $line = substr($line, 0, $pos) . substr($line, $pos + 7);
532 while (strpos("*" . $line, '[/quote]') > 0) {
538 $pos = strpos($line, '[/quote]');
539 $line = substr($line, 0, $pos) . substr($line, $pos + 8);
542 if (!$startquote || ($line != '')) {
543 $newlines[] = self::breakLines($line, $currlevel, $wraplength);
547 return implode("\n", $newlines);
550 private static function collectURLs(string $message): array
552 $pattern = '/<a.*?href="(.*?)".*?>(.*?)<\/a>/is';
553 preg_match_all($pattern, $message, $result, PREG_SET_ORDER);
556 foreach ($result as $treffer) {
559 // A list of some links that should be ignored
560 $list = ["/user/", "/tag/", "/group/", "/profile/", "/search?search=", "/search?tag=", "mailto:", "/u/", "/node/",
561 "//plus.google.com/", "//twitter.com/"];
562 foreach ($list as $listitem) {
563 if (strpos($treffer[1], $listitem) !== false) {
568 if ((strpos($treffer[1], "//twitter.com/") !== false) && (strpos($treffer[1], "/status/") !== false)) {
572 if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/posts") !== false)) {
576 if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/photos") !== false)) {
580 $ignore = $ignore || strpos($treffer[1], '#') === 0;
583 $urls[$treffer[1]] = $treffer[1];
591 * @param string $html
592 * @param int $wraplength Ensures individual lines aren't longer than this many characters. Doesn't break words.
593 * @param bool $compact True: Completely strips image tags; False: Keeps image URLs
596 public static function toPlaintext(string $html, int $wraplength = 75, bool $compact = false): string
598 DI::profiler()->startRecording('rendering');
599 $message = str_replace("\r", "", $html);
601 $doc = new DOMDocument();
602 $doc->preserveWhiteSpace = false;
604 $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8");
606 if (empty($message)) {
607 DI::profiler()->stopRecording();
611 @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
613 $message = $doc->saveHTML();
614 // Remove eventual UTF-8 BOM
615 $message = str_replace("\xC3\x82\xC2\xA0", "", $message);
617 // Collecting all links
618 $urls = self::collectURLs($message);
620 if (empty($message)) {
621 DI::profiler()->stopRecording();
625 @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
627 self::tagToBBCode($doc, 'html', [], '', '');
628 self::tagToBBCode($doc, 'body', [], '', '');
631 self::tagToBBCode($doc, 'blockquote', [], "»", "«");
633 self::tagToBBCode($doc, 'blockquote', [], '[quote]', "[/quote]\n");
636 self::tagToBBCode($doc, 'br', [], "\n", '');
638 self::tagToBBCode($doc, 'span', [], "", "");
639 self::tagToBBCode($doc, 'pre', [], "", "");
640 self::tagToBBCode($doc, 'div', [], "\r", "\r");
641 self::tagToBBCode($doc, 'p', [], "\n", "\n");
643 self::tagToBBCode($doc, 'li', [], "\n* ", "\n");
645 self::tagToBBCode($doc, 'hr', [], "\n" . str_repeat("-", 70) . "\n", "");
647 self::tagToBBCode($doc, 'tr', [], "\n", "");
648 self::tagToBBCode($doc, 'td', [], "\t", "");
650 self::tagToBBCode($doc, 'h1', [], "\n\n*", "*\n");
651 self::tagToBBCode($doc, 'h2', [], "\n\n*", "*\n");
652 self::tagToBBCode($doc, 'h3', [], "\n\n*", "*\n");
653 self::tagToBBCode($doc, 'h4', [], "\n\n*", "*\n");
654 self::tagToBBCode($doc, 'h5', [], "\n\n*", "*\n");
655 self::tagToBBCode($doc, 'h6', [], "\n\n*", "*\n");
658 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], ' [img]$1', '[/img] ');
660 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], ' ', ' ');
663 // Backward compatibility, [iframe] support has been removed in version 2020.12
664 self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], ' $1 ', '');
666 $message = $doc->saveHTML();
669 $message = str_replace("[img]", "", $message);
670 $message = str_replace("[/img]", "", $message);
673 // was ersetze ich da?
674 // Irgendein stoerrisches UTF-Zeug
675 $message = str_replace(chr(194) . chr(160), ' ', $message);
677 $message = str_replace(" ", " ", $message);
679 // Aufeinanderfolgende DIVs
680 $message = preg_replace('=\r *\r=i', "\n", $message);
681 $message = str_replace("\r", "\n", $message);
683 $message = strip_tags($message);
685 $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
687 if (!$compact && ($message != '')) {
688 foreach ($urls as $id => $url) {
689 if ($url != '' && strpos($message, $url) === false) {
690 $message .= "\n" . $url . ' ';
695 $message = str_replace("\n«", "«\n", $message);
696 $message = str_replace("»\n", "\n»", $message);
699 $oldmessage = $message;
700 $message = str_replace("\n\n\n", "\n\n", $message);
701 } while ($oldmessage != $message);
703 $message = self::quoteLevel(trim($message), $wraplength);
705 DI::profiler()->stopRecording();
706 return trim($message);
710 * Converts provided HTML code to Markdown. The hardwrap parameter maximizes
711 * compatibility with Diaspora in spite of the Markdown standards.
713 * @param string $html
716 public static function toMarkdown(string $html): string
718 DI::profiler()->startRecording('rendering');
719 $converter = new HtmlConverter(['hard_break' => true]);
720 $markdown = $converter->convert($html);
722 DI::profiler()->stopRecording();
727 * Convert video HTML to BBCode tags
732 public static function toBBCodeVideo(string $s): string
735 '#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
736 '[youtube]$2[/youtube]',
741 '#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
742 '[youtube]$2[/youtube]',
747 '#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
756 * transform link href and img src from relative to absolute
758 * @param string $text
759 * @param string $base base url
762 public static function relToAbs(string $text, string $base): string
768 $base = rtrim($base, '/');
770 $base2 = $base . "/";
773 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
774 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
775 $text = preg_replace($pattern, $replace, $text);
777 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
778 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
779 $text = preg_replace($pattern, $replace, $text);
782 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
783 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
784 $text = preg_replace($pattern, $replace, $text);
786 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
787 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
788 $text = preg_replace($pattern, $replace, $text);
796 * Loader for infinite scrolling
798 * @return string html for loader
799 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
801 public static function scrollLoader(): string
803 $tpl = Renderer::getMarkupTemplate("scroll_loader.tpl");
804 return Renderer::replaceMacros($tpl, [
805 'wait' => DI::l10n()->t('Loading more entries...'),
806 'end' => DI::l10n()->t('The end')
811 * Format contacts as picture links or as text links
813 * @param array $contact Array with contacts which contains an array with
814 * int 'id' => The ID of the contact
815 * int 'uid' => The user ID of the user who owns this data
816 * string 'name' => The name of the contact
817 * string 'url' => The url to the profile page of the contact
818 * string 'addr' => The webbie of the contact (e.g.) username@friendica.com
819 * string 'network' => The network to which the contact belongs to
820 * string 'thumb' => The contact picture
821 * string 'click' => js code which is performed when clicking on the contact
822 * @param boolean $redirect If true try to use the redir url if it's possible
823 * @param string $class CSS class for the
824 * @param boolean $textmode If true display the contacts as text links
825 * if false display the contacts as picture links
826 * @return string Formatted html
827 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
828 * @throws \ImagickException
830 public static function micropro(array $contact, bool $redirect = false, string $class = '', bool $textmode = false): string
832 // Use the contact URL if no address is available
833 if (empty($contact['addr'])) {
834 $contact["addr"] = $contact["url"];
837 $url = $contact['url'];
842 $url = Contact::magicLinkByContact($contact);
843 if (strpos($url, 'redir/') === 0) {
844 $sparkle = ' sparkle';
848 // If there is some js available we don't need the url
849 if (!empty($contact['click'])) {
853 return Renderer::replaceMacros(Renderer::getMarkupTemplate($textmode ? 'micropro_txt.tpl' : 'micropro_img.tpl'), [
854 '$click' => $contact['click'] ?? '',
857 '$photo' => Contact::getThumb($contact),
858 '$name' => $contact['name'],
859 'title' => $contact['name'] . ' [' . $contact['addr'] . ']',
860 '$parkle' => $sparkle,
868 * @param string $s Search query.
869 * @param string $id HTML id
870 * @param bool $aside Display the search widgit aside.
872 * @return string Formatted HTML.
875 public static function search(string $s, string $id = 'search-box', bool $aside = true): string
879 if (strpos($s, '#') === 0) {
882 $save_label = $mode === 'text' ? DI::l10n()->t('Save') : DI::l10n()->t('Follow');
886 '$q' => urlencode($s),
888 '$search_label' => DI::l10n()->t('Search'),
889 '$save_label' => $save_label,
890 '$search_hint' => DI::l10n()->t('@name, !forum, #tags, content'),
892 '$return_url' => urlencode(Search::getSearchPath($s)),
896 $values['$search_options'] = [
897 'fulltext' => DI::l10n()->t('Full Text'),
898 'tags' => DI::l10n()->t('Tags'),
899 'contacts' => DI::l10n()->t('Contacts')
902 if (DI::config()->get('system', 'poco_local_search')) {
903 $values['$searchoption']['forums'] = DI::l10n()->t('Forums');
907 return Renderer::replaceMacros(Renderer::getMarkupTemplate('searchbox.tpl'), $values);
911 * Replace naked text hyperlink with HTML formatted hyperlink
916 public static function toLink(string $s): string
918 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank" rel="noopener noreferrer">$1</a>', $s);
919 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism", '<$1$2=$3&$4>', $s);
924 * Given a HTML text and a set of filtering reasons, adds a content hiding header with the provided reasons
926 * Reasons are expected to have been translated already.
928 * @param string $html
929 * @param array $reasons
931 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
933 public static function applyContentFilter(string $html, array $reasons): string
935 if (count($reasons)) {
936 $tpl = Renderer::getMarkupTemplate('wall/content_filter.tpl');
937 $html = Renderer::replaceMacros($tpl, [
938 '$reasons' => $reasons,
939 '$rnd' => Strings::getRandomHex(8),
940 '$openclose' => DI::l10n()->t('Click to open/close'),
949 * replace html amp entity with amp char
953 public static function unamp(string $s): string
955 return str_replace('&', '&', $s);
959 * Clean an HTML text for potentially harmful code
961 * @param string $text
962 * @param array $allowedIframeDomains List of allowed iframe source domains without the scheme
965 public static function purify(string $text, array $allowedIframeDomains = []): string
967 // Allows cid: URL scheme
968 \HTMLPurifier_URISchemeRegistry::instance()->register('cid', new HTMLPurifier_URIScheme_cid());
970 $config = \HTMLPurifier_HTML5Config::createDefault();
971 $config->set('HTML.Doctype', 'HTML5');
973 // Used to remove iframe with src attribute filtered out
974 $config->set('AutoFormat.RemoveEmpty', true);
976 $config->set('HTML.SafeIframe', true);
978 array_walk($allowedIframeDomains, function (&$domain) {
979 // Allow the domain and all its eventual sub-domains
980 $domain = '(?:(?!-)[A-Za-z0-9-]{1,63}(?<!-)\.)*' . preg_quote(trim($domain, '/'), '%');
983 $config->set('URI.SafeIframeRegexp',
985 ' . implode('|', $allowedIframeDomains) . '
987 (?:/|$) # Prevents bogus domains like youtube.com.fake.tld
991 $config->set('Attr.AllowedRel', [
992 'noreferrer' => true,
996 $config->set('Attr.AllowedFrameTargets', [
1000 $config->set('AutoFormat.RemoveEmpty.Predicate', [
1001 'colgroup' => [], // |
1004 'iframe' => ['src'], // ↳ Default HTMLPurify values
1005 'i' => ['class'], // Allows forkawesome icons
1008 // Uncomment to debug HTMLPurifier behavior
1009 //$config->set('Core.CollectErrors', true);
1010 //$config->set('Core.MaintainLineNumbers', true);
1012 $HTMLPurifier = new \HTMLPurifier($config);
1014 $text = $HTMLPurifier->purify($text);
1016 /** @var \HTMLPurifier_ErrorCollector $errorCollector */
1017 // Uncomment to debug HTML Purifier behavior
1018 //$errorCollector = $HTMLPurifier->context->get('ErrorCollector');
1019 //var_dump($errorCollector->getRaw());