3 * @file src/Content/Text/HTML.php
6 namespace Friendica\Content\Text;
10 use Friendica\Content\Widget\ContactBlock;
11 use Friendica\Core\Hook;
12 use Friendica\Core\L10n;
13 use Friendica\Core\Config;
14 use Friendica\Core\Renderer;
16 use Friendica\Model\Contact;
17 use Friendica\Util\Network;
18 use Friendica\Util\Proxy as ProxyUtils;
19 use Friendica\Util\Strings;
20 use Friendica\Util\XML;
21 use League\HTMLToMarkdown\HtmlConverter;
25 public static function sanitizeCSS($input)
29 $input = strtolower($input);
31 for ($i = 0; $i < strlen($input); $i++) {
32 $char = substr($input, $i, 1);
34 if (($char >= "a") && ($char <= "z")) {
38 if (!(strpos(" #;:0123456789-_.%", $char) === false)) {
47 * Search all instances of a specific HTML tag node in the provided DOM document and replaces them with BBCode text nodes.
49 * @see HTML::tagToBBCodeSub()
51 private static function tagToBBCode(DOMDocument $doc, string $tag, array $attributes, string $startbb, string $endbb, bool $ignoreChildren = false)
54 $done = self::tagToBBCodeSub($doc, $tag, $attributes, $startbb, $endbb, $ignoreChildren);
59 * Search the first specific HTML tag node in the provided DOM document and replaces it with BBCode text nodes.
61 * @param DOMDocument $doc
62 * @param string $tag HTML tag name
63 * @param array $attributes Array of attributes to match and optionally use the value from
64 * @param string $startbb BBCode tag opening
65 * @param string $endbb BBCode tag closing
66 * @param bool $ignoreChildren If set to false, the HTML tag children will be appended as text inside the BBCode tag
67 * Otherwise, they will be entirely ignored. Useful for simple BBCode that draw their
68 * inner value from an attribute value and disregard the tag children.
69 * @return bool Whether a replacement was done
71 private static function tagToBBCodeSub(DOMDocument $doc, string $tag, array $attributes, string $startbb, string $endbb, bool $ignoreChildren = false)
73 $savestart = str_replace('$', '\x01', $startbb);
76 $xpath = new DOMXPath($doc);
78 /** @var \DOMNode[] $list */
79 $list = $xpath->query("//" . $tag);
80 foreach ($list as $node) {
82 if ($node->attributes->length) {
83 foreach ($node->attributes as $attribute) {
84 $attr[$attribute->name] = $attribute->value;
90 $startbb = $savestart;
94 foreach ($attributes as $attribute => $value) {
95 $startbb = str_replace('\x01' . ++$i, '$1', $startbb);
96 if (strpos('*' . $startbb, '$1') > 0) {
97 if ($replace && (@$attr[$attribute] != '')) {
98 $startbb = preg_replace($value, $startbb, $attr[$attribute], -1, $count);
100 // If nothing could be changed
108 if (@$attr[$attribute] != $value) {
115 $StartCode = $doc->createTextNode($startbb);
116 $EndCode = $doc->createTextNode($endbb);
118 $node->parentNode->insertBefore($StartCode, $node);
120 if (!$ignoreChildren && $node->hasChildNodes()) {
121 /** @var \DOMNode $child */
122 foreach ($node->childNodes as $key => $child) {
123 /* Remove empty text nodes at the start or at the end of the children list */
124 if ($key > 0 && $key < $node->childNodes->length - 1 || $child->nodeName != '#text' || trim($child->nodeValue)) {
125 $newNode = $child->cloneNode(true);
126 $node->parentNode->insertBefore($newNode, $node);
131 $node->parentNode->insertBefore($EndCode, $node);
132 $node->parentNode->removeChild($node);
140 * Made by: ike@piratenpartei.de
141 * Originally made for the syncom project: http://wiki.piratenpartei.de/Syncom
142 * https://github.com/annando/Syncom
144 * @brief Converter for HTML to BBCode
145 * @param string $message
146 * @param string $basepath
148 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
150 public static function toBBCode($message, $basepath = '')
152 $message = str_replace("\r", "", $message);
154 // Removing code blocks before the whitespace removal processing below
156 $message = preg_replace_callback(
157 '#<pre><code(?: class="language-([^"]*)")?>(.*)</code></pre>#iUs',
158 function ($matches) use (&$codeblocks) {
159 $return = '[codeblock-' . count($codeblocks) . ']';
162 if ($matches[1] != '') {
163 $prefix = '[code=' . $matches[1] . ']';
166 $codeblocks[] = $prefix . PHP_EOL . trim($matches[2]) . PHP_EOL . '[/code]';
172 $message = str_replace(
185 $message = preg_replace('=<(\w+):(.+?)>=', '<removeme>', $message);
186 $message = preg_replace('=</(\w+):(.+?)>=', '</removeme>', $message);
188 $doc = new DOMDocument();
189 $doc->preserveWhiteSpace = false;
191 $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8");
193 @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
195 XML::deleteNode($doc, 'style');
196 XML::deleteNode($doc, 'head');
197 XML::deleteNode($doc, 'title');
198 XML::deleteNode($doc, 'meta');
199 XML::deleteNode($doc, 'xml');
200 XML::deleteNode($doc, 'removeme');
202 $xpath = new DomXPath($doc);
203 $list = $xpath->query("//pre");
204 foreach ($list as $node) {
205 // Ensure to escape unescaped & - they will otherwise raise a warning
206 $safe_value = preg_replace('/&(?!\w+;)/', '&', $node->nodeValue);
207 $node->nodeValue = str_replace("\n", "\r", $safe_value);
210 $message = $doc->saveHTML();
211 $message = str_replace(["\n<", ">\n", "\r", "\n", "\xC3\x82\xC2\xA0"], ["<", ">", "<br />", " ", ""], $message);
212 $message = preg_replace('= [\s]*=i', " ", $message);
214 @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
216 self::tagToBBCode($doc, 'html', [], "", "");
217 self::tagToBBCode($doc, 'body', [], "", "");
219 // Outlook-Quote - Variant 1
220 self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal', 'style' => 'margin-left:35.4pt'], '[quote]', '[/quote]');
222 // Outlook-Quote - Variant 2
226 ['style' => 'border:none;border-left:solid blue 1.5pt;padding:0cm 0cm 0cm 4.0pt'],
232 self::tagToBBCode($doc, 'span', ['style' => 'text-decoration: underline;'], '[u]', '[/u]');
233 self::tagToBBCode($doc, 'span', ['style' => 'font-style: italic;'], '[i]', '[/i]');
234 self::tagToBBCode($doc, 'span', ['style' => 'font-weight: bold;'], '[b]', '[/b]');
236 /* self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[font=$1][size=$2][color=$3]', '[/color][/size][/font]');
237 self::node2BBCode($doc, 'font', array('size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[size=$1][color=$2]', '[/color][/size]');
238 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(.+)/'), '[font=$1][size=$2]', '[/size][/font]');
239 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'color'=>'/(.+)/'), '[font=$1][color=$3]', '[/color][/font]');
240 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/'), '[font=$1]', '[/font]');
241 self::node2BBCode($doc, 'font', array('size'=>'/(\d+)/'), '[size=$1]', '[/size]');
242 self::node2BBCode($doc, 'font', array('color'=>'/(.+)/'), '[color=$1]', '[/color]');
245 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*font-family:\s*(.+?)[,;].*color:\s*(.+?)[,;].*/'), '[size=$1][font=$2][color=$3]', '[/color][/font][/size]');
246 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(\d+)[,;].*/'), '[size=$1]', '[/size]');
247 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*/'), '[size=$1]', '[/size]');
249 self::tagToBBCode($doc, 'span', ['style' => '/.*color:\s*(.+?)[,;].*/'], '[color="$1"]', '[/color]');
251 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
252 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)pt.*/'), '[font=$1][size=$2]', '[/size][/font]');
253 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)px.*/'), '[font=$1][size=$2]', '[/size][/font]');
254 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
255 // Importing the classes - interesting for importing of posts from third party networks that were exported from friendica
257 //self::node2BBCode($doc, 'span', array('class'=>'/([\w ]+)/'), '[class=$1]', '[/class]');
258 self::tagToBBCode($doc, 'span', ['class' => 'type-link'], '[class=type-link]', '[/class]');
259 self::tagToBBCode($doc, 'span', ['class' => 'type-video'], '[class=type-video]', '[/class]');
261 self::tagToBBCode($doc, 'strong', [], '[b]', '[/b]');
262 self::tagToBBCode($doc, 'em', [], '[i]', '[/i]');
263 self::tagToBBCode($doc, 'b', [], '[b]', '[/b]');
264 self::tagToBBCode($doc, 'i', [], '[i]', '[/i]');
265 self::tagToBBCode($doc, 'u', [], '[u]', '[/u]');
266 self::tagToBBCode($doc, 's', [], '[s]', '[/s]');
267 self::tagToBBCode($doc, 'del', [], '[s]', '[/s]');
268 self::tagToBBCode($doc, 'strike', [], '[s]', '[/s]');
270 self::tagToBBCode($doc, 'big', [], "[size=large]", "[/size]");
271 self::tagToBBCode($doc, 'small', [], "[size=small]", "[/size]");
273 self::tagToBBCode($doc, 'blockquote', [], '[quote]', '[/quote]');
275 self::tagToBBCode($doc, 'br', [], "\n", '');
277 self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal'], "\n", "");
278 self::tagToBBCode($doc, 'div', ['class' => 'MsoNormal'], "\r", "");
280 self::tagToBBCode($doc, 'span', [], "", "");
282 self::tagToBBCode($doc, 'span', [], "", "");
283 self::tagToBBCode($doc, 'pre', [], "", "");
285 self::tagToBBCode($doc, 'div', [], "\r", "\r");
286 self::tagToBBCode($doc, 'p', [], "\n", "\n");
288 self::tagToBBCode($doc, 'ul', [], "[list]", "[/list]");
289 self::tagToBBCode($doc, 'ol', [], "[list=1]", "[/list]");
290 self::tagToBBCode($doc, 'li', [], "[*]", "");
292 self::tagToBBCode($doc, 'hr', [], "[hr]", "");
294 self::tagToBBCode($doc, 'table', [], "[table]", "[/table]");
295 self::tagToBBCode($doc, 'th', [], "[th]", "[/th]");
296 self::tagToBBCode($doc, 'tr', [], "[tr]", "[/tr]");
297 self::tagToBBCode($doc, 'td', [], "[td]", "[/td]");
299 self::tagToBBCode($doc, 'h1', [], "[h1]", "[/h1]");
300 self::tagToBBCode($doc, 'h2', [], "[h2]", "[/h2]");
301 self::tagToBBCode($doc, 'h3', [], "[h3]", "[/h3]");
302 self::tagToBBCode($doc, 'h4', [], "[h4]", "[/h4]");
303 self::tagToBBCode($doc, 'h5', [], "[h5]", "[/h5]");
304 self::tagToBBCode($doc, 'h6', [], "[h6]", "[/h6]");
306 self::tagToBBCode($doc, 'a', ['href' => '/mailto:(.+)/'], '[mail=$1]', '[/mail]');
307 self::tagToBBCode($doc, 'a', ['href' => '/(.+)/'], '[url=$1]', '[/url]');
309 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/', 'alt' => '/(.+)/'], '[img=$1]$2', '[/img]', true);
310 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/', 'width' => '/(\d+)/', 'height' => '/(\d+)/'], '[img=$2x$3]$1', '[/img]', true);
311 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], '[img]$1', '[/img]', true);
314 self::tagToBBCode($doc, 'video', ['src' => '/(.+)/'], '[video]$1', '[/video]', true);
315 self::tagToBBCode($doc, 'audio', ['src' => '/(.+)/'], '[audio]$1', '[/audio]', true);
316 self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], '[iframe]$1', '[/iframe]', true);
318 self::tagToBBCode($doc, 'key', [], '[code]', '[/code]');
319 self::tagToBBCode($doc, 'code', [], '[code]', '[/code]');
321 $message = $doc->saveHTML();
323 // I'm removing something really disturbing
324 // Don't know exactly what it is
325 $message = str_replace(chr(194) . chr(160), ' ', $message);
327 $message = str_replace(" ", " ", $message);
329 // removing multiple DIVs
330 $message = preg_replace('=\r *\r=i', "\n", $message);
331 $message = str_replace("\r", "\n", $message);
333 Hook::callAll('html2bbcode', $message);
335 $message = strip_tags($message);
337 $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
339 $message = str_replace(["<"], ["<"], $message);
341 // remove quotes if they don't make sense
342 $message = preg_replace('=\[/quote\][\s]*\[quote\]=i', "\n", $message);
344 $message = preg_replace('=\[quote\]\s*=i', "[quote]", $message);
345 $message = preg_replace('=\s*\[/quote\]=i', "[/quote]", $message);
348 $oldmessage = $message;
349 $message = str_replace("\n \n", "\n\n", $message);
350 } while ($oldmessage != $message);
353 $oldmessage = $message;
354 $message = str_replace("\n\n\n", "\n\n", $message);
355 } while ($oldmessage != $message);
358 $oldmessage = $message;
359 $message = str_replace(
382 } while ($message != $oldmessage);
384 $message = str_replace(
385 ['[b][b]', '[/b][/b]', '[i][i]', '[/i][/i]'],
386 ['[b]', '[/b]', '[i]', '[/i]'],
390 // Handling Yahoo style of mails
391 $message = str_replace('[hr][b]From:[/b]', '[quote][b]From:[/b]', $message);
393 // Restore code blocks
394 $message = preg_replace_callback(
395 '#\[codeblock-([0-9]+)\]#iU',
396 function ($matches) use ($codeblocks) {
398 if (isset($codeblocks[intval($matches[1])])) {
399 $return = $codeblocks[$matches[1]];
406 $message = trim($message);
408 if ($basepath != '') {
409 $message = self::qualifyURLs($message, $basepath);
416 * @brief Sub function to complete incomplete URL
418 * @param array $matches Result of preg_replace_callback
419 * @param string $basepath Basepath that is used to complete the URL
421 * @return string The expanded URL
423 private static function qualifyURLsSub($matches, $basepath)
425 $base = parse_url($basepath);
426 unset($base['query']);
427 unset($base['fragment']);
432 if (empty($url) || empty(parse_url($url))) {
436 $parts = array_merge($base, parse_url($url));
437 $url2 = Network::unparseURL($parts);
439 return str_replace($url, $url2, $link);
443 * @brief Complete incomplete URLs in BBCode
445 * @param string $body Body with URLs
446 * @param string $basepath Base path that is used to complete the URL
448 * @return string Body with expanded URLs
450 private static function qualifyURLs($body, $basepath)
452 $URLSearchString = "^\[\]";
454 $matches = ["/\[url\=([$URLSearchString]*)\].*?\[\/url\]/ism",
455 "/\[url\]([$URLSearchString]*)\[\/url\]/ism",
456 "/\[img\=[0-9]*x[0-9]*\](.*?)\[\/img\]/ism",
457 "/\[img\](.*?)\[\/img\]/ism",
458 "/\[zmg\=[0-9]*x[0-9]*\](.*?)\[\/img\]/ism",
459 "/\[zmg\](.*?)\[\/zmg\]/ism",
460 "/\[video\](.*?)\[\/video\]/ism",
461 "/\[audio\](.*?)\[\/audio\]/ism",
464 foreach ($matches as $match) {
465 $body = preg_replace_callback(
467 function ($match) use ($basepath) {
468 return self::qualifyURLsSub($match, $basepath);
476 private static function breakLines($line, $level, $wraplength = 75)
478 if ($wraplength == 0) {
479 $wraplength = 2000000;
482 $wraplen = $wraplength - $level;
489 $subline = substr($line, 0, $wraplen);
491 $pos = strrpos($subline, ' ');
494 $pos = strpos($line, ' ');
497 if (($pos > 0) && strlen($line) > $wraplen) {
498 $newline = trim(substr($line, 0, $pos));
500 $newline = str_repeat(">", $level) . ' ' . $newline;
503 $newlines[] = $newline . " ";
504 $line = substr($line, $pos + 1);
506 } while ((strlen($line) > $wraplen) && !($oldline == $line));
509 $line = str_repeat(">", $level) . ' ' . $line;
514 return implode($newlines, "\n");
517 private static function quoteLevel($message, $wraplength = 75)
519 $lines = explode("\n", $message);
523 foreach ($lines as $line) {
526 while (strpos("*" . $line, '[quote]') > 0) {
528 $pos = strpos($line, '[quote]');
529 $line = substr($line, 0, $pos) . substr($line, $pos + 7);
535 while (strpos("*" . $line, '[/quote]') > 0) {
541 $pos = strpos($line, '[/quote]');
542 $line = substr($line, 0, $pos) . substr($line, $pos + 8);
545 if (!$startquote || ($line != '')) {
546 $newlines[] = self::breakLines($line, $currlevel, $wraplength);
550 return implode($newlines, "\n");
553 private static function collectURLs($message)
555 $pattern = '/<a.*?href="(.*?)".*?>(.*?)<\/a>/is';
556 preg_match_all($pattern, $message, $result, PREG_SET_ORDER);
559 foreach ($result as $treffer) {
562 // A list of some links that should be ignored
563 $list = ["/user/", "/tag/", "/group/", "/profile/", "/search?search=", "/search?tag=", "mailto:", "/u/", "/node/",
564 "//plus.google.com/", "//twitter.com/"];
565 foreach ($list as $listitem) {
566 if (strpos($treffer[1], $listitem) !== false) {
571 if ((strpos($treffer[1], "//twitter.com/") !== false) && (strpos($treffer[1], "/status/") !== false)) {
575 if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/posts") !== false)) {
579 if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/photos") !== false)) {
583 $ignore = $ignore || strpos($treffer[1], '#') === 0;
586 $urls[$treffer[1]] = $treffer[1];
594 * @param string $html
595 * @param int $wraplength Ensures individual lines aren't longer than this many characters. Doesn't break words.
596 * @param bool $compact True: Completely strips image tags; False: Keeps image URLs
599 public static function toPlaintext(string $html, $wraplength = 75, $compact = false)
601 $message = str_replace("\r", "", $html);
603 $doc = new DOMDocument();
604 $doc->preserveWhiteSpace = false;
606 $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8");
608 @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
610 $message = $doc->saveHTML();
611 // Remove eventual UTF-8 BOM
612 $message = str_replace("\xC3\x82\xC2\xA0", "", $message);
614 // Collecting all links
615 $urls = self::collectURLs($message);
617 @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
619 self::tagToBBCode($doc, 'html', [], '', '');
620 self::tagToBBCode($doc, 'body', [], '', '');
623 self::tagToBBCode($doc, 'blockquote', [], "»", "«");
625 self::tagToBBCode($doc, 'blockquote', [], '[quote]', "[/quote]\n");
628 self::tagToBBCode($doc, 'br', [], "\n", '');
630 self::tagToBBCode($doc, 'span', [], "", "");
631 self::tagToBBCode($doc, 'pre', [], "", "");
632 self::tagToBBCode($doc, 'div', [], "\r", "\r");
633 self::tagToBBCode($doc, 'p', [], "\n", "\n");
635 self::tagToBBCode($doc, 'li', [], "\n* ", "\n");
637 self::tagToBBCode($doc, 'hr', [], "\n" . str_repeat("-", 70) . "\n", "");
639 self::tagToBBCode($doc, 'tr', [], "\n", "");
640 self::tagToBBCode($doc, 'td', [], "\t", "");
642 self::tagToBBCode($doc, 'h1', [], "\n\n*", "*\n");
643 self::tagToBBCode($doc, 'h2', [], "\n\n*", "*\n");
644 self::tagToBBCode($doc, 'h3', [], "\n\n*", "*\n");
645 self::tagToBBCode($doc, 'h4', [], "\n\n*", "*\n");
646 self::tagToBBCode($doc, 'h5', [], "\n\n*", "*\n");
647 self::tagToBBCode($doc, 'h6', [], "\n\n*", "*\n");
650 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], ' [img]$1', '[/img] ');
652 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], ' ', ' ');
655 self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], ' $1 ', '');
657 $message = $doc->saveHTML();
660 $message = str_replace("[img]", "", $message);
661 $message = str_replace("[/img]", "", $message);
664 // was ersetze ich da?
665 // Irgendein stoerrisches UTF-Zeug
666 $message = str_replace(chr(194) . chr(160), ' ', $message);
668 $message = str_replace(" ", " ", $message);
670 // Aufeinanderfolgende DIVs
671 $message = preg_replace('=\r *\r=i', "\n", $message);
672 $message = str_replace("\r", "\n", $message);
674 $message = strip_tags($message);
676 $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
678 if (!$compact && ($message != '')) {
679 foreach ($urls as $id => $url) {
680 if ($url != '' && strpos($message, $url) === false) {
681 $message .= "\n" . $url . ' ';
686 $message = str_replace("\n«", "«\n", $message);
687 $message = str_replace("»\n", "\n»", $message);
690 $oldmessage = $message;
691 $message = str_replace("\n\n\n", "\n\n", $message);
692 } while ($oldmessage != $message);
694 $message = self::quoteLevel(trim($message), $wraplength);
696 return trim($message);
700 * Converts provided HTML code to Markdown. The hardwrap parameter maximizes
701 * compatibility with Diaspora in spite of the Markdown standards.
703 * @param string $html
706 public static function toMarkdown($html)
708 $converter = new HtmlConverter(['hard_break' => true]);
709 $markdown = $converter->convert($html);
715 * @brief Convert video HTML to BBCode tags
720 public static function toBBCodeVideo($s)
723 '#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
724 '[youtube]$2[/youtube]',
729 '#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
730 '[youtube]$2[/youtube]',
735 '#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
744 * transform link href and img src from relative to absolute
746 * @param string $text
747 * @param string $base base url
750 public static function relToAbs($text, $base)
756 $base = rtrim($base, '/');
758 $base2 = $base . "/";
761 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
762 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
763 $text = preg_replace($pattern, $replace, $text);
765 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
766 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
767 $text = preg_replace($pattern, $replace, $text);
770 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
771 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
772 $text = preg_replace($pattern, $replace, $text);
774 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
775 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
776 $text = preg_replace($pattern, $replace, $text);
784 * return div element with class 'clear'
788 public static function clearDiv()
790 return '<div class="clear"></div>';
794 * Loader for infinite scrolling
796 * @return string html for loader
797 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
799 public static function scrollLoader()
801 $tpl = Renderer::getMarkupTemplate("scroll_loader.tpl");
802 return Renderer::replaceMacros($tpl, [
803 'wait' => L10n::t('Loading more entries...'),
804 'end' => L10n::t('The end')
809 * Get html for contact block.
811 * @deprecated since version 2019.03
812 * @see ContactBlock::getHTML()
814 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
815 * @throws \ImagickException
817 public static function contactBlock()
821 return ContactBlock::getHTML($a->profile);
825 * @brief Format contacts as picture links or as text links
827 * @param array $contact Array with contacts which contains an array with
828 * int 'id' => The ID of the contact
829 * int 'uid' => The user ID of the user who owns this data
830 * string 'name' => The name of the contact
831 * string 'url' => The url to the profile page of the contact
832 * string 'addr' => The webbie of the contact (e.g.) username@friendica.com
833 * string 'network' => The network to which the contact belongs to
834 * string 'thumb' => The contact picture
835 * string 'click' => js code which is performed when clicking on the contact
836 * @param boolean $redirect If true try to use the redir url if it's possible
837 * @param string $class CSS class for the
838 * @param boolean $textmode If true display the contacts as text links
839 * if false display the contacts as picture links
840 * @return string Formatted html
841 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
842 * @throws \ImagickException
844 public static function micropro($contact, $redirect = false, $class = '', $textmode = false)
846 // Use the contact URL if no address is available
847 if (empty($contact['addr'])) {
848 $contact["addr"] = $contact["url"];
851 $url = $contact['url'];
856 $url = Contact::magicLink($contact['url']);
857 if (strpos($url, 'redir/') === 0) {
858 $sparkle = ' sparkle';
862 // If there is some js available we don't need the url
863 if (!empty($contact['click'])) {
867 return Renderer::replaceMacros(Renderer::getMarkupTemplate($textmode ? 'micropro_txt.tpl' : 'micropro_img.tpl'), [
868 '$click' => $contact['click'] ?? '',
871 '$photo' => ProxyUtils::proxifyUrl($contact['thumb'], false, ProxyUtils::SIZE_THUMB),
872 '$name' => $contact['name'],
873 'title' => $contact['name'] . ' [' . $contact['addr'] . ']',
874 '$parkle' => $sparkle,
882 * @param string $s Search query.
883 * @param string $id HTML id
884 * @param string $url Search url.
885 * @param bool $aside Display the search widgit aside.
887 * @return string Formatted HTML.
890 public static function search($s, $id = 'search-box', $aside = true)
894 if (strpos($s, '#') === 0) {
897 $save_label = $mode === 'text' ? L10n::t('Save') : L10n::t('Follow');
901 '$q' => urlencode($s),
903 '$search_label' => L10n::t('Search'),
904 '$save_label' => $save_label,
905 '$search_hint' => L10n::t('@name, !forum, #tags, content'),
907 '$return_url' => urlencode('search?q=' . urlencode($s)),
911 $values['$search_options'] = [
912 'fulltext' => L10n::t('Full Text'),
913 'tags' => L10n::t('Tags'),
914 'contacts' => L10n::t('Contacts')
917 if (Config::get('system', 'poco_local_search')) {
918 $values['$searchoption']['forums'] = L10n::t('Forums');
922 return Renderer::replaceMacros(Renderer::getMarkupTemplate('searchbox.tpl'), $values);
926 * Replace naked text hyperlink with HTML formatted hyperlink
931 public static function toLink($s)
933 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank">$1</a>', $s);
934 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism", '<$1$2=$3&$4>', $s);
939 * Given a HTML text and a set of filtering reasons, adds a content hiding header with the provided reasons
941 * Reasons are expected to have been translated already.
943 * @param string $html
944 * @param array $reasons
946 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
948 public static function applyContentFilter($html, array $reasons)
950 if (count($reasons)) {
951 $tpl = Renderer::getMarkupTemplate('wall/content_filter.tpl');
952 $html = Renderer::replaceMacros($tpl, [
953 '$reasons' => $reasons,
954 '$rnd' => Strings::getRandomHex(8),
955 '$openclose' => L10n::t('Click to open/close'),
964 * replace html amp entity with amp char
968 public static function unamp($s)
970 return str_replace('&', '&', $s);