3 * @file src/Content/Text/HTML.php
6 namespace Friendica\Content\Text;
10 use Friendica\Content\Feature;
11 use Friendica\Core\Addon;
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
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 $node->nodeValue = str_replace("\n", "\r", $node->nodeValue);
186 $message = $doc->saveHTML();
187 $message = str_replace(["\n<", ">\n", "\r", "\n", "\xC3\x82\xC2\xA0"], ["<", ">", "<br />", " ", ""], $message);
188 $message = preg_replace('= [\s]*=i', " ", $message);
189 @$doc->loadHTML($message);
191 self::tagToBBCode($doc, 'html', [], "", "");
192 self::tagToBBCode($doc, 'body', [], "", "");
194 // Outlook-Quote - Variant 1
195 self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal', 'style' => 'margin-left:35.4pt'], '[quote]', '[/quote]');
197 // Outlook-Quote - Variant 2
201 ['style' => 'border:none;border-left:solid blue 1.5pt;padding:0cm 0cm 0cm 4.0pt'],
207 self::tagToBBCode($doc, 'span', ['style' => 'text-decoration: underline;'], '[u]', '[/u]');
208 self::tagToBBCode($doc, 'span', ['style' => 'font-style: italic;'], '[i]', '[/i]');
209 self::tagToBBCode($doc, 'span', ['style' => 'font-weight: bold;'], '[b]', '[/b]');
211 /* self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[font=$1][size=$2][color=$3]', '[/color][/size][/font]');
212 self::node2BBCode($doc, 'font', array('size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[size=$1][color=$2]', '[/color][/size]');
213 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(.+)/'), '[font=$1][size=$2]', '[/size][/font]');
214 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'color'=>'/(.+)/'), '[font=$1][color=$3]', '[/color][/font]');
215 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/'), '[font=$1]', '[/font]');
216 self::node2BBCode($doc, 'font', array('size'=>'/(\d+)/'), '[size=$1]', '[/size]');
217 self::node2BBCode($doc, 'font', array('color'=>'/(.+)/'), '[color=$1]', '[/color]');
220 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*font-family:\s*(.+?)[,;].*color:\s*(.+?)[,;].*/'), '[size=$1][font=$2][color=$3]', '[/color][/font][/size]');
221 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(\d+)[,;].*/'), '[size=$1]', '[/size]');
222 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*/'), '[size=$1]', '[/size]');
224 self::tagToBBCode($doc, 'span', ['style' => '/.*color:\s*(.+?)[,;].*/'], '[color="$1"]', '[/color]');
226 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
227 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)pt.*/'), '[font=$1][size=$2]', '[/size][/font]');
228 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)px.*/'), '[font=$1][size=$2]', '[/size][/font]');
229 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
230 // Importing the classes - interesting for importing of posts from third party networks that were exported from friendica
232 //self::node2BBCode($doc, 'span', array('class'=>'/([\w ]+)/'), '[class=$1]', '[/class]');
233 self::tagToBBCode($doc, 'span', ['class' => 'type-link'], '[class=type-link]', '[/class]');
234 self::tagToBBCode($doc, 'span', ['class' => 'type-video'], '[class=type-video]', '[/class]');
236 self::tagToBBCode($doc, 'strong', [], '[b]', '[/b]');
237 self::tagToBBCode($doc, 'em', [], '[i]', '[/i]');
238 self::tagToBBCode($doc, 'b', [], '[b]', '[/b]');
239 self::tagToBBCode($doc, 'i', [], '[i]', '[/i]');
240 self::tagToBBCode($doc, 'u', [], '[u]', '[/u]');
241 self::tagToBBCode($doc, 's', [], '[s]', '[/s]');
242 self::tagToBBCode($doc, 'del', [], '[s]', '[/s]');
243 self::tagToBBCode($doc, 'strike', [], '[s]', '[/s]');
245 self::tagToBBCode($doc, 'big', [], "[size=large]", "[/size]");
246 self::tagToBBCode($doc, 'small', [], "[size=small]", "[/size]");
248 self::tagToBBCode($doc, 'blockquote', [], '[quote]', '[/quote]');
250 self::tagToBBCode($doc, 'br', [], "\n", '');
252 self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal'], "\n", "");
253 self::tagToBBCode($doc, 'div', ['class' => 'MsoNormal'], "\r", "");
255 self::tagToBBCode($doc, 'span', [], "", "");
257 self::tagToBBCode($doc, 'span', [], "", "");
258 self::tagToBBCode($doc, 'pre', [], "", "");
260 self::tagToBBCode($doc, 'div', [], "\r", "\r");
261 self::tagToBBCode($doc, 'p', [], "\n", "\n");
263 self::tagToBBCode($doc, 'ul', [], "[list]", "[/list]");
264 self::tagToBBCode($doc, 'ol', [], "[list=1]", "[/list]");
265 self::tagToBBCode($doc, 'li', [], "[*]", "");
267 self::tagToBBCode($doc, 'hr', [], "[hr]", "");
269 self::tagToBBCode($doc, 'table', [], "", "");
270 self::tagToBBCode($doc, 'tr', [], "\n", "");
271 self::tagToBBCode($doc, 'td', [], "\t", "");
272 //self::node2BBCode($doc, 'table', array(), "[table]", "[/table]");
273 //self::node2BBCode($doc, 'th', array(), "[th]", "[/th]");
274 //self::node2BBCode($doc, 'tr', array(), "[tr]", "[/tr]");
275 //self::node2BBCode($doc, 'td', array(), "[td]", "[/td]");
276 //self::node2BBCode($doc, 'h1', array(), "\n\n[size=xx-large][b]", "[/b][/size]\n");
277 //self::node2BBCode($doc, 'h2', array(), "\n\n[size=x-large][b]", "[/b][/size]\n");
278 //self::node2BBCode($doc, 'h3', array(), "\n\n[size=large][b]", "[/b][/size]\n");
279 //self::node2BBCode($doc, 'h4', array(), "\n\n[size=medium][b]", "[/b][/size]\n");
280 //self::node2BBCode($doc, 'h5', array(), "\n\n[size=small][b]", "[/b][/size]\n");
281 //self::node2BBCode($doc, 'h6', array(), "\n\n[size=x-small][b]", "[/b][/size]\n");
283 self::tagToBBCode($doc, 'h1', [], "[h1]", "[/h1]");
284 self::tagToBBCode($doc, 'h2', [], "[h2]", "[/h2]");
285 self::tagToBBCode($doc, 'h3', [], "[h3]", "[/h3]");
286 self::tagToBBCode($doc, 'h4', [], "[h4]", "[/h4]");
287 self::tagToBBCode($doc, 'h5', [], "[h5]", "[/h5]");
288 self::tagToBBCode($doc, 'h6', [], "[h6]", "[/h6]");
290 self::tagToBBCode($doc, 'a', ['href' => '/mailto:(.+)/'], '[mail=$1]', '[/mail]');
291 self::tagToBBCode($doc, 'a', ['href' => '/(.+)/'], '[url=$1]', '[/url]');
293 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/', 'width' => '/(\d+)/', 'height' => '/(\d+)/'], '[img=$2x$3]$1', '[/img]');
294 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], '[img]$1', '[/img]');
297 self::tagToBBCode($doc, 'video', ['src' => '/(.+)/'], '[video]$1', '[/video]');
298 self::tagToBBCode($doc, 'audio', ['src' => '/(.+)/'], '[audio]$1', '[/audio]');
299 self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], '[iframe]$1', '[/iframe]');
301 self::tagToBBCode($doc, 'key', [], '[code]', '[/code]');
302 self::tagToBBCode($doc, 'code', [], '[code]', '[/code]');
304 $message = $doc->saveHTML();
306 // I'm removing something really disturbing
307 // Don't know exactly what it is
308 $message = str_replace(chr(194) . chr(160), ' ', $message);
310 $message = str_replace(" ", " ", $message);
312 // removing multiple DIVs
313 $message = preg_replace('=\r *\r=i', "\n", $message);
314 $message = str_replace("\r", "\n", $message);
316 Addon::callHooks('html2bbcode', $message);
318 $message = strip_tags($message);
320 $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
322 $message = str_replace(["<"], ["<"], $message);
324 // remove quotes if they don't make sense
325 $message = preg_replace('=\[/quote\][\s]*\[quote\]=i', "\n", $message);
327 $message = preg_replace('=\[quote\]\s*=i', "[quote]", $message);
328 $message = preg_replace('=\s*\[/quote\]=i', "[/quote]", $message);
331 $oldmessage = $message;
332 $message = str_replace("\n \n", "\n\n", $message);
333 } while ($oldmessage != $message);
336 $oldmessage = $message;
337 $message = str_replace("\n\n\n", "\n\n", $message);
338 } while ($oldmessage != $message);
341 $oldmessage = $message;
342 $message = str_replace(
365 } while ($message != $oldmessage);
367 $message = str_replace(
368 ['[b][b]', '[/b][/b]', '[i][i]', '[/i][/i]'],
369 ['[b]', '[/b]', '[i]', '[/i]'],
373 // Handling Yahoo style of mails
374 $message = str_replace('[hr][b]From:[/b]', '[quote][b]From:[/b]', $message);
376 // Restore code blocks
377 $message = preg_replace_callback(
378 '#\[codeblock-([0-9]+)\]#iU',
379 function ($matches) use ($codeblocks) {
381 if (isset($codeblocks[intval($matches[1])])) {
382 $return = $codeblocks[$matches[1]];
389 $message = trim($message);
391 if ($basepath != '') {
392 $message = self::qualifyURLs($message, $basepath);
399 * @brief Sub function to complete incomplete URL
401 * @param array $matches Result of preg_replace_callback
402 * @param string $basepath Basepath that is used to complete the URL
404 * @return string The expanded URL
406 private static function qualifyURLsSub($matches, $basepath)
408 $base = parse_url($basepath);
409 unset($base['query']);
410 unset($base['fragment']);
415 $parts = array_merge($base, parse_url($url));
416 $url2 = Network::unparseURL($parts);
418 return str_replace($url, $url2, $link);
422 * @brief Complete incomplete URLs in BBCode
424 * @param string $body Body with URLs
425 * @param string $basepath Base path that is used to complete the URL
427 * @return string Body with expanded URLs
429 private static function qualifyURLs($body, $basepath)
431 $URLSearchString = "^\[\]";
433 $matches = ["/\[url\=([$URLSearchString]*)\].*?\[\/url\]/ism",
434 "/\[url\]([$URLSearchString]*)\[\/url\]/ism",
435 "/\[img\=[0-9]*x[0-9]*\](.*?)\[\/img\]/ism",
436 "/\[img\](.*?)\[\/img\]/ism",
437 "/\[zmg\=[0-9]*x[0-9]*\](.*?)\[\/img\]/ism",
438 "/\[zmg\](.*?)\[\/zmg\]/ism",
439 "/\[video\](.*?)\[\/video\]/ism",
440 "/\[audio\](.*?)\[\/audio\]/ism",
443 foreach ($matches as $match) {
444 $body = preg_replace_callback(
446 function ($match) use ($basepath) {
447 return self::qualifyURLsSub($match, $basepath);
455 private static function breakLines($line, $level, $wraplength = 75)
457 if ($wraplength == 0) {
458 $wraplength = 2000000;
461 $wraplen = $wraplength - $level;
468 $subline = substr($line, 0, $wraplen);
470 $pos = strrpos($subline, ' ');
473 $pos = strpos($line, ' ');
476 if (($pos > 0) && strlen($line) > $wraplen) {
477 $newline = trim(substr($line, 0, $pos));
479 $newline = str_repeat(">", $level) . ' ' . $newline;
482 $newlines[] = $newline . " ";
483 $line = substr($line, $pos + 1);
485 } while ((strlen($line) > $wraplen) && !($oldline == $line));
488 $line = str_repeat(">", $level) . ' ' . $line;
493 return implode($newlines, "\n");
496 private static function quoteLevel($message, $wraplength = 75)
498 $lines = explode("\n", $message);
502 foreach ($lines as $line) {
505 while (strpos("*" . $line, '[quote]') > 0) {
507 $pos = strpos($line, '[quote]');
508 $line = substr($line, 0, $pos) . substr($line, $pos + 7);
514 while (strpos("*" . $line, '[/quote]') > 0) {
520 $pos = strpos($line, '[/quote]');
521 $line = substr($line, 0, $pos) . substr($line, $pos + 8);
524 if (!$startquote || ($line != '')) {
525 $newlines[] = self::breakLines($line, $currlevel, $wraplength);
529 return implode($newlines, "\n");
532 private static function collectURLs($message)
534 $pattern = '/<a.*?href="(.*?)".*?>(.*?)<\/a>/is';
535 preg_match_all($pattern, $message, $result, PREG_SET_ORDER);
538 foreach ($result as $treffer) {
541 // A list of some links that should be ignored
542 $list = ["/user/", "/tag/", "/group/", "/profile/", "/search?search=", "/search?tag=", "mailto:", "/u/", "/node/",
543 "//plus.google.com/", "//twitter.com/"];
544 foreach ($list as $listitem) {
545 if (strpos($treffer[1], $listitem) !== false) {
550 if ((strpos($treffer[1], "//twitter.com/") !== false) && (strpos($treffer[1], "/status/") !== false)) {
554 if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/posts") !== false)) {
558 if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/photos") !== false)) {
563 $urls[$treffer[1]] = $treffer[1];
570 public static function toPlaintext($html, $wraplength = 75, $compact = false)
572 $message = str_replace("\r", "", $html);
574 $doc = new DOMDocument();
575 $doc->preserveWhiteSpace = false;
577 $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8");
579 @$doc->loadHTML($message);
581 $xpath = new DOMXPath($doc);
582 $list = $xpath->query("//pre");
583 foreach ($list as $node) {
584 $node->nodeValue = str_replace("\n", "\r", $node->nodeValue);
587 $message = $doc->saveHTML();
588 $message = str_replace(["\n<", ">\n", "\r", "\n", "\xC3\x82\xC2\xA0"], ["<", ">", "<br>", " ", ""], $message);
589 $message = preg_replace('= [\s]*=i', " ", $message);
591 // Collecting all links
592 $urls = self::collectURLs($message);
594 @$doc->loadHTML($message);
596 self::tagToBBCode($doc, 'html', [], '', '');
597 self::tagToBBCode($doc, 'body', [], '', '');
599 // MyBB-Auszeichnungen
601 self::node2BBCode($doc, 'span', array('style'=>'text-decoration: underline;'), '_', '_');
602 self::node2BBCode($doc, 'span', array('style'=>'font-style: italic;'), '/', '/');
603 self::node2BBCode($doc, 'span', array('style'=>'font-weight: bold;'), '*', '*');
605 self::node2BBCode($doc, 'strong', array(), '*', '*');
606 self::node2BBCode($doc, 'b', array(), '*', '*');
607 self::node2BBCode($doc, 'i', array(), '/', '/');
608 self::node2BBCode($doc, 'u', array(), '_', '_');
612 self::tagToBBCode($doc, 'blockquote', [], "»", "«");
614 self::tagToBBCode($doc, 'blockquote', [], '[quote]', "[/quote]\n");
617 self::tagToBBCode($doc, 'br', [], "\n", '');
619 self::tagToBBCode($doc, 'span', [], "", "");
620 self::tagToBBCode($doc, 'pre', [], "", "");
621 self::tagToBBCode($doc, 'div', [], "\r", "\r");
622 self::tagToBBCode($doc, 'p', [], "\n", "\n");
624 //self::node2BBCode($doc, 'ul', array(), "\n[list]", "[/list]\n");
625 //self::node2BBCode($doc, 'ol', array(), "\n[list=1]", "[/list]\n");
626 self::tagToBBCode($doc, 'li', [], "\n* ", "\n");
628 self::tagToBBCode($doc, 'hr', [], "\n" . str_repeat("-", 70) . "\n", "");
630 self::tagToBBCode($doc, 'tr', [], "\n", "");
631 self::tagToBBCode($doc, 'td', [], "\t", "");
633 self::tagToBBCode($doc, 'h1', [], "\n\n*", "*\n");
634 self::tagToBBCode($doc, 'h2', [], "\n\n*", "*\n");
635 self::tagToBBCode($doc, 'h3', [], "\n\n*", "*\n");
636 self::tagToBBCode($doc, 'h4', [], "\n\n*", "*\n");
637 self::tagToBBCode($doc, 'h5', [], "\n\n*", "*\n");
638 self::tagToBBCode($doc, 'h6', [], "\n\n*", "*\n");
640 // Problem: there is no reliable way to detect if it is a link to a tag or profile
641 //self::node2BBCode($doc, 'a', array('href'=>'/(.+)/'), ' $1 ', ' ', true);
642 //self::node2BBCode($doc, 'a', array('href'=>'/(.+)/', 'rel'=>'oembed'), ' $1 ', '', true);
643 //self::node2BBCode($doc, 'img', array('alt'=>'/(.+)/'), '$1', '');
644 //self::node2BBCode($doc, 'img', array('title'=>'/(.+)/'), '$1', '');
645 //self::node2BBCode($doc, 'img', array(), '', '');
647 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], ' [img]$1', '[/img] ');
649 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], ' ', ' ');
652 self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], ' $1 ', '');
654 $message = $doc->saveHTML();
657 $message = str_replace("[img]", "", $message);
658 $message = str_replace("[/img]", "", $message);
661 // was ersetze ich da?
662 // Irgendein stoerrisches UTF-Zeug
663 $message = str_replace(chr(194) . chr(160), ' ', $message);
665 $message = str_replace(" ", " ", $message);
667 // Aufeinanderfolgende DIVs
668 $message = preg_replace('=\r *\r=i', "\n", $message);
669 $message = str_replace("\r", "\n", $message);
671 $message = strip_tags($message);
673 $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
675 if (!$compact && ($message != '')) {
676 foreach ($urls as $id => $url) {
677 if ($url != '' && strpos($message, $url) === false) {
678 $message .= "\n" . $url . ' ';
683 $message = str_replace("\n«", "«\n", $message);
684 $message = str_replace("»\n", "\n»", $message);
687 $oldmessage = $message;
688 $message = str_replace("\n\n\n", "\n\n", $message);
689 } while ($oldmessage != $message);
691 $message = self::quoteLevel(trim($message), $wraplength);
693 return trim($message);
697 * Converts provided HTML code to Markdown. The hardwrap parameter maximizes
698 * compatibility with Diaspora in spite of the Markdown standards.
700 * @param string $html
703 public static function toMarkdown($html)
705 $converter = new HtmlConverter(['hard_break' => true]);
706 $markdown = $converter->convert($html);
712 * @brief Convert video HTML to BBCode tags
716 public static function toBBCodeVideo($s)
719 '#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
720 '[youtube]$2[/youtube]',
725 '#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
726 '[youtube]$2[/youtube]',
731 '#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
740 * transform link href and img src from relative to absolute
742 * @param string $text
743 * @param string $base base url
746 public static function relToAbs($text, $base)
752 $base = rtrim($base, '/');
754 $base2 = $base . "/";
757 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
758 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
759 $text = preg_replace($pattern, $replace, $text);
761 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
762 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
763 $text = preg_replace($pattern, $replace, $text);
766 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
767 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
768 $text = preg_replace($pattern, $replace, $text);
770 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
771 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
772 $text = preg_replace($pattern, $replace, $text);
780 * return div element with class 'clear'
784 public static function clearDiv()
786 return '<div class="clear"></div>';
790 * Loader for infinite scrolling
791 * @return string html for loader
793 public static function scrollLoader()
795 $tpl = Renderer::getMarkupTemplate("scroll_loader.tpl");
796 return Renderer::replaceMacros($tpl, [
797 'wait' => L10n::t('Loading more entries...'),
798 'end' => L10n::t('The end')
803 * Get html for contact block.
805 * @template contact_block.tpl
806 * @hook contact_block_end (contacts=>array, output=>string)
809 public static function contactBlock()
814 $shown = PConfig::get($a->profile['uid'], 'system', 'display_friend_count', 24);
819 if (!is_array($a->profile) || $a->profile['hide-friends']) {
823 $r = q("SELECT COUNT(*) AS `total` FROM `contact`
824 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
825 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
826 AND `network` IN ('%s', '%s', '%s')",
827 intval($a->profile['uid']),
828 DBA::escape(Protocol::DFRN),
829 DBA::escape(Protocol::OSTATUS),
830 DBA::escape(Protocol::DIASPORA)
833 if (DBA::isResult($r)) {
834 $total = intval($r[0]['total']);
838 $contacts = L10n::t('No contacts');
841 // Splitting the query in two parts makes it much faster
842 $r = q("SELECT `id` FROM `contact`
843 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
844 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
845 AND `network` IN ('%s', '%s', '%s')
846 ORDER BY RAND() LIMIT %d",
847 intval($a->profile['uid']),
848 DBA::escape(Protocol::DFRN),
849 DBA::escape(Protocol::OSTATUS),
850 DBA::escape(Protocol::DIASPORA),
854 if (DBA::isResult($r)) {
856 foreach ($r as $contact) {
857 $contacts[] = $contact["id"];
860 $r = q("SELECT `id`, `uid`, `addr`, `url`, `name`, `thumb`, `network` FROM `contact` WHERE `id` IN (%s)",
861 DBA::escape(implode(",", $contacts))
864 if (DBA::isResult($r)) {
865 $contacts = L10n::tt('%d Contact', '%d Contacts', $total);
867 foreach ($r as $rr) {
868 $micropro[] = self::micropro($rr, true, 'mpfriend');
874 $tpl = Renderer::getMarkupTemplate('contact_block.tpl');
875 $o = Renderer::replaceMacros($tpl, [
876 '$contacts' => $contacts,
877 '$nickname' => $a->profile['nickname'],
878 '$viewcontacts' => L10n::t('View Contacts'),
879 '$micropro' => $micropro,
882 $arr = ['contacts' => $r, 'output' => $o];
884 Addon::callHooks('contact_block_end', $arr);
890 * @brief Format contacts as picture links or as texxt links
892 * @param array $contact Array with contacts which contains an array with
893 * int 'id' => The ID of the contact
894 * int 'uid' => The user ID of the user who owns this data
895 * string 'name' => The name of the contact
896 * string 'url' => The url to the profile page of the contact
897 * string 'addr' => The webbie of the contact (e.g.) username@friendica.com
898 * string 'network' => The network to which the contact belongs to
899 * string 'thumb' => The contact picture
900 * string 'click' => js code which is performed when clicking on the contact
901 * @param boolean $redirect If true try to use the redir url if it's possible
902 * @param string $class CSS class for the
903 * @param boolean $textmode If true display the contacts as text links
904 * if false display the contacts as picture links
906 * @return string Formatted html
908 public static function micropro($contact, $redirect = false, $class = '', $textmode = false)
910 // Use the contact URL if no address is available
911 if (empty($contact['addr'])) {
912 $contact["addr"] = $contact["url"];
915 $url = $contact['url'];
920 $url = Contact::magicLink($contact['url']);
921 if (strpos($url, 'redir/') === 0) {
922 $sparkle = ' sparkle';
926 // If there is some js available we don't need the url
927 if (!empty($contact['click'])) {
931 return Renderer::replaceMacros(Renderer::getMarkupTemplate(($textmode)?'micropro_txt.tpl':'micropro_img.tpl'), [
932 '$click' => defaults($contact, 'click', ''),
935 '$photo' => ProxyUtils::proxifyUrl($contact['thumb'], false, ProxyUtils::SIZE_THUMB),
936 '$name' => $contact['name'],
937 'title' => $contact['name'] . ' [' . $contact['addr'] . ']',
938 '$parkle' => $sparkle,
946 * @param string $s Search query.
947 * @param string $id HTML id
948 * @param string $url Search url.
949 * @param bool $save Show save search button.
950 * @param bool $aside Display the search widgit aside.
952 * @return string Formatted HTML.
954 public static function search($s, $id = 'search-box', $url = 'search', $aside = true)
958 if (strpos($s, '#') === 0) {
961 $save_label = $mode === 'text' ? L10n::t('Save') : L10n::t('Follow');
964 '$s' => htmlspecialchars($s),
966 '$action_url' => $url,
967 '$search_label' => L10n::t('Search'),
968 '$save_label' => $save_label,
969 '$savedsearch' => 'savedsearch',
970 '$search_hint' => L10n::t('@name, !forum, #tags, content'),
975 $values['$searchoption'] = [
976 L10n::t("Full Text"),
978 L10n::t("Contacts")];
980 if (Config::get('system', 'poco_local_search')) {
981 $values['$searchoption'][] = L10n::t("Forums");
985 return Renderer::replaceMacros(Renderer::getMarkupTemplate('searchbox.tpl'), $values);
989 * Replace naked text hyperlink with HTML formatted hyperlink
993 public static function toLink($s)
995 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank">$1</a>', $s);
996 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism", '<$1$2=$3&$4>', $s);
1001 * Given a HTML text and a set of filtering reasons, adds a content hiding header with the provided reasons
1003 * Reasons are expected to have been translated already.
1005 * @param string $html
1006 * @param array $reasons
1009 public static function applyContentFilter($html, array $reasons)
1011 if (count($reasons)) {
1012 $tpl = Renderer::getMarkupTemplate('wall/content_filter.tpl');
1013 $html = Renderer::replaceMacros($tpl, [
1014 '$reasons' => $reasons,
1015 '$rnd' => Strings::getRandomHex(8),
1016 '$openclose' => L10n::t('Click to open/close'),
1025 * replace html amp entity with amp char
1029 public static function unamp($s)
1031 return str_replace('&', '&', $s);