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;
30 use Friendica\Model\Contact;
31 use Friendica\Util\Network;
32 use Friendica\Util\Proxy as ProxyUtils;
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 // Removing code blocks before the whitespace removal processing below
171 $message = preg_replace_callback(
172 '#<pre><code(?: class="language-([^"]*)")?>(.*)</code></pre>#iUs',
173 function ($matches) use (&$codeblocks) {
174 $return = '[codeblock-' . count($codeblocks) . ']';
177 if ($matches[1] != '') {
178 $prefix = '[code=' . $matches[1] . ']';
181 $codeblocks[] = $prefix . PHP_EOL . trim($matches[2]) . PHP_EOL . '[/code]';
187 $message = str_replace(
200 $message = preg_replace('=<(\w+):(.+?)>=', '<removeme>', $message);
201 $message = preg_replace('=</(\w+):(.+?)>=', '</removeme>', $message);
203 $doc = new DOMDocument();
204 $doc->preserveWhiteSpace = false;
206 $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8");
208 @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
210 XML::deleteNode($doc, 'style');
211 XML::deleteNode($doc, 'head');
212 XML::deleteNode($doc, 'title');
213 XML::deleteNode($doc, 'meta');
214 XML::deleteNode($doc, 'xml');
215 XML::deleteNode($doc, 'removeme');
217 $xpath = new DomXPath($doc);
218 $list = $xpath->query("//pre");
219 foreach ($list as $node) {
220 // Ensure to escape unescaped & - they will otherwise raise a warning
221 $safe_value = preg_replace('/&(?!\w+;)/', '&', $node->nodeValue);
222 $node->nodeValue = str_replace("\n", "\r", $safe_value);
225 $message = $doc->saveHTML();
226 $message = str_replace(["\n<", ">\n", "\r", "\n", "\xC3\x82\xC2\xA0"], ["<", ">", "<br />", " ", ""], $message);
227 $message = preg_replace('= [\s]*=i', " ", $message);
229 @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
231 self::tagToBBCode($doc, 'html', [], "", "");
232 self::tagToBBCode($doc, 'body', [], "", "");
234 // Outlook-Quote - Variant 1
235 self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal', 'style' => 'margin-left:35.4pt'], '[quote]', '[/quote]');
237 // Outlook-Quote - Variant 2
241 ['style' => 'border:none;border-left:solid blue 1.5pt;padding:0cm 0cm 0cm 4.0pt'],
247 self::tagToBBCode($doc, 'span', ['style' => 'text-decoration: underline;'], '[u]', '[/u]');
248 self::tagToBBCode($doc, 'span', ['style' => 'font-style: italic;'], '[i]', '[/i]');
249 self::tagToBBCode($doc, 'span', ['style' => 'font-weight: bold;'], '[b]', '[/b]');
251 /* self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[font=$1][size=$2][color=$3]', '[/color][/size][/font]');
252 self::node2BBCode($doc, 'font', array('size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[size=$1][color=$2]', '[/color][/size]');
253 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(.+)/'), '[font=$1][size=$2]', '[/size][/font]');
254 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'color'=>'/(.+)/'), '[font=$1][color=$3]', '[/color][/font]');
255 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/'), '[font=$1]', '[/font]');
256 self::node2BBCode($doc, 'font', array('size'=>'/(\d+)/'), '[size=$1]', '[/size]');
257 self::node2BBCode($doc, 'font', array('color'=>'/(.+)/'), '[color=$1]', '[/color]');
260 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*font-family:\s*(.+?)[,;].*color:\s*(.+?)[,;].*/'), '[size=$1][font=$2][color=$3]', '[/color][/font][/size]');
261 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(\d+)[,;].*/'), '[size=$1]', '[/size]');
262 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*/'), '[size=$1]', '[/size]');
264 self::tagToBBCode($doc, 'span', ['style' => '/.*color:\s*(.+?)[,;].*/'], '[color="$1"]', '[/color]');
266 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
267 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)pt.*/'), '[font=$1][size=$2]', '[/size][/font]');
268 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)px.*/'), '[font=$1][size=$2]', '[/size][/font]');
269 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
270 // Importing the classes - interesting for importing of posts from third party networks that were exported from friendica
272 //self::node2BBCode($doc, 'span', array('class'=>'/([\w ]+)/'), '[class=$1]', '[/class]');
273 self::tagToBBCode($doc, 'span', ['class' => 'type-link'], '[class=type-link]', '[/class]');
274 self::tagToBBCode($doc, 'span', ['class' => 'type-video'], '[class=type-video]', '[/class]');
276 self::tagToBBCode($doc, 'strong', [], '[b]', '[/b]');
277 self::tagToBBCode($doc, 'em', [], '[i]', '[/i]');
278 self::tagToBBCode($doc, 'b', [], '[b]', '[/b]');
279 self::tagToBBCode($doc, 'i', [], '[i]', '[/i]');
280 self::tagToBBCode($doc, 'u', [], '[u]', '[/u]');
281 self::tagToBBCode($doc, 's', [], '[s]', '[/s]');
282 self::tagToBBCode($doc, 'del', [], '[s]', '[/s]');
283 self::tagToBBCode($doc, 'strike', [], '[s]', '[/s]');
285 self::tagToBBCode($doc, 'big', [], "[size=large]", "[/size]");
286 self::tagToBBCode($doc, 'small', [], "[size=small]", "[/size]");
288 self::tagToBBCode($doc, 'blockquote', [], '[quote]', '[/quote]');
290 self::tagToBBCode($doc, 'br', [], "\n", '');
292 self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal'], "\n", "");
293 self::tagToBBCode($doc, 'div', ['class' => 'MsoNormal'], "\r", "");
295 self::tagToBBCode($doc, 'span', [], "", "");
297 self::tagToBBCode($doc, 'span', [], "", "");
298 self::tagToBBCode($doc, 'pre', [], "", "");
300 self::tagToBBCode($doc, 'div', [], "\r", "\r");
301 self::tagToBBCode($doc, 'p', [], "\n", "\n");
303 self::tagToBBCode($doc, 'ul', [], "[list]", "[/list]");
304 self::tagToBBCode($doc, 'ol', [], "[list=1]", "[/list]");
305 self::tagToBBCode($doc, 'li', [], "[*]", "");
307 self::tagToBBCode($doc, 'hr', [], "[hr]", "");
309 self::tagToBBCode($doc, 'table', [], "[table]", "[/table]");
310 self::tagToBBCode($doc, 'th', [], "[th]", "[/th]");
311 self::tagToBBCode($doc, 'tr', [], "[tr]", "[/tr]");
312 self::tagToBBCode($doc, 'td', [], "[td]", "[/td]");
314 self::tagToBBCode($doc, 'h1', [], "[h1]", "[/h1]");
315 self::tagToBBCode($doc, 'h2', [], "[h2]", "[/h2]");
316 self::tagToBBCode($doc, 'h3', [], "[h3]", "[/h3]");
317 self::tagToBBCode($doc, 'h4', [], "[h4]", "[/h4]");
318 self::tagToBBCode($doc, 'h5', [], "[h5]", "[/h5]");
319 self::tagToBBCode($doc, 'h6', [], "[h6]", "[/h6]");
321 self::tagToBBCode($doc, 'a', ['href' => '/mailto:(.+)/'], '[mail=$1]', '[/mail]');
322 self::tagToBBCode($doc, 'a', ['href' => '/(.+)/'], '[url=$1]', '[/url]');
324 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/', 'alt' => '/(.+)/'], '[img=$1]$2', '[/img]', true);
325 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/', 'width' => '/(\d+)/', 'height' => '/(\d+)/'], '[img=$2x$3]$1', '[/img]', true);
326 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], '[img]$1', '[/img]', true);
329 self::tagToBBCode($doc, 'video', ['src' => '/(.+)/'], '[video]$1', '[/video]', true);
330 self::tagToBBCode($doc, 'audio', ['src' => '/(.+)/'], '[audio]$1', '[/audio]', true);
331 self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], '[iframe]$1', '[/iframe]', true);
333 self::tagToBBCode($doc, 'key', [], '[code]', '[/code]');
334 self::tagToBBCode($doc, 'code', [], '[code]', '[/code]');
336 $message = $doc->saveHTML();
338 // I'm removing something really disturbing
339 // Don't know exactly what it is
340 $message = str_replace(chr(194) . chr(160), ' ', $message);
342 $message = str_replace(" ", " ", $message);
344 // removing multiple DIVs
345 $message = preg_replace('=\r *\r=i', "\n", $message);
346 $message = str_replace("\r", "\n", $message);
348 Hook::callAll('html2bbcode', $message);
350 $message = strip_tags($message);
352 $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
354 // remove quotes if they don't make sense
355 $message = preg_replace('=\[/quote\][\s]*\[quote\]=i', "\n", $message);
357 $message = preg_replace('=\[quote\]\s*=i', "[quote]", $message);
358 $message = preg_replace('=\s*\[/quote\]=i', "[/quote]", $message);
361 $oldmessage = $message;
362 $message = str_replace("\n \n", "\n\n", $message);
363 } while ($oldmessage != $message);
366 $oldmessage = $message;
367 $message = str_replace("\n\n\n", "\n\n", $message);
368 } while ($oldmessage != $message);
371 $oldmessage = $message;
372 $message = str_replace(
395 } while ($message != $oldmessage);
397 $message = str_replace(
398 ['[b][b]', '[/b][/b]', '[i][i]', '[/i][/i]'],
399 ['[b]', '[/b]', '[i]', '[/i]'],
403 // Handling Yahoo style of mails
404 $message = str_replace('[hr][b]From:[/b]', '[quote][b]From:[/b]', $message);
406 // Restore code blocks
407 $message = preg_replace_callback(
408 '#\[codeblock-([0-9]+)\]#iU',
409 function ($matches) use ($codeblocks) {
411 if (isset($codeblocks[intval($matches[1])])) {
412 $return = $codeblocks[$matches[1]];
419 $message = trim($message);
421 if ($basepath != '') {
422 $message = self::qualifyURLs($message, $basepath);
429 * Sub function to complete incomplete URL
431 * @param array $matches Result of preg_replace_callback
432 * @param string $basepath Basepath that is used to complete the URL
434 * @return string The expanded URL
436 private static function qualifyURLsSub($matches, $basepath)
438 $base = parse_url($basepath);
439 unset($base['query']);
440 unset($base['fragment']);
445 if (empty($url) || empty(parse_url($url))) {
449 $parts = array_merge($base, parse_url($url));
450 $url2 = Network::unparseURL($parts);
452 return str_replace($url, $url2, $link);
456 * Complete incomplete URLs in BBCode
458 * @param string $body Body with URLs
459 * @param string $basepath Base path that is used to complete the URL
461 * @return string Body with expanded URLs
463 private static function qualifyURLs($body, $basepath)
465 $URLSearchString = "^\[\]";
467 $matches = ["/\[url\=([$URLSearchString]*)\].*?\[\/url\]/ism",
468 "/\[url\]([$URLSearchString]*)\[\/url\]/ism",
469 "/\[img\=[0-9]*x[0-9]*\](.*?)\[\/img\]/ism",
470 "/\[img\](.*?)\[\/img\]/ism",
471 "/\[zmg\=[0-9]*x[0-9]*\](.*?)\[\/img\]/ism",
472 "/\[zmg\](.*?)\[\/zmg\]/ism",
473 "/\[video\](.*?)\[\/video\]/ism",
474 "/\[audio\](.*?)\[\/audio\]/ism",
477 foreach ($matches as $match) {
478 $body = preg_replace_callback(
480 function ($match) use ($basepath) {
481 return self::qualifyURLsSub($match, $basepath);
489 private static function breakLines($line, $level, $wraplength = 75)
491 if ($wraplength == 0) {
492 $wraplength = 2000000;
495 $wraplen = $wraplength - $level;
502 $subline = substr($line, 0, $wraplen);
504 $pos = strrpos($subline, ' ');
507 $pos = strpos($line, ' ');
510 if (($pos > 0) && strlen($line) > $wraplen) {
511 $newline = trim(substr($line, 0, $pos));
513 $newline = str_repeat(">", $level) . ' ' . $newline;
516 $newlines[] = $newline . " ";
517 $line = substr($line, $pos + 1);
519 } while ((strlen($line) > $wraplen) && !($oldline == $line));
522 $line = str_repeat(">", $level) . ' ' . $line;
527 return implode("\n", $newlines);
530 private static function quoteLevel($message, $wraplength = 75)
532 $lines = explode("\n", $message);
536 foreach ($lines as $line) {
539 while (strpos("*" . $line, '[quote]') > 0) {
541 $pos = strpos($line, '[quote]');
542 $line = substr($line, 0, $pos) . substr($line, $pos + 7);
548 while (strpos("*" . $line, '[/quote]') > 0) {
554 $pos = strpos($line, '[/quote]');
555 $line = substr($line, 0, $pos) . substr($line, $pos + 8);
558 if (!$startquote || ($line != '')) {
559 $newlines[] = self::breakLines($line, $currlevel, $wraplength);
563 return implode("\n", $newlines);
566 private static function collectURLs($message)
568 $pattern = '/<a.*?href="(.*?)".*?>(.*?)<\/a>/is';
569 preg_match_all($pattern, $message, $result, PREG_SET_ORDER);
572 foreach ($result as $treffer) {
575 // A list of some links that should be ignored
576 $list = ["/user/", "/tag/", "/group/", "/profile/", "/search?search=", "/search?tag=", "mailto:", "/u/", "/node/",
577 "//plus.google.com/", "//twitter.com/"];
578 foreach ($list as $listitem) {
579 if (strpos($treffer[1], $listitem) !== false) {
584 if ((strpos($treffer[1], "//twitter.com/") !== false) && (strpos($treffer[1], "/status/") !== false)) {
588 if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/posts") !== false)) {
592 if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/photos") !== false)) {
596 $ignore = $ignore || strpos($treffer[1], '#') === 0;
599 $urls[$treffer[1]] = $treffer[1];
607 * @param string $html
608 * @param int $wraplength Ensures individual lines aren't longer than this many characters. Doesn't break words.
609 * @param bool $compact True: Completely strips image tags; False: Keeps image URLs
612 public static function toPlaintext(string $html, $wraplength = 75, $compact = false)
614 $message = str_replace("\r", "", $html);
616 $doc = new DOMDocument();
617 $doc->preserveWhiteSpace = false;
619 $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8");
621 @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
623 $message = $doc->saveHTML();
624 // Remove eventual UTF-8 BOM
625 $message = str_replace("\xC3\x82\xC2\xA0", "", $message);
627 // Collecting all links
628 $urls = self::collectURLs($message);
630 @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
632 self::tagToBBCode($doc, 'html', [], '', '');
633 self::tagToBBCode($doc, 'body', [], '', '');
636 self::tagToBBCode($doc, 'blockquote', [], "»", "«");
638 self::tagToBBCode($doc, 'blockquote', [], '[quote]', "[/quote]\n");
641 self::tagToBBCode($doc, 'br', [], "\n", '');
643 self::tagToBBCode($doc, 'span', [], "", "");
644 self::tagToBBCode($doc, 'pre', [], "", "");
645 self::tagToBBCode($doc, 'div', [], "\r", "\r");
646 self::tagToBBCode($doc, 'p', [], "\n", "\n");
648 self::tagToBBCode($doc, 'li', [], "\n* ", "\n");
650 self::tagToBBCode($doc, 'hr', [], "\n" . str_repeat("-", 70) . "\n", "");
652 self::tagToBBCode($doc, 'tr', [], "\n", "");
653 self::tagToBBCode($doc, 'td', [], "\t", "");
655 self::tagToBBCode($doc, 'h1', [], "\n\n*", "*\n");
656 self::tagToBBCode($doc, 'h2', [], "\n\n*", "*\n");
657 self::tagToBBCode($doc, 'h3', [], "\n\n*", "*\n");
658 self::tagToBBCode($doc, 'h4', [], "\n\n*", "*\n");
659 self::tagToBBCode($doc, 'h5', [], "\n\n*", "*\n");
660 self::tagToBBCode($doc, 'h6', [], "\n\n*", "*\n");
663 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], ' [img]$1', '[/img] ');
665 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], ' ', ' ');
668 self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], ' $1 ', '');
670 $message = $doc->saveHTML();
673 $message = str_replace("[img]", "", $message);
674 $message = str_replace("[/img]", "", $message);
677 // was ersetze ich da?
678 // Irgendein stoerrisches UTF-Zeug
679 $message = str_replace(chr(194) . chr(160), ' ', $message);
681 $message = str_replace(" ", " ", $message);
683 // Aufeinanderfolgende DIVs
684 $message = preg_replace('=\r *\r=i', "\n", $message);
685 $message = str_replace("\r", "\n", $message);
687 $message = strip_tags($message);
689 $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
691 if (!$compact && ($message != '')) {
692 foreach ($urls as $id => $url) {
693 if ($url != '' && strpos($message, $url) === false) {
694 $message .= "\n" . $url . ' ';
699 $message = str_replace("\n«", "«\n", $message);
700 $message = str_replace("»\n", "\n»", $message);
703 $oldmessage = $message;
704 $message = str_replace("\n\n\n", "\n\n", $message);
705 } while ($oldmessage != $message);
707 $message = self::quoteLevel(trim($message), $wraplength);
709 return trim($message);
713 * Converts provided HTML code to Markdown. The hardwrap parameter maximizes
714 * compatibility with Diaspora in spite of the Markdown standards.
716 * @param string $html
719 public static function toMarkdown($html)
721 $converter = new HtmlConverter(['hard_break' => true]);
722 $markdown = $converter->convert($html);
728 * Convert video HTML to BBCode tags
733 public static function toBBCodeVideo($s)
736 '#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
737 '[youtube]$2[/youtube]',
742 '#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
743 '[youtube]$2[/youtube]',
748 '#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
757 * transform link href and img src from relative to absolute
759 * @param string $text
760 * @param string $base base url
763 public static function relToAbs($text, $base)
769 $base = rtrim($base, '/');
771 $base2 = $base . "/";
774 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
775 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
776 $text = preg_replace($pattern, $replace, $text);
778 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
779 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
780 $text = preg_replace($pattern, $replace, $text);
783 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
784 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
785 $text = preg_replace($pattern, $replace, $text);
787 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
788 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
789 $text = preg_replace($pattern, $replace, $text);
797 * return div element with class 'clear'
801 public static function clearDiv()
803 return '<div class="clear"></div>';
807 * Loader for infinite scrolling
809 * @return string html for loader
810 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
812 public static function scrollLoader()
814 $tpl = Renderer::getMarkupTemplate("scroll_loader.tpl");
815 return Renderer::replaceMacros($tpl, [
816 'wait' => DI::l10n()->t('Loading more entries...'),
817 'end' => DI::l10n()->t('The end')
822 * Get html for contact block.
824 * @deprecated since version 2019.03
825 * @see ContactBlock::getHTML()
827 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
828 * @throws \ImagickException
830 public static function contactBlock()
834 return ContactBlock::getHTML($a->profile);
838 * Format contacts as picture links or as text links
840 * @param array $contact Array with contacts which contains an array with
841 * int 'id' => The ID of the contact
842 * int 'uid' => The user ID of the user who owns this data
843 * string 'name' => The name of the contact
844 * string 'url' => The url to the profile page of the contact
845 * string 'addr' => The webbie of the contact (e.g.) username@friendica.com
846 * string 'network' => The network to which the contact belongs to
847 * string 'thumb' => The contact picture
848 * string 'click' => js code which is performed when clicking on the contact
849 * @param boolean $redirect If true try to use the redir url if it's possible
850 * @param string $class CSS class for the
851 * @param boolean $textmode If true display the contacts as text links
852 * if false display the contacts as picture links
853 * @return string Formatted html
854 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
855 * @throws \ImagickException
857 public static function micropro($contact, $redirect = false, $class = '', $textmode = false)
859 // Use the contact URL if no address is available
860 if (empty($contact['addr'])) {
861 $contact["addr"] = $contact["url"];
864 $url = $contact['url'];
869 $url = Contact::magicLink($contact['url']);
870 if (strpos($url, 'redir/') === 0) {
871 $sparkle = ' sparkle';
875 // If there is some js available we don't need the url
876 if (!empty($contact['click'])) {
880 return Renderer::replaceMacros(Renderer::getMarkupTemplate($textmode ? 'micropro_txt.tpl' : 'micropro_img.tpl'), [
881 '$click' => $contact['click'] ?? '',
884 '$photo' => ProxyUtils::proxifyUrl($contact['thumb'], false, ProxyUtils::SIZE_THUMB),
885 '$name' => $contact['name'],
886 'title' => $contact['name'] . ' [' . $contact['addr'] . ']',
887 '$parkle' => $sparkle,
895 * @param string $s Search query.
896 * @param string $id HTML id
897 * @param string $url Search url.
898 * @param bool $aside Display the search widgit aside.
900 * @return string Formatted HTML.
903 public static function search($s, $id = 'search-box', $aside = true)
907 if (strpos($s, '#') === 0) {
910 $save_label = $mode === 'text' ? DI::l10n()->t('Save') : DI::l10n()->t('Follow');
914 '$q' => urlencode($s),
916 '$search_label' => DI::l10n()->t('Search'),
917 '$save_label' => $save_label,
918 '$search_hint' => DI::l10n()->t('@name, !forum, #tags, content'),
920 '$return_url' => urlencode('search?q=' . urlencode($s)),
924 $values['$search_options'] = [
925 'fulltext' => DI::l10n()->t('Full Text'),
926 'tags' => DI::l10n()->t('Tags'),
927 'contacts' => DI::l10n()->t('Contacts')
930 if (DI::config()->get('system', 'poco_local_search')) {
931 $values['$searchoption']['forums'] = DI::l10n()->t('Forums');
935 return Renderer::replaceMacros(Renderer::getMarkupTemplate('searchbox.tpl'), $values);
939 * Replace naked text hyperlink with HTML formatted hyperlink
944 public static function toLink($s)
946 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank" rel="noopener noreferrer">$1</a>', $s);
947 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism", '<$1$2=$3&$4>', $s);
952 * Given a HTML text and a set of filtering reasons, adds a content hiding header with the provided reasons
954 * Reasons are expected to have been translated already.
956 * @param string $html
957 * @param array $reasons
959 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
961 public static function applyContentFilter($html, array $reasons)
963 if (count($reasons)) {
964 $tpl = Renderer::getMarkupTemplate('wall/content_filter.tpl');
965 $html = Renderer::replaceMacros($tpl, [
966 '$reasons' => $reasons,
967 '$rnd' => Strings::getRandomHex(8),
968 '$openclose' => DI::l10n()->t('Click to open/close'),
977 * replace html amp entity with amp char
981 public static function unamp($s)
983 return str_replace('&', '&', $s);