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\PConfig;
15 use Friendica\Core\Protocol;
16 use Friendica\Core\Renderer;
17 use Friendica\Database\DBA;
18 use Friendica\Model\Contact;
19 use Friendica\Util\Network;
20 use Friendica\Util\Proxy as ProxyUtils;
21 use Friendica\Util\Strings;
22 use Friendica\Util\XML;
23 use League\HTMLToMarkdown\HtmlConverter;
27 public static function sanitizeCSS($input)
31 $input = strtolower($input);
33 for ($i = 0; $i < strlen($input); $i++) {
34 $char = substr($input, $i, 1);
36 if (($char >= "a") && ($char <= "z")) {
40 if (!(strpos(" #;:0123456789-_.%", $char) === false)) {
48 private static function tagToBBCode(DOMDocument $doc, $tag, $attributes, $startbb, $endbb)
51 $done = self::tagToBBCodeSub($doc, $tag, $attributes, $startbb, $endbb);
55 private static function tagToBBCodeSub(DOMDocument $doc, $tag, $attributes, $startbb, $endbb)
57 $savestart = str_replace('$', '\x01', $startbb);
60 $xpath = new DOMXPath($doc);
62 $list = $xpath->query("//" . $tag);
63 foreach ($list as $node) {
65 if ($node->attributes->length) {
66 foreach ($node->attributes as $attribute) {
67 $attr[$attribute->name] = $attribute->value;
73 $startbb = $savestart;
77 foreach ($attributes as $attribute => $value) {
78 $startbb = str_replace('\x01' . ++$i, '$1', $startbb);
79 if (strpos('*' . $startbb, '$1') > 0) {
80 if ($replace && (@$attr[$attribute] != '')) {
81 $startbb = preg_replace($value, $startbb, $attr[$attribute], -1, $count);
83 // If nothing could be changed
91 if (@$attr[$attribute] != $value) {
98 $StartCode = $doc->createTextNode($startbb);
99 $EndCode = $doc->createTextNode($endbb);
101 $node->parentNode->insertBefore($StartCode, $node);
103 if ($node->hasChildNodes()) {
104 foreach ($node->childNodes as $child) {
105 $newNode = $child->cloneNode(true);
106 $node->parentNode->insertBefore($newNode, $node);
110 $node->parentNode->insertBefore($EndCode, $node);
111 $node->parentNode->removeChild($node);
119 * Made by: ike@piratenpartei.de
120 * Originally made for the syncom project: http://wiki.piratenpartei.de/Syncom
121 * https://github.com/annando/Syncom
123 * @brief Converter for HTML to BBCode
124 * @param string $message
125 * @param string $basepath
127 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
129 public static function toBBCode($message, $basepath = '')
131 $message = str_replace("\r", "", $message);
133 // Removing code blocks before the whitespace removal processing below
135 $message = preg_replace_callback(
136 '#<pre><code(?: class="language-([^"]*)")?>(.*)</code></pre>#iUs',
137 function ($matches) use (&$codeblocks) {
138 $return = '[codeblock-' . count($codeblocks) . ']';
141 if ($matches[1] != '') {
142 $prefix = '[code=' . $matches[1] . ']';
145 $codeblocks[] = $prefix . PHP_EOL . trim($matches[2]) . PHP_EOL . '[/code]';
151 $message = str_replace(
164 $message = preg_replace('=<(\w+):(.+?)>=', '<removeme>', $message);
165 $message = preg_replace('=</(\w+):(.+?)>=', '</removeme>', $message);
167 $doc = new DOMDocument();
168 $doc->preserveWhiteSpace = false;
170 $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8");
172 @$doc->loadHTML($message);
174 XML::deleteNode($doc, 'style');
175 XML::deleteNode($doc, 'head');
176 XML::deleteNode($doc, 'title');
177 XML::deleteNode($doc, 'meta');
178 XML::deleteNode($doc, 'xml');
179 XML::deleteNode($doc, 'removeme');
181 $xpath = new DomXPath($doc);
182 $list = $xpath->query("//pre");
183 foreach ($list as $node) {
184 // Ensure to escape unescaped & - they will otherwise raise a warning
185 $safe_value = preg_replace('/&(?!\w+;)/', '&', $node->nodeValue);
186 $node->nodeValue = str_replace("\n", "\r", $safe_value);
189 $message = $doc->saveHTML();
190 $message = str_replace(["\n<", ">\n", "\r", "\n", "\xC3\x82\xC2\xA0"], ["<", ">", "<br />", " ", ""], $message);
191 $message = preg_replace('= [\s]*=i', " ", $message);
192 @$doc->loadHTML($message);
194 self::tagToBBCode($doc, 'html', [], "", "");
195 self::tagToBBCode($doc, 'body', [], "", "");
197 // Outlook-Quote - Variant 1
198 self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal', 'style' => 'margin-left:35.4pt'], '[quote]', '[/quote]');
200 // Outlook-Quote - Variant 2
204 ['style' => 'border:none;border-left:solid blue 1.5pt;padding:0cm 0cm 0cm 4.0pt'],
210 self::tagToBBCode($doc, 'span', ['style' => 'text-decoration: underline;'], '[u]', '[/u]');
211 self::tagToBBCode($doc, 'span', ['style' => 'font-style: italic;'], '[i]', '[/i]');
212 self::tagToBBCode($doc, 'span', ['style' => 'font-weight: bold;'], '[b]', '[/b]');
214 /* self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[font=$1][size=$2][color=$3]', '[/color][/size][/font]');
215 self::node2BBCode($doc, 'font', array('size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[size=$1][color=$2]', '[/color][/size]');
216 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(.+)/'), '[font=$1][size=$2]', '[/size][/font]');
217 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'color'=>'/(.+)/'), '[font=$1][color=$3]', '[/color][/font]');
218 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/'), '[font=$1]', '[/font]');
219 self::node2BBCode($doc, 'font', array('size'=>'/(\d+)/'), '[size=$1]', '[/size]');
220 self::node2BBCode($doc, 'font', array('color'=>'/(.+)/'), '[color=$1]', '[/color]');
223 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*font-family:\s*(.+?)[,;].*color:\s*(.+?)[,;].*/'), '[size=$1][font=$2][color=$3]', '[/color][/font][/size]');
224 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(\d+)[,;].*/'), '[size=$1]', '[/size]');
225 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*/'), '[size=$1]', '[/size]');
227 self::tagToBBCode($doc, 'span', ['style' => '/.*color:\s*(.+?)[,;].*/'], '[color="$1"]', '[/color]');
229 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
230 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)pt.*/'), '[font=$1][size=$2]', '[/size][/font]');
231 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)px.*/'), '[font=$1][size=$2]', '[/size][/font]');
232 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
233 // Importing the classes - interesting for importing of posts from third party networks that were exported from friendica
235 //self::node2BBCode($doc, 'span', array('class'=>'/([\w ]+)/'), '[class=$1]', '[/class]');
236 self::tagToBBCode($doc, 'span', ['class' => 'type-link'], '[class=type-link]', '[/class]');
237 self::tagToBBCode($doc, 'span', ['class' => 'type-video'], '[class=type-video]', '[/class]');
239 self::tagToBBCode($doc, 'strong', [], '[b]', '[/b]');
240 self::tagToBBCode($doc, 'em', [], '[i]', '[/i]');
241 self::tagToBBCode($doc, 'b', [], '[b]', '[/b]');
242 self::tagToBBCode($doc, 'i', [], '[i]', '[/i]');
243 self::tagToBBCode($doc, 'u', [], '[u]', '[/u]');
244 self::tagToBBCode($doc, 's', [], '[s]', '[/s]');
245 self::tagToBBCode($doc, 'del', [], '[s]', '[/s]');
246 self::tagToBBCode($doc, 'strike', [], '[s]', '[/s]');
248 self::tagToBBCode($doc, 'big', [], "[size=large]", "[/size]");
249 self::tagToBBCode($doc, 'small', [], "[size=small]", "[/size]");
251 self::tagToBBCode($doc, 'blockquote', [], '[quote]', '[/quote]');
253 self::tagToBBCode($doc, 'br', [], "\n", '');
255 self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal'], "\n", "");
256 self::tagToBBCode($doc, 'div', ['class' => 'MsoNormal'], "\r", "");
258 self::tagToBBCode($doc, 'span', [], "", "");
260 self::tagToBBCode($doc, 'span', [], "", "");
261 self::tagToBBCode($doc, 'pre', [], "", "");
263 self::tagToBBCode($doc, 'div', [], "\r", "\r");
264 self::tagToBBCode($doc, 'p', [], "\n", "\n");
266 self::tagToBBCode($doc, 'ul', [], "[list]", "[/list]");
267 self::tagToBBCode($doc, 'ol', [], "[list=1]", "[/list]");
268 self::tagToBBCode($doc, 'li', [], "[*]", "");
270 self::tagToBBCode($doc, 'hr', [], "[hr]", "");
272 self::tagToBBCode($doc, 'table', [], "", "");
273 self::tagToBBCode($doc, 'tr', [], "\n", "");
274 self::tagToBBCode($doc, 'td', [], "\t", "");
275 //self::node2BBCode($doc, 'table', array(), "[table]", "[/table]");
276 //self::node2BBCode($doc, 'th', array(), "[th]", "[/th]");
277 //self::node2BBCode($doc, 'tr', array(), "[tr]", "[/tr]");
278 //self::node2BBCode($doc, 'td', array(), "[td]", "[/td]");
279 //self::node2BBCode($doc, 'h1', array(), "\n\n[size=xx-large][b]", "[/b][/size]\n");
280 //self::node2BBCode($doc, 'h2', array(), "\n\n[size=x-large][b]", "[/b][/size]\n");
281 //self::node2BBCode($doc, 'h3', array(), "\n\n[size=large][b]", "[/b][/size]\n");
282 //self::node2BBCode($doc, 'h4', array(), "\n\n[size=medium][b]", "[/b][/size]\n");
283 //self::node2BBCode($doc, 'h5', array(), "\n\n[size=small][b]", "[/b][/size]\n");
284 //self::node2BBCode($doc, 'h6', array(), "\n\n[size=x-small][b]", "[/b][/size]\n");
286 self::tagToBBCode($doc, 'h1', [], "[h1]", "[/h1]");
287 self::tagToBBCode($doc, 'h2', [], "[h2]", "[/h2]");
288 self::tagToBBCode($doc, 'h3', [], "[h3]", "[/h3]");
289 self::tagToBBCode($doc, 'h4', [], "[h4]", "[/h4]");
290 self::tagToBBCode($doc, 'h5', [], "[h5]", "[/h5]");
291 self::tagToBBCode($doc, 'h6', [], "[h6]", "[/h6]");
293 self::tagToBBCode($doc, 'a', ['href' => '/mailto:(.+)/'], '[mail=$1]', '[/mail]');
294 self::tagToBBCode($doc, 'a', ['href' => '/(.+)/'], '[url=$1]', '[/url]');
296 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/', 'width' => '/(\d+)/', 'height' => '/(\d+)/'], '[img=$2x$3]$1', '[/img]');
297 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], '[img]$1', '[/img]');
300 self::tagToBBCode($doc, 'video', ['src' => '/(.+)/'], '[video]$1', '[/video]');
301 self::tagToBBCode($doc, 'audio', ['src' => '/(.+)/'], '[audio]$1', '[/audio]');
302 self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], '[iframe]$1', '[/iframe]');
304 self::tagToBBCode($doc, 'key', [], '[code]', '[/code]');
305 self::tagToBBCode($doc, 'code', [], '[code]', '[/code]');
307 $message = $doc->saveHTML();
309 // I'm removing something really disturbing
310 // Don't know exactly what it is
311 $message = str_replace(chr(194) . chr(160), ' ', $message);
313 $message = str_replace(" ", " ", $message);
315 // removing multiple DIVs
316 $message = preg_replace('=\r *\r=i', "\n", $message);
317 $message = str_replace("\r", "\n", $message);
319 Hook::callAll('html2bbcode', $message);
321 $message = strip_tags($message);
323 $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
325 $message = str_replace(["<"], ["<"], $message);
327 // remove quotes if they don't make sense
328 $message = preg_replace('=\[/quote\][\s]*\[quote\]=i', "\n", $message);
330 $message = preg_replace('=\[quote\]\s*=i', "[quote]", $message);
331 $message = preg_replace('=\s*\[/quote\]=i', "[/quote]", $message);
334 $oldmessage = $message;
335 $message = str_replace("\n \n", "\n\n", $message);
336 } while ($oldmessage != $message);
339 $oldmessage = $message;
340 $message = str_replace("\n\n\n", "\n\n", $message);
341 } while ($oldmessage != $message);
344 $oldmessage = $message;
345 $message = str_replace(
368 } while ($message != $oldmessage);
370 $message = str_replace(
371 ['[b][b]', '[/b][/b]', '[i][i]', '[/i][/i]'],
372 ['[b]', '[/b]', '[i]', '[/i]'],
376 // Handling Yahoo style of mails
377 $message = str_replace('[hr][b]From:[/b]', '[quote][b]From:[/b]', $message);
379 // Restore code blocks
380 $message = preg_replace_callback(
381 '#\[codeblock-([0-9]+)\]#iU',
382 function ($matches) use ($codeblocks) {
384 if (isset($codeblocks[intval($matches[1])])) {
385 $return = $codeblocks[$matches[1]];
392 $message = trim($message);
394 if ($basepath != '') {
395 $message = self::qualifyURLs($message, $basepath);
402 * @brief Sub function to complete incomplete URL
404 * @param array $matches Result of preg_replace_callback
405 * @param string $basepath Basepath that is used to complete the URL
407 * @return string The expanded URL
409 private static function qualifyURLsSub($matches, $basepath)
411 $base = parse_url($basepath);
412 unset($base['query']);
413 unset($base['fragment']);
418 $parts = array_merge($base, parse_url($url));
419 $url2 = Network::unparseURL($parts);
421 return str_replace($url, $url2, $link);
425 * @brief Complete incomplete URLs in BBCode
427 * @param string $body Body with URLs
428 * @param string $basepath Base path that is used to complete the URL
430 * @return string Body with expanded URLs
432 private static function qualifyURLs($body, $basepath)
434 $URLSearchString = "^\[\]";
436 $matches = ["/\[url\=([$URLSearchString]*)\].*?\[\/url\]/ism",
437 "/\[url\]([$URLSearchString]*)\[\/url\]/ism",
438 "/\[img\=[0-9]*x[0-9]*\](.*?)\[\/img\]/ism",
439 "/\[img\](.*?)\[\/img\]/ism",
440 "/\[zmg\=[0-9]*x[0-9]*\](.*?)\[\/img\]/ism",
441 "/\[zmg\](.*?)\[\/zmg\]/ism",
442 "/\[video\](.*?)\[\/video\]/ism",
443 "/\[audio\](.*?)\[\/audio\]/ism",
446 foreach ($matches as $match) {
447 $body = preg_replace_callback(
449 function ($match) use ($basepath) {
450 return self::qualifyURLsSub($match, $basepath);
458 private static function breakLines($line, $level, $wraplength = 75)
460 if ($wraplength == 0) {
461 $wraplength = 2000000;
464 $wraplen = $wraplength - $level;
471 $subline = substr($line, 0, $wraplen);
473 $pos = strrpos($subline, ' ');
476 $pos = strpos($line, ' ');
479 if (($pos > 0) && strlen($line) > $wraplen) {
480 $newline = trim(substr($line, 0, $pos));
482 $newline = str_repeat(">", $level) . ' ' . $newline;
485 $newlines[] = $newline . " ";
486 $line = substr($line, $pos + 1);
488 } while ((strlen($line) > $wraplen) && !($oldline == $line));
491 $line = str_repeat(">", $level) . ' ' . $line;
496 return implode($newlines, "\n");
499 private static function quoteLevel($message, $wraplength = 75)
501 $lines = explode("\n", $message);
505 foreach ($lines as $line) {
508 while (strpos("*" . $line, '[quote]') > 0) {
510 $pos = strpos($line, '[quote]');
511 $line = substr($line, 0, $pos) . substr($line, $pos + 7);
517 while (strpos("*" . $line, '[/quote]') > 0) {
523 $pos = strpos($line, '[/quote]');
524 $line = substr($line, 0, $pos) . substr($line, $pos + 8);
527 if (!$startquote || ($line != '')) {
528 $newlines[] = self::breakLines($line, $currlevel, $wraplength);
532 return implode($newlines, "\n");
535 private static function collectURLs($message)
537 $pattern = '/<a.*?href="(.*?)".*?>(.*?)<\/a>/is';
538 preg_match_all($pattern, $message, $result, PREG_SET_ORDER);
541 foreach ($result as $treffer) {
544 // A list of some links that should be ignored
545 $list = ["/user/", "/tag/", "/group/", "/profile/", "/search?search=", "/search?tag=", "mailto:", "/u/", "/node/",
546 "//plus.google.com/", "//twitter.com/"];
547 foreach ($list as $listitem) {
548 if (strpos($treffer[1], $listitem) !== false) {
553 if ((strpos($treffer[1], "//twitter.com/") !== false) && (strpos($treffer[1], "/status/") !== false)) {
557 if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/posts") !== false)) {
561 if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/photos") !== false)) {
566 $urls[$treffer[1]] = $treffer[1];
573 public static function toPlaintext($html, $wraplength = 75, $compact = false)
575 $message = str_replace("\r", "", $html);
577 $doc = new DOMDocument();
578 $doc->preserveWhiteSpace = false;
580 $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8");
582 @$doc->loadHTML($message);
584 $xpath = new DOMXPath($doc);
585 $list = $xpath->query("//pre");
586 foreach ($list as $node) {
587 $node->nodeValue = str_replace("\n", "\r", $node->nodeValue);
590 $message = $doc->saveHTML();
591 $message = str_replace(["\n<", ">\n", "\r", "\n", "\xC3\x82\xC2\xA0"], ["<", ">", "<br>", " ", ""], $message);
592 $message = preg_replace('= [\s]*=i', " ", $message);
594 // Collecting all links
595 $urls = self::collectURLs($message);
597 @$doc->loadHTML($message);
599 self::tagToBBCode($doc, 'html', [], '', '');
600 self::tagToBBCode($doc, 'body', [], '', '');
602 // MyBB-Auszeichnungen
604 self::node2BBCode($doc, 'span', array('style'=>'text-decoration: underline;'), '_', '_');
605 self::node2BBCode($doc, 'span', array('style'=>'font-style: italic;'), '/', '/');
606 self::node2BBCode($doc, 'span', array('style'=>'font-weight: bold;'), '*', '*');
608 self::node2BBCode($doc, 'strong', array(), '*', '*');
609 self::node2BBCode($doc, 'b', array(), '*', '*');
610 self::node2BBCode($doc, 'i', array(), '/', '/');
611 self::node2BBCode($doc, 'u', array(), '_', '_');
615 self::tagToBBCode($doc, 'blockquote', [], "»", "«");
617 self::tagToBBCode($doc, 'blockquote', [], '[quote]', "[/quote]\n");
620 self::tagToBBCode($doc, 'br', [], "\n", '');
622 self::tagToBBCode($doc, 'span', [], "", "");
623 self::tagToBBCode($doc, 'pre', [], "", "");
624 self::tagToBBCode($doc, 'div', [], "\r", "\r");
625 self::tagToBBCode($doc, 'p', [], "\n", "\n");
627 //self::node2BBCode($doc, 'ul', array(), "\n[list]", "[/list]\n");
628 //self::node2BBCode($doc, 'ol', array(), "\n[list=1]", "[/list]\n");
629 self::tagToBBCode($doc, 'li', [], "\n* ", "\n");
631 self::tagToBBCode($doc, 'hr', [], "\n" . str_repeat("-", 70) . "\n", "");
633 self::tagToBBCode($doc, 'tr', [], "\n", "");
634 self::tagToBBCode($doc, 'td', [], "\t", "");
636 self::tagToBBCode($doc, 'h1', [], "\n\n*", "*\n");
637 self::tagToBBCode($doc, 'h2', [], "\n\n*", "*\n");
638 self::tagToBBCode($doc, 'h3', [], "\n\n*", "*\n");
639 self::tagToBBCode($doc, 'h4', [], "\n\n*", "*\n");
640 self::tagToBBCode($doc, 'h5', [], "\n\n*", "*\n");
641 self::tagToBBCode($doc, 'h6', [], "\n\n*", "*\n");
643 // Problem: there is no reliable way to detect if it is a link to a tag or profile
644 //self::node2BBCode($doc, 'a', array('href'=>'/(.+)/'), ' $1 ', ' ', true);
645 //self::node2BBCode($doc, 'a', array('href'=>'/(.+)/', 'rel'=>'oembed'), ' $1 ', '', true);
646 //self::node2BBCode($doc, 'img', array('alt'=>'/(.+)/'), '$1', '');
647 //self::node2BBCode($doc, 'img', array('title'=>'/(.+)/'), '$1', '');
648 //self::node2BBCode($doc, 'img', array(), '', '');
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' => defaults($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.
888 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
890 public static function search($s, $id = 'search-box', $url = 'search', $aside = true)
894 if (strpos($s, '#') === 0) {
897 $save_label = $mode === 'text' ? L10n::t('Save') : L10n::t('Follow');
902 '$action_url' => $url,
903 '$search_label' => L10n::t('Search'),
904 '$save_label' => $save_label,
905 '$savedsearch' => 'savedsearch',
906 '$search_hint' => L10n::t('@name, !forum, #tags, content'),
911 $values['$searchoption'] = [
912 L10n::t("Full Text"),
914 L10n::t("Contacts")];
916 if (Config::get('system', 'poco_local_search')) {
917 $values['$searchoption'][] = L10n::t("Forums");
921 return Renderer::replaceMacros(Renderer::getMarkupTemplate('searchbox.tpl'), $values);
925 * Replace naked text hyperlink with HTML formatted hyperlink
930 public static function toLink($s)
932 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank">$1</a>', $s);
933 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism", '<$1$2=$3&$4>', $s);
938 * Given a HTML text and a set of filtering reasons, adds a content hiding header with the provided reasons
940 * Reasons are expected to have been translated already.
942 * @param string $html
943 * @param array $reasons
945 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
947 public static function applyContentFilter($html, array $reasons)
949 if (count($reasons)) {
950 $tpl = Renderer::getMarkupTemplate('wall/content_filter.tpl');
951 $html = Renderer::replaceMacros($tpl, [
952 '$reasons' => $reasons,
953 '$rnd' => Strings::getRandomHex(8),
954 '$openclose' => L10n::t('Click to open/close'),
963 * replace html amp entity with amp char
967 public static function unamp($s)
969 return str_replace('&', '&', $s);