3 * @file src/Content/Text/HTML.php
6 namespace Friendica\Content\Text;
10 use Friendica\Core\Hook;
11 use Friendica\Core\L10n;
12 use Friendica\Core\Config;
13 use Friendica\Core\PConfig;
14 use Friendica\Core\Protocol;
15 use Friendica\Core\Renderer;
16 use Friendica\Database\DBA;
17 use Friendica\Model\Contact;
18 use Friendica\Util\Network;
19 use Friendica\Util\Proxy as ProxyUtils;
20 use Friendica\Util\Strings;
21 use Friendica\Util\XML;
22 use League\HTMLToMarkdown\HtmlConverter;
26 public static function sanitizeCSS($input)
30 $input = strtolower($input);
32 for ($i = 0; $i < strlen($input); $i++) {
33 $char = substr($input, $i, 1);
35 if (($char >= "a") && ($char <= "z")) {
39 if (!(strpos(" #;:0123456789-_.%", $char) === false)) {
47 private static function tagToBBCode(DOMDocument $doc, $tag, $attributes, $startbb, $endbb)
50 $done = self::tagToBBCodeSub($doc, $tag, $attributes, $startbb, $endbb);
54 private static function tagToBBCodeSub(DOMDocument $doc, $tag, $attributes, $startbb, $endbb)
56 $savestart = str_replace('$', '\x01', $startbb);
59 $xpath = new DOMXPath($doc);
61 $list = $xpath->query("//" . $tag);
62 foreach ($list as $node) {
64 if ($node->attributes->length) {
65 foreach ($node->attributes as $attribute) {
66 $attr[$attribute->name] = $attribute->value;
72 $startbb = $savestart;
76 foreach ($attributes as $attribute => $value) {
77 $startbb = str_replace('\x01' . ++$i, '$1', $startbb);
78 if (strpos('*' . $startbb, '$1') > 0) {
79 if ($replace && (@$attr[$attribute] != '')) {
80 $startbb = preg_replace($value, $startbb, $attr[$attribute], -1, $count);
82 // If nothing could be changed
90 if (@$attr[$attribute] != $value) {
97 $StartCode = $doc->createTextNode($startbb);
98 $EndCode = $doc->createTextNode($endbb);
100 $node->parentNode->insertBefore($StartCode, $node);
102 if ($node->hasChildNodes()) {
103 foreach ($node->childNodes as $child) {
104 $newNode = $child->cloneNode(true);
105 $node->parentNode->insertBefore($newNode, $node);
109 $node->parentNode->insertBefore($EndCode, $node);
110 $node->parentNode->removeChild($node);
118 * Made by: ike@piratenpartei.de
119 * Originally made for the syncom project: http://wiki.piratenpartei.de/Syncom
120 * https://github.com/annando/Syncom
122 * @brief Converter for HTML to BBCode
123 * @param string $message
124 * @param string $basepath
126 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
128 public static function toBBCode($message, $basepath = '')
130 $message = str_replace("\r", "", $message);
132 // Removing code blocks before the whitespace removal processing below
134 $message = preg_replace_callback(
135 '#<pre><code(?: class="language-([^"]*)")?>(.*)</code></pre>#iUs',
136 function ($matches) use (&$codeblocks) {
137 $return = '[codeblock-' . count($codeblocks) . ']';
140 if ($matches[1] != '') {
141 $prefix = '[code=' . $matches[1] . ']';
144 $codeblocks[] = $prefix . PHP_EOL . trim($matches[2]) . PHP_EOL . '[/code]';
150 $message = str_replace(
163 $message = preg_replace('=<(\w+):(.+?)>=', '<removeme>', $message);
164 $message = preg_replace('=</(\w+):(.+?)>=', '</removeme>', $message);
166 $doc = new DOMDocument();
167 $doc->preserveWhiteSpace = false;
169 $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8");
171 @$doc->loadHTML($message);
173 XML::deleteNode($doc, 'style');
174 XML::deleteNode($doc, 'head');
175 XML::deleteNode($doc, 'title');
176 XML::deleteNode($doc, 'meta');
177 XML::deleteNode($doc, 'xml');
178 XML::deleteNode($doc, 'removeme');
180 $xpath = new DomXPath($doc);
181 $list = $xpath->query("//pre");
182 foreach ($list as $node) {
183 // Ensure to escape unescaped & - they will otherwise raise a warning
184 $safe_value = preg_replace('/&(?!\w+;)/', '&', $node->nodeValue);
185 $node->nodeValue = str_replace("\n", "\r", $safe_value);
188 $message = $doc->saveHTML();
189 $message = str_replace(["\n<", ">\n", "\r", "\n", "\xC3\x82\xC2\xA0"], ["<", ">", "<br />", " ", ""], $message);
190 $message = preg_replace('= [\s]*=i', " ", $message);
191 @$doc->loadHTML($message);
193 self::tagToBBCode($doc, 'html', [], "", "");
194 self::tagToBBCode($doc, 'body', [], "", "");
196 // Outlook-Quote - Variant 1
197 self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal', 'style' => 'margin-left:35.4pt'], '[quote]', '[/quote]');
199 // Outlook-Quote - Variant 2
203 ['style' => 'border:none;border-left:solid blue 1.5pt;padding:0cm 0cm 0cm 4.0pt'],
209 self::tagToBBCode($doc, 'span', ['style' => 'text-decoration: underline;'], '[u]', '[/u]');
210 self::tagToBBCode($doc, 'span', ['style' => 'font-style: italic;'], '[i]', '[/i]');
211 self::tagToBBCode($doc, 'span', ['style' => 'font-weight: bold;'], '[b]', '[/b]');
213 /* self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[font=$1][size=$2][color=$3]', '[/color][/size][/font]');
214 self::node2BBCode($doc, 'font', array('size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[size=$1][color=$2]', '[/color][/size]');
215 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(.+)/'), '[font=$1][size=$2]', '[/size][/font]');
216 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'color'=>'/(.+)/'), '[font=$1][color=$3]', '[/color][/font]');
217 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/'), '[font=$1]', '[/font]');
218 self::node2BBCode($doc, 'font', array('size'=>'/(\d+)/'), '[size=$1]', '[/size]');
219 self::node2BBCode($doc, 'font', array('color'=>'/(.+)/'), '[color=$1]', '[/color]');
222 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*font-family:\s*(.+?)[,;].*color:\s*(.+?)[,;].*/'), '[size=$1][font=$2][color=$3]', '[/color][/font][/size]');
223 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(\d+)[,;].*/'), '[size=$1]', '[/size]');
224 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*/'), '[size=$1]', '[/size]');
226 self::tagToBBCode($doc, 'span', ['style' => '/.*color:\s*(.+?)[,;].*/'], '[color="$1"]', '[/color]');
228 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
229 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)pt.*/'), '[font=$1][size=$2]', '[/size][/font]');
230 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)px.*/'), '[font=$1][size=$2]', '[/size][/font]');
231 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
232 // Importing the classes - interesting for importing of posts from third party networks that were exported from friendica
234 //self::node2BBCode($doc, 'span', array('class'=>'/([\w ]+)/'), '[class=$1]', '[/class]');
235 self::tagToBBCode($doc, 'span', ['class' => 'type-link'], '[class=type-link]', '[/class]');
236 self::tagToBBCode($doc, 'span', ['class' => 'type-video'], '[class=type-video]', '[/class]');
238 self::tagToBBCode($doc, 'strong', [], '[b]', '[/b]');
239 self::tagToBBCode($doc, 'em', [], '[i]', '[/i]');
240 self::tagToBBCode($doc, 'b', [], '[b]', '[/b]');
241 self::tagToBBCode($doc, 'i', [], '[i]', '[/i]');
242 self::tagToBBCode($doc, 'u', [], '[u]', '[/u]');
243 self::tagToBBCode($doc, 's', [], '[s]', '[/s]');
244 self::tagToBBCode($doc, 'del', [], '[s]', '[/s]');
245 self::tagToBBCode($doc, 'strike', [], '[s]', '[/s]');
247 self::tagToBBCode($doc, 'big', [], "[size=large]", "[/size]");
248 self::tagToBBCode($doc, 'small', [], "[size=small]", "[/size]");
250 self::tagToBBCode($doc, 'blockquote', [], '[quote]', '[/quote]');
252 self::tagToBBCode($doc, 'br', [], "\n", '');
254 self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal'], "\n", "");
255 self::tagToBBCode($doc, 'div', ['class' => 'MsoNormal'], "\r", "");
257 self::tagToBBCode($doc, 'span', [], "", "");
259 self::tagToBBCode($doc, 'span', [], "", "");
260 self::tagToBBCode($doc, 'pre', [], "", "");
262 self::tagToBBCode($doc, 'div', [], "\r", "\r");
263 self::tagToBBCode($doc, 'p', [], "\n", "\n");
265 self::tagToBBCode($doc, 'ul', [], "[list]", "[/list]");
266 self::tagToBBCode($doc, 'ol', [], "[list=1]", "[/list]");
267 self::tagToBBCode($doc, 'li', [], "[*]", "");
269 self::tagToBBCode($doc, 'hr', [], "[hr]", "");
271 self::tagToBBCode($doc, 'table', [], "", "");
272 self::tagToBBCode($doc, 'tr', [], "\n", "");
273 self::tagToBBCode($doc, 'td', [], "\t", "");
274 //self::node2BBCode($doc, 'table', array(), "[table]", "[/table]");
275 //self::node2BBCode($doc, 'th', array(), "[th]", "[/th]");
276 //self::node2BBCode($doc, 'tr', array(), "[tr]", "[/tr]");
277 //self::node2BBCode($doc, 'td', array(), "[td]", "[/td]");
278 //self::node2BBCode($doc, 'h1', array(), "\n\n[size=xx-large][b]", "[/b][/size]\n");
279 //self::node2BBCode($doc, 'h2', array(), "\n\n[size=x-large][b]", "[/b][/size]\n");
280 //self::node2BBCode($doc, 'h3', array(), "\n\n[size=large][b]", "[/b][/size]\n");
281 //self::node2BBCode($doc, 'h4', array(), "\n\n[size=medium][b]", "[/b][/size]\n");
282 //self::node2BBCode($doc, 'h5', array(), "\n\n[size=small][b]", "[/b][/size]\n");
283 //self::node2BBCode($doc, 'h6', array(), "\n\n[size=x-small][b]", "[/b][/size]\n");
285 self::tagToBBCode($doc, 'h1', [], "[h1]", "[/h1]");
286 self::tagToBBCode($doc, 'h2', [], "[h2]", "[/h2]");
287 self::tagToBBCode($doc, 'h3', [], "[h3]", "[/h3]");
288 self::tagToBBCode($doc, 'h4', [], "[h4]", "[/h4]");
289 self::tagToBBCode($doc, 'h5', [], "[h5]", "[/h5]");
290 self::tagToBBCode($doc, 'h6', [], "[h6]", "[/h6]");
292 self::tagToBBCode($doc, 'a', ['href' => '/mailto:(.+)/'], '[mail=$1]', '[/mail]');
293 self::tagToBBCode($doc, 'a', ['href' => '/(.+)/'], '[url=$1]', '[/url]');
295 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/', 'width' => '/(\d+)/', 'height' => '/(\d+)/'], '[img=$2x$3]$1', '[/img]');
296 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], '[img]$1', '[/img]');
299 self::tagToBBCode($doc, 'video', ['src' => '/(.+)/'], '[video]$1', '[/video]');
300 self::tagToBBCode($doc, 'audio', ['src' => '/(.+)/'], '[audio]$1', '[/audio]');
301 self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], '[iframe]$1', '[/iframe]');
303 self::tagToBBCode($doc, 'key', [], '[code]', '[/code]');
304 self::tagToBBCode($doc, 'code', [], '[code]', '[/code]');
306 $message = $doc->saveHTML();
308 // I'm removing something really disturbing
309 // Don't know exactly what it is
310 $message = str_replace(chr(194) . chr(160), ' ', $message);
312 $message = str_replace(" ", " ", $message);
314 // removing multiple DIVs
315 $message = preg_replace('=\r *\r=i', "\n", $message);
316 $message = str_replace("\r", "\n", $message);
318 Hook::callAll('html2bbcode', $message);
320 $message = strip_tags($message);
322 $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
324 $message = str_replace(["<"], ["<"], $message);
326 // remove quotes if they don't make sense
327 $message = preg_replace('=\[/quote\][\s]*\[quote\]=i', "\n", $message);
329 $message = preg_replace('=\[quote\]\s*=i', "[quote]", $message);
330 $message = preg_replace('=\s*\[/quote\]=i', "[/quote]", $message);
333 $oldmessage = $message;
334 $message = str_replace("\n \n", "\n\n", $message);
335 } while ($oldmessage != $message);
338 $oldmessage = $message;
339 $message = str_replace("\n\n\n", "\n\n", $message);
340 } while ($oldmessage != $message);
343 $oldmessage = $message;
344 $message = str_replace(
367 } while ($message != $oldmessage);
369 $message = str_replace(
370 ['[b][b]', '[/b][/b]', '[i][i]', '[/i][/i]'],
371 ['[b]', '[/b]', '[i]', '[/i]'],
375 // Handling Yahoo style of mails
376 $message = str_replace('[hr][b]From:[/b]', '[quote][b]From:[/b]', $message);
378 // Restore code blocks
379 $message = preg_replace_callback(
380 '#\[codeblock-([0-9]+)\]#iU',
381 function ($matches) use ($codeblocks) {
383 if (isset($codeblocks[intval($matches[1])])) {
384 $return = $codeblocks[$matches[1]];
391 $message = trim($message);
393 if ($basepath != '') {
394 $message = self::qualifyURLs($message, $basepath);
401 * @brief Sub function to complete incomplete URL
403 * @param array $matches Result of preg_replace_callback
404 * @param string $basepath Basepath that is used to complete the URL
406 * @return string The expanded URL
408 private static function qualifyURLsSub($matches, $basepath)
410 $base = parse_url($basepath);
411 unset($base['query']);
412 unset($base['fragment']);
417 $parts = array_merge($base, parse_url($url));
418 $url2 = Network::unparseURL($parts);
420 return str_replace($url, $url2, $link);
424 * @brief Complete incomplete URLs in BBCode
426 * @param string $body Body with URLs
427 * @param string $basepath Base path that is used to complete the URL
429 * @return string Body with expanded URLs
431 private static function qualifyURLs($body, $basepath)
433 $URLSearchString = "^\[\]";
435 $matches = ["/\[url\=([$URLSearchString]*)\].*?\[\/url\]/ism",
436 "/\[url\]([$URLSearchString]*)\[\/url\]/ism",
437 "/\[img\=[0-9]*x[0-9]*\](.*?)\[\/img\]/ism",
438 "/\[img\](.*?)\[\/img\]/ism",
439 "/\[zmg\=[0-9]*x[0-9]*\](.*?)\[\/img\]/ism",
440 "/\[zmg\](.*?)\[\/zmg\]/ism",
441 "/\[video\](.*?)\[\/video\]/ism",
442 "/\[audio\](.*?)\[\/audio\]/ism",
445 foreach ($matches as $match) {
446 $body = preg_replace_callback(
448 function ($match) use ($basepath) {
449 return self::qualifyURLsSub($match, $basepath);
457 private static function breakLines($line, $level, $wraplength = 75)
459 if ($wraplength == 0) {
460 $wraplength = 2000000;
463 $wraplen = $wraplength - $level;
470 $subline = substr($line, 0, $wraplen);
472 $pos = strrpos($subline, ' ');
475 $pos = strpos($line, ' ');
478 if (($pos > 0) && strlen($line) > $wraplen) {
479 $newline = trim(substr($line, 0, $pos));
481 $newline = str_repeat(">", $level) . ' ' . $newline;
484 $newlines[] = $newline . " ";
485 $line = substr($line, $pos + 1);
487 } while ((strlen($line) > $wraplen) && !($oldline == $line));
490 $line = str_repeat(">", $level) . ' ' . $line;
495 return implode($newlines, "\n");
498 private static function quoteLevel($message, $wraplength = 75)
500 $lines = explode("\n", $message);
504 foreach ($lines as $line) {
507 while (strpos("*" . $line, '[quote]') > 0) {
509 $pos = strpos($line, '[quote]');
510 $line = substr($line, 0, $pos) . substr($line, $pos + 7);
516 while (strpos("*" . $line, '[/quote]') > 0) {
522 $pos = strpos($line, '[/quote]');
523 $line = substr($line, 0, $pos) . substr($line, $pos + 8);
526 if (!$startquote || ($line != '')) {
527 $newlines[] = self::breakLines($line, $currlevel, $wraplength);
531 return implode($newlines, "\n");
534 private static function collectURLs($message)
536 $pattern = '/<a.*?href="(.*?)".*?>(.*?)<\/a>/is';
537 preg_match_all($pattern, $message, $result, PREG_SET_ORDER);
540 foreach ($result as $treffer) {
543 // A list of some links that should be ignored
544 $list = ["/user/", "/tag/", "/group/", "/profile/", "/search?search=", "/search?tag=", "mailto:", "/u/", "/node/",
545 "//plus.google.com/", "//twitter.com/"];
546 foreach ($list as $listitem) {
547 if (strpos($treffer[1], $listitem) !== false) {
552 if ((strpos($treffer[1], "//twitter.com/") !== false) && (strpos($treffer[1], "/status/") !== false)) {
556 if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/posts") !== false)) {
560 if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/photos") !== false)) {
565 $urls[$treffer[1]] = $treffer[1];
572 public static function toPlaintext($html, $wraplength = 75, $compact = false)
574 $message = str_replace("\r", "", $html);
576 $doc = new DOMDocument();
577 $doc->preserveWhiteSpace = false;
579 $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8");
581 @$doc->loadHTML($message);
583 $xpath = new DOMXPath($doc);
584 $list = $xpath->query("//pre");
585 foreach ($list as $node) {
586 $node->nodeValue = str_replace("\n", "\r", $node->nodeValue);
589 $message = $doc->saveHTML();
590 $message = str_replace(["\n<", ">\n", "\r", "\n", "\xC3\x82\xC2\xA0"], ["<", ">", "<br>", " ", ""], $message);
591 $message = preg_replace('= [\s]*=i', " ", $message);
593 // Collecting all links
594 $urls = self::collectURLs($message);
596 @$doc->loadHTML($message);
598 self::tagToBBCode($doc, 'html', [], '', '');
599 self::tagToBBCode($doc, 'body', [], '', '');
601 // MyBB-Auszeichnungen
603 self::node2BBCode($doc, 'span', array('style'=>'text-decoration: underline;'), '_', '_');
604 self::node2BBCode($doc, 'span', array('style'=>'font-style: italic;'), '/', '/');
605 self::node2BBCode($doc, 'span', array('style'=>'font-weight: bold;'), '*', '*');
607 self::node2BBCode($doc, 'strong', array(), '*', '*');
608 self::node2BBCode($doc, 'b', array(), '*', '*');
609 self::node2BBCode($doc, 'i', array(), '/', '/');
610 self::node2BBCode($doc, 'u', array(), '_', '_');
614 self::tagToBBCode($doc, 'blockquote', [], "»", "«");
616 self::tagToBBCode($doc, 'blockquote', [], '[quote]', "[/quote]\n");
619 self::tagToBBCode($doc, 'br', [], "\n", '');
621 self::tagToBBCode($doc, 'span', [], "", "");
622 self::tagToBBCode($doc, 'pre', [], "", "");
623 self::tagToBBCode($doc, 'div', [], "\r", "\r");
624 self::tagToBBCode($doc, 'p', [], "\n", "\n");
626 //self::node2BBCode($doc, 'ul', array(), "\n[list]", "[/list]\n");
627 //self::node2BBCode($doc, 'ol', array(), "\n[list=1]", "[/list]\n");
628 self::tagToBBCode($doc, 'li', [], "\n* ", "\n");
630 self::tagToBBCode($doc, 'hr', [], "\n" . str_repeat("-", 70) . "\n", "");
632 self::tagToBBCode($doc, 'tr', [], "\n", "");
633 self::tagToBBCode($doc, 'td', [], "\t", "");
635 self::tagToBBCode($doc, 'h1', [], "\n\n*", "*\n");
636 self::tagToBBCode($doc, 'h2', [], "\n\n*", "*\n");
637 self::tagToBBCode($doc, 'h3', [], "\n\n*", "*\n");
638 self::tagToBBCode($doc, 'h4', [], "\n\n*", "*\n");
639 self::tagToBBCode($doc, 'h5', [], "\n\n*", "*\n");
640 self::tagToBBCode($doc, 'h6', [], "\n\n*", "*\n");
642 // Problem: there is no reliable way to detect if it is a link to a tag or profile
643 //self::node2BBCode($doc, 'a', array('href'=>'/(.+)/'), ' $1 ', ' ', true);
644 //self::node2BBCode($doc, 'a', array('href'=>'/(.+)/', 'rel'=>'oembed'), ' $1 ', '', true);
645 //self::node2BBCode($doc, 'img', array('alt'=>'/(.+)/'), '$1', '');
646 //self::node2BBCode($doc, 'img', array('title'=>'/(.+)/'), '$1', '');
647 //self::node2BBCode($doc, 'img', array(), '', '');
649 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], ' [img]$1', '[/img] ');
651 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], ' ', ' ');
654 self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], ' $1 ', '');
656 $message = $doc->saveHTML();
659 $message = str_replace("[img]", "", $message);
660 $message = str_replace("[/img]", "", $message);
663 // was ersetze ich da?
664 // Irgendein stoerrisches UTF-Zeug
665 $message = str_replace(chr(194) . chr(160), ' ', $message);
667 $message = str_replace(" ", " ", $message);
669 // Aufeinanderfolgende DIVs
670 $message = preg_replace('=\r *\r=i', "\n", $message);
671 $message = str_replace("\r", "\n", $message);
673 $message = strip_tags($message);
675 $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
677 if (!$compact && ($message != '')) {
678 foreach ($urls as $id => $url) {
679 if ($url != '' && strpos($message, $url) === false) {
680 $message .= "\n" . $url . ' ';
685 $message = str_replace("\n«", "«\n", $message);
686 $message = str_replace("»\n", "\n»", $message);
689 $oldmessage = $message;
690 $message = str_replace("\n\n\n", "\n\n", $message);
691 } while ($oldmessage != $message);
693 $message = self::quoteLevel(trim($message), $wraplength);
695 return trim($message);
699 * Converts provided HTML code to Markdown. The hardwrap parameter maximizes
700 * compatibility with Diaspora in spite of the Markdown standards.
702 * @param string $html
705 public static function toMarkdown($html)
707 $converter = new HtmlConverter(['hard_break' => true]);
708 $markdown = $converter->convert($html);
714 * @brief Convert video HTML to BBCode tags
719 public static function toBBCodeVideo($s)
722 '#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
723 '[youtube]$2[/youtube]',
728 '#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
729 '[youtube]$2[/youtube]',
734 '#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
743 * transform link href and img src from relative to absolute
745 * @param string $text
746 * @param string $base base url
749 public static function relToAbs($text, $base)
755 $base = rtrim($base, '/');
757 $base2 = $base . "/";
760 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
761 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
762 $text = preg_replace($pattern, $replace, $text);
764 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
765 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
766 $text = preg_replace($pattern, $replace, $text);
769 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
770 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
771 $text = preg_replace($pattern, $replace, $text);
773 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
774 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
775 $text = preg_replace($pattern, $replace, $text);
783 * return div element with class 'clear'
787 public static function clearDiv()
789 return '<div class="clear"></div>';
793 * Loader for infinite scrolling
795 * @return string html for loader
796 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
798 public static function scrollLoader()
800 $tpl = Renderer::getMarkupTemplate("scroll_loader.tpl");
801 return Renderer::replaceMacros($tpl, [
802 'wait' => L10n::t('Loading more entries...'),
803 'end' => L10n::t('The end')
808 * Get html for contact block.
810 * @template contact_block.tpl
811 * @hook contact_block_end (contacts=>array, output=>string)
813 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
814 * @throws \ImagickException
816 public static function contactBlock()
821 $shown = PConfig::get($a->profile['uid'], 'system', 'display_friend_count', 24);
826 if (!is_array($a->profile) || $a->profile['hide-friends']) {
830 $r = q("SELECT COUNT(*) AS `total` FROM `contact`
831 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
832 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
833 AND `network` IN ('%s', '%s', '%s')",
834 intval($a->profile['uid']),
835 DBA::escape(Protocol::DFRN),
836 DBA::escape(Protocol::OSTATUS),
837 DBA::escape(Protocol::DIASPORA)
840 if (DBA::isResult($r)) {
841 $total = intval($r[0]['total']);
845 $contacts = L10n::t('No contacts');
848 // Splitting the query in two parts makes it much faster
849 $r = q("SELECT `id` FROM `contact`
850 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
851 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
852 AND `network` IN ('%s', '%s', '%s')
853 ORDER BY RAND() LIMIT %d",
854 intval($a->profile['uid']),
855 DBA::escape(Protocol::DFRN),
856 DBA::escape(Protocol::OSTATUS),
857 DBA::escape(Protocol::DIASPORA),
861 if (DBA::isResult($r)) {
863 foreach ($r as $contact) {
864 $contacts[] = $contact["id"];
867 $r = q("SELECT `id`, `uid`, `addr`, `url`, `name`, `thumb`, `network` FROM `contact` WHERE `id` IN (%s)",
868 DBA::escape(implode(",", $contacts))
871 if (DBA::isResult($r)) {
872 $contacts = L10n::tt('%d Contact', '%d Contacts', $total);
874 foreach ($r as $rr) {
875 $micropro[] = self::micropro($rr, true, 'mpfriend');
881 $tpl = Renderer::getMarkupTemplate('contact_block.tpl');
882 $o = Renderer::replaceMacros($tpl, [
883 '$contacts' => $contacts,
884 '$nickname' => $a->profile['nickname'],
885 '$viewcontacts' => L10n::t('View Contacts'),
886 '$micropro' => $micropro,
889 $arr = ['contacts' => $r, 'output' => $o];
891 Hook::callAll('contact_block_end', $arr);
897 * @brief Format contacts as picture links or as text links
899 * @param array $contact Array with contacts which contains an array with
900 * int 'id' => The ID of the contact
901 * int 'uid' => The user ID of the user who owns this data
902 * string 'name' => The name of the contact
903 * string 'url' => The url to the profile page of the contact
904 * string 'addr' => The webbie of the contact (e.g.) username@friendica.com
905 * string 'network' => The network to which the contact belongs to
906 * string 'thumb' => The contact picture
907 * string 'click' => js code which is performed when clicking on the contact
908 * @param boolean $redirect If true try to use the redir url if it's possible
909 * @param string $class CSS class for the
910 * @param boolean $textmode If true display the contacts as text links
911 * if false display the contacts as picture links
912 * @return string Formatted html
913 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
914 * @throws \ImagickException
916 public static function micropro($contact, $redirect = false, $class = '', $textmode = false)
918 // Use the contact URL if no address is available
919 if (empty($contact['addr'])) {
920 $contact["addr"] = $contact["url"];
923 $url = $contact['url'];
928 $url = Contact::magicLink($contact['url']);
929 if (strpos($url, 'redir/') === 0) {
930 $sparkle = ' sparkle';
934 // If there is some js available we don't need the url
935 if (!empty($contact['click'])) {
939 return Renderer::replaceMacros(Renderer::getMarkupTemplate(($textmode)?'micropro_txt.tpl':'micropro_img.tpl'), [
940 '$click' => defaults($contact, 'click', ''),
943 '$photo' => ProxyUtils::proxifyUrl($contact['thumb'], false, ProxyUtils::SIZE_THUMB),
944 '$name' => $contact['name'],
945 'title' => $contact['name'] . ' [' . $contact['addr'] . ']',
946 '$parkle' => $sparkle,
954 * @param string $s Search query.
955 * @param string $id HTML id
956 * @param string $url Search url.
957 * @param bool $aside Display the search widgit aside.
959 * @return string Formatted HTML.
960 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
962 public static function search($s, $id = 'search-box', $url = 'search', $aside = true)
966 if (strpos($s, '#') === 0) {
969 $save_label = $mode === 'text' ? L10n::t('Save') : L10n::t('Follow');
974 '$action_url' => $url,
975 '$search_label' => L10n::t('Search'),
976 '$save_label' => $save_label,
977 '$savedsearch' => 'savedsearch',
978 '$search_hint' => L10n::t('@name, !forum, #tags, content'),
983 $values['$searchoption'] = [
984 L10n::t("Full Text"),
986 L10n::t("Contacts")];
988 if (Config::get('system', 'poco_local_search')) {
989 $values['$searchoption'][] = L10n::t("Forums");
993 return Renderer::replaceMacros(Renderer::getMarkupTemplate('searchbox.tpl'), $values);
997 * Replace naked text hyperlink with HTML formatted hyperlink
1002 public static function toLink($s)
1004 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank">$1</a>', $s);
1005 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism", '<$1$2=$3&$4>', $s);
1010 * Given a HTML text and a set of filtering reasons, adds a content hiding header with the provided reasons
1012 * Reasons are expected to have been translated already.
1014 * @param string $html
1015 * @param array $reasons
1017 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1019 public static function applyContentFilter($html, array $reasons)
1021 if (count($reasons)) {
1022 $tpl = Renderer::getMarkupTemplate('wall/content_filter.tpl');
1023 $html = Renderer::replaceMacros($tpl, [
1024 '$reasons' => $reasons,
1025 '$rnd' => Strings::getRandomHex(8),
1026 '$openclose' => L10n::t('Click to open/close'),
1035 * replace html amp entity with amp char
1039 public static function unamp($s)
1041 return str_replace('&', '&', $s);