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;
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 @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
172 XML::deleteNode($doc, 'style');
173 XML::deleteNode($doc, 'head');
174 XML::deleteNode($doc, 'title');
175 XML::deleteNode($doc, 'meta');
176 XML::deleteNode($doc, 'xml');
177 XML::deleteNode($doc, 'removeme');
179 $xpath = new DomXPath($doc);
180 $list = $xpath->query("//pre");
181 foreach ($list as $node) {
182 // Ensure to escape unescaped & - they will otherwise raise a warning
183 $safe_value = preg_replace('/&(?!\w+;)/', '&', $node->nodeValue);
184 $node->nodeValue = str_replace("\n", "\r", $safe_value);
187 $message = $doc->saveHTML();
188 $message = str_replace(["\n<", ">\n", "\r", "\n", "\xC3\x82\xC2\xA0"], ["<", ">", "<br />", " ", ""], $message);
189 $message = preg_replace('= [\s]*=i', " ", $message);
191 if (empty($message)) {
195 @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
197 self::tagToBBCode($doc, 'html', [], "", "");
198 self::tagToBBCode($doc, 'body', [], "", "");
200 // Outlook-Quote - Variant 1
201 self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal', 'style' => 'margin-left:35.4pt'], '[quote]', '[/quote]');
203 // Outlook-Quote - Variant 2
207 ['style' => 'border:none;border-left:solid blue 1.5pt;padding:0cm 0cm 0cm 4.0pt'],
213 self::tagToBBCode($doc, 'span', ['style' => 'text-decoration: underline;'], '[u]', '[/u]');
214 self::tagToBBCode($doc, 'span', ['style' => 'font-style: italic;'], '[i]', '[/i]');
215 self::tagToBBCode($doc, 'span', ['style' => 'font-weight: bold;'], '[b]', '[/b]');
217 /* self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[font=$1][size=$2][color=$3]', '[/color][/size][/font]');
218 self::node2BBCode($doc, 'font', array('size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[size=$1][color=$2]', '[/color][/size]');
219 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(.+)/'), '[font=$1][size=$2]', '[/size][/font]');
220 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'color'=>'/(.+)/'), '[font=$1][color=$3]', '[/color][/font]');
221 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/'), '[font=$1]', '[/font]');
222 self::node2BBCode($doc, 'font', array('size'=>'/(\d+)/'), '[size=$1]', '[/size]');
223 self::node2BBCode($doc, 'font', array('color'=>'/(.+)/'), '[color=$1]', '[/color]');
226 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*font-family:\s*(.+?)[,;].*color:\s*(.+?)[,;].*/'), '[size=$1][font=$2][color=$3]', '[/color][/font][/size]');
227 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(\d+)[,;].*/'), '[size=$1]', '[/size]');
228 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*/'), '[size=$1]', '[/size]');
230 self::tagToBBCode($doc, 'span', ['style' => '/.*color:\s*(.+?)[,;].*/'], '[color="$1"]', '[/color]');
232 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
233 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)pt.*/'), '[font=$1][size=$2]', '[/size][/font]');
234 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)px.*/'), '[font=$1][size=$2]', '[/size][/font]');
235 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
236 // Importing the classes - interesting for importing of posts from third party networks that were exported from friendica
238 //self::node2BBCode($doc, 'span', array('class'=>'/([\w ]+)/'), '[class=$1]', '[/class]');
239 self::tagToBBCode($doc, 'span', ['class' => 'type-link'], '[class=type-link]', '[/class]');
240 self::tagToBBCode($doc, 'span', ['class' => 'type-video'], '[class=type-video]', '[/class]');
242 self::tagToBBCode($doc, 'strong', [], '[b]', '[/b]');
243 self::tagToBBCode($doc, 'em', [], '[i]', '[/i]');
244 self::tagToBBCode($doc, 'b', [], '[b]', '[/b]');
245 self::tagToBBCode($doc, 'i', [], '[i]', '[/i]');
246 self::tagToBBCode($doc, 'u', [], '[u]', '[/u]');
247 self::tagToBBCode($doc, 's', [], '[s]', '[/s]');
248 self::tagToBBCode($doc, 'del', [], '[s]', '[/s]');
249 self::tagToBBCode($doc, 'strike', [], '[s]', '[/s]');
251 self::tagToBBCode($doc, 'big', [], "[size=large]", "[/size]");
252 self::tagToBBCode($doc, 'small', [], "[size=small]", "[/size]");
254 self::tagToBBCode($doc, 'blockquote', [], '[quote]', '[/quote]');
256 self::tagToBBCode($doc, 'br', [], "\n", '');
258 self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal'], "\n", "");
259 self::tagToBBCode($doc, 'div', ['class' => 'MsoNormal'], "\r", "");
261 self::tagToBBCode($doc, 'span', [], "", "");
263 self::tagToBBCode($doc, 'span', [], "", "");
264 self::tagToBBCode($doc, 'pre', [], "", "");
266 self::tagToBBCode($doc, 'div', [], "\r", "\r");
267 self::tagToBBCode($doc, 'p', [], "\n", "\n");
269 self::tagToBBCode($doc, 'ul', [], "[list]", "[/list]");
270 self::tagToBBCode($doc, 'ol', [], "[list=1]", "[/list]");
271 self::tagToBBCode($doc, 'li', [], "[*]", "");
273 self::tagToBBCode($doc, 'hr', [], "[hr]", "");
275 self::tagToBBCode($doc, 'table', [], "[table]", "[/table]");
276 self::tagToBBCode($doc, 'th', [], "[th]", "[/th]");
277 self::tagToBBCode($doc, 'tr', [], "[tr]", "[/tr]");
278 self::tagToBBCode($doc, 'td', [], "[td]", "[/td]");
280 self::tagToBBCode($doc, 'h1', [], "[h1]", "[/h1]");
281 self::tagToBBCode($doc, 'h2', [], "[h2]", "[/h2]");
282 self::tagToBBCode($doc, 'h3', [], "[h3]", "[/h3]");
283 self::tagToBBCode($doc, 'h4', [], "[h4]", "[/h4]");
284 self::tagToBBCode($doc, 'h5', [], "[h5]", "[/h5]");
285 self::tagToBBCode($doc, 'h6', [], "[h6]", "[/h6]");
287 self::tagToBBCode($doc, 'a', ['href' => '/mailto:(.+)/'], '[mail=$1]', '[/mail]');
288 self::tagToBBCode($doc, 'a', ['href' => '/(.+)/'], '[url=$1]', '[/url]');
290 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/', 'alt' => '/(.+)/'], '[img=$1]$2', '[/img]', true);
291 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/', 'width' => '/(\d+)/', 'height' => '/(\d+)/'], '[img=$2x$3]$1', '[/img]', true);
292 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], '[img]$1', '[/img]', true);
295 self::tagToBBCode($doc, 'video', ['src' => '/(.+)/'], '[video]$1', '[/video]', true);
296 self::tagToBBCode($doc, 'audio', ['src' => '/(.+)/'], '[audio]$1', '[/audio]', true);
297 // Backward compatibility, [iframe] support has been removed in version 2020.12
298 self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], '[url]$1', '[/url]', true);
300 self::tagToBBCode($doc, 'key', [], '[code]', '[/code]');
301 self::tagToBBCode($doc, 'code', [], '[code]', '[/code]');
303 $message = $doc->saveHTML();
305 // I'm removing something really disturbing
306 // Don't know exactly what it is
307 $message = str_replace(chr(194) . chr(160), ' ', $message);
309 $message = str_replace(" ", " ", $message);
311 // removing multiple DIVs
312 $message = preg_replace('=\r *\r=i', "\n", $message);
313 $message = str_replace("\r", "\n", $message);
315 Hook::callAll('html2bbcode', $message);
317 $message = strip_tags($message);
319 $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
321 // remove quotes if they don't make sense
322 $message = preg_replace('=\[/quote\][\s]*\[quote\]=i', "\n", $message);
324 $message = preg_replace('=\[quote\]\s*=i', "[quote]", $message);
325 $message = preg_replace('=\s*\[/quote\]=i', "[/quote]", $message);
328 $oldmessage = $message;
329 $message = str_replace("\n \n", "\n\n", $message);
330 } while ($oldmessage != $message);
333 $oldmessage = $message;
334 $message = str_replace("\n\n\n", "\n\n", $message);
335 } while ($oldmessage != $message);
338 $oldmessage = $message;
339 $message = str_replace(
362 } while ($message != $oldmessage);
364 $message = str_replace(
365 ['[b][b]', '[/b][/b]', '[i][i]', '[/i][/i]'],
366 ['[b]', '[/b]', '[i]', '[/i]'],
370 // Handling Yahoo style of mails
371 $message = str_replace('[hr][b]From:[/b]', '[quote][b]From:[/b]', $message);
376 $message = preg_replace_callback(
377 '#<pre><code(?: class="language-([^"]*)")?>(.*)</code></pre>#iUs',
378 function ($matches) {
380 if ($matches[1] != '') {
381 $prefix = '[code=' . $matches[1] . ']';
384 return $prefix . PHP_EOL . trim($matches[2]) . PHP_EOL . '[/code]';
389 $message = trim($message);
391 if ($basepath != '') {
392 $message = self::qualifyURLs($message, $basepath);
399 * Sub function to complete incomplete URL
401 * @param array $matches Result of preg_replace_callback
402 * @param string $basepath Basepath that is used to complete the URL
404 * @return string The expanded URL
406 private static function qualifyURLsSub($matches, $basepath)
408 $base = parse_url($basepath);
409 unset($base['query']);
410 unset($base['fragment']);
415 if (empty($url) || empty(parse_url($url))) {
419 $parts = array_merge($base, parse_url($url));
420 $url2 = Network::unparseURL($parts);
422 return str_replace($url, $url2, $link);
426 * Complete incomplete URLs in BBCode
428 * @param string $body Body with URLs
429 * @param string $basepath Base path that is used to complete the URL
431 * @return string Body with expanded URLs
433 private static function qualifyURLs($body, $basepath)
435 $URLSearchString = "^\[\]";
437 $matches = ["/\[url\=([$URLSearchString]*)\].*?\[\/url\]/ism",
438 "/\[url\]([$URLSearchString]*)\[\/url\]/ism",
439 "/\[img\=[0-9]*x[0-9]*\](.*?)\[\/img\]/ism",
440 "/\[img\](.*?)\[\/img\]/ism",
441 "/\[zmg\=[0-9]*x[0-9]*\](.*?)\[\/img\]/ism",
442 "/\[zmg\](.*?)\[\/zmg\]/ism",
443 "/\[video\](.*?)\[\/video\]/ism",
444 "/\[audio\](.*?)\[\/audio\]/ism",
447 foreach ($matches as $match) {
448 $body = preg_replace_callback(
450 function ($match) use ($basepath) {
451 return self::qualifyURLsSub($match, $basepath);
459 private static function breakLines($line, $level, $wraplength = 75)
461 if ($wraplength == 0) {
462 $wraplength = 2000000;
465 $wraplen = $wraplength - $level;
472 $subline = substr($line, 0, $wraplen);
474 $pos = strrpos($subline, ' ');
477 $pos = strpos($line, ' ');
480 if (($pos > 0) && strlen($line) > $wraplen) {
481 $newline = trim(substr($line, 0, $pos));
483 $newline = str_repeat(">", $level) . ' ' . $newline;
486 $newlines[] = $newline . " ";
487 $line = substr($line, $pos + 1);
489 } while ((strlen($line) > $wraplen) && !($oldline == $line));
492 $line = str_repeat(">", $level) . ' ' . $line;
497 return implode("\n", $newlines);
500 private static function quoteLevel($message, $wraplength = 75)
502 $lines = explode("\n", $message);
506 foreach ($lines as $line) {
509 while (strpos("*" . $line, '[quote]') > 0) {
511 $pos = strpos($line, '[quote]');
512 $line = substr($line, 0, $pos) . substr($line, $pos + 7);
518 while (strpos("*" . $line, '[/quote]') > 0) {
524 $pos = strpos($line, '[/quote]');
525 $line = substr($line, 0, $pos) . substr($line, $pos + 8);
528 if (!$startquote || ($line != '')) {
529 $newlines[] = self::breakLines($line, $currlevel, $wraplength);
533 return implode("\n", $newlines);
536 private static function collectURLs($message)
538 $pattern = '/<a.*?href="(.*?)".*?>(.*?)<\/a>/is';
539 preg_match_all($pattern, $message, $result, PREG_SET_ORDER);
542 foreach ($result as $treffer) {
545 // A list of some links that should be ignored
546 $list = ["/user/", "/tag/", "/group/", "/profile/", "/search?search=", "/search?tag=", "mailto:", "/u/", "/node/",
547 "//plus.google.com/", "//twitter.com/"];
548 foreach ($list as $listitem) {
549 if (strpos($treffer[1], $listitem) !== false) {
554 if ((strpos($treffer[1], "//twitter.com/") !== false) && (strpos($treffer[1], "/status/") !== false)) {
558 if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/posts") !== false)) {
562 if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/photos") !== false)) {
566 $ignore = $ignore || strpos($treffer[1], '#') === 0;
569 $urls[$treffer[1]] = $treffer[1];
577 * @param string $html
578 * @param int $wraplength Ensures individual lines aren't longer than this many characters. Doesn't break words.
579 * @param bool $compact True: Completely strips image tags; False: Keeps image URLs
582 public static function toPlaintext(string $html, $wraplength = 75, $compact = false)
584 $message = str_replace("\r", "", $html);
586 $doc = new DOMDocument();
587 $doc->preserveWhiteSpace = false;
589 $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8");
591 @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
593 $message = $doc->saveHTML();
594 // Remove eventual UTF-8 BOM
595 $message = str_replace("\xC3\x82\xC2\xA0", "", $message);
597 // Collecting all links
598 $urls = self::collectURLs($message);
600 @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
602 self::tagToBBCode($doc, 'html', [], '', '');
603 self::tagToBBCode($doc, 'body', [], '', '');
606 self::tagToBBCode($doc, 'blockquote', [], "»", "«");
608 self::tagToBBCode($doc, 'blockquote', [], '[quote]', "[/quote]\n");
611 self::tagToBBCode($doc, 'br', [], "\n", '');
613 self::tagToBBCode($doc, 'span', [], "", "");
614 self::tagToBBCode($doc, 'pre', [], "", "");
615 self::tagToBBCode($doc, 'div', [], "\r", "\r");
616 self::tagToBBCode($doc, 'p', [], "\n", "\n");
618 self::tagToBBCode($doc, 'li', [], "\n* ", "\n");
620 self::tagToBBCode($doc, 'hr', [], "\n" . str_repeat("-", 70) . "\n", "");
622 self::tagToBBCode($doc, 'tr', [], "\n", "");
623 self::tagToBBCode($doc, 'td', [], "\t", "");
625 self::tagToBBCode($doc, 'h1', [], "\n\n*", "*\n");
626 self::tagToBBCode($doc, 'h2', [], "\n\n*", "*\n");
627 self::tagToBBCode($doc, 'h3', [], "\n\n*", "*\n");
628 self::tagToBBCode($doc, 'h4', [], "\n\n*", "*\n");
629 self::tagToBBCode($doc, 'h5', [], "\n\n*", "*\n");
630 self::tagToBBCode($doc, 'h6', [], "\n\n*", "*\n");
633 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], ' [img]$1', '[/img] ');
635 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], ' ', ' ');
638 // Backward compatibility, [iframe] support has been removed in version 2020.12
639 self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], ' $1 ', '');
641 $message = $doc->saveHTML();
644 $message = str_replace("[img]", "", $message);
645 $message = str_replace("[/img]", "", $message);
648 // was ersetze ich da?
649 // Irgendein stoerrisches UTF-Zeug
650 $message = str_replace(chr(194) . chr(160), ' ', $message);
652 $message = str_replace(" ", " ", $message);
654 // Aufeinanderfolgende DIVs
655 $message = preg_replace('=\r *\r=i', "\n", $message);
656 $message = str_replace("\r", "\n", $message);
658 $message = strip_tags($message);
660 $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
662 if (!$compact && ($message != '')) {
663 foreach ($urls as $id => $url) {
664 if ($url != '' && strpos($message, $url) === false) {
665 $message .= "\n" . $url . ' ';
670 $message = str_replace("\n«", "«\n", $message);
671 $message = str_replace("»\n", "\n»", $message);
674 $oldmessage = $message;
675 $message = str_replace("\n\n\n", "\n\n", $message);
676 } while ($oldmessage != $message);
678 $message = self::quoteLevel(trim($message), $wraplength);
680 return trim($message);
684 * Converts provided HTML code to Markdown. The hardwrap parameter maximizes
685 * compatibility with Diaspora in spite of the Markdown standards.
687 * @param string $html
690 public static function toMarkdown($html)
692 $converter = new HtmlConverter(['hard_break' => true]);
693 $markdown = $converter->convert($html);
699 * Convert video HTML to BBCode tags
704 public static function toBBCodeVideo($s)
707 '#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
708 '[youtube]$2[/youtube]',
713 '#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
714 '[youtube]$2[/youtube]',
719 '#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
728 * transform link href and img src from relative to absolute
730 * @param string $text
731 * @param string $base base url
734 public static function relToAbs($text, $base)
740 $base = rtrim($base, '/');
742 $base2 = $base . "/";
745 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
746 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
747 $text = preg_replace($pattern, $replace, $text);
749 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
750 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
751 $text = preg_replace($pattern, $replace, $text);
754 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
755 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
756 $text = preg_replace($pattern, $replace, $text);
758 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
759 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
760 $text = preg_replace($pattern, $replace, $text);
768 * return div element with class 'clear'
772 public static function clearDiv()
774 return '<div class="clear"></div>';
778 * Loader for infinite scrolling
780 * @return string html for loader
781 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
783 public static function scrollLoader()
785 $tpl = Renderer::getMarkupTemplate("scroll_loader.tpl");
786 return Renderer::replaceMacros($tpl, [
787 'wait' => DI::l10n()->t('Loading more entries...'),
788 'end' => DI::l10n()->t('The end')
793 * Get html for contact block.
795 * @deprecated since version 2019.03
796 * @see ContactBlock::getHTML()
798 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
799 * @throws \ImagickException
801 public static function contactBlock()
805 return ContactBlock::getHTML($a->profile);
809 * Format contacts as picture links or as text links
811 * @param array $contact Array with contacts which contains an array with
812 * int 'id' => The ID of the contact
813 * int 'uid' => The user ID of the user who owns this data
814 * string 'name' => The name of the contact
815 * string 'url' => The url to the profile page of the contact
816 * string 'addr' => The webbie of the contact (e.g.) username@friendica.com
817 * string 'network' => The network to which the contact belongs to
818 * string 'thumb' => The contact picture
819 * string 'click' => js code which is performed when clicking on the contact
820 * @param boolean $redirect If true try to use the redir url if it's possible
821 * @param string $class CSS class for the
822 * @param boolean $textmode If true display the contacts as text links
823 * if false display the contacts as picture links
824 * @return string Formatted html
825 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
826 * @throws \ImagickException
828 public static function micropro($contact, $redirect = false, $class = '', $textmode = false)
830 // Use the contact URL if no address is available
831 if (empty($contact['addr'])) {
832 $contact["addr"] = $contact["url"];
835 $url = $contact['url'];
840 $url = Contact::magicLink($contact['url']);
841 if (strpos($url, 'redir/') === 0) {
842 $sparkle = ' sparkle';
846 // If there is some js available we don't need the url
847 if (!empty($contact['click'])) {
851 return Renderer::replaceMacros(Renderer::getMarkupTemplate($textmode ? 'micropro_txt.tpl' : 'micropro_img.tpl'), [
852 '$click' => $contact['click'] ?? '',
855 '$photo' => Contact::getThumb($contact),
856 '$name' => $contact['name'],
857 'title' => $contact['name'] . ' [' . $contact['addr'] . ']',
858 '$parkle' => $sparkle,
866 * @param string $s Search query.
867 * @param string $id HTML id
868 * @param string $url Search url.
869 * @param bool $aside Display the search widgit aside.
871 * @return string Formatted HTML.
874 public static function search($s, $id = 'search-box', $aside = true)
878 if (strpos($s, '#') === 0) {
881 $save_label = $mode === 'text' ? DI::l10n()->t('Save') : DI::l10n()->t('Follow');
885 '$q' => urlencode($s),
887 '$search_label' => DI::l10n()->t('Search'),
888 '$save_label' => $save_label,
889 '$search_hint' => DI::l10n()->t('@name, !forum, #tags, content'),
891 '$return_url' => urlencode(Search::getSearchPath($s)),
895 $values['$search_options'] = [
896 'fulltext' => DI::l10n()->t('Full Text'),
897 'tags' => DI::l10n()->t('Tags'),
898 'contacts' => DI::l10n()->t('Contacts')
901 if (DI::config()->get('system', 'poco_local_search')) {
902 $values['$searchoption']['forums'] = DI::l10n()->t('Forums');
906 return Renderer::replaceMacros(Renderer::getMarkupTemplate('searchbox.tpl'), $values);
910 * Replace naked text hyperlink with HTML formatted hyperlink
915 public static function toLink($s)
917 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank" rel="noopener noreferrer">$1</a>', $s);
918 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism", '<$1$2=$3&$4>', $s);
923 * Given a HTML text and a set of filtering reasons, adds a content hiding header with the provided reasons
925 * Reasons are expected to have been translated already.
927 * @param string $html
928 * @param array $reasons
930 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
932 public static function applyContentFilter($html, array $reasons)
934 if (count($reasons)) {
935 $tpl = Renderer::getMarkupTemplate('wall/content_filter.tpl');
936 $html = Renderer::replaceMacros($tpl, [
937 '$reasons' => $reasons,
938 '$rnd' => Strings::getRandomHex(8),
939 '$openclose' => DI::l10n()->t('Click to open/close'),
948 * replace html amp entity with amp char
952 public static function unamp($s)
954 return str_replace('&', '&', $s);