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\Proxy as ProxyUtils;
34 use Friendica\Util\Strings;
35 use Friendica\Util\XML;
36 use League\HTMLToMarkdown\HtmlConverter;
40 public static function sanitizeCSS($input)
44 $input = strtolower($input);
46 for ($i = 0; $i < strlen($input); $i++) {
47 $char = substr($input, $i, 1);
49 if (($char >= "a") && ($char <= "z")) {
53 if (!(strpos(" #;:0123456789-_.%", $char) === false)) {
62 * Search all instances of a specific HTML tag node in the provided DOM document and replaces them with BBCode text nodes.
64 * @see HTML::tagToBBCodeSub()
66 private static function tagToBBCode(DOMDocument $doc, string $tag, array $attributes, string $startbb, string $endbb, bool $ignoreChildren = false)
69 $done = self::tagToBBCodeSub($doc, $tag, $attributes, $startbb, $endbb, $ignoreChildren);
74 * Search the first specific HTML tag node in the provided DOM document and replaces it with BBCode text nodes.
76 * @param DOMDocument $doc
77 * @param string $tag HTML tag name
78 * @param array $attributes Array of attributes to match and optionally use the value from
79 * @param string $startbb BBCode tag opening
80 * @param string $endbb BBCode tag closing
81 * @param bool $ignoreChildren If set to false, the HTML tag children will be appended as text inside the BBCode tag
82 * Otherwise, they will be entirely ignored. Useful for simple BBCode that draw their
83 * inner value from an attribute value and disregard the tag children.
84 * @return bool Whether a replacement was done
86 private static function tagToBBCodeSub(DOMDocument $doc, string $tag, array $attributes, string $startbb, string $endbb, bool $ignoreChildren = false)
88 $savestart = str_replace('$', '\x01', $startbb);
91 $xpath = new DOMXPath($doc);
93 /** @var \DOMNode[] $list */
94 $list = $xpath->query("//" . $tag);
95 foreach ($list as $node) {
97 if ($node->attributes->length) {
98 foreach ($node->attributes as $attribute) {
99 $attr[$attribute->name] = $attribute->value;
105 $startbb = $savestart;
109 foreach ($attributes as $attribute => $value) {
110 $startbb = str_replace('\x01' . ++$i, '$1', $startbb);
111 if (strpos('*' . $startbb, '$1') > 0) {
112 if ($replace && (@$attr[$attribute] != '')) {
113 $startbb = preg_replace($value, $startbb, $attr[$attribute], -1, $count);
115 // If nothing could be changed
123 if (@$attr[$attribute] != $value) {
130 $StartCode = $doc->createTextNode($startbb);
131 $EndCode = $doc->createTextNode($endbb);
133 $node->parentNode->insertBefore($StartCode, $node);
135 if (!$ignoreChildren && $node->hasChildNodes()) {
136 /** @var \DOMNode $child */
137 foreach ($node->childNodes as $key => $child) {
138 /* Remove empty text nodes at the start or at the end of the children list */
139 if ($key > 0 && $key < $node->childNodes->length - 1 || $child->nodeName != '#text' || trim($child->nodeValue)) {
140 $newNode = $child->cloneNode(true);
141 $node->parentNode->insertBefore($newNode, $node);
146 $node->parentNode->insertBefore($EndCode, $node);
147 $node->parentNode->removeChild($node);
155 * Converter for HTML to BBCode
157 * Made by: ike@piratenpartei.de
158 * Originally made for the syncom project: http://wiki.piratenpartei.de/Syncom
159 * https://github.com/annando/Syncom
161 * @param string $message
162 * @param string $basepath
164 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
166 public static function toBBCode($message, $basepath = '')
168 $message = str_replace("\r", "", $message);
170 // Removing code blocks before the whitespace removal processing below
172 $message = preg_replace_callback(
173 '#<pre><code(?: class="language-([^"]*)")?>(.*)</code></pre>#iUs',
174 function ($matches) use (&$codeblocks) {
175 $return = '[codeblock-' . count($codeblocks) . ']';
178 if ($matches[1] != '') {
179 $prefix = '[code=' . $matches[1] . ']';
182 $codeblocks[] = $prefix . PHP_EOL . trim($matches[2]) . PHP_EOL . '[/code]';
188 $message = str_replace(
201 $message = preg_replace('=<(\w+):(.+?)>=', '<removeme>', $message);
202 $message = preg_replace('=</(\w+):(.+?)>=', '</removeme>', $message);
204 $doc = new DOMDocument();
205 $doc->preserveWhiteSpace = false;
207 $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8");
209 @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
211 XML::deleteNode($doc, 'style');
212 XML::deleteNode($doc, 'head');
213 XML::deleteNode($doc, 'title');
214 XML::deleteNode($doc, 'meta');
215 XML::deleteNode($doc, 'xml');
216 XML::deleteNode($doc, 'removeme');
218 $xpath = new DomXPath($doc);
219 $list = $xpath->query("//pre");
220 foreach ($list as $node) {
221 // Ensure to escape unescaped & - they will otherwise raise a warning
222 $safe_value = preg_replace('/&(?!\w+;)/', '&', $node->nodeValue);
223 $node->nodeValue = str_replace("\n", "\r", $safe_value);
226 $message = $doc->saveHTML();
227 $message = str_replace(["\n<", ">\n", "\r", "\n", "\xC3\x82\xC2\xA0"], ["<", ">", "<br />", " ", ""], $message);
228 $message = preg_replace('= [\s]*=i', " ", $message);
230 @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
232 self::tagToBBCode($doc, 'html', [], "", "");
233 self::tagToBBCode($doc, 'body', [], "", "");
235 // Outlook-Quote - Variant 1
236 self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal', 'style' => 'margin-left:35.4pt'], '[quote]', '[/quote]');
238 // Outlook-Quote - Variant 2
242 ['style' => 'border:none;border-left:solid blue 1.5pt;padding:0cm 0cm 0cm 4.0pt'],
248 self::tagToBBCode($doc, 'span', ['style' => 'text-decoration: underline;'], '[u]', '[/u]');
249 self::tagToBBCode($doc, 'span', ['style' => 'font-style: italic;'], '[i]', '[/i]');
250 self::tagToBBCode($doc, 'span', ['style' => 'font-weight: bold;'], '[b]', '[/b]');
252 /* self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[font=$1][size=$2][color=$3]', '[/color][/size][/font]');
253 self::node2BBCode($doc, 'font', array('size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[size=$1][color=$2]', '[/color][/size]');
254 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(.+)/'), '[font=$1][size=$2]', '[/size][/font]');
255 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'color'=>'/(.+)/'), '[font=$1][color=$3]', '[/color][/font]');
256 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/'), '[font=$1]', '[/font]');
257 self::node2BBCode($doc, 'font', array('size'=>'/(\d+)/'), '[size=$1]', '[/size]');
258 self::node2BBCode($doc, 'font', array('color'=>'/(.+)/'), '[color=$1]', '[/color]');
261 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*font-family:\s*(.+?)[,;].*color:\s*(.+?)[,;].*/'), '[size=$1][font=$2][color=$3]', '[/color][/font][/size]');
262 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(\d+)[,;].*/'), '[size=$1]', '[/size]');
263 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*/'), '[size=$1]', '[/size]');
265 self::tagToBBCode($doc, 'span', ['style' => '/.*color:\s*(.+?)[,;].*/'], '[color="$1"]', '[/color]');
267 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
268 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)pt.*/'), '[font=$1][size=$2]', '[/size][/font]');
269 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)px.*/'), '[font=$1][size=$2]', '[/size][/font]');
270 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
271 // Importing the classes - interesting for importing of posts from third party networks that were exported from friendica
273 //self::node2BBCode($doc, 'span', array('class'=>'/([\w ]+)/'), '[class=$1]', '[/class]');
274 self::tagToBBCode($doc, 'span', ['class' => 'type-link'], '[class=type-link]', '[/class]');
275 self::tagToBBCode($doc, 'span', ['class' => 'type-video'], '[class=type-video]', '[/class]');
277 self::tagToBBCode($doc, 'strong', [], '[b]', '[/b]');
278 self::tagToBBCode($doc, 'em', [], '[i]', '[/i]');
279 self::tagToBBCode($doc, 'b', [], '[b]', '[/b]');
280 self::tagToBBCode($doc, 'i', [], '[i]', '[/i]');
281 self::tagToBBCode($doc, 'u', [], '[u]', '[/u]');
282 self::tagToBBCode($doc, 's', [], '[s]', '[/s]');
283 self::tagToBBCode($doc, 'del', [], '[s]', '[/s]');
284 self::tagToBBCode($doc, 'strike', [], '[s]', '[/s]');
286 self::tagToBBCode($doc, 'big', [], "[size=large]", "[/size]");
287 self::tagToBBCode($doc, 'small', [], "[size=small]", "[/size]");
289 self::tagToBBCode($doc, 'blockquote', [], '[quote]', '[/quote]');
291 self::tagToBBCode($doc, 'br', [], "\n", '');
293 self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal'], "\n", "");
294 self::tagToBBCode($doc, 'div', ['class' => 'MsoNormal'], "\r", "");
296 self::tagToBBCode($doc, 'span', [], "", "");
298 self::tagToBBCode($doc, 'span', [], "", "");
299 self::tagToBBCode($doc, 'pre', [], "", "");
301 self::tagToBBCode($doc, 'div', [], "\r", "\r");
302 self::tagToBBCode($doc, 'p', [], "\n", "\n");
304 self::tagToBBCode($doc, 'ul', [], "[list]", "[/list]");
305 self::tagToBBCode($doc, 'ol', [], "[list=1]", "[/list]");
306 self::tagToBBCode($doc, 'li', [], "[*]", "");
308 self::tagToBBCode($doc, 'hr', [], "[hr]", "");
310 self::tagToBBCode($doc, 'table', [], "[table]", "[/table]");
311 self::tagToBBCode($doc, 'th', [], "[th]", "[/th]");
312 self::tagToBBCode($doc, 'tr', [], "[tr]", "[/tr]");
313 self::tagToBBCode($doc, 'td', [], "[td]", "[/td]");
315 self::tagToBBCode($doc, 'h1', [], "[h1]", "[/h1]");
316 self::tagToBBCode($doc, 'h2', [], "[h2]", "[/h2]");
317 self::tagToBBCode($doc, 'h3', [], "[h3]", "[/h3]");
318 self::tagToBBCode($doc, 'h4', [], "[h4]", "[/h4]");
319 self::tagToBBCode($doc, 'h5', [], "[h5]", "[/h5]");
320 self::tagToBBCode($doc, 'h6', [], "[h6]", "[/h6]");
322 self::tagToBBCode($doc, 'a', ['href' => '/mailto:(.+)/'], '[mail=$1]', '[/mail]');
323 self::tagToBBCode($doc, 'a', ['href' => '/(.+)/'], '[url=$1]', '[/url]');
325 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/', 'alt' => '/(.+)/'], '[img=$1]$2', '[/img]', true);
326 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/', 'width' => '/(\d+)/', 'height' => '/(\d+)/'], '[img=$2x$3]$1', '[/img]', true);
327 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], '[img]$1', '[/img]', true);
330 self::tagToBBCode($doc, 'video', ['src' => '/(.+)/'], '[video]$1', '[/video]', true);
331 self::tagToBBCode($doc, 'audio', ['src' => '/(.+)/'], '[audio]$1', '[/audio]', true);
332 self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], '[iframe]$1', '[/iframe]', true);
334 self::tagToBBCode($doc, 'key', [], '[code]', '[/code]');
335 self::tagToBBCode($doc, 'code', [], '[code]', '[/code]');
337 $message = $doc->saveHTML();
339 // I'm removing something really disturbing
340 // Don't know exactly what it is
341 $message = str_replace(chr(194) . chr(160), ' ', $message);
343 $message = str_replace(" ", " ", $message);
345 // removing multiple DIVs
346 $message = preg_replace('=\r *\r=i', "\n", $message);
347 $message = str_replace("\r", "\n", $message);
349 Hook::callAll('html2bbcode', $message);
351 $message = strip_tags($message);
353 $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
355 // remove quotes if they don't make sense
356 $message = preg_replace('=\[/quote\][\s]*\[quote\]=i', "\n", $message);
358 $message = preg_replace('=\[quote\]\s*=i', "[quote]", $message);
359 $message = preg_replace('=\s*\[/quote\]=i', "[/quote]", $message);
362 $oldmessage = $message;
363 $message = str_replace("\n \n", "\n\n", $message);
364 } while ($oldmessage != $message);
367 $oldmessage = $message;
368 $message = str_replace("\n\n\n", "\n\n", $message);
369 } while ($oldmessage != $message);
372 $oldmessage = $message;
373 $message = str_replace(
396 } while ($message != $oldmessage);
398 $message = str_replace(
399 ['[b][b]', '[/b][/b]', '[i][i]', '[/i][/i]'],
400 ['[b]', '[/b]', '[i]', '[/i]'],
404 // Handling Yahoo style of mails
405 $message = str_replace('[hr][b]From:[/b]', '[quote][b]From:[/b]', $message);
407 // Restore code blocks
408 $message = preg_replace_callback(
409 '#\[codeblock-([0-9]+)\]#iU',
410 function ($matches) use ($codeblocks) {
412 if (isset($codeblocks[intval($matches[1])])) {
413 $return = $codeblocks[$matches[1]];
420 $message = trim($message);
422 if ($basepath != '') {
423 $message = self::qualifyURLs($message, $basepath);
430 * Sub function to complete incomplete URL
432 * @param array $matches Result of preg_replace_callback
433 * @param string $basepath Basepath that is used to complete the URL
435 * @return string The expanded URL
437 private static function qualifyURLsSub($matches, $basepath)
439 $base = parse_url($basepath);
440 unset($base['query']);
441 unset($base['fragment']);
446 if (empty($url) || empty(parse_url($url))) {
450 $parts = array_merge($base, parse_url($url));
451 $url2 = Network::unparseURL($parts);
453 return str_replace($url, $url2, $link);
457 * Complete incomplete URLs in BBCode
459 * @param string $body Body with URLs
460 * @param string $basepath Base path that is used to complete the URL
462 * @return string Body with expanded URLs
464 private static function qualifyURLs($body, $basepath)
466 $URLSearchString = "^\[\]";
468 $matches = ["/\[url\=([$URLSearchString]*)\].*?\[\/url\]/ism",
469 "/\[url\]([$URLSearchString]*)\[\/url\]/ism",
470 "/\[img\=[0-9]*x[0-9]*\](.*?)\[\/img\]/ism",
471 "/\[img\](.*?)\[\/img\]/ism",
472 "/\[zmg\=[0-9]*x[0-9]*\](.*?)\[\/img\]/ism",
473 "/\[zmg\](.*?)\[\/zmg\]/ism",
474 "/\[video\](.*?)\[\/video\]/ism",
475 "/\[audio\](.*?)\[\/audio\]/ism",
478 foreach ($matches as $match) {
479 $body = preg_replace_callback(
481 function ($match) use ($basepath) {
482 return self::qualifyURLsSub($match, $basepath);
490 private static function breakLines($line, $level, $wraplength = 75)
492 if ($wraplength == 0) {
493 $wraplength = 2000000;
496 $wraplen = $wraplength - $level;
503 $subline = substr($line, 0, $wraplen);
505 $pos = strrpos($subline, ' ');
508 $pos = strpos($line, ' ');
511 if (($pos > 0) && strlen($line) > $wraplen) {
512 $newline = trim(substr($line, 0, $pos));
514 $newline = str_repeat(">", $level) . ' ' . $newline;
517 $newlines[] = $newline . " ";
518 $line = substr($line, $pos + 1);
520 } while ((strlen($line) > $wraplen) && !($oldline == $line));
523 $line = str_repeat(">", $level) . ' ' . $line;
528 return implode("\n", $newlines);
531 private static function quoteLevel($message, $wraplength = 75)
533 $lines = explode("\n", $message);
537 foreach ($lines as $line) {
540 while (strpos("*" . $line, '[quote]') > 0) {
542 $pos = strpos($line, '[quote]');
543 $line = substr($line, 0, $pos) . substr($line, $pos + 7);
549 while (strpos("*" . $line, '[/quote]') > 0) {
555 $pos = strpos($line, '[/quote]');
556 $line = substr($line, 0, $pos) . substr($line, $pos + 8);
559 if (!$startquote || ($line != '')) {
560 $newlines[] = self::breakLines($line, $currlevel, $wraplength);
564 return implode("\n", $newlines);
567 private static function collectURLs($message)
569 $pattern = '/<a.*?href="(.*?)".*?>(.*?)<\/a>/is';
570 preg_match_all($pattern, $message, $result, PREG_SET_ORDER);
573 foreach ($result as $treffer) {
576 // A list of some links that should be ignored
577 $list = ["/user/", "/tag/", "/group/", "/profile/", "/search?search=", "/search?tag=", "mailto:", "/u/", "/node/",
578 "//plus.google.com/", "//twitter.com/"];
579 foreach ($list as $listitem) {
580 if (strpos($treffer[1], $listitem) !== false) {
585 if ((strpos($treffer[1], "//twitter.com/") !== false) && (strpos($treffer[1], "/status/") !== false)) {
589 if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/posts") !== false)) {
593 if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/photos") !== false)) {
597 $ignore = $ignore || strpos($treffer[1], '#') === 0;
600 $urls[$treffer[1]] = $treffer[1];
608 * @param string $html
609 * @param int $wraplength Ensures individual lines aren't longer than this many characters. Doesn't break words.
610 * @param bool $compact True: Completely strips image tags; False: Keeps image URLs
613 public static function toPlaintext(string $html, $wraplength = 75, $compact = false)
615 $message = str_replace("\r", "", $html);
617 $doc = new DOMDocument();
618 $doc->preserveWhiteSpace = false;
620 $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8");
622 @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
624 $message = $doc->saveHTML();
625 // Remove eventual UTF-8 BOM
626 $message = str_replace("\xC3\x82\xC2\xA0", "", $message);
628 // Collecting all links
629 $urls = self::collectURLs($message);
631 @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
633 self::tagToBBCode($doc, 'html', [], '', '');
634 self::tagToBBCode($doc, 'body', [], '', '');
637 self::tagToBBCode($doc, 'blockquote', [], "»", "«");
639 self::tagToBBCode($doc, 'blockquote', [], '[quote]', "[/quote]\n");
642 self::tagToBBCode($doc, 'br', [], "\n", '');
644 self::tagToBBCode($doc, 'span', [], "", "");
645 self::tagToBBCode($doc, 'pre', [], "", "");
646 self::tagToBBCode($doc, 'div', [], "\r", "\r");
647 self::tagToBBCode($doc, 'p', [], "\n", "\n");
649 self::tagToBBCode($doc, 'li', [], "\n* ", "\n");
651 self::tagToBBCode($doc, 'hr', [], "\n" . str_repeat("-", 70) . "\n", "");
653 self::tagToBBCode($doc, 'tr', [], "\n", "");
654 self::tagToBBCode($doc, 'td', [], "\t", "");
656 self::tagToBBCode($doc, 'h1', [], "\n\n*", "*\n");
657 self::tagToBBCode($doc, 'h2', [], "\n\n*", "*\n");
658 self::tagToBBCode($doc, 'h3', [], "\n\n*", "*\n");
659 self::tagToBBCode($doc, 'h4', [], "\n\n*", "*\n");
660 self::tagToBBCode($doc, 'h5', [], "\n\n*", "*\n");
661 self::tagToBBCode($doc, 'h6', [], "\n\n*", "*\n");
664 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], ' [img]$1', '[/img] ');
666 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], ' ', ' ');
669 self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], ' $1 ', '');
671 $message = $doc->saveHTML();
674 $message = str_replace("[img]", "", $message);
675 $message = str_replace("[/img]", "", $message);
678 // was ersetze ich da?
679 // Irgendein stoerrisches UTF-Zeug
680 $message = str_replace(chr(194) . chr(160), ' ', $message);
682 $message = str_replace(" ", " ", $message);
684 // Aufeinanderfolgende DIVs
685 $message = preg_replace('=\r *\r=i', "\n", $message);
686 $message = str_replace("\r", "\n", $message);
688 $message = strip_tags($message);
690 $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
692 if (!$compact && ($message != '')) {
693 foreach ($urls as $id => $url) {
694 if ($url != '' && strpos($message, $url) === false) {
695 $message .= "\n" . $url . ' ';
700 $message = str_replace("\n«", "«\n", $message);
701 $message = str_replace("»\n", "\n»", $message);
704 $oldmessage = $message;
705 $message = str_replace("\n\n\n", "\n\n", $message);
706 } while ($oldmessage != $message);
708 $message = self::quoteLevel(trim($message), $wraplength);
710 return trim($message);
714 * Converts provided HTML code to Markdown. The hardwrap parameter maximizes
715 * compatibility with Diaspora in spite of the Markdown standards.
717 * @param string $html
720 public static function toMarkdown($html)
722 $converter = new HtmlConverter(['hard_break' => true]);
723 $markdown = $converter->convert($html);
729 * Convert video HTML to BBCode tags
734 public static function toBBCodeVideo($s)
737 '#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
738 '[youtube]$2[/youtube]',
743 '#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
744 '[youtube]$2[/youtube]',
749 '#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
758 * transform link href and img src from relative to absolute
760 * @param string $text
761 * @param string $base base url
764 public static function relToAbs($text, $base)
770 $base = rtrim($base, '/');
772 $base2 = $base . "/";
775 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
776 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
777 $text = preg_replace($pattern, $replace, $text);
779 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
780 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
781 $text = preg_replace($pattern, $replace, $text);
784 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
785 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
786 $text = preg_replace($pattern, $replace, $text);
788 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
789 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
790 $text = preg_replace($pattern, $replace, $text);
798 * return div element with class 'clear'
802 public static function clearDiv()
804 return '<div class="clear"></div>';
808 * Loader for infinite scrolling
810 * @return string html for loader
811 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
813 public static function scrollLoader()
815 $tpl = Renderer::getMarkupTemplate("scroll_loader.tpl");
816 return Renderer::replaceMacros($tpl, [
817 'wait' => DI::l10n()->t('Loading more entries...'),
818 'end' => DI::l10n()->t('The end')
823 * Get html for contact block.
825 * @deprecated since version 2019.03
826 * @see ContactBlock::getHTML()
828 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
829 * @throws \ImagickException
831 public static function contactBlock()
835 return ContactBlock::getHTML($a->profile);
839 * Format contacts as picture links or as text links
841 * @param array $contact Array with contacts which contains an array with
842 * int 'id' => The ID of the contact
843 * int 'uid' => The user ID of the user who owns this data
844 * string 'name' => The name of the contact
845 * string 'url' => The url to the profile page of the contact
846 * string 'addr' => The webbie of the contact (e.g.) username@friendica.com
847 * string 'network' => The network to which the contact belongs to
848 * string 'thumb' => The contact picture
849 * string 'click' => js code which is performed when clicking on the contact
850 * @param boolean $redirect If true try to use the redir url if it's possible
851 * @param string $class CSS class for the
852 * @param boolean $textmode If true display the contacts as text links
853 * if false display the contacts as picture links
854 * @return string Formatted html
855 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
856 * @throws \ImagickException
858 public static function micropro($contact, $redirect = false, $class = '', $textmode = false)
860 // Use the contact URL if no address is available
861 if (empty($contact['addr'])) {
862 $contact["addr"] = $contact["url"];
865 $url = $contact['url'];
870 $url = Contact::magicLink($contact['url']);
871 if (strpos($url, 'redir/') === 0) {
872 $sparkle = ' sparkle';
876 // If there is some js available we don't need the url
877 if (!empty($contact['click'])) {
881 return Renderer::replaceMacros(Renderer::getMarkupTemplate($textmode ? 'micropro_txt.tpl' : 'micropro_img.tpl'), [
882 '$click' => $contact['click'] ?? '',
885 '$photo' => ProxyUtils::proxifyUrl($contact['thumb'], false, ProxyUtils::SIZE_THUMB),
886 '$name' => $contact['name'],
887 'title' => $contact['name'] . ' [' . $contact['addr'] . ']',
888 '$parkle' => $sparkle,
896 * @param string $s Search query.
897 * @param string $id HTML id
898 * @param string $url Search url.
899 * @param bool $aside Display the search widgit aside.
901 * @return string Formatted HTML.
904 public static function search($s, $id = 'search-box', $aside = true)
908 if (strpos($s, '#') === 0) {
911 $save_label = $mode === 'text' ? DI::l10n()->t('Save') : DI::l10n()->t('Follow');
915 '$q' => urlencode($s),
917 '$search_label' => DI::l10n()->t('Search'),
918 '$save_label' => $save_label,
919 '$search_hint' => DI::l10n()->t('@name, !forum, #tags, content'),
921 '$return_url' => urlencode(Search::getSearchPath($s)),
925 $values['$search_options'] = [
926 'fulltext' => DI::l10n()->t('Full Text'),
927 'tags' => DI::l10n()->t('Tags'),
928 'contacts' => DI::l10n()->t('Contacts')
931 if (DI::config()->get('system', 'poco_local_search')) {
932 $values['$searchoption']['forums'] = DI::l10n()->t('Forums');
936 return Renderer::replaceMacros(Renderer::getMarkupTemplate('searchbox.tpl'), $values);
940 * Replace naked text hyperlink with HTML formatted hyperlink
945 public static function toLink($s)
947 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank" rel="noopener noreferrer">$1</a>', $s);
948 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism", '<$1$2=$3&$4>', $s);
953 * Given a HTML text and a set of filtering reasons, adds a content hiding header with the provided reasons
955 * Reasons are expected to have been translated already.
957 * @param string $html
958 * @param array $reasons
960 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
962 public static function applyContentFilter($html, array $reasons)
964 if (count($reasons)) {
965 $tpl = Renderer::getMarkupTemplate('wall/content_filter.tpl');
966 $html = Renderer::replaceMacros($tpl, [
967 '$reasons' => $reasons,
968 '$rnd' => Strings::getRandomHex(8),
969 '$openclose' => DI::l10n()->t('Click to open/close'),
978 * replace html amp entity with amp char
982 public static function unamp($s)
984 return str_replace('&', '&', $s);