3 * @copyright Copyright (C) 2020, Friendica
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;
39 public static function sanitizeCSS($input)
43 $input = strtolower($input);
45 for ($i = 0; $i < strlen($input); $i++) {
46 $char = substr($input, $i, 1);
48 if (($char >= "a") && ($char <= "z")) {
52 if (!(strpos(" #;:0123456789-_.%", $char) === false)) {
61 * Search all instances of a specific HTML tag node in the provided DOM document and replaces them with BBCode text nodes.
63 * @see HTML::tagToBBCodeSub()
65 private static function tagToBBCode(DOMDocument $doc, string $tag, array $attributes, string $startbb, string $endbb, bool $ignoreChildren = false)
68 $done = self::tagToBBCodeSub($doc, $tag, $attributes, $startbb, $endbb, $ignoreChildren);
73 * Search the first specific HTML tag node in the provided DOM document and replaces it with BBCode text nodes.
75 * @param DOMDocument $doc
76 * @param string $tag HTML tag name
77 * @param array $attributes Array of attributes to match and optionally use the value from
78 * @param string $startbb BBCode tag opening
79 * @param string $endbb BBCode tag closing
80 * @param bool $ignoreChildren If set to false, the HTML tag children will be appended as text inside the BBCode tag
81 * Otherwise, they will be entirely ignored. Useful for simple BBCode that draw their
82 * inner value from an attribute value and disregard the tag children.
83 * @return bool Whether a replacement was done
85 private static function tagToBBCodeSub(DOMDocument $doc, string $tag, array $attributes, string $startbb, string $endbb, bool $ignoreChildren = false)
87 $savestart = str_replace('$', '\x01', $startbb);
90 $xpath = new DOMXPath($doc);
92 /** @var \DOMNode[] $list */
93 $list = $xpath->query("//" . $tag);
94 foreach ($list as $node) {
96 if ($node->attributes->length) {
97 foreach ($node->attributes as $attribute) {
98 $attr[$attribute->name] = $attribute->value;
104 $startbb = $savestart;
108 foreach ($attributes as $attribute => $value) {
109 $startbb = str_replace('\x01' . ++$i, '$1', $startbb);
110 if (strpos('*' . $startbb, '$1') > 0) {
111 if ($replace && (@$attr[$attribute] != '')) {
112 $startbb = preg_replace($value, $startbb, $attr[$attribute], -1, $count);
114 // If nothing could be changed
122 if (@$attr[$attribute] != $value) {
129 $StartCode = $doc->createTextNode($startbb);
130 $EndCode = $doc->createTextNode($endbb);
132 $node->parentNode->insertBefore($StartCode, $node);
134 if (!$ignoreChildren && $node->hasChildNodes()) {
135 /** @var \DOMNode $child */
136 foreach ($node->childNodes as $key => $child) {
137 /* Remove empty text nodes at the start or at the end of the children list */
138 if ($key > 0 && $key < $node->childNodes->length - 1 || $child->nodeName != '#text' || trim($child->nodeValue)) {
139 $newNode = $child->cloneNode(true);
140 $node->parentNode->insertBefore($newNode, $node);
145 $node->parentNode->insertBefore($EndCode, $node);
146 $node->parentNode->removeChild($node);
154 * Converter for HTML to BBCode
156 * Made by: ike@piratenpartei.de
157 * Originally made for the syncom project: http://wiki.piratenpartei.de/Syncom
158 * https://github.com/annando/Syncom
160 * @param string $message
161 * @param string $basepath
163 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
165 public static function toBBCode($message, $basepath = '')
167 $message = str_replace("\r", "", $message);
169 $message = Strings::performWithEscapedBlocks($message, '#<pre><code.*</code></pre>#iUs', function ($message) {
170 $message = str_replace(
183 $message = preg_replace('=<(\w+):(.+?)>=', '<removeme>', $message);
184 $message = preg_replace('=</(\w+):(.+?)>=', '</removeme>', $message);
186 $doc = new DOMDocument();
187 $doc->preserveWhiteSpace = false;
189 $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8");
191 @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
193 XML::deleteNode($doc, 'style');
194 XML::deleteNode($doc, 'head');
195 XML::deleteNode($doc, 'title');
196 XML::deleteNode($doc, 'meta');
197 XML::deleteNode($doc, 'xml');
198 XML::deleteNode($doc, 'removeme');
200 $xpath = new DomXPath($doc);
201 $list = $xpath->query("//pre");
202 foreach ($list as $node) {
203 // Ensure to escape unescaped & - they will otherwise raise a warning
204 $safe_value = preg_replace('/&(?!\w+;)/', '&', $node->nodeValue);
205 $node->nodeValue = str_replace("\n", "\r", $safe_value);
208 $message = $doc->saveHTML();
209 $message = str_replace(["\n<", ">\n", "\r", "\n", "\xC3\x82\xC2\xA0"], ["<", ">", "<br />", " ", ""], $message);
210 $message = preg_replace('= [\s]*=i', " ", $message);
212 @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
214 self::tagToBBCode($doc, 'html', [], "", "");
215 self::tagToBBCode($doc, 'body', [], "", "");
217 // Outlook-Quote - Variant 1
218 self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal', 'style' => 'margin-left:35.4pt'], '[quote]', '[/quote]');
220 // Outlook-Quote - Variant 2
224 ['style' => 'border:none;border-left:solid blue 1.5pt;padding:0cm 0cm 0cm 4.0pt'],
230 self::tagToBBCode($doc, 'span', ['style' => 'text-decoration: underline;'], '[u]', '[/u]');
231 self::tagToBBCode($doc, 'span', ['style' => 'font-style: italic;'], '[i]', '[/i]');
232 self::tagToBBCode($doc, 'span', ['style' => 'font-weight: bold;'], '[b]', '[/b]');
234 /* self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[font=$1][size=$2][color=$3]', '[/color][/size][/font]');
235 self::node2BBCode($doc, 'font', array('size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[size=$1][color=$2]', '[/color][/size]');
236 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(.+)/'), '[font=$1][size=$2]', '[/size][/font]');
237 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'color'=>'/(.+)/'), '[font=$1][color=$3]', '[/color][/font]');
238 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/'), '[font=$1]', '[/font]');
239 self::node2BBCode($doc, 'font', array('size'=>'/(\d+)/'), '[size=$1]', '[/size]');
240 self::node2BBCode($doc, 'font', array('color'=>'/(.+)/'), '[color=$1]', '[/color]');
243 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*font-family:\s*(.+?)[,;].*color:\s*(.+?)[,;].*/'), '[size=$1][font=$2][color=$3]', '[/color][/font][/size]');
244 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(\d+)[,;].*/'), '[size=$1]', '[/size]');
245 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*/'), '[size=$1]', '[/size]');
247 self::tagToBBCode($doc, 'span', ['style' => '/.*color:\s*(.+?)[,;].*/'], '[color="$1"]', '[/color]');
249 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
250 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)pt.*/'), '[font=$1][size=$2]', '[/size][/font]');
251 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)px.*/'), '[font=$1][size=$2]', '[/size][/font]');
252 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
253 // Importing the classes - interesting for importing of posts from third party networks that were exported from friendica
255 //self::node2BBCode($doc, 'span', array('class'=>'/([\w ]+)/'), '[class=$1]', '[/class]');
256 self::tagToBBCode($doc, 'span', ['class' => 'type-link'], '[class=type-link]', '[/class]');
257 self::tagToBBCode($doc, 'span', ['class' => 'type-video'], '[class=type-video]', '[/class]');
259 self::tagToBBCode($doc, 'strong', [], '[b]', '[/b]');
260 self::tagToBBCode($doc, 'em', [], '[i]', '[/i]');
261 self::tagToBBCode($doc, 'b', [], '[b]', '[/b]');
262 self::tagToBBCode($doc, 'i', [], '[i]', '[/i]');
263 self::tagToBBCode($doc, 'u', [], '[u]', '[/u]');
264 self::tagToBBCode($doc, 's', [], '[s]', '[/s]');
265 self::tagToBBCode($doc, 'del', [], '[s]', '[/s]');
266 self::tagToBBCode($doc, 'strike', [], '[s]', '[/s]');
268 self::tagToBBCode($doc, 'big', [], "[size=large]", "[/size]");
269 self::tagToBBCode($doc, 'small', [], "[size=small]", "[/size]");
271 self::tagToBBCode($doc, 'blockquote', [], '[quote]', '[/quote]');
273 self::tagToBBCode($doc, 'br', [], "\n", '');
275 self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal'], "\n", "");
276 self::tagToBBCode($doc, 'div', ['class' => 'MsoNormal'], "\r", "");
278 self::tagToBBCode($doc, 'span', [], "", "");
280 self::tagToBBCode($doc, 'span', [], "", "");
281 self::tagToBBCode($doc, 'pre', [], "", "");
283 self::tagToBBCode($doc, 'div', [], "\r", "\r");
284 self::tagToBBCode($doc, 'p', [], "\n", "\n");
286 self::tagToBBCode($doc, 'ul', [], "[list]", "[/list]");
287 self::tagToBBCode($doc, 'ol', [], "[list=1]", "[/list]");
288 self::tagToBBCode($doc, 'li', [], "[*]", "");
290 self::tagToBBCode($doc, 'hr', [], "[hr]", "");
292 self::tagToBBCode($doc, 'table', [], "[table]", "[/table]");
293 self::tagToBBCode($doc, 'th', [], "[th]", "[/th]");
294 self::tagToBBCode($doc, 'tr', [], "[tr]", "[/tr]");
295 self::tagToBBCode($doc, 'td', [], "[td]", "[/td]");
297 self::tagToBBCode($doc, 'h1', [], "[h1]", "[/h1]");
298 self::tagToBBCode($doc, 'h2', [], "[h2]", "[/h2]");
299 self::tagToBBCode($doc, 'h3', [], "[h3]", "[/h3]");
300 self::tagToBBCode($doc, 'h4', [], "[h4]", "[/h4]");
301 self::tagToBBCode($doc, 'h5', [], "[h5]", "[/h5]");
302 self::tagToBBCode($doc, 'h6', [], "[h6]", "[/h6]");
304 self::tagToBBCode($doc, 'a', ['href' => '/mailto:(.+)/'], '[mail=$1]', '[/mail]');
305 self::tagToBBCode($doc, 'a', ['href' => '/(.+)/'], '[url=$1]', '[/url]');
307 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/', 'alt' => '/(.+)/'], '[img=$1]$2', '[/img]', true);
308 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/', 'width' => '/(\d+)/', 'height' => '/(\d+)/'], '[img=$2x$3]$1', '[/img]', true);
309 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], '[img]$1', '[/img]', true);
312 self::tagToBBCode($doc, 'video', ['src' => '/(.+)/'], '[video]$1', '[/video]', true);
313 self::tagToBBCode($doc, 'audio', ['src' => '/(.+)/'], '[audio]$1', '[/audio]', true);
314 self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], '[iframe]$1', '[/iframe]', true);
316 self::tagToBBCode($doc, 'key', [], '[code]', '[/code]');
317 self::tagToBBCode($doc, 'code', [], '[code]', '[/code]');
319 $message = $doc->saveHTML();
321 // I'm removing something really disturbing
322 // Don't know exactly what it is
323 $message = str_replace(chr(194) . chr(160), ' ', $message);
325 $message = str_replace(" ", " ", $message);
327 // removing multiple DIVs
328 $message = preg_replace('=\r *\r=i', "\n", $message);
329 $message = str_replace("\r", "\n", $message);
331 Hook::callAll('html2bbcode', $message);
333 $message = strip_tags($message);
335 $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
337 // remove quotes if they don't make sense
338 $message = preg_replace('=\[/quote\][\s]*\[quote\]=i', "\n", $message);
340 $message = preg_replace('=\[quote\]\s*=i', "[quote]", $message);
341 $message = preg_replace('=\s*\[/quote\]=i', "[/quote]", $message);
344 $oldmessage = $message;
345 $message = str_replace("\n \n", "\n\n", $message);
346 } while ($oldmessage != $message);
349 $oldmessage = $message;
350 $message = str_replace("\n\n\n", "\n\n", $message);
351 } while ($oldmessage != $message);
354 $oldmessage = $message;
355 $message = str_replace(
378 } while ($message != $oldmessage);
380 $message = str_replace(
381 ['[b][b]', '[/b][/b]', '[i][i]', '[/i][/i]'],
382 ['[b]', '[/b]', '[i]', '[/i]'],
386 // Handling Yahoo style of mails
387 $message = str_replace('[hr][b]From:[/b]', '[quote][b]From:[/b]', $message);
392 $message = preg_replace_callback(
393 '#<pre><code(?: class="language-([^"]*)")?>(.*)</code></pre>#iUs',
394 function ($matches) {
396 if ($matches[1] != '') {
397 $prefix = '[code=' . $matches[1] . ']';
400 return $prefix . PHP_EOL . trim($matches[2]) . PHP_EOL . '[/code]';
405 $message = trim($message);
407 if ($basepath != '') {
408 $message = self::qualifyURLs($message, $basepath);
415 * Sub function to complete incomplete URL
417 * @param array $matches Result of preg_replace_callback
418 * @param string $basepath Basepath that is used to complete the URL
420 * @return string The expanded URL
422 private static function qualifyURLsSub($matches, $basepath)
424 $base = parse_url($basepath);
425 unset($base['query']);
426 unset($base['fragment']);
431 if (empty($url) || empty(parse_url($url))) {
435 $parts = array_merge($base, parse_url($url));
436 $url2 = Network::unparseURL($parts);
438 return str_replace($url, $url2, $link);
442 * Complete incomplete URLs in BBCode
444 * @param string $body Body with URLs
445 * @param string $basepath Base path that is used to complete the URL
447 * @return string Body with expanded URLs
449 private static function qualifyURLs($body, $basepath)
451 $URLSearchString = "^\[\]";
453 $matches = ["/\[url\=([$URLSearchString]*)\].*?\[\/url\]/ism",
454 "/\[url\]([$URLSearchString]*)\[\/url\]/ism",
455 "/\[img\=[0-9]*x[0-9]*\](.*?)\[\/img\]/ism",
456 "/\[img\](.*?)\[\/img\]/ism",
457 "/\[zmg\=[0-9]*x[0-9]*\](.*?)\[\/img\]/ism",
458 "/\[zmg\](.*?)\[\/zmg\]/ism",
459 "/\[video\](.*?)\[\/video\]/ism",
460 "/\[audio\](.*?)\[\/audio\]/ism",
463 foreach ($matches as $match) {
464 $body = preg_replace_callback(
466 function ($match) use ($basepath) {
467 return self::qualifyURLsSub($match, $basepath);
475 private static function breakLines($line, $level, $wraplength = 75)
477 if ($wraplength == 0) {
478 $wraplength = 2000000;
481 $wraplen = $wraplength - $level;
488 $subline = substr($line, 0, $wraplen);
490 $pos = strrpos($subline, ' ');
493 $pos = strpos($line, ' ');
496 if (($pos > 0) && strlen($line) > $wraplen) {
497 $newline = trim(substr($line, 0, $pos));
499 $newline = str_repeat(">", $level) . ' ' . $newline;
502 $newlines[] = $newline . " ";
503 $line = substr($line, $pos + 1);
505 } while ((strlen($line) > $wraplen) && !($oldline == $line));
508 $line = str_repeat(">", $level) . ' ' . $line;
513 return implode("\n", $newlines);
516 private static function quoteLevel($message, $wraplength = 75)
518 $lines = explode("\n", $message);
522 foreach ($lines as $line) {
525 while (strpos("*" . $line, '[quote]') > 0) {
527 $pos = strpos($line, '[quote]');
528 $line = substr($line, 0, $pos) . substr($line, $pos + 7);
534 while (strpos("*" . $line, '[/quote]') > 0) {
540 $pos = strpos($line, '[/quote]');
541 $line = substr($line, 0, $pos) . substr($line, $pos + 8);
544 if (!$startquote || ($line != '')) {
545 $newlines[] = self::breakLines($line, $currlevel, $wraplength);
549 return implode("\n", $newlines);
552 private static function collectURLs($message)
554 $pattern = '/<a.*?href="(.*?)".*?>(.*?)<\/a>/is';
555 preg_match_all($pattern, $message, $result, PREG_SET_ORDER);
558 foreach ($result as $treffer) {
561 // A list of some links that should be ignored
562 $list = ["/user/", "/tag/", "/group/", "/profile/", "/search?search=", "/search?tag=", "mailto:", "/u/", "/node/",
563 "//plus.google.com/", "//twitter.com/"];
564 foreach ($list as $listitem) {
565 if (strpos($treffer[1], $listitem) !== false) {
570 if ((strpos($treffer[1], "//twitter.com/") !== false) && (strpos($treffer[1], "/status/") !== false)) {
574 if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/posts") !== false)) {
578 if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/photos") !== false)) {
582 $ignore = $ignore || strpos($treffer[1], '#') === 0;
585 $urls[$treffer[1]] = $treffer[1];
593 * @param string $html
594 * @param int $wraplength Ensures individual lines aren't longer than this many characters. Doesn't break words.
595 * @param bool $compact True: Completely strips image tags; False: Keeps image URLs
598 public static function toPlaintext(string $html, $wraplength = 75, $compact = false)
600 $message = str_replace("\r", "", $html);
602 $doc = new DOMDocument();
603 $doc->preserveWhiteSpace = false;
605 $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8");
607 @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
609 $message = $doc->saveHTML();
610 // Remove eventual UTF-8 BOM
611 $message = str_replace("\xC3\x82\xC2\xA0", "", $message);
613 // Collecting all links
614 $urls = self::collectURLs($message);
616 @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
618 self::tagToBBCode($doc, 'html', [], '', '');
619 self::tagToBBCode($doc, 'body', [], '', '');
622 self::tagToBBCode($doc, 'blockquote', [], "»", "«");
624 self::tagToBBCode($doc, 'blockquote', [], '[quote]', "[/quote]\n");
627 self::tagToBBCode($doc, 'br', [], "\n", '');
629 self::tagToBBCode($doc, 'span', [], "", "");
630 self::tagToBBCode($doc, 'pre', [], "", "");
631 self::tagToBBCode($doc, 'div', [], "\r", "\r");
632 self::tagToBBCode($doc, 'p', [], "\n", "\n");
634 self::tagToBBCode($doc, 'li', [], "\n* ", "\n");
636 self::tagToBBCode($doc, 'hr', [], "\n" . str_repeat("-", 70) . "\n", "");
638 self::tagToBBCode($doc, 'tr', [], "\n", "");
639 self::tagToBBCode($doc, 'td', [], "\t", "");
641 self::tagToBBCode($doc, 'h1', [], "\n\n*", "*\n");
642 self::tagToBBCode($doc, 'h2', [], "\n\n*", "*\n");
643 self::tagToBBCode($doc, 'h3', [], "\n\n*", "*\n");
644 self::tagToBBCode($doc, 'h4', [], "\n\n*", "*\n");
645 self::tagToBBCode($doc, 'h5', [], "\n\n*", "*\n");
646 self::tagToBBCode($doc, 'h6', [], "\n\n*", "*\n");
649 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], ' [img]$1', '[/img] ');
651 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], ' ', ' ');
654 self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], ' $1 ', '');
656 $message = $doc->saveHTML();
659 $message = str_replace("[img]", "", $message);
660 $message = str_replace("[/img]", "", $message);
663 // was ersetze ich da?
664 // Irgendein stoerrisches UTF-Zeug
665 $message = str_replace(chr(194) . chr(160), ' ', $message);
667 $message = str_replace(" ", " ", $message);
669 // Aufeinanderfolgende DIVs
670 $message = preg_replace('=\r *\r=i', "\n", $message);
671 $message = str_replace("\r", "\n", $message);
673 $message = strip_tags($message);
675 $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
677 if (!$compact && ($message != '')) {
678 foreach ($urls as $id => $url) {
679 if ($url != '' && strpos($message, $url) === false) {
680 $message .= "\n" . $url . ' ';
685 $message = str_replace("\n«", "«\n", $message);
686 $message = str_replace("»\n", "\n»", $message);
689 $oldmessage = $message;
690 $message = str_replace("\n\n\n", "\n\n", $message);
691 } while ($oldmessage != $message);
693 $message = self::quoteLevel(trim($message), $wraplength);
695 return trim($message);
699 * Converts provided HTML code to Markdown. The hardwrap parameter maximizes
700 * compatibility with Diaspora in spite of the Markdown standards.
702 * @param string $html
705 public static function toMarkdown($html)
707 $converter = new HtmlConverter(['hard_break' => true]);
708 $markdown = $converter->convert($html);
714 * Convert video HTML to BBCode tags
719 public static function toBBCodeVideo($s)
722 '#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
723 '[youtube]$2[/youtube]',
728 '#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
729 '[youtube]$2[/youtube]',
734 '#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
743 * transform link href and img src from relative to absolute
745 * @param string $text
746 * @param string $base base url
749 public static function relToAbs($text, $base)
755 $base = rtrim($base, '/');
757 $base2 = $base . "/";
760 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
761 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
762 $text = preg_replace($pattern, $replace, $text);
764 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
765 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
766 $text = preg_replace($pattern, $replace, $text);
769 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
770 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
771 $text = preg_replace($pattern, $replace, $text);
773 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
774 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
775 $text = preg_replace($pattern, $replace, $text);
783 * return div element with class 'clear'
787 public static function clearDiv()
789 return '<div class="clear"></div>';
793 * Loader for infinite scrolling
795 * @return string html for loader
796 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
798 public static function scrollLoader()
800 $tpl = Renderer::getMarkupTemplate("scroll_loader.tpl");
801 return Renderer::replaceMacros($tpl, [
802 'wait' => DI::l10n()->t('Loading more entries...'),
803 'end' => DI::l10n()->t('The end')
808 * Get html for contact block.
810 * @deprecated since version 2019.03
811 * @see ContactBlock::getHTML()
813 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
814 * @throws \ImagickException
816 public static function contactBlock()
820 return ContactBlock::getHTML($a->profile);
824 * Format contacts as picture links or as text links
826 * @param array $contact Array with contacts which contains an array with
827 * int 'id' => The ID of the contact
828 * int 'uid' => The user ID of the user who owns this data
829 * string 'name' => The name of the contact
830 * string 'url' => The url to the profile page of the contact
831 * string 'addr' => The webbie of the contact (e.g.) username@friendica.com
832 * string 'network' => The network to which the contact belongs to
833 * string 'thumb' => The contact picture
834 * string 'click' => js code which is performed when clicking on the contact
835 * @param boolean $redirect If true try to use the redir url if it's possible
836 * @param string $class CSS class for the
837 * @param boolean $textmode If true display the contacts as text links
838 * if false display the contacts as picture links
839 * @return string Formatted html
840 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
841 * @throws \ImagickException
843 public static function micropro($contact, $redirect = false, $class = '', $textmode = false)
845 // Use the contact URL if no address is available
846 if (empty($contact['addr'])) {
847 $contact["addr"] = $contact["url"];
850 $url = $contact['url'];
855 $url = Contact::magicLink($contact['url']);
856 if (strpos($url, 'redir/') === 0) {
857 $sparkle = ' sparkle';
861 // If there is some js available we don't need the url
862 if (!empty($contact['click'])) {
866 return Renderer::replaceMacros(Renderer::getMarkupTemplate($textmode ? 'micropro_txt.tpl' : 'micropro_img.tpl'), [
867 '$click' => $contact['click'] ?? '',
870 '$photo' => Contact::getThumb($contact),
871 '$name' => $contact['name'],
872 'title' => $contact['name'] . ' [' . $contact['addr'] . ']',
873 '$parkle' => $sparkle,
881 * @param string $s Search query.
882 * @param string $id HTML id
883 * @param string $url Search url.
884 * @param bool $aside Display the search widgit aside.
886 * @return string Formatted HTML.
889 public static function search($s, $id = 'search-box', $aside = true)
893 if (strpos($s, '#') === 0) {
896 $save_label = $mode === 'text' ? DI::l10n()->t('Save') : DI::l10n()->t('Follow');
900 '$q' => urlencode($s),
902 '$search_label' => DI::l10n()->t('Search'),
903 '$save_label' => $save_label,
904 '$search_hint' => DI::l10n()->t('@name, !forum, #tags, content'),
906 '$return_url' => urlencode(Search::getSearchPath($s)),
910 $values['$search_options'] = [
911 'fulltext' => DI::l10n()->t('Full Text'),
912 'tags' => DI::l10n()->t('Tags'),
913 'contacts' => DI::l10n()->t('Contacts')
916 if (DI::config()->get('system', 'poco_local_search')) {
917 $values['$searchoption']['forums'] = DI::l10n()->t('Forums');
921 return Renderer::replaceMacros(Renderer::getMarkupTemplate('searchbox.tpl'), $values);
925 * Replace naked text hyperlink with HTML formatted hyperlink
930 public static function toLink($s)
932 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank" rel="noopener noreferrer">$1</a>', $s);
933 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism", '<$1$2=$3&$4>', $s);
938 * Given a HTML text and a set of filtering reasons, adds a content hiding header with the provided reasons
940 * Reasons are expected to have been translated already.
942 * @param string $html
943 * @param array $reasons
945 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
947 public static function applyContentFilter($html, array $reasons)
949 if (count($reasons)) {
950 $tpl = Renderer::getMarkupTemplate('wall/content_filter.tpl');
951 $html = Renderer::replaceMacros($tpl, [
952 '$reasons' => $reasons,
953 '$rnd' => Strings::getRandomHex(8),
954 '$openclose' => DI::l10n()->t('Click to open/close'),
963 * replace html amp entity with amp char
967 public static function unamp($s)
969 return str_replace('&', '&', $s);