3 * @file src/Content/Text/HTML.php
6 namespace Friendica\Content\Text;
10 use Friendica\Core\Addon;
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\XML;
21 use League\HTMLToMarkdown\HtmlConverter;
22 use Friendica\Content\Feature;
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
127 public static function toBBCode($message, $basepath = '')
129 $message = str_replace("\r", "", $message);
131 // Removing code blocks before the whitespace removal processing below
133 $message = preg_replace_callback(
134 '#<pre><code(?: class="language-([^"]*)")?>(.*)</code></pre>#iUs',
135 function ($matches) use (&$codeblocks) {
136 $return = '[codeblock-' . count($codeblocks) . ']';
139 if ($matches[1] != '') {
140 $prefix = '[code=' . $matches[1] . ']';
143 $codeblocks[] = $prefix . PHP_EOL . trim($matches[2]) . PHP_EOL . '[/code]';
149 $message = str_replace(
162 $message = preg_replace('=<(\w+):(.+?)>=', '<removeme>', $message);
163 $message = preg_replace('=</(\w+):(.+?)>=', '</removeme>', $message);
165 $doc = new DOMDocument();
166 $doc->preserveWhiteSpace = false;
168 $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8");
170 @$doc->loadHTML($message);
172 XML::deleteNode($doc, 'style');
173 XML::deleteNode($doc, 'head');
174 XML::deleteNode($doc, 'title');
175 XML::deleteNode($doc, 'meta');
176 XML::deleteNode($doc, 'xml');
177 XML::deleteNode($doc, 'removeme');
179 $xpath = new DomXPath($doc);
180 $list = $xpath->query("//pre");
181 foreach ($list as $node) {
182 $node->nodeValue = str_replace("\n", "\r", $node->nodeValue);
185 $message = $doc->saveHTML();
186 $message = str_replace(["\n<", ">\n", "\r", "\n", "\xC3\x82\xC2\xA0"], ["<", ">", "<br />", " ", ""], $message);
187 $message = preg_replace('= [\s]*=i', " ", $message);
188 @$doc->loadHTML($message);
190 self::tagToBBCode($doc, 'html', [], "", "");
191 self::tagToBBCode($doc, 'body', [], "", "");
193 // Outlook-Quote - Variant 1
194 self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal', 'style' => 'margin-left:35.4pt'], '[quote]', '[/quote]');
196 // Outlook-Quote - Variant 2
200 ['style' => 'border:none;border-left:solid blue 1.5pt;padding:0cm 0cm 0cm 4.0pt'],
206 self::tagToBBCode($doc, 'span', ['style' => 'text-decoration: underline;'], '[u]', '[/u]');
207 self::tagToBBCode($doc, 'span', ['style' => 'font-style: italic;'], '[i]', '[/i]');
208 self::tagToBBCode($doc, 'span', ['style' => 'font-weight: bold;'], '[b]', '[/b]');
210 /* self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[font=$1][size=$2][color=$3]', '[/color][/size][/font]');
211 self::node2BBCode($doc, 'font', array('size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[size=$1][color=$2]', '[/color][/size]');
212 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(.+)/'), '[font=$1][size=$2]', '[/size][/font]');
213 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'color'=>'/(.+)/'), '[font=$1][color=$3]', '[/color][/font]');
214 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/'), '[font=$1]', '[/font]');
215 self::node2BBCode($doc, 'font', array('size'=>'/(\d+)/'), '[size=$1]', '[/size]');
216 self::node2BBCode($doc, 'font', array('color'=>'/(.+)/'), '[color=$1]', '[/color]');
219 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*font-family:\s*(.+?)[,;].*color:\s*(.+?)[,;].*/'), '[size=$1][font=$2][color=$3]', '[/color][/font][/size]');
220 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(\d+)[,;].*/'), '[size=$1]', '[/size]');
221 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*/'), '[size=$1]', '[/size]');
223 self::tagToBBCode($doc, 'span', ['style' => '/.*color:\s*(.+?)[,;].*/'], '[color="$1"]', '[/color]');
225 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
226 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)pt.*/'), '[font=$1][size=$2]', '[/size][/font]');
227 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)px.*/'), '[font=$1][size=$2]', '[/size][/font]');
228 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
229 // Importing the classes - interesting for importing of posts from third party networks that were exported from friendica
231 //self::node2BBCode($doc, 'span', array('class'=>'/([\w ]+)/'), '[class=$1]', '[/class]');
232 self::tagToBBCode($doc, 'span', ['class' => 'type-link'], '[class=type-link]', '[/class]');
233 self::tagToBBCode($doc, 'span', ['class' => 'type-video'], '[class=type-video]', '[/class]');
235 self::tagToBBCode($doc, 'strong', [], '[b]', '[/b]');
236 self::tagToBBCode($doc, 'em', [], '[i]', '[/i]');
237 self::tagToBBCode($doc, 'b', [], '[b]', '[/b]');
238 self::tagToBBCode($doc, 'i', [], '[i]', '[/i]');
239 self::tagToBBCode($doc, 'u', [], '[u]', '[/u]');
240 self::tagToBBCode($doc, 's', [], '[s]', '[/s]');
241 self::tagToBBCode($doc, 'del', [], '[s]', '[/s]');
242 self::tagToBBCode($doc, 'strike', [], '[s]', '[/s]');
244 self::tagToBBCode($doc, 'big', [], "[size=large]", "[/size]");
245 self::tagToBBCode($doc, 'small', [], "[size=small]", "[/size]");
247 self::tagToBBCode($doc, 'blockquote', [], '[quote]', '[/quote]');
249 self::tagToBBCode($doc, 'br', [], "\n", '');
251 self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal'], "\n", "");
252 self::tagToBBCode($doc, 'div', ['class' => 'MsoNormal'], "\r", "");
254 self::tagToBBCode($doc, 'span', [], "", "");
256 self::tagToBBCode($doc, 'span', [], "", "");
257 self::tagToBBCode($doc, 'pre', [], "", "");
259 self::tagToBBCode($doc, 'div', [], "\r", "\r");
260 self::tagToBBCode($doc, 'p', [], "\n", "\n");
262 self::tagToBBCode($doc, 'ul', [], "[list]", "[/list]");
263 self::tagToBBCode($doc, 'ol', [], "[list=1]", "[/list]");
264 self::tagToBBCode($doc, 'li', [], "[*]", "");
266 self::tagToBBCode($doc, 'hr', [], "[hr]", "");
268 self::tagToBBCode($doc, 'table', [], "", "");
269 self::tagToBBCode($doc, 'tr', [], "\n", "");
270 self::tagToBBCode($doc, 'td', [], "\t", "");
271 //self::node2BBCode($doc, 'table', array(), "[table]", "[/table]");
272 //self::node2BBCode($doc, 'th', array(), "[th]", "[/th]");
273 //self::node2BBCode($doc, 'tr', array(), "[tr]", "[/tr]");
274 //self::node2BBCode($doc, 'td', array(), "[td]", "[/td]");
275 //self::node2BBCode($doc, 'h1', array(), "\n\n[size=xx-large][b]", "[/b][/size]\n");
276 //self::node2BBCode($doc, 'h2', array(), "\n\n[size=x-large][b]", "[/b][/size]\n");
277 //self::node2BBCode($doc, 'h3', array(), "\n\n[size=large][b]", "[/b][/size]\n");
278 //self::node2BBCode($doc, 'h4', array(), "\n\n[size=medium][b]", "[/b][/size]\n");
279 //self::node2BBCode($doc, 'h5', array(), "\n\n[size=small][b]", "[/b][/size]\n");
280 //self::node2BBCode($doc, 'h6', array(), "\n\n[size=x-small][b]", "[/b][/size]\n");
282 self::tagToBBCode($doc, 'h1', [], "[h1]", "[/h1]");
283 self::tagToBBCode($doc, 'h2', [], "[h2]", "[/h2]");
284 self::tagToBBCode($doc, 'h3', [], "[h3]", "[/h3]");
285 self::tagToBBCode($doc, 'h4', [], "[h4]", "[/h4]");
286 self::tagToBBCode($doc, 'h5', [], "[h5]", "[/h5]");
287 self::tagToBBCode($doc, 'h6', [], "[h6]", "[/h6]");
289 self::tagToBBCode($doc, 'a', ['href' => '/mailto:(.+)/'], '[mail=$1]', '[/mail]');
290 self::tagToBBCode($doc, 'a', ['href' => '/(.+)/'], '[url=$1]', '[/url]');
292 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/', 'width' => '/(\d+)/', 'height' => '/(\d+)/'], '[img=$2x$3]$1', '[/img]');
293 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], '[img]$1', '[/img]');
296 self::tagToBBCode($doc, 'video', ['src' => '/(.+)/'], '[video]$1', '[/video]');
297 self::tagToBBCode($doc, 'audio', ['src' => '/(.+)/'], '[audio]$1', '[/audio]');
298 self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], '[iframe]$1', '[/iframe]');
300 self::tagToBBCode($doc, 'key', [], '[code]', '[/code]');
301 self::tagToBBCode($doc, 'code', [], '[code]', '[/code]');
303 $message = $doc->saveHTML();
305 // I'm removing something really disturbing
306 // Don't know exactly what it is
307 $message = str_replace(chr(194) . chr(160), ' ', $message);
309 $message = str_replace(" ", " ", $message);
311 // removing multiple DIVs
312 $message = preg_replace('=\r *\r=i', "\n", $message);
313 $message = str_replace("\r", "\n", $message);
315 Addon::callHooks('html2bbcode', $message);
317 $message = strip_tags($message);
319 $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
321 $message = str_replace(["<"], ["<"], $message);
323 // remove quotes if they don't make sense
324 $message = preg_replace('=\[/quote\][\s]*\[quote\]=i', "\n", $message);
326 $message = preg_replace('=\[quote\]\s*=i', "[quote]", $message);
327 $message = preg_replace('=\s*\[/quote\]=i', "[/quote]", $message);
330 $oldmessage = $message;
331 $message = str_replace("\n \n", "\n\n", $message);
332 } while ($oldmessage != $message);
335 $oldmessage = $message;
336 $message = str_replace("\n\n\n", "\n\n", $message);
337 } while ($oldmessage != $message);
340 $oldmessage = $message;
341 $message = str_replace(
364 } while ($message != $oldmessage);
366 $message = str_replace(
367 ['[b][b]', '[/b][/b]', '[i][i]', '[/i][/i]'],
368 ['[b]', '[/b]', '[i]', '[/i]'],
372 // Handling Yahoo style of mails
373 $message = str_replace('[hr][b]From:[/b]', '[quote][b]From:[/b]', $message);
375 // Restore code blocks
376 $message = preg_replace_callback(
377 '#\[codeblock-([0-9]+)\]#iU',
378 function ($matches) use ($codeblocks) {
380 if (isset($codeblocks[intval($matches[1])])) {
381 $return = $codeblocks[$matches[1]];
388 $message = trim($message);
390 if ($basepath != '') {
391 $message = self::qualifyURLs($message, $basepath);
398 * @brief Sub function to complete incomplete URL
400 * @param array $matches Result of preg_replace_callback
401 * @param string $basepath Basepath that is used to complete the URL
403 * @return string The expanded URL
405 private static function qualifyURLsSub($matches, $basepath)
407 $base = parse_url($basepath);
408 unset($base['query']);
409 unset($base['fragment']);
414 $parts = array_merge($base, parse_url($url));
415 $url2 = Network::unparseURL($parts);
417 return str_replace($url, $url2, $link);
421 * @brief Complete incomplete URLs in BBCode
423 * @param string $body Body with URLs
424 * @param string $basepath Base path that is used to complete the URL
426 * @return string Body with expanded URLs
428 private static function qualifyURLs($body, $basepath)
430 $URLSearchString = "^\[\]";
432 $matches = ["/\[url\=([$URLSearchString]*)\].*?\[\/url\]/ism",
433 "/\[url\]([$URLSearchString]*)\[\/url\]/ism",
434 "/\[img\=[0-9]*x[0-9]*\](.*?)\[\/img\]/ism",
435 "/\[img\](.*?)\[\/img\]/ism",
436 "/\[zmg\=[0-9]*x[0-9]*\](.*?)\[\/img\]/ism",
437 "/\[zmg\](.*?)\[\/zmg\]/ism",
438 "/\[video\](.*?)\[\/video\]/ism",
439 "/\[audio\](.*?)\[\/audio\]/ism",
442 foreach ($matches as $match) {
443 $body = preg_replace_callback(
445 function ($match) use ($basepath) {
446 return self::qualifyURLsSub($match, $basepath);
454 private static function breakLines($line, $level, $wraplength = 75)
456 if ($wraplength == 0) {
457 $wraplength = 2000000;
460 $wraplen = $wraplength - $level;
467 $subline = substr($line, 0, $wraplen);
469 $pos = strrpos($subline, ' ');
472 $pos = strpos($line, ' ');
475 if (($pos > 0) && strlen($line) > $wraplen) {
476 $newline = trim(substr($line, 0, $pos));
478 $newline = str_repeat(">", $level) . ' ' . $newline;
481 $newlines[] = $newline . " ";
482 $line = substr($line, $pos + 1);
484 } while ((strlen($line) > $wraplen) && !($oldline == $line));
487 $line = str_repeat(">", $level) . ' ' . $line;
492 return implode($newlines, "\n");
495 private static function quoteLevel($message, $wraplength = 75)
497 $lines = explode("\n", $message);
501 foreach ($lines as $line) {
504 while (strpos("*" . $line, '[quote]') > 0) {
506 $pos = strpos($line, '[quote]');
507 $line = substr($line, 0, $pos) . substr($line, $pos + 7);
513 while (strpos("*" . $line, '[/quote]') > 0) {
519 $pos = strpos($line, '[/quote]');
520 $line = substr($line, 0, $pos) . substr($line, $pos + 8);
523 if (!$startquote || ($line != '')) {
524 $newlines[] = self::breakLines($line, $currlevel, $wraplength);
528 return implode($newlines, "\n");
531 private static function collectURLs($message)
533 $pattern = '/<a.*?href="(.*?)".*?>(.*?)<\/a>/is';
534 preg_match_all($pattern, $message, $result, PREG_SET_ORDER);
537 foreach ($result as $treffer) {
540 // A list of some links that should be ignored
541 $list = ["/user/", "/tag/", "/group/", "/profile/", "/search?search=", "/search?tag=", "mailto:", "/u/", "/node/",
542 "//plus.google.com/", "//twitter.com/"];
543 foreach ($list as $listitem) {
544 if (strpos($treffer[1], $listitem) !== false) {
549 if ((strpos($treffer[1], "//twitter.com/") !== false) && (strpos($treffer[1], "/status/") !== false)) {
553 if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/posts") !== false)) {
557 if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/photos") !== false)) {
562 $urls[$treffer[1]] = $treffer[1];
569 public static function toPlaintext($html, $wraplength = 75, $compact = false)
571 $message = str_replace("\r", "", $html);
573 $doc = new DOMDocument();
574 $doc->preserveWhiteSpace = false;
576 $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8");
578 @$doc->loadHTML($message);
580 $xpath = new DOMXPath($doc);
581 $list = $xpath->query("//pre");
582 foreach ($list as $node) {
583 $node->nodeValue = str_replace("\n", "\r", $node->nodeValue);
586 $message = $doc->saveHTML();
587 $message = str_replace(["\n<", ">\n", "\r", "\n", "\xC3\x82\xC2\xA0"], ["<", ">", "<br>", " ", ""], $message);
588 $message = preg_replace('= [\s]*=i', " ", $message);
590 // Collecting all links
591 $urls = self::collectURLs($message);
593 @$doc->loadHTML($message);
595 self::tagToBBCode($doc, 'html', [], '', '');
596 self::tagToBBCode($doc, 'body', [], '', '');
598 // MyBB-Auszeichnungen
600 self::node2BBCode($doc, 'span', array('style'=>'text-decoration: underline;'), '_', '_');
601 self::node2BBCode($doc, 'span', array('style'=>'font-style: italic;'), '/', '/');
602 self::node2BBCode($doc, 'span', array('style'=>'font-weight: bold;'), '*', '*');
604 self::node2BBCode($doc, 'strong', array(), '*', '*');
605 self::node2BBCode($doc, 'b', array(), '*', '*');
606 self::node2BBCode($doc, 'i', array(), '/', '/');
607 self::node2BBCode($doc, 'u', array(), '_', '_');
611 self::tagToBBCode($doc, 'blockquote', [], "»", "«");
613 self::tagToBBCode($doc, 'blockquote', [], '[quote]', "[/quote]\n");
616 self::tagToBBCode($doc, 'br', [], "\n", '');
618 self::tagToBBCode($doc, 'span', [], "", "");
619 self::tagToBBCode($doc, 'pre', [], "", "");
620 self::tagToBBCode($doc, 'div', [], "\r", "\r");
621 self::tagToBBCode($doc, 'p', [], "\n", "\n");
623 //self::node2BBCode($doc, 'ul', array(), "\n[list]", "[/list]\n");
624 //self::node2BBCode($doc, 'ol', array(), "\n[list=1]", "[/list]\n");
625 self::tagToBBCode($doc, 'li', [], "\n* ", "\n");
627 self::tagToBBCode($doc, 'hr', [], "\n" . str_repeat("-", 70) . "\n", "");
629 self::tagToBBCode($doc, 'tr', [], "\n", "");
630 self::tagToBBCode($doc, 'td', [], "\t", "");
632 self::tagToBBCode($doc, 'h1', [], "\n\n*", "*\n");
633 self::tagToBBCode($doc, 'h2', [], "\n\n*", "*\n");
634 self::tagToBBCode($doc, 'h3', [], "\n\n*", "*\n");
635 self::tagToBBCode($doc, 'h4', [], "\n\n*", "*\n");
636 self::tagToBBCode($doc, 'h5', [], "\n\n*", "*\n");
637 self::tagToBBCode($doc, 'h6', [], "\n\n*", "*\n");
639 // Problem: there is no reliable way to detect if it is a link to a tag or profile
640 //self::node2BBCode($doc, 'a', array('href'=>'/(.+)/'), ' $1 ', ' ', true);
641 //self::node2BBCode($doc, 'a', array('href'=>'/(.+)/', 'rel'=>'oembed'), ' $1 ', '', true);
642 //self::node2BBCode($doc, 'img', array('alt'=>'/(.+)/'), '$1', '');
643 //self::node2BBCode($doc, 'img', array('title'=>'/(.+)/'), '$1', '');
644 //self::node2BBCode($doc, 'img', array(), '', '');
646 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], ' [img]$1', '[/img] ');
648 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], ' ', ' ');
651 self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], ' $1 ', '');
653 $message = $doc->saveHTML();
656 $message = str_replace("[img]", "", $message);
657 $message = str_replace("[/img]", "", $message);
660 // was ersetze ich da?
661 // Irgendein stoerrisches UTF-Zeug
662 $message = str_replace(chr(194) . chr(160), ' ', $message);
664 $message = str_replace(" ", " ", $message);
666 // Aufeinanderfolgende DIVs
667 $message = preg_replace('=\r *\r=i', "\n", $message);
668 $message = str_replace("\r", "\n", $message);
670 $message = strip_tags($message);
672 $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
674 if (!$compact && ($message != '')) {
675 foreach ($urls as $id => $url) {
676 if ($url != '' && strpos($message, $url) === false) {
677 $message .= "\n" . $url . ' ';
682 $message = str_replace("\n«", "«\n", $message);
683 $message = str_replace("»\n", "\n»", $message);
686 $oldmessage = $message;
687 $message = str_replace("\n\n\n", "\n\n", $message);
688 } while ($oldmessage != $message);
690 $message = self::quoteLevel(trim($message), $wraplength);
692 return trim($message);
696 * Converts provided HTML code to Markdown. The hardwrap parameter maximizes
697 * compatibility with Diaspora in spite of the Markdown standards.
699 * @param string $html
702 public static function toMarkdown($html)
704 $converter = new HtmlConverter(['hard_break' => true]);
705 $markdown = $converter->convert($html);
711 * @brief Convert video HTML to BBCode tags
715 public static function toBBCodeVideo($s)
718 '#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
719 '[youtube]$2[/youtube]',
724 '#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
725 '[youtube]$2[/youtube]',
730 '#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
739 * transform link href and img src from relative to absolute
741 * @param string $text
742 * @param string $base base url
745 public static function relToAbs($text, $base)
751 $base = rtrim($base, '/');
753 $base2 = $base . "/";
756 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
757 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
758 $text = preg_replace($pattern, $replace, $text);
760 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
761 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
762 $text = preg_replace($pattern, $replace, $text);
765 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
766 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
767 $text = preg_replace($pattern, $replace, $text);
769 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
770 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
771 $text = preg_replace($pattern, $replace, $text);
779 * return div element with class 'clear'
783 public static function clearDiv()
785 return '<div class="clear"></div>';
789 * Loader for infinite scrolling
790 * @return string html for loader
792 public static function scrollLoader()
794 $tpl = Renderer::getMarkupTemplate("scroll_loader.tpl");
795 return Renderer::replaceMacros($tpl, [
796 'wait' => L10n::t('Loading more entries...'),
797 'end' => L10n::t('The end')
802 * Get html for contact block.
804 * @template contact_block.tpl
805 * @hook contact_block_end (contacts=>array, output=>string)
808 public static function contactBlock()
813 $shown = PConfig::get($a->profile['uid'], 'system', 'display_friend_count', 24);
818 if (!is_array($a->profile) || $a->profile['hide-friends']) {
822 $r = q("SELECT COUNT(*) AS `total` FROM `contact`
823 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
824 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
825 AND `network` IN ('%s', '%s', '%s')",
826 intval($a->profile['uid']),
827 DBA::escape(Protocol::DFRN),
828 DBA::escape(Protocol::OSTATUS),
829 DBA::escape(Protocol::DIASPORA)
832 if (DBA::isResult($r)) {
833 $total = intval($r[0]['total']);
837 $contacts = L10n::t('No contacts');
840 // Splitting the query in two parts makes it much faster
841 $r = q("SELECT `id` FROM `contact`
842 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
843 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
844 AND `network` IN ('%s', '%s', '%s')
845 ORDER BY RAND() LIMIT %d",
846 intval($a->profile['uid']),
847 DBA::escape(Protocol::DFRN),
848 DBA::escape(Protocol::OSTATUS),
849 DBA::escape(Protocol::DIASPORA),
853 if (DBA::isResult($r)) {
855 foreach ($r as $contact) {
856 $contacts[] = $contact["id"];
859 $r = q("SELECT `id`, `uid`, `addr`, `url`, `name`, `thumb`, `network` FROM `contact` WHERE `id` IN (%s)",
860 DBA::escape(implode(",", $contacts))
863 if (DBA::isResult($r)) {
864 $contacts = L10n::tt('%d Contact', '%d Contacts', $total);
866 foreach ($r as $rr) {
867 $micropro[] = self::micropro($rr, true, 'mpfriend');
873 $tpl = Renderer::getMarkupTemplate('contact_block.tpl');
874 $o = Renderer::replaceMacros($tpl, [
875 '$contacts' => $contacts,
876 '$nickname' => $a->profile['nickname'],
877 '$viewcontacts' => L10n::t('View Contacts'),
878 '$micropro' => $micropro,
881 $arr = ['contacts' => $r, 'output' => $o];
883 Addon::callHooks('contact_block_end', $arr);
889 * @brief Format contacts as picture links or as texxt links
891 * @param array $contact Array with contacts which contains an array with
892 * int 'id' => The ID of the contact
893 * int 'uid' => The user ID of the user who owns this data
894 * string 'name' => The name of the contact
895 * string 'url' => The url to the profile page of the contact
896 * string 'addr' => The webbie of the contact (e.g.) username@friendica.com
897 * string 'network' => The network to which the contact belongs to
898 * string 'thumb' => The contact picture
899 * string 'click' => js code which is performed when clicking on the contact
900 * @param boolean $redirect If true try to use the redir url if it's possible
901 * @param string $class CSS class for the
902 * @param boolean $textmode If true display the contacts as text links
903 * if false display the contacts as picture links
905 * @return string Formatted html
907 public static function micropro($contact, $redirect = false, $class = '', $textmode = false)
909 // Use the contact URL if no address is available
910 if (!x($contact, "addr")) {
911 $contact["addr"] = $contact["url"];
914 $url = $contact['url'];
919 $url = Contact::magicLink($contact['url']);
920 if (strpos($url, 'redir/') === 0) {
921 $sparkle = ' sparkle';
925 // If there is some js available we don't need the url
926 if (x($contact, 'click')) {
930 return Renderer::replaceMacros(Renderer::getMarkupTemplate(($textmode)?'micropro_txt.tpl':'micropro_img.tpl'), [
931 '$click' => defaults($contact, 'click', ''),
934 '$photo' => ProxyUtils::proxifyUrl($contact['thumb'], false, ProxyUtils::SIZE_THUMB),
935 '$name' => $contact['name'],
936 'title' => $contact['name'] . ' [' . $contact['addr'] . ']',
937 '$parkle' => $sparkle,
945 * @param string $s Search query.
946 * @param string $id HTML id
947 * @param string $url Search url.
948 * @param bool $save Show save search button.
949 * @param bool $aside Display the search widgit aside.
951 * @return string Formatted HTML.
953 public static function search($s, $id = 'search-box', $url = 'search', $save = false, $aside = true)
957 if (strpos($s, '#') === 0) {
960 $save_label = $mode === 'text' ? L10n::t('Save') : L10n::t('Follow');
963 '$s' => htmlspecialchars($s),
965 '$action_url' => $url,
966 '$search_label' => L10n::t('Search'),
967 '$save_label' => $save_label,
968 '$savedsearch' => local_user() && Feature::isEnabled(local_user(), 'savedsearch'),
969 '$search_hint' => L10n::t('@name, !forum, #tags, content'),
974 $values['$searchoption'] = [
975 L10n::t("Full Text"),
977 L10n::t("Contacts")];
979 if (Config::get('system', 'poco_local_search')) {
980 $values['$searchoption'][] = L10n::t("Forums");
984 return Renderer::replaceMacros(Renderer::getMarkupTemplate('searchbox.tpl'), $values);
988 * Replace naked text hyperlink with HTML formatted hyperlink
992 public static function toLink($s)
994 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank">$1</a>', $s);
995 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism", '<$1$2=$3&$4>', $s);
1000 * Given a HTML text and a set of filtering reasons, adds a content hiding header with the provided reasons
1002 * Reasons are expected to have been translated already.
1004 * @param string $html
1005 * @param array $reasons
1008 public static function applyContentFilter($html, array $reasons)
1010 if (count($reasons)) {
1011 $tpl = Renderer::getMarkupTemplate('wall/content_filter.tpl');
1012 $html = Renderer::replaceMacros($tpl, [
1013 '$reasons' => $reasons,
1014 '$rnd' => random_string(8),
1015 '$openclose' => L10n::t('Click to open/close'),
1024 * replace html amp entity with amp char
1028 public static function unamp($s)
1030 return str_replace('&', '&', $s);