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 @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
193 self::tagToBBCode($doc, 'html', [], "", "");
194 self::tagToBBCode($doc, 'body', [], "", "");
196 // Outlook-Quote - Variant 1
197 self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal', 'style' => 'margin-left:35.4pt'], '[quote]', '[/quote]');
199 // Outlook-Quote - Variant 2
203 ['style' => 'border:none;border-left:solid blue 1.5pt;padding:0cm 0cm 0cm 4.0pt'],
209 self::tagToBBCode($doc, 'span', ['style' => 'text-decoration: underline;'], '[u]', '[/u]');
210 self::tagToBBCode($doc, 'span', ['style' => 'font-style: italic;'], '[i]', '[/i]');
211 self::tagToBBCode($doc, 'span', ['style' => 'font-weight: bold;'], '[b]', '[/b]');
213 /* self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[font=$1][size=$2][color=$3]', '[/color][/size][/font]');
214 self::node2BBCode($doc, 'font', array('size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[size=$1][color=$2]', '[/color][/size]');
215 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(.+)/'), '[font=$1][size=$2]', '[/size][/font]');
216 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'color'=>'/(.+)/'), '[font=$1][color=$3]', '[/color][/font]');
217 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/'), '[font=$1]', '[/font]');
218 self::node2BBCode($doc, 'font', array('size'=>'/(\d+)/'), '[size=$1]', '[/size]');
219 self::node2BBCode($doc, 'font', array('color'=>'/(.+)/'), '[color=$1]', '[/color]');
222 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*font-family:\s*(.+?)[,;].*color:\s*(.+?)[,;].*/'), '[size=$1][font=$2][color=$3]', '[/color][/font][/size]');
223 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(\d+)[,;].*/'), '[size=$1]', '[/size]');
224 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*/'), '[size=$1]', '[/size]');
226 self::tagToBBCode($doc, 'span', ['style' => '/.*color:\s*(.+?)[,;].*/'], '[color="$1"]', '[/color]');
228 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
229 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)pt.*/'), '[font=$1][size=$2]', '[/size][/font]');
230 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)px.*/'), '[font=$1][size=$2]', '[/size][/font]');
231 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
232 // Importing the classes - interesting for importing of posts from third party networks that were exported from friendica
234 //self::node2BBCode($doc, 'span', array('class'=>'/([\w ]+)/'), '[class=$1]', '[/class]');
235 self::tagToBBCode($doc, 'span', ['class' => 'type-link'], '[class=type-link]', '[/class]');
236 self::tagToBBCode($doc, 'span', ['class' => 'type-video'], '[class=type-video]', '[/class]');
238 self::tagToBBCode($doc, 'strong', [], '[b]', '[/b]');
239 self::tagToBBCode($doc, 'em', [], '[i]', '[/i]');
240 self::tagToBBCode($doc, 'b', [], '[b]', '[/b]');
241 self::tagToBBCode($doc, 'i', [], '[i]', '[/i]');
242 self::tagToBBCode($doc, 'u', [], '[u]', '[/u]');
243 self::tagToBBCode($doc, 's', [], '[s]', '[/s]');
244 self::tagToBBCode($doc, 'del', [], '[s]', '[/s]');
245 self::tagToBBCode($doc, 'strike', [], '[s]', '[/s]');
247 self::tagToBBCode($doc, 'big', [], "[size=large]", "[/size]");
248 self::tagToBBCode($doc, 'small', [], "[size=small]", "[/size]");
250 self::tagToBBCode($doc, 'blockquote', [], '[quote]', '[/quote]');
252 self::tagToBBCode($doc, 'br', [], "\n", '');
254 self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal'], "\n", "");
255 self::tagToBBCode($doc, 'div', ['class' => 'MsoNormal'], "\r", "");
257 self::tagToBBCode($doc, 'span', [], "", "");
259 self::tagToBBCode($doc, 'span', [], "", "");
260 self::tagToBBCode($doc, 'pre', [], "", "");
262 self::tagToBBCode($doc, 'div', [], "\r", "\r");
263 self::tagToBBCode($doc, 'p', [], "\n", "\n");
265 self::tagToBBCode($doc, 'ul', [], "[list]", "[/list]");
266 self::tagToBBCode($doc, 'ol', [], "[list=1]", "[/list]");
267 self::tagToBBCode($doc, 'li', [], "[*]", "");
269 self::tagToBBCode($doc, 'hr', [], "[hr]", "");
271 self::tagToBBCode($doc, 'table', [], "[table]", "[/table]");
272 self::tagToBBCode($doc, 'th', [], "[th]", "[/th]");
273 self::tagToBBCode($doc, 'tr', [], "[tr]", "[/tr]");
274 self::tagToBBCode($doc, 'td', [], "[td]", "[/td]");
276 self::tagToBBCode($doc, 'h1', [], "[h1]", "[/h1]");
277 self::tagToBBCode($doc, 'h2', [], "[h2]", "[/h2]");
278 self::tagToBBCode($doc, 'h3', [], "[h3]", "[/h3]");
279 self::tagToBBCode($doc, 'h4', [], "[h4]", "[/h4]");
280 self::tagToBBCode($doc, 'h5', [], "[h5]", "[/h5]");
281 self::tagToBBCode($doc, 'h6', [], "[h6]", "[/h6]");
283 self::tagToBBCode($doc, 'a', ['href' => '/mailto:(.+)/'], '[mail=$1]', '[/mail]');
284 self::tagToBBCode($doc, 'a', ['href' => '/(.+)/'], '[url=$1]', '[/url]');
286 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/', 'alt' => '/(.+)/'], '[img=$1]$2', '[/img]', true);
287 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/', 'width' => '/(\d+)/', 'height' => '/(\d+)/'], '[img=$2x$3]$1', '[/img]', true);
288 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], '[img]$1', '[/img]', true);
291 self::tagToBBCode($doc, 'video', ['src' => '/(.+)/'], '[video]$1', '[/video]', true);
292 self::tagToBBCode($doc, 'audio', ['src' => '/(.+)/'], '[audio]$1', '[/audio]', true);
293 self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], '[iframe]$1', '[/iframe]', true);
295 self::tagToBBCode($doc, 'key', [], '[code]', '[/code]');
296 self::tagToBBCode($doc, 'code', [], '[code]', '[/code]');
298 $message = $doc->saveHTML();
300 // I'm removing something really disturbing
301 // Don't know exactly what it is
302 $message = str_replace(chr(194) . chr(160), ' ', $message);
304 $message = str_replace(" ", " ", $message);
306 // removing multiple DIVs
307 $message = preg_replace('=\r *\r=i', "\n", $message);
308 $message = str_replace("\r", "\n", $message);
310 Hook::callAll('html2bbcode', $message);
312 $message = strip_tags($message);
314 $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
316 // remove quotes if they don't make sense
317 $message = preg_replace('=\[/quote\][\s]*\[quote\]=i', "\n", $message);
319 $message = preg_replace('=\[quote\]\s*=i', "[quote]", $message);
320 $message = preg_replace('=\s*\[/quote\]=i', "[/quote]", $message);
323 $oldmessage = $message;
324 $message = str_replace("\n \n", "\n\n", $message);
325 } while ($oldmessage != $message);
328 $oldmessage = $message;
329 $message = str_replace("\n\n\n", "\n\n", $message);
330 } while ($oldmessage != $message);
333 $oldmessage = $message;
334 $message = str_replace(
357 } while ($message != $oldmessage);
359 $message = str_replace(
360 ['[b][b]', '[/b][/b]', '[i][i]', '[/i][/i]'],
361 ['[b]', '[/b]', '[i]', '[/i]'],
365 // Handling Yahoo style of mails
366 $message = str_replace('[hr][b]From:[/b]', '[quote][b]From:[/b]', $message);
371 $message = preg_replace_callback(
372 '#<pre><code(?: class="language-([^"]*)")?>(.*)</code></pre>#iUs',
373 function ($matches) {
375 if ($matches[1] != '') {
376 $prefix = '[code=' . $matches[1] . ']';
379 return $prefix . PHP_EOL . trim($matches[2]) . PHP_EOL . '[/code]';
384 $message = trim($message);
386 if ($basepath != '') {
387 $message = self::qualifyURLs($message, $basepath);
394 * Sub function to complete incomplete URL
396 * @param array $matches Result of preg_replace_callback
397 * @param string $basepath Basepath that is used to complete the URL
399 * @return string The expanded URL
401 private static function qualifyURLsSub($matches, $basepath)
403 $base = parse_url($basepath);
404 unset($base['query']);
405 unset($base['fragment']);
410 if (empty($url) || empty(parse_url($url))) {
414 $parts = array_merge($base, parse_url($url));
415 $url2 = Network::unparseURL($parts);
417 return str_replace($url, $url2, $link);
421 * Complete incomplete URLs in BBCode
423 * @param string $body Body with URLs
424 * @param string $basepath Base path that is used to complete the URL
426 * @return string Body with expanded URLs
428 private static function qualifyURLs($body, $basepath)
430 $URLSearchString = "^\[\]";
432 $matches = ["/\[url\=([$URLSearchString]*)\].*?\[\/url\]/ism",
433 "/\[url\]([$URLSearchString]*)\[\/url\]/ism",
434 "/\[img\=[0-9]*x[0-9]*\](.*?)\[\/img\]/ism",
435 "/\[img\](.*?)\[\/img\]/ism",
436 "/\[zmg\=[0-9]*x[0-9]*\](.*?)\[\/img\]/ism",
437 "/\[zmg\](.*?)\[\/zmg\]/ism",
438 "/\[video\](.*?)\[\/video\]/ism",
439 "/\[audio\](.*?)\[\/audio\]/ism",
442 foreach ($matches as $match) {
443 $body = preg_replace_callback(
445 function ($match) use ($basepath) {
446 return self::qualifyURLsSub($match, $basepath);
454 private static function breakLines($line, $level, $wraplength = 75)
456 if ($wraplength == 0) {
457 $wraplength = 2000000;
460 $wraplen = $wraplength - $level;
467 $subline = substr($line, 0, $wraplen);
469 $pos = strrpos($subline, ' ');
472 $pos = strpos($line, ' ');
475 if (($pos > 0) && strlen($line) > $wraplen) {
476 $newline = trim(substr($line, 0, $pos));
478 $newline = str_repeat(">", $level) . ' ' . $newline;
481 $newlines[] = $newline . " ";
482 $line = substr($line, $pos + 1);
484 } while ((strlen($line) > $wraplen) && !($oldline == $line));
487 $line = str_repeat(">", $level) . ' ' . $line;
492 return implode("\n", $newlines);
495 private static function quoteLevel($message, $wraplength = 75)
497 $lines = explode("\n", $message);
501 foreach ($lines as $line) {
504 while (strpos("*" . $line, '[quote]') > 0) {
506 $pos = strpos($line, '[quote]');
507 $line = substr($line, 0, $pos) . substr($line, $pos + 7);
513 while (strpos("*" . $line, '[/quote]') > 0) {
519 $pos = strpos($line, '[/quote]');
520 $line = substr($line, 0, $pos) . substr($line, $pos + 8);
523 if (!$startquote || ($line != '')) {
524 $newlines[] = self::breakLines($line, $currlevel, $wraplength);
528 return implode("\n", $newlines);
531 private static function collectURLs($message)
533 $pattern = '/<a.*?href="(.*?)".*?>(.*?)<\/a>/is';
534 preg_match_all($pattern, $message, $result, PREG_SET_ORDER);
537 foreach ($result as $treffer) {
540 // A list of some links that should be ignored
541 $list = ["/user/", "/tag/", "/group/", "/profile/", "/search?search=", "/search?tag=", "mailto:", "/u/", "/node/",
542 "//plus.google.com/", "//twitter.com/"];
543 foreach ($list as $listitem) {
544 if (strpos($treffer[1], $listitem) !== false) {
549 if ((strpos($treffer[1], "//twitter.com/") !== false) && (strpos($treffer[1], "/status/") !== false)) {
553 if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/posts") !== false)) {
557 if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/photos") !== false)) {
561 $ignore = $ignore || strpos($treffer[1], '#') === 0;
564 $urls[$treffer[1]] = $treffer[1];
572 * @param string $html
573 * @param int $wraplength Ensures individual lines aren't longer than this many characters. Doesn't break words.
574 * @param bool $compact True: Completely strips image tags; False: Keeps image URLs
577 public static function toPlaintext(string $html, $wraplength = 75, $compact = false)
579 $message = str_replace("\r", "", $html);
581 $doc = new DOMDocument();
582 $doc->preserveWhiteSpace = false;
584 $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8");
586 @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
588 $message = $doc->saveHTML();
589 // Remove eventual UTF-8 BOM
590 $message = str_replace("\xC3\x82\xC2\xA0", "", $message);
592 // Collecting all links
593 $urls = self::collectURLs($message);
595 @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
597 self::tagToBBCode($doc, 'html', [], '', '');
598 self::tagToBBCode($doc, 'body', [], '', '');
601 self::tagToBBCode($doc, 'blockquote', [], "»", "«");
603 self::tagToBBCode($doc, 'blockquote', [], '[quote]', "[/quote]\n");
606 self::tagToBBCode($doc, 'br', [], "\n", '');
608 self::tagToBBCode($doc, 'span', [], "", "");
609 self::tagToBBCode($doc, 'pre', [], "", "");
610 self::tagToBBCode($doc, 'div', [], "\r", "\r");
611 self::tagToBBCode($doc, 'p', [], "\n", "\n");
613 self::tagToBBCode($doc, 'li', [], "\n* ", "\n");
615 self::tagToBBCode($doc, 'hr', [], "\n" . str_repeat("-", 70) . "\n", "");
617 self::tagToBBCode($doc, 'tr', [], "\n", "");
618 self::tagToBBCode($doc, 'td', [], "\t", "");
620 self::tagToBBCode($doc, 'h1', [], "\n\n*", "*\n");
621 self::tagToBBCode($doc, 'h2', [], "\n\n*", "*\n");
622 self::tagToBBCode($doc, 'h3', [], "\n\n*", "*\n");
623 self::tagToBBCode($doc, 'h4', [], "\n\n*", "*\n");
624 self::tagToBBCode($doc, 'h5', [], "\n\n*", "*\n");
625 self::tagToBBCode($doc, 'h6', [], "\n\n*", "*\n");
628 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], ' [img]$1', '[/img] ');
630 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], ' ', ' ');
633 self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], ' $1 ', '');
635 $message = $doc->saveHTML();
638 $message = str_replace("[img]", "", $message);
639 $message = str_replace("[/img]", "", $message);
642 // was ersetze ich da?
643 // Irgendein stoerrisches UTF-Zeug
644 $message = str_replace(chr(194) . chr(160), ' ', $message);
646 $message = str_replace(" ", " ", $message);
648 // Aufeinanderfolgende DIVs
649 $message = preg_replace('=\r *\r=i', "\n", $message);
650 $message = str_replace("\r", "\n", $message);
652 $message = strip_tags($message);
654 $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
656 if (!$compact && ($message != '')) {
657 foreach ($urls as $id => $url) {
658 if ($url != '' && strpos($message, $url) === false) {
659 $message .= "\n" . $url . ' ';
664 $message = str_replace("\n«", "«\n", $message);
665 $message = str_replace("»\n", "\n»", $message);
668 $oldmessage = $message;
669 $message = str_replace("\n\n\n", "\n\n", $message);
670 } while ($oldmessage != $message);
672 $message = self::quoteLevel(trim($message), $wraplength);
674 return trim($message);
678 * Converts provided HTML code to Markdown. The hardwrap parameter maximizes
679 * compatibility with Diaspora in spite of the Markdown standards.
681 * @param string $html
684 public static function toMarkdown($html)
686 $converter = new HtmlConverter(['hard_break' => true]);
687 $markdown = $converter->convert($html);
693 * Convert video HTML to BBCode tags
698 public static function toBBCodeVideo($s)
701 '#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
702 '[youtube]$2[/youtube]',
707 '#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
708 '[youtube]$2[/youtube]',
713 '#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
722 * transform link href and img src from relative to absolute
724 * @param string $text
725 * @param string $base base url
728 public static function relToAbs($text, $base)
734 $base = rtrim($base, '/');
736 $base2 = $base . "/";
739 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
740 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
741 $text = preg_replace($pattern, $replace, $text);
743 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
744 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
745 $text = preg_replace($pattern, $replace, $text);
748 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
749 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
750 $text = preg_replace($pattern, $replace, $text);
752 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
753 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
754 $text = preg_replace($pattern, $replace, $text);
762 * return div element with class 'clear'
766 public static function clearDiv()
768 return '<div class="clear"></div>';
772 * Loader for infinite scrolling
774 * @return string html for loader
775 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
777 public static function scrollLoader()
779 $tpl = Renderer::getMarkupTemplate("scroll_loader.tpl");
780 return Renderer::replaceMacros($tpl, [
781 'wait' => DI::l10n()->t('Loading more entries...'),
782 'end' => DI::l10n()->t('The end')
787 * Get html for contact block.
789 * @deprecated since version 2019.03
790 * @see ContactBlock::getHTML()
792 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
793 * @throws \ImagickException
795 public static function contactBlock()
799 return ContactBlock::getHTML($a->profile);
803 * Format contacts as picture links or as text links
805 * @param array $contact Array with contacts which contains an array with
806 * int 'id' => The ID of the contact
807 * int 'uid' => The user ID of the user who owns this data
808 * string 'name' => The name of the contact
809 * string 'url' => The url to the profile page of the contact
810 * string 'addr' => The webbie of the contact (e.g.) username@friendica.com
811 * string 'network' => The network to which the contact belongs to
812 * string 'thumb' => The contact picture
813 * string 'click' => js code which is performed when clicking on the contact
814 * @param boolean $redirect If true try to use the redir url if it's possible
815 * @param string $class CSS class for the
816 * @param boolean $textmode If true display the contacts as text links
817 * if false display the contacts as picture links
818 * @return string Formatted html
819 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
820 * @throws \ImagickException
822 public static function micropro($contact, $redirect = false, $class = '', $textmode = false)
824 // Use the contact URL if no address is available
825 if (empty($contact['addr'])) {
826 $contact["addr"] = $contact["url"];
829 $url = $contact['url'];
834 $url = Contact::magicLink($contact['url']);
835 if (strpos($url, 'redir/') === 0) {
836 $sparkle = ' sparkle';
840 // If there is some js available we don't need the url
841 if (!empty($contact['click'])) {
845 return Renderer::replaceMacros(Renderer::getMarkupTemplate($textmode ? 'micropro_txt.tpl' : 'micropro_img.tpl'), [
846 '$click' => $contact['click'] ?? '',
849 '$photo' => Contact::getThumb($contact),
850 '$name' => $contact['name'],
851 'title' => $contact['name'] . ' [' . $contact['addr'] . ']',
852 '$parkle' => $sparkle,
860 * @param string $s Search query.
861 * @param string $id HTML id
862 * @param string $url Search url.
863 * @param bool $aside Display the search widgit aside.
865 * @return string Formatted HTML.
868 public static function search($s, $id = 'search-box', $aside = true)
872 if (strpos($s, '#') === 0) {
875 $save_label = $mode === 'text' ? DI::l10n()->t('Save') : DI::l10n()->t('Follow');
879 '$q' => urlencode($s),
881 '$search_label' => DI::l10n()->t('Search'),
882 '$save_label' => $save_label,
883 '$search_hint' => DI::l10n()->t('@name, !forum, #tags, content'),
885 '$return_url' => urlencode(Search::getSearchPath($s)),
889 $values['$search_options'] = [
890 'fulltext' => DI::l10n()->t('Full Text'),
891 'tags' => DI::l10n()->t('Tags'),
892 'contacts' => DI::l10n()->t('Contacts')
895 if (DI::config()->get('system', 'poco_local_search')) {
896 $values['$searchoption']['forums'] = DI::l10n()->t('Forums');
900 return Renderer::replaceMacros(Renderer::getMarkupTemplate('searchbox.tpl'), $values);
904 * Replace naked text hyperlink with HTML formatted hyperlink
909 public static function toLink($s)
911 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank" rel="noopener noreferrer">$1</a>', $s);
912 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism", '<$1$2=$3&$4>', $s);
917 * Given a HTML text and a set of filtering reasons, adds a content hiding header with the provided reasons
919 * Reasons are expected to have been translated already.
921 * @param string $html
922 * @param array $reasons
924 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
926 public static function applyContentFilter($html, array $reasons)
928 if (count($reasons)) {
929 $tpl = Renderer::getMarkupTemplate('wall/content_filter.tpl');
930 $html = Renderer::replaceMacros($tpl, [
931 '$reasons' => $reasons,
932 '$rnd' => Strings::getRandomHex(8),
933 '$openclose' => DI::l10n()->t('Click to open/close'),
942 * replace html amp entity with amp char
946 public static function unamp($s)
948 return str_replace('&', '&', $s);