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;
25 public static function sanitizeCSS($input)
29 $input = strtolower($input);
31 for ($i = 0; $i < strlen($input); $i++) {
32 $char = substr($input, $i, 1);
34 if (($char >= "a") && ($char <= "z")) {
38 if (!(strpos(" #;:0123456789-_.%", $char) === false)) {
46 private static function tagToBBCode(DOMDocument $doc, $tag, $attributes, $startbb, $endbb)
49 $done = self::tagToBBCodeSub($doc, $tag, $attributes, $startbb, $endbb);
53 private static function tagToBBCodeSub(DOMDocument $doc, $tag, $attributes, $startbb, $endbb)
55 $savestart = str_replace('$', '\x01', $startbb);
58 $xpath = new DOMXPath($doc);
60 $list = $xpath->query("//" . $tag);
61 foreach ($list as $node) {
63 if ($node->attributes->length) {
64 foreach ($node->attributes as $attribute) {
65 $attr[$attribute->name] = $attribute->value;
71 $startbb = $savestart;
75 foreach ($attributes as $attribute => $value) {
76 $startbb = str_replace('\x01' . ++$i, '$1', $startbb);
77 if (strpos('*' . $startbb, '$1') > 0) {
78 if ($replace && (@$attr[$attribute] != '')) {
79 $startbb = preg_replace($value, $startbb, $attr[$attribute], -1, $count);
81 // If nothing could be changed
89 if (@$attr[$attribute] != $value) {
96 $StartCode = $doc->createTextNode($startbb);
97 $EndCode = $doc->createTextNode($endbb);
99 $node->parentNode->insertBefore($StartCode, $node);
101 if ($node->hasChildNodes()) {
102 foreach ($node->childNodes as $child) {
103 $newNode = $child->cloneNode(true);
104 $node->parentNode->insertBefore($newNode, $node);
108 $node->parentNode->insertBefore($EndCode, $node);
109 $node->parentNode->removeChild($node);
117 * Made by: ike@piratenpartei.de
118 * Originally made for the syncom project: http://wiki.piratenpartei.de/Syncom
119 * https://github.com/annando/Syncom
121 * @brief Converter for HTML to BBCode
122 * @param string $message
123 * @param string $basepath
126 public static function toBBCode($message, $basepath = '')
128 $message = str_replace("\r", "", $message);
130 // Removing code blocks before the whitespace removal processing below
132 $message = preg_replace_callback(
133 '#<pre><code(?: class="language-([^"]*)")?>(.*)</code></pre>#iUs',
134 function ($matches) use (&$codeblocks) {
135 $return = '[codeblock-' . count($codeblocks) . ']';
138 if ($matches[1] != '') {
139 $prefix = '[code=' . $matches[1] . ']';
142 $codeblocks[] = $prefix . PHP_EOL . trim($matches[2]) . PHP_EOL . '[/code]';
148 $message = str_replace(
161 $message = preg_replace('=<(\w+):(.+?)>=', '<removeme>', $message);
162 $message = preg_replace('=</(\w+):(.+?)>=', '</removeme>', $message);
164 $doc = new DOMDocument();
165 $doc->preserveWhiteSpace = false;
167 $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8");
169 @$doc->loadHTML($message);
171 XML::deleteNode($doc, 'style');
172 XML::deleteNode($doc, 'head');
173 XML::deleteNode($doc, 'title');
174 XML::deleteNode($doc, 'meta');
175 XML::deleteNode($doc, 'xml');
176 XML::deleteNode($doc, 'removeme');
178 $xpath = new DomXPath($doc);
179 $list = $xpath->query("//pre");
180 foreach ($list as $node) {
181 $node->nodeValue = str_replace("\n", "\r", $node->nodeValue);
184 $message = $doc->saveHTML();
185 $message = str_replace(["\n<", ">\n", "\r", "\n", "\xC3\x82\xC2\xA0"], ["<", ">", "<br />", " ", ""], $message);
186 $message = preg_replace('= [\s]*=i', " ", $message);
187 @$doc->loadHTML($message);
189 self::tagToBBCode($doc, 'html', [], "", "");
190 self::tagToBBCode($doc, 'body', [], "", "");
192 // Outlook-Quote - Variant 1
193 self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal', 'style' => 'margin-left:35.4pt'], '[quote]', '[/quote]');
195 // Outlook-Quote - Variant 2
199 ['style' => 'border:none;border-left:solid blue 1.5pt;padding:0cm 0cm 0cm 4.0pt'],
205 self::tagToBBCode($doc, 'span', ['style' => 'text-decoration: underline;'], '[u]', '[/u]');
206 self::tagToBBCode($doc, 'span', ['style' => 'font-style: italic;'], '[i]', '[/i]');
207 self::tagToBBCode($doc, 'span', ['style' => 'font-weight: bold;'], '[b]', '[/b]');
209 /* self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[font=$1][size=$2][color=$3]', '[/color][/size][/font]');
210 self::node2BBCode($doc, 'font', array('size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[size=$1][color=$2]', '[/color][/size]');
211 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(.+)/'), '[font=$1][size=$2]', '[/size][/font]');
212 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'color'=>'/(.+)/'), '[font=$1][color=$3]', '[/color][/font]');
213 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/'), '[font=$1]', '[/font]');
214 self::node2BBCode($doc, 'font', array('size'=>'/(\d+)/'), '[size=$1]', '[/size]');
215 self::node2BBCode($doc, 'font', array('color'=>'/(.+)/'), '[color=$1]', '[/color]');
218 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*font-family:\s*(.+?)[,;].*color:\s*(.+?)[,;].*/'), '[size=$1][font=$2][color=$3]', '[/color][/font][/size]');
219 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(\d+)[,;].*/'), '[size=$1]', '[/size]');
220 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*/'), '[size=$1]', '[/size]');
222 self::tagToBBCode($doc, 'span', ['style' => '/.*color:\s*(.+?)[,;].*/'], '[color="$1"]', '[/color]');
224 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
225 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)pt.*/'), '[font=$1][size=$2]', '[/size][/font]');
226 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)px.*/'), '[font=$1][size=$2]', '[/size][/font]');
227 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
228 // Importing the classes - interesting for importing of posts from third party networks that were exported from friendica
230 //self::node2BBCode($doc, 'span', array('class'=>'/([\w ]+)/'), '[class=$1]', '[/class]');
231 self::tagToBBCode($doc, 'span', ['class' => 'type-link'], '[class=type-link]', '[/class]');
232 self::tagToBBCode($doc, 'span', ['class' => 'type-video'], '[class=type-video]', '[/class]');
234 self::tagToBBCode($doc, 'strong', [], '[b]', '[/b]');
235 self::tagToBBCode($doc, 'em', [], '[i]', '[/i]');
236 self::tagToBBCode($doc, 'b', [], '[b]', '[/b]');
237 self::tagToBBCode($doc, 'i', [], '[i]', '[/i]');
238 self::tagToBBCode($doc, 'u', [], '[u]', '[/u]');
239 self::tagToBBCode($doc, 's', [], '[s]', '[/s]');
240 self::tagToBBCode($doc, 'del', [], '[s]', '[/s]');
241 self::tagToBBCode($doc, 'strike', [], '[s]', '[/s]');
243 self::tagToBBCode($doc, 'big', [], "[size=large]", "[/size]");
244 self::tagToBBCode($doc, 'small', [], "[size=small]", "[/size]");
246 self::tagToBBCode($doc, 'blockquote', [], '[quote]', '[/quote]');
248 self::tagToBBCode($doc, 'br', [], "\n", '');
250 self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal'], "\n", "");
251 self::tagToBBCode($doc, 'div', ['class' => 'MsoNormal'], "\r", "");
253 self::tagToBBCode($doc, 'span', [], "", "");
255 self::tagToBBCode($doc, 'span', [], "", "");
256 self::tagToBBCode($doc, 'pre', [], "", "");
258 self::tagToBBCode($doc, 'div', [], "\r", "\r");
259 self::tagToBBCode($doc, 'p', [], "\n", "\n");
261 self::tagToBBCode($doc, 'ul', [], "[list]", "[/list]");
262 self::tagToBBCode($doc, 'ol', [], "[list=1]", "[/list]");
263 self::tagToBBCode($doc, 'li', [], "[*]", "");
265 self::tagToBBCode($doc, 'hr', [], "[hr]", "");
267 self::tagToBBCode($doc, 'table', [], "", "");
268 self::tagToBBCode($doc, 'tr', [], "\n", "");
269 self::tagToBBCode($doc, 'td', [], "\t", "");
270 //self::node2BBCode($doc, 'table', array(), "[table]", "[/table]");
271 //self::node2BBCode($doc, 'th', array(), "[th]", "[/th]");
272 //self::node2BBCode($doc, 'tr', array(), "[tr]", "[/tr]");
273 //self::node2BBCode($doc, 'td', array(), "[td]", "[/td]");
274 //self::node2BBCode($doc, 'h1', array(), "\n\n[size=xx-large][b]", "[/b][/size]\n");
275 //self::node2BBCode($doc, 'h2', array(), "\n\n[size=x-large][b]", "[/b][/size]\n");
276 //self::node2BBCode($doc, 'h3', array(), "\n\n[size=large][b]", "[/b][/size]\n");
277 //self::node2BBCode($doc, 'h4', array(), "\n\n[size=medium][b]", "[/b][/size]\n");
278 //self::node2BBCode($doc, 'h5', array(), "\n\n[size=small][b]", "[/b][/size]\n");
279 //self::node2BBCode($doc, 'h6', array(), "\n\n[size=x-small][b]", "[/b][/size]\n");
281 self::tagToBBCode($doc, 'h1', [], "[h1]", "[/h1]");
282 self::tagToBBCode($doc, 'h2', [], "[h2]", "[/h2]");
283 self::tagToBBCode($doc, 'h3', [], "[h3]", "[/h3]");
284 self::tagToBBCode($doc, 'h4', [], "[h4]", "[/h4]");
285 self::tagToBBCode($doc, 'h5', [], "[h5]", "[/h5]");
286 self::tagToBBCode($doc, 'h6', [], "[h6]", "[/h6]");
288 self::tagToBBCode($doc, 'a', ['href' => '/mailto:(.+)/'], '[mail=$1]', '[/mail]');
289 self::tagToBBCode($doc, 'a', ['href' => '/(.+)/'], '[url=$1]', '[/url]');
291 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/', 'width' => '/(\d+)/', 'height' => '/(\d+)/'], '[img=$2x$3]$1', '[/img]');
292 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], '[img]$1', '[/img]');
295 self::tagToBBCode($doc, 'video', ['src' => '/(.+)/'], '[video]$1', '[/video]');
296 self::tagToBBCode($doc, 'audio', ['src' => '/(.+)/'], '[audio]$1', '[/audio]');
297 self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], '[iframe]$1', '[/iframe]');
299 self::tagToBBCode($doc, 'key', [], '[code]', '[/code]');
300 self::tagToBBCode($doc, 'code', [], '[code]', '[/code]');
302 $message = $doc->saveHTML();
304 // I'm removing something really disturbing
305 // Don't know exactly what it is
306 $message = str_replace(chr(194) . chr(160), ' ', $message);
308 $message = str_replace(" ", " ", $message);
310 // removing multiple DIVs
311 $message = preg_replace('=\r *\r=i', "\n", $message);
312 $message = str_replace("\r", "\n", $message);
314 Addon::callHooks('html2bbcode', $message);
316 $message = strip_tags($message);
318 $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
320 $message = str_replace(["<"], ["<"], $message);
322 // remove quotes if they don't make sense
323 $message = preg_replace('=\[/quote\][\s]*\[quote\]=i', "\n", $message);
325 $message = preg_replace('=\[quote\]\s*=i', "[quote]", $message);
326 $message = preg_replace('=\s*\[/quote\]=i', "[/quote]", $message);
329 $oldmessage = $message;
330 $message = str_replace("\n \n", "\n\n", $message);
331 } while ($oldmessage != $message);
334 $oldmessage = $message;
335 $message = str_replace("\n\n\n", "\n\n", $message);
336 } while ($oldmessage != $message);
339 $oldmessage = $message;
340 $message = str_replace(
363 } while ($message != $oldmessage);
365 $message = str_replace(
366 ['[b][b]', '[/b][/b]', '[i][i]', '[/i][/i]'],
367 ['[b]', '[/b]', '[i]', '[/i]'],
371 // Handling Yahoo style of mails
372 $message = str_replace('[hr][b]From:[/b]', '[quote][b]From:[/b]', $message);
374 // Restore code blocks
375 $message = preg_replace_callback(
376 '#\[codeblock-([0-9]+)\]#iU',
377 function ($matches) use ($codeblocks) {
379 if (isset($codeblocks[intval($matches[1])])) {
380 $return = $codeblocks[$matches[1]];
387 $message = trim($message);
389 if ($basepath != '') {
390 $message = self::qualifyURLs($message, $basepath);
397 * @brief Sub function to complete incomplete URL
399 * @param array $matches Result of preg_replace_callback
400 * @param string $basepath Basepath that is used to complete the URL
402 * @return string The expanded URL
404 private static function qualifyURLsSub($matches, $basepath)
406 $base = parse_url($basepath);
407 unset($base['query']);
408 unset($base['fragment']);
413 $parts = array_merge($base, parse_url($url));
414 $url2 = Network::unparseURL($parts);
416 return str_replace($url, $url2, $link);
420 * @brief Complete incomplete URLs in BBCode
422 * @param string $body Body with URLs
423 * @param string $basepath Base path that is used to complete the URL
425 * @return string Body with expanded URLs
427 private static function qualifyURLs($body, $basepath)
429 $URLSearchString = "^\[\]";
431 $matches = ["/\[url\=([$URLSearchString]*)\].*?\[\/url\]/ism",
432 "/\[url\]([$URLSearchString]*)\[\/url\]/ism",
433 "/\[img\=[0-9]*x[0-9]*\](.*?)\[\/img\]/ism",
434 "/\[img\](.*?)\[\/img\]/ism",
435 "/\[zmg\=[0-9]*x[0-9]*\](.*?)\[\/img\]/ism",
436 "/\[zmg\](.*?)\[\/zmg\]/ism",
437 "/\[video\](.*?)\[\/video\]/ism",
438 "/\[audio\](.*?)\[\/audio\]/ism",
441 foreach ($matches as $match) {
442 $body = preg_replace_callback(
444 function ($match) use ($basepath) {
445 return self::qualifyURLsSub($match, $basepath);
453 private static function breakLines($line, $level, $wraplength = 75)
455 if ($wraplength == 0) {
456 $wraplength = 2000000;
459 $wraplen = $wraplength - $level;
466 $subline = substr($line, 0, $wraplen);
468 $pos = strrpos($subline, ' ');
471 $pos = strpos($line, ' ');
474 if (($pos > 0) && strlen($line) > $wraplen) {
475 $newline = trim(substr($line, 0, $pos));
477 $newline = str_repeat(">", $level) . ' ' . $newline;
480 $newlines[] = $newline . " ";
481 $line = substr($line, $pos + 1);
483 } while ((strlen($line) > $wraplen) && !($oldline == $line));
486 $line = str_repeat(">", $level) . ' ' . $line;
491 return implode($newlines, "\n");
494 private static function quoteLevel($message, $wraplength = 75)
496 $lines = explode("\n", $message);
500 foreach ($lines as $line) {
503 while (strpos("*" . $line, '[quote]') > 0) {
505 $pos = strpos($line, '[quote]');
506 $line = substr($line, 0, $pos) . substr($line, $pos + 7);
512 while (strpos("*" . $line, '[/quote]') > 0) {
518 $pos = strpos($line, '[/quote]');
519 $line = substr($line, 0, $pos) . substr($line, $pos + 8);
522 if (!$startquote || ($line != '')) {
523 $newlines[] = self::breakLines($line, $currlevel, $wraplength);
527 return implode($newlines, "\n");
530 private static function collectURLs($message)
532 $pattern = '/<a.*?href="(.*?)".*?>(.*?)<\/a>/is';
533 preg_match_all($pattern, $message, $result, PREG_SET_ORDER);
536 foreach ($result as $treffer) {
539 // A list of some links that should be ignored
540 $list = ["/user/", "/tag/", "/group/", "/profile/", "/search?search=", "/search?tag=", "mailto:", "/u/", "/node/",
541 "//plus.google.com/", "//twitter.com/"];
542 foreach ($list as $listitem) {
543 if (strpos($treffer[1], $listitem) !== false) {
548 if ((strpos($treffer[1], "//twitter.com/") !== false) && (strpos($treffer[1], "/status/") !== false)) {
552 if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/posts") !== false)) {
556 if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/photos") !== false)) {
561 $urls[$treffer[1]] = $treffer[1];
568 public static function toPlaintext($html, $wraplength = 75, $compact = false)
570 $message = str_replace("\r", "", $html);
572 $doc = new DOMDocument();
573 $doc->preserveWhiteSpace = false;
575 $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8");
577 @$doc->loadHTML($message);
579 $xpath = new DOMXPath($doc);
580 $list = $xpath->query("//pre");
581 foreach ($list as $node) {
582 $node->nodeValue = str_replace("\n", "\r", $node->nodeValue);
585 $message = $doc->saveHTML();
586 $message = str_replace(["\n<", ">\n", "\r", "\n", "\xC3\x82\xC2\xA0"], ["<", ">", "<br>", " ", ""], $message);
587 $message = preg_replace('= [\s]*=i', " ", $message);
589 // Collecting all links
590 $urls = self::collectURLs($message);
592 @$doc->loadHTML($message);
594 self::tagToBBCode($doc, 'html', [], '', '');
595 self::tagToBBCode($doc, 'body', [], '', '');
597 // MyBB-Auszeichnungen
599 self::node2BBCode($doc, 'span', array('style'=>'text-decoration: underline;'), '_', '_');
600 self::node2BBCode($doc, 'span', array('style'=>'font-style: italic;'), '/', '/');
601 self::node2BBCode($doc, 'span', array('style'=>'font-weight: bold;'), '*', '*');
603 self::node2BBCode($doc, 'strong', array(), '*', '*');
604 self::node2BBCode($doc, 'b', array(), '*', '*');
605 self::node2BBCode($doc, 'i', array(), '/', '/');
606 self::node2BBCode($doc, 'u', array(), '_', '_');
610 self::tagToBBCode($doc, 'blockquote', [], "»", "«");
612 self::tagToBBCode($doc, 'blockquote', [], '[quote]', "[/quote]\n");
615 self::tagToBBCode($doc, 'br', [], "\n", '');
617 self::tagToBBCode($doc, 'span', [], "", "");
618 self::tagToBBCode($doc, 'pre', [], "", "");
619 self::tagToBBCode($doc, 'div', [], "\r", "\r");
620 self::tagToBBCode($doc, 'p', [], "\n", "\n");
622 //self::node2BBCode($doc, 'ul', array(), "\n[list]", "[/list]\n");
623 //self::node2BBCode($doc, 'ol', array(), "\n[list=1]", "[/list]\n");
624 self::tagToBBCode($doc, 'li', [], "\n* ", "\n");
626 self::tagToBBCode($doc, 'hr', [], "\n" . str_repeat("-", 70) . "\n", "");
628 self::tagToBBCode($doc, 'tr', [], "\n", "");
629 self::tagToBBCode($doc, 'td', [], "\t", "");
631 self::tagToBBCode($doc, 'h1', [], "\n\n*", "*\n");
632 self::tagToBBCode($doc, 'h2', [], "\n\n*", "*\n");
633 self::tagToBBCode($doc, 'h3', [], "\n\n*", "*\n");
634 self::tagToBBCode($doc, 'h4', [], "\n\n*", "*\n");
635 self::tagToBBCode($doc, 'h5', [], "\n\n*", "*\n");
636 self::tagToBBCode($doc, 'h6', [], "\n\n*", "*\n");
638 // Problem: there is no reliable way to detect if it is a link to a tag or profile
639 //self::node2BBCode($doc, 'a', array('href'=>'/(.+)/'), ' $1 ', ' ', true);
640 //self::node2BBCode($doc, 'a', array('href'=>'/(.+)/', 'rel'=>'oembed'), ' $1 ', '', true);
641 //self::node2BBCode($doc, 'img', array('alt'=>'/(.+)/'), '$1', '');
642 //self::node2BBCode($doc, 'img', array('title'=>'/(.+)/'), '$1', '');
643 //self::node2BBCode($doc, 'img', array(), '', '');
645 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], ' [img]$1', '[/img] ');
647 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], ' ', ' ');
650 self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], ' $1 ', '');
652 $message = $doc->saveHTML();
655 $message = str_replace("[img]", "", $message);
656 $message = str_replace("[/img]", "", $message);
659 // was ersetze ich da?
660 // Irgendein stoerrisches UTF-Zeug
661 $message = str_replace(chr(194) . chr(160), ' ', $message);
663 $message = str_replace(" ", " ", $message);
665 // Aufeinanderfolgende DIVs
666 $message = preg_replace('=\r *\r=i', "\n", $message);
667 $message = str_replace("\r", "\n", $message);
669 $message = strip_tags($message);
671 $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
673 if (!$compact && ($message != '')) {
674 foreach ($urls as $id => $url) {
675 if ($url != '' && strpos($message, $url) === false) {
676 $message .= "\n" . $url . ' ';
681 $message = str_replace("\n«", "«\n", $message);
682 $message = str_replace("»\n", "\n»", $message);
685 $oldmessage = $message;
686 $message = str_replace("\n\n\n", "\n\n", $message);
687 } while ($oldmessage != $message);
689 $message = self::quoteLevel(trim($message), $wraplength);
691 return trim($message);
695 * Converts provided HTML code to Markdown. The hardwrap parameter maximizes
696 * compatibility with Diaspora in spite of the Markdown standards.
698 * @param string $html
701 public static function toMarkdown($html)
703 $converter = new HtmlConverter(['hard_break' => true]);
704 $markdown = $converter->convert($html);
710 * @brief Convert video HTML to BBCode tags
714 public static function toBBCodeVideo($s)
717 '#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
718 '[youtube]$2[/youtube]',
723 '#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
724 '[youtube]$2[/youtube]',
729 '#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
738 * transform link href and img src from relative to absolute
740 * @param string $text
741 * @param string $base base url
744 public static function relToAbs($text, $base)
750 $base = rtrim($base, '/');
752 $base2 = $base . "/";
755 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
756 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
757 $text = preg_replace($pattern, $replace, $text);
759 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
760 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
761 $text = preg_replace($pattern, $replace, $text);
764 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
765 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
766 $text = preg_replace($pattern, $replace, $text);
768 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
769 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
770 $text = preg_replace($pattern, $replace, $text);
778 * return div element with class 'clear'
782 public static function clearDiv()
784 return '<div class="clear"></div>';
788 * Loader for infinite scrolling
789 * @return string html for loader
791 public static function scrollLoader()
793 $tpl = Renderer::getMarkupTemplate("scroll_loader.tpl");
794 return Renderer::replaceMacros($tpl, [
795 'wait' => L10n::t('Loading more entries...'),
796 'end' => L10n::t('The end')
801 * Get html for contact block.
803 * @template contact_block.tpl
804 * @hook contact_block_end (contacts=>array, output=>string)
807 public static function contactBlock()
812 $shown = PConfig::get($a->profile['uid'], 'system', 'display_friend_count', 24);
817 if (!is_array($a->profile) || $a->profile['hide-friends']) {
821 $r = q("SELECT COUNT(*) AS `total` FROM `contact`
822 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
823 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
824 AND `network` IN ('%s', '%s', '%s')",
825 intval($a->profile['uid']),
826 DBA::escape(Protocol::DFRN),
827 DBA::escape(Protocol::OSTATUS),
828 DBA::escape(Protocol::DIASPORA)
831 if (DBA::isResult($r)) {
832 $total = intval($r[0]['total']);
836 $contacts = L10n::t('No contacts');
839 // Splitting the query in two parts makes it much faster
840 $r = q("SELECT `id` FROM `contact`
841 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
842 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
843 AND `network` IN ('%s', '%s', '%s')
844 ORDER BY RAND() LIMIT %d",
845 intval($a->profile['uid']),
846 DBA::escape(Protocol::DFRN),
847 DBA::escape(Protocol::OSTATUS),
848 DBA::escape(Protocol::DIASPORA),
852 if (DBA::isResult($r)) {
854 foreach ($r as $contact) {
855 $contacts[] = $contact["id"];
858 $r = q("SELECT `id`, `uid`, `addr`, `url`, `name`, `thumb`, `network` FROM `contact` WHERE `id` IN (%s)",
859 DBA::escape(implode(",", $contacts))
862 if (DBA::isResult($r)) {
863 $contacts = L10n::tt('%d Contact', '%d Contacts', $total);
865 foreach ($r as $rr) {
866 $micropro[] = self::micropro($rr, true, 'mpfriend');
872 $tpl = Renderer::getMarkupTemplate('contact_block.tpl');
873 $o = Renderer::replaceMacros($tpl, [
874 '$contacts' => $contacts,
875 '$nickname' => $a->profile['nickname'],
876 '$viewcontacts' => L10n::t('View Contacts'),
877 '$micropro' => $micropro,
880 $arr = ['contacts' => $r, 'output' => $o];
882 Addon::callHooks('contact_block_end', $arr);
888 * @brief Format contacts as picture links or as texxt links
890 * @param array $contact Array with contacts which contains an array with
891 * int 'id' => The ID of the contact
892 * int 'uid' => The user ID of the user who owns this data
893 * string 'name' => The name of the contact
894 * string 'url' => The url to the profile page of the contact
895 * string 'addr' => The webbie of the contact (e.g.) username@friendica.com
896 * string 'network' => The network to which the contact belongs to
897 * string 'thumb' => The contact picture
898 * string 'click' => js code which is performed when clicking on the contact
899 * @param boolean $redirect If true try to use the redir url if it's possible
900 * @param string $class CSS class for the
901 * @param boolean $textmode If true display the contacts as text links
902 * if false display the contacts as picture links
904 * @return string Formatted html
906 public static function micropro($contact, $redirect = false, $class = '', $textmode = false)
908 // Use the contact URL if no address is available
909 if (!x($contact, "addr")) {
910 $contact["addr"] = $contact["url"];
913 $url = $contact['url'];
918 $url = Contact::magicLink($contact['url']);
919 if (strpos($url, 'redir/') === 0) {
920 $sparkle = ' sparkle';
924 // If there is some js available we don't need the url
925 if (x($contact, 'click')) {
929 return Renderer::replaceMacros(Renderer::getMarkupTemplate(($textmode)?'micropro_txt.tpl':'micropro_img.tpl'), [
930 '$click' => defaults($contact, 'click', ''),
933 '$photo' => ProxyUtils::proxifyUrl($contact['thumb'], false, ProxyUtils::SIZE_THUMB),
934 '$name' => $contact['name'],
935 'title' => $contact['name'] . ' [' . $contact['addr'] . ']',
936 '$parkle' => $sparkle,
944 * @param string $s Search query.
945 * @param string $id HTML id
946 * @param string $url Search url.
947 * @param bool $save Show save search button.
948 * @param bool $aside Display the search widgit aside.
950 * @return string Formatted HTML.
952 public static function search($s, $id = 'search-box', $url = 'search', $save = false, $aside = true)
956 if (strpos($s, '#') === 0) {
959 $save_label = $mode === 'text' ? L10n::t('Save') : L10n::t('Follow');
962 '$s' => htmlspecialchars($s),
964 '$action_url' => $url,
965 '$search_label' => L10n::t('Search'),
966 '$save_label' => $save_label,
967 '$savedsearch' => local_user() && Feature::isEnabled(local_user(), 'savedsearch'),
968 '$search_hint' => L10n::t('@name, !forum, #tags, content'),
973 $values['$searchoption'] = [
974 L10n::t("Full Text"),
976 L10n::t("Contacts")];
978 if (Config::get('system', 'poco_local_search')) {
979 $values['$searchoption'][] = L10n::t("Forums");
983 return Renderer::replaceMacros(Renderer::getMarkupTemplate('searchbox.tpl'), $values);
987 * Replace naked text hyperlink with HTML formatted hyperlink
991 public static function toLink($s)
993 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank">$1</a>', $s);
994 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism", '<$1$2=$3&$4>', $s);
999 * Given a HTML text and a set of filtering reasons, adds a content hiding header with the provided reasons
1001 * Reasons are expected to have been translated already.
1003 * @param string $html
1004 * @param array $reasons
1007 public static function applyContentFilter($html, array $reasons)
1009 if (count($reasons)) {
1010 $tpl = Renderer::getMarkupTemplate('wall/content_filter.tpl');
1011 $html = Renderer::replaceMacros($tpl, [
1012 '$reasons' => $reasons,
1013 '$rnd' => random_string(8),
1014 '$openclose' => L10n::t('Click to open/close'),
1023 * replace html amp entity with amp char
1027 public static function unamp($s)
1029 return str_replace('&', '&', $s);