3 * @copyright Copyright (C) 2010-2021, 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)
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($message, $basepath = '')
146 $message = str_replace("\r", "", $message);
148 $message = Strings::performWithEscapedBlocks($message, '#<pre><code.*</code></pre>#iUs', function ($message) {
149 $message = str_replace(
162 $message = preg_replace('=<(\w+):(.+?)>=', '<removeme>', $message);
163 $message = preg_replace('=</(\w+):(.+?)>=', '</removeme>', $message);
165 $doc = new DOMDocument();
166 $doc->preserveWhiteSpace = false;
168 $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8");
170 if (empty($message)) {
174 @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
176 XML::deleteNode($doc, 'style');
177 XML::deleteNode($doc, 'head');
178 XML::deleteNode($doc, 'title');
179 XML::deleteNode($doc, 'meta');
180 XML::deleteNode($doc, 'xml');
181 XML::deleteNode($doc, 'removeme');
183 $xpath = new DomXPath($doc);
184 $list = $xpath->query("//pre");
185 foreach ($list as $node) {
186 // Ensure to escape unescaped & - they will otherwise raise a warning
187 $safe_value = preg_replace('/&(?!\w+;)/', '&', $node->nodeValue);
188 $node->nodeValue = str_replace("\n", "\r", $safe_value);
191 $message = $doc->saveHTML();
192 $message = str_replace(["\n<", ">\n", "\r", "\n", "\xC3\x82\xC2\xA0"], ["<", ">", "<br />", " ", ""], $message);
193 $message = preg_replace('= [\s]*=i', " ", $message);
195 if (empty($message)) {
199 @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
201 self::tagToBBCode($doc, 'html', [], "", "");
202 self::tagToBBCode($doc, 'body', [], "", "");
204 // Outlook-Quote - Variant 1
205 self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal', 'style' => 'margin-left:35.4pt'], '[quote]', '[/quote]');
207 // Outlook-Quote - Variant 2
211 ['style' => 'border:none;border-left:solid blue 1.5pt;padding:0cm 0cm 0cm 4.0pt'],
217 self::tagToBBCode($doc, 'span', ['style' => 'text-decoration: underline;'], '[u]', '[/u]');
218 self::tagToBBCode($doc, 'span', ['style' => 'font-style: italic;'], '[i]', '[/i]');
219 self::tagToBBCode($doc, 'span', ['style' => 'font-weight: bold;'], '[b]', '[/b]');
221 /* self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[font=$1][size=$2][color=$3]', '[/color][/size][/font]');
222 self::node2BBCode($doc, 'font', array('size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[size=$1][color=$2]', '[/color][/size]');
223 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(.+)/'), '[font=$1][size=$2]', '[/size][/font]');
224 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'color'=>'/(.+)/'), '[font=$1][color=$3]', '[/color][/font]');
225 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/'), '[font=$1]', '[/font]');
226 self::node2BBCode($doc, 'font', array('size'=>'/(\d+)/'), '[size=$1]', '[/size]');
227 self::node2BBCode($doc, 'font', array('color'=>'/(.+)/'), '[color=$1]', '[/color]');
230 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*font-family:\s*(.+?)[,;].*color:\s*(.+?)[,;].*/'), '[size=$1][font=$2][color=$3]', '[/color][/font][/size]');
231 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(\d+)[,;].*/'), '[size=$1]', '[/size]');
232 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*/'), '[size=$1]', '[/size]');
234 self::tagToBBCode($doc, 'span', ['style' => '/.*color:\s*(.+?)[,;].*/'], '[color="$1"]', '[/color]');
236 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
237 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)pt.*/'), '[font=$1][size=$2]', '[/size][/font]');
238 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)px.*/'), '[font=$1][size=$2]', '[/size][/font]');
239 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
240 // Importing the classes - interesting for importing of posts from third party networks that were exported from friendica
242 //self::node2BBCode($doc, 'span', array('class'=>'/([\w ]+)/'), '[class=$1]', '[/class]');
243 self::tagToBBCode($doc, 'span', ['class' => 'type-link'], '[class=type-link]', '[/class]');
244 self::tagToBBCode($doc, 'span', ['class' => 'type-video'], '[class=type-video]', '[/class]');
246 self::tagToBBCode($doc, 'strong', [], '[b]', '[/b]');
247 self::tagToBBCode($doc, 'em', [], '[i]', '[/i]');
248 self::tagToBBCode($doc, 'b', [], '[b]', '[/b]');
249 self::tagToBBCode($doc, 'i', [], '[i]', '[/i]');
250 self::tagToBBCode($doc, 'u', [], '[u]', '[/u]');
251 self::tagToBBCode($doc, 's', [], '[s]', '[/s]');
252 self::tagToBBCode($doc, 'del', [], '[s]', '[/s]');
253 self::tagToBBCode($doc, 'strike', [], '[s]', '[/s]');
255 self::tagToBBCode($doc, 'big', [], "[size=large]", "[/size]");
256 self::tagToBBCode($doc, 'small', [], "[size=small]", "[/size]");
258 self::tagToBBCode($doc, 'blockquote', [], '[quote]', '[/quote]');
260 self::tagToBBCode($doc, 'br', [], "\n", '');
262 self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal'], "\n", "");
263 self::tagToBBCode($doc, 'div', ['class' => 'MsoNormal'], "\r", "");
265 self::tagToBBCode($doc, 'span', [], "", "");
267 self::tagToBBCode($doc, 'span', [], "", "");
268 self::tagToBBCode($doc, 'pre', [], "", "");
270 self::tagToBBCode($doc, 'div', [], "\r", "\r");
271 self::tagToBBCode($doc, 'p', [], "\n", "\n");
273 self::tagToBBCode($doc, 'ul', [], "[list]", "[/list]");
274 self::tagToBBCode($doc, 'ol', [], "[list=1]", "[/list]");
275 self::tagToBBCode($doc, 'li', [], "[*]", "");
277 self::tagToBBCode($doc, 'hr', [], "[hr]", "");
279 self::tagToBBCode($doc, 'table', [], "[table]", "[/table]");
280 self::tagToBBCode($doc, 'th', [], "[th]", "[/th]");
281 self::tagToBBCode($doc, 'tr', [], "[tr]", "[/tr]");
282 self::tagToBBCode($doc, 'td', [], "[td]", "[/td]");
284 self::tagToBBCode($doc, 'h1', [], "[h1]", "[/h1]");
285 self::tagToBBCode($doc, 'h2', [], "[h2]", "[/h2]");
286 self::tagToBBCode($doc, 'h3', [], "[h3]", "[/h3]");
287 self::tagToBBCode($doc, 'h4', [], "[h4]", "[/h4]");
288 self::tagToBBCode($doc, 'h5', [], "[h5]", "[/h5]");
289 self::tagToBBCode($doc, 'h6', [], "[h6]", "[/h6]");
291 self::tagToBBCode($doc, 'a', ['href' => '/mailto:(.+)/'], '[mail=$1]', '[/mail]');
292 self::tagToBBCode($doc, 'a', ['href' => '/(.+)/'], '[url=$1]', '[/url]');
294 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/', 'alt' => '/(.+)/'], '[img=$1]$2', '[/img]', true);
295 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/', 'width' => '/(\d+)/', 'height' => '/(\d+)/'], '[img=$2x$3]$1', '[/img]', true);
296 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], '[img]$1', '[/img]', true);
299 self::tagToBBCode($doc, 'video', ['src' => '/(.+)/'], '[video]$1', '[/video]', true);
300 self::tagToBBCode($doc, 'audio', ['src' => '/(.+)/'], '[audio]$1', '[/audio]', true);
301 // Backward compatibility, [iframe] support has been removed in version 2020.12
302 self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], '[url]$1', '[/url]', true);
304 self::tagToBBCode($doc, 'key', [], '[code]', '[/code]');
305 self::tagToBBCode($doc, 'code', [], '[code]', '[/code]');
307 $message = $doc->saveHTML();
309 // I'm removing something really disturbing
310 // Don't know exactly what it is
311 $message = str_replace(chr(194) . chr(160), ' ', $message);
313 $message = str_replace(" ", " ", $message);
315 // removing multiple DIVs
316 $message = preg_replace('=\r *\r=i', "\n", $message);
317 $message = str_replace("\r", "\n", $message);
319 Hook::callAll('html2bbcode', $message);
321 $message = strip_tags($message);
323 $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
325 // remove quotes if they don't make sense
326 $message = preg_replace('=\[/quote\][\s]*\[quote\]=i', "\n", $message);
328 $message = preg_replace('=\[quote\]\s*=i', "[quote]", $message);
329 $message = preg_replace('=\s*\[/quote\]=i', "[/quote]", $message);
332 $oldmessage = $message;
333 $message = str_replace("\n \n", "\n\n", $message);
334 } while ($oldmessage != $message);
337 $oldmessage = $message;
338 $message = str_replace("\n\n\n", "\n\n", $message);
339 } while ($oldmessage != $message);
342 $oldmessage = $message;
343 $message = str_replace(
366 } while ($message != $oldmessage);
368 $message = str_replace(
369 ['[b][b]', '[/b][/b]', '[i][i]', '[/i][/i]'],
370 ['[b]', '[/b]', '[i]', '[/i]'],
374 // Handling Yahoo style of mails
375 $message = str_replace('[hr][b]From:[/b]', '[quote][b]From:[/b]', $message);
380 $message = preg_replace_callback(
381 '#<pre><code(?: class="language-([^"]*)")?>(.*)</code></pre>#iUs',
382 function ($matches) {
384 if ($matches[1] != '') {
385 $prefix = '[code=' . $matches[1] . ']';
388 return $prefix . PHP_EOL . trim($matches[2]) . PHP_EOL . '[/code]';
393 $message = trim($message);
395 if ($basepath != '') {
396 $message = self::qualifyURLs($message, $basepath);
403 * Sub function to complete incomplete URL
405 * @param array $matches Result of preg_replace_callback
406 * @param string $basepath Basepath that is used to complete the URL
408 * @return string The expanded URL
410 private static function qualifyURLsSub($matches, $basepath)
412 $base = parse_url($basepath);
413 unset($base['query']);
414 unset($base['fragment']);
419 if (empty($url) || empty(parse_url($url))) {
423 $parts = array_merge($base, parse_url($url));
424 $url2 = Network::unparseURL($parts);
426 return str_replace($url, $url2, $link);
430 * Complete incomplete URLs in BBCode
432 * @param string $body Body with URLs
433 * @param string $basepath Base path that is used to complete the URL
435 * @return string Body with expanded URLs
437 private static function qualifyURLs($body, $basepath)
439 $URLSearchString = "^\[\]";
441 $matches = ["/\[url\=([$URLSearchString]*)\].*?\[\/url\]/ism",
442 "/\[url\]([$URLSearchString]*)\[\/url\]/ism",
443 "/\[img\=[0-9]*x[0-9]*\](.*?)\[\/img\]/ism",
444 "/\[img\](.*?)\[\/img\]/ism",
445 "/\[zmg\=[0-9]*x[0-9]*\](.*?)\[\/img\]/ism",
446 "/\[zmg\](.*?)\[\/zmg\]/ism",
447 "/\[video\](.*?)\[\/video\]/ism",
448 "/\[audio\](.*?)\[\/audio\]/ism",
451 foreach ($matches as $match) {
452 $body = preg_replace_callback(
454 function ($match) use ($basepath) {
455 return self::qualifyURLsSub($match, $basepath);
463 private static function breakLines($line, $level, $wraplength = 75)
465 if ($wraplength == 0) {
466 $wraplength = 2000000;
469 $wraplen = $wraplength - $level;
476 $subline = substr($line, 0, $wraplen);
478 $pos = strrpos($subline, ' ');
481 $pos = strpos($line, ' ');
484 if (($pos > 0) && strlen($line) > $wraplen) {
485 $newline = trim(substr($line, 0, $pos));
487 $newline = str_repeat(">", $level) . ' ' . $newline;
490 $newlines[] = $newline . " ";
491 $line = substr($line, $pos + 1);
493 } while ((strlen($line) > $wraplen) && !($oldline == $line));
496 $line = str_repeat(">", $level) . ' ' . $line;
501 return implode("\n", $newlines);
504 private static function quoteLevel($message, $wraplength = 75)
506 $lines = explode("\n", $message);
510 foreach ($lines as $line) {
513 while (strpos("*" . $line, '[quote]') > 0) {
515 $pos = strpos($line, '[quote]');
516 $line = substr($line, 0, $pos) . substr($line, $pos + 7);
522 while (strpos("*" . $line, '[/quote]') > 0) {
528 $pos = strpos($line, '[/quote]');
529 $line = substr($line, 0, $pos) . substr($line, $pos + 8);
532 if (!$startquote || ($line != '')) {
533 $newlines[] = self::breakLines($line, $currlevel, $wraplength);
537 return implode("\n", $newlines);
540 private static function collectURLs($message)
542 $pattern = '/<a.*?href="(.*?)".*?>(.*?)<\/a>/is';
543 preg_match_all($pattern, $message, $result, PREG_SET_ORDER);
546 foreach ($result as $treffer) {
549 // A list of some links that should be ignored
550 $list = ["/user/", "/tag/", "/group/", "/profile/", "/search?search=", "/search?tag=", "mailto:", "/u/", "/node/",
551 "//plus.google.com/", "//twitter.com/"];
552 foreach ($list as $listitem) {
553 if (strpos($treffer[1], $listitem) !== false) {
558 if ((strpos($treffer[1], "//twitter.com/") !== false) && (strpos($treffer[1], "/status/") !== false)) {
562 if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/posts") !== false)) {
566 if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/photos") !== false)) {
570 $ignore = $ignore || strpos($treffer[1], '#') === 0;
573 $urls[$treffer[1]] = $treffer[1];
581 * @param string $html
582 * @param int $wraplength Ensures individual lines aren't longer than this many characters. Doesn't break words.
583 * @param bool $compact True: Completely strips image tags; False: Keeps image URLs
586 public static function toPlaintext(string $html, $wraplength = 75, $compact = false)
588 $message = str_replace("\r", "", $html);
590 $doc = new DOMDocument();
591 $doc->preserveWhiteSpace = false;
593 $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8");
595 if (empty($message)) {
599 @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
601 $message = $doc->saveHTML();
602 // Remove eventual UTF-8 BOM
603 $message = str_replace("\xC3\x82\xC2\xA0", "", $message);
605 // Collecting all links
606 $urls = self::collectURLs($message);
608 if (empty($message)) {
612 @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
614 self::tagToBBCode($doc, 'html', [], '', '');
615 self::tagToBBCode($doc, 'body', [], '', '');
618 self::tagToBBCode($doc, 'blockquote', [], "»", "«");
620 self::tagToBBCode($doc, 'blockquote', [], '[quote]', "[/quote]\n");
623 self::tagToBBCode($doc, 'br', [], "\n", '');
625 self::tagToBBCode($doc, 'span', [], "", "");
626 self::tagToBBCode($doc, 'pre', [], "", "");
627 self::tagToBBCode($doc, 'div', [], "\r", "\r");
628 self::tagToBBCode($doc, 'p', [], "\n", "\n");
630 self::tagToBBCode($doc, 'li', [], "\n* ", "\n");
632 self::tagToBBCode($doc, 'hr', [], "\n" . str_repeat("-", 70) . "\n", "");
634 self::tagToBBCode($doc, 'tr', [], "\n", "");
635 self::tagToBBCode($doc, 'td', [], "\t", "");
637 self::tagToBBCode($doc, 'h1', [], "\n\n*", "*\n");
638 self::tagToBBCode($doc, 'h2', [], "\n\n*", "*\n");
639 self::tagToBBCode($doc, 'h3', [], "\n\n*", "*\n");
640 self::tagToBBCode($doc, 'h4', [], "\n\n*", "*\n");
641 self::tagToBBCode($doc, 'h5', [], "\n\n*", "*\n");
642 self::tagToBBCode($doc, 'h6', [], "\n\n*", "*\n");
645 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], ' [img]$1', '[/img] ');
647 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], ' ', ' ');
650 // Backward compatibility, [iframe] support has been removed in version 2020.12
651 self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], ' $1 ', '');
653 $message = $doc->saveHTML();
656 $message = str_replace("[img]", "", $message);
657 $message = str_replace("[/img]", "", $message);
660 // was ersetze ich da?
661 // Irgendein stoerrisches UTF-Zeug
662 $message = str_replace(chr(194) . chr(160), ' ', $message);
664 $message = str_replace(" ", " ", $message);
666 // Aufeinanderfolgende DIVs
667 $message = preg_replace('=\r *\r=i', "\n", $message);
668 $message = str_replace("\r", "\n", $message);
670 $message = strip_tags($message);
672 $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
674 if (!$compact && ($message != '')) {
675 foreach ($urls as $id => $url) {
676 if ($url != '' && strpos($message, $url) === false) {
677 $message .= "\n" . $url . ' ';
682 $message = str_replace("\n«", "«\n", $message);
683 $message = str_replace("»\n", "\n»", $message);
686 $oldmessage = $message;
687 $message = str_replace("\n\n\n", "\n\n", $message);
688 } while ($oldmessage != $message);
690 $message = self::quoteLevel(trim($message), $wraplength);
692 return trim($message);
696 * Converts provided HTML code to Markdown. The hardwrap parameter maximizes
697 * compatibility with Diaspora in spite of the Markdown standards.
699 * @param string $html
702 public static function toMarkdown($html)
704 $converter = new HtmlConverter(['hard_break' => true]);
705 $markdown = $converter->convert($html);
711 * Convert video HTML to BBCode tags
716 public static function toBBCodeVideo($s)
719 '#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
720 '[youtube]$2[/youtube]',
725 '#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
726 '[youtube]$2[/youtube]',
731 '#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
740 * transform link href and img src from relative to absolute
742 * @param string $text
743 * @param string $base base url
746 public static function relToAbs($text, $base)
752 $base = rtrim($base, '/');
754 $base2 = $base . "/";
757 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
758 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
759 $text = preg_replace($pattern, $replace, $text);
761 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
762 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
763 $text = preg_replace($pattern, $replace, $text);
766 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
767 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
768 $text = preg_replace($pattern, $replace, $text);
770 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
771 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
772 $text = preg_replace($pattern, $replace, $text);
780 * return div element with class 'clear'
784 public static function clearDiv()
786 return '<div class="clear"></div>';
790 * Loader for infinite scrolling
792 * @return string html for loader
793 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
795 public static function scrollLoader()
797 $tpl = Renderer::getMarkupTemplate("scroll_loader.tpl");
798 return Renderer::replaceMacros($tpl, [
799 'wait' => DI::l10n()->t('Loading more entries...'),
800 'end' => DI::l10n()->t('The end')
805 * Get html for contact block.
807 * @deprecated since version 2019.03
808 * @see ContactBlock::getHTML()
810 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
811 * @throws \ImagickException
813 public static function contactBlock()
817 return ContactBlock::getHTML($a->profile);
821 * Format contacts as picture links or as text links
823 * @param array $contact Array with contacts which contains an array with
824 * int 'id' => The ID of the contact
825 * int 'uid' => The user ID of the user who owns this data
826 * string 'name' => The name of the contact
827 * string 'url' => The url to the profile page of the contact
828 * string 'addr' => The webbie of the contact (e.g.) username@friendica.com
829 * string 'network' => The network to which the contact belongs to
830 * string 'thumb' => The contact picture
831 * string 'click' => js code which is performed when clicking on the contact
832 * @param boolean $redirect If true try to use the redir url if it's possible
833 * @param string $class CSS class for the
834 * @param boolean $textmode If true display the contacts as text links
835 * if false display the contacts as picture links
836 * @return string Formatted html
837 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
838 * @throws \ImagickException
840 public static function micropro($contact, $redirect = false, $class = '', $textmode = false)
842 // Use the contact URL if no address is available
843 if (empty($contact['addr'])) {
844 $contact["addr"] = $contact["url"];
847 $url = $contact['url'];
852 $url = Contact::magicLinkByContact($contact);
853 if (strpos($url, 'redir/') === 0) {
854 $sparkle = ' sparkle';
858 // If there is some js available we don't need the url
859 if (!empty($contact['click'])) {
863 return Renderer::replaceMacros(Renderer::getMarkupTemplate($textmode ? 'micropro_txt.tpl' : 'micropro_img.tpl'), [
864 '$click' => $contact['click'] ?? '',
867 '$photo' => Contact::getThumb($contact),
868 '$name' => $contact['name'],
869 'title' => $contact['name'] . ' [' . $contact['addr'] . ']',
870 '$parkle' => $sparkle,
878 * @param string $s Search query.
879 * @param string $id HTML id
880 * @param string $url Search url.
881 * @param bool $aside Display the search widgit aside.
883 * @return string Formatted HTML.
886 public static function search($s, $id = 'search-box', $aside = true)
890 if (strpos($s, '#') === 0) {
893 $save_label = $mode === 'text' ? DI::l10n()->t('Save') : DI::l10n()->t('Follow');
897 '$q' => urlencode($s),
899 '$search_label' => DI::l10n()->t('Search'),
900 '$save_label' => $save_label,
901 '$search_hint' => DI::l10n()->t('@name, !forum, #tags, content'),
903 '$return_url' => urlencode(Search::getSearchPath($s)),
907 $values['$search_options'] = [
908 'fulltext' => DI::l10n()->t('Full Text'),
909 'tags' => DI::l10n()->t('Tags'),
910 'contacts' => DI::l10n()->t('Contacts')
913 if (DI::config()->get('system', 'poco_local_search')) {
914 $values['$searchoption']['forums'] = DI::l10n()->t('Forums');
918 return Renderer::replaceMacros(Renderer::getMarkupTemplate('searchbox.tpl'), $values);
922 * Replace naked text hyperlink with HTML formatted hyperlink
927 public static function toLink($s)
929 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank" rel="noopener noreferrer">$1</a>', $s);
930 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism", '<$1$2=$3&$4>', $s);
935 * Given a HTML text and a set of filtering reasons, adds a content hiding header with the provided reasons
937 * Reasons are expected to have been translated already.
939 * @param string $html
940 * @param array $reasons
942 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
944 public static function applyContentFilter($html, array $reasons)
946 if (count($reasons)) {
947 $tpl = Renderer::getMarkupTemplate('wall/content_filter.tpl');
948 $html = Renderer::replaceMacros($tpl, [
949 '$reasons' => $reasons,
950 '$rnd' => Strings::getRandomHex(8),
951 '$openclose' => DI::l10n()->t('Click to open/close'),
960 * replace html amp entity with amp char
964 public static function unamp($s)
966 return str_replace('&', '&', $s);
970 * Clean an HTML text for potentially harmful code
972 * @param string $text
973 * @param array $allowedIframeDomains List of allowed iframe source domains without the scheme
976 public static function purify(string $text, array $allowedIframeDomains = []): string
978 // Allows cid: URL scheme
979 \HTMLPurifier_URISchemeRegistry::instance()->register('cid', new HTMLPurifier_URIScheme_cid());
981 $config = \HTMLPurifier_HTML5Config::createDefault();
982 $config->set('HTML.Doctype', 'HTML5');
984 // Used to remove iframe with src attribute filtered out
985 $config->set('AutoFormat.RemoveEmpty', true);
987 $config->set('HTML.SafeIframe', true);
989 array_walk($allowedIframeDomains, function (&$domain) {
990 // Allow the domain and all its eventual sub-domains
991 $domain = '(?:(?!-)[A-Za-z0-9-]{1,63}(?<!-)\.)*' . preg_quote(trim($domain, '/'), '%');
994 $config->set('URI.SafeIframeRegexp',
996 ' . implode('|', $allowedIframeDomains) . '
998 (?:/|$) # Prevents bogus domains like youtube.com.fake.tld
1002 $config->set('Attr.AllowedRel', [
1003 'noreferrer' => true,
1006 $config->set('Attr.AllowedFrameTargets', [
1010 $config->set('AutoFormat.RemoveEmpty.Predicate', [
1011 'colgroup' => [], // |
1014 'iframe' => ['src'], // ↳ Default HTMLPurify values
1015 'i' => ['class'], // Allows forkawesome icons
1018 // Uncomment to debug HTMLPurifier behavior
1019 //$config->set('Core.CollectErrors', true);
1020 //$config->set('Core.MaintainLineNumbers', true);
1022 $HTMLPurifier = new \HTMLPurifier($config);
1024 $text = $HTMLPurifier->purify($text);
1026 /** @var \HTMLPurifier_ErrorCollector $errorCollector */
1027 // Uncomment to debug HTML Purifier behavior
1028 //$errorCollector = $HTMLPurifier->context->get('ErrorCollector');
1029 //var_dump($errorCollector->getRaw());