4 * @file src/Content/Text/HTML.php
7 namespace Friendica\Content\Text;
11 use Friendica\Core\Addon;
12 use Friendica\Util\Network;
13 use Friendica\Util\XML;
14 use League\HTMLToMarkdown\HtmlConverter;
18 public static function sanitizeCSS($input)
22 $input = strtolower($input);
24 for ($i = 0; $i < strlen($input); $i++) {
25 $char = substr($input, $i, 1);
27 if (($char >= "a") && ($char <= "z")) {
31 if (!(strpos(" #;:0123456789-_.%", $char) === false)) {
39 private static function tagToBBCode(DOMDocument $doc, $tag, $attributes, $startbb, $endbb)
42 $done = self::tagToBBCodeSub($doc, $tag, $attributes, $startbb, $endbb);
46 private static function tagToBBCodeSub(DOMDocument $doc, $tag, $attributes, $startbb, $endbb)
48 $savestart = str_replace('$', '\x01', $startbb);
51 $xpath = new DOMXPath($doc);
53 $list = $xpath->query("//" . $tag);
54 foreach ($list as $node) {
56 if ($node->attributes->length) {
57 foreach ($node->attributes as $attribute) {
58 $attr[$attribute->name] = $attribute->value;
64 $startbb = $savestart;
68 foreach ($attributes as $attribute => $value) {
69 $startbb = str_replace('\x01' . ++$i, '$1', $startbb);
70 if (strpos('*' . $startbb, '$1') > 0) {
71 if ($replace && (@$attr[$attribute] != '')) {
72 $startbb = preg_replace($value, $startbb, $attr[$attribute], -1, $count);
74 // If nothing could be changed
82 if (@$attr[$attribute] != $value) {
89 $StartCode = $doc->createTextNode($startbb);
90 $EndCode = $doc->createTextNode($endbb);
92 $node->parentNode->insertBefore($StartCode, $node);
94 if ($node->hasChildNodes()) {
95 foreach ($node->childNodes as $child) {
96 $newNode = $child->cloneNode(true);
97 $node->parentNode->insertBefore($newNode, $node);
101 $node->parentNode->insertBefore($EndCode, $node);
102 $node->parentNode->removeChild($node);
110 * Made by: ike@piratenpartei.de
111 * Originally made for the syncom project: http://wiki.piratenpartei.de/Syncom
112 * https://github.com/annando/Syncom
114 * @brief Converter for HTML to BBCode
115 * @param string $message
116 * @param string $basepath
119 public static function toBBCode($message, $basepath = '')
121 $message = str_replace("\r", "", $message);
123 // Removing code blocks before the whitespace removal processing below
125 $message = preg_replace_callback(
126 '#<pre><code(?: class="language-([^"]*)")?>(.*)</code></pre>#iUs',
127 function ($matches) use (&$codeblocks) {
128 $return = '[codeblock-' . count($codeblocks) . ']';
131 if ($matches[1] != '') {
132 $prefix = '[code=' . $matches[1] . ']';
135 $codeblocks[] = $prefix . PHP_EOL . trim($matches[2]) . PHP_EOL . '[/code]';
141 $message = str_replace(
152 $message = preg_replace('=<(\w+):(.+?)>=', '<removeme>', $message);
153 $message = preg_replace('=</(\w+):(.+?)>=', '</removeme>', $message);
155 $doc = new DOMDocument();
156 $doc->preserveWhiteSpace = false;
158 $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8");
160 @$doc->loadHTML($message);
162 XML::deleteNode($doc, 'style');
163 XML::deleteNode($doc, 'head');
164 XML::deleteNode($doc, 'title');
165 XML::deleteNode($doc, 'meta');
166 XML::deleteNode($doc, 'xml');
167 XML::deleteNode($doc, 'removeme');
169 $xpath = new DomXPath($doc);
170 $list = $xpath->query("//pre");
171 foreach ($list as $node) {
172 $node->nodeValue = str_replace("\n", "\r", $node->nodeValue);
175 $message = $doc->saveHTML();
176 $message = str_replace(["\n<", ">\n", "\r", "\n", "\xC3\x82\xC2\xA0"], ["<", ">", "<br />", " ", ""], $message);
177 $message = preg_replace('= [\s]*=i', " ", $message);
178 @$doc->loadHTML($message);
180 self::tagToBBCode($doc, 'html', [], "", "");
181 self::tagToBBCode($doc, 'body', [], "", "");
183 // Outlook-Quote - Variant 1
184 self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal', 'style' => 'margin-left:35.4pt'], '[quote]', '[/quote]');
186 // Outlook-Quote - Variant 2
187 self::tagToBBCode($doc, 'div', ['style' => 'border:none;border-left:solid blue 1.5pt;padding:0cm 0cm 0cm 4.0pt'],
188 '[quote]', '[/quote]');
191 self::tagToBBCode($doc, 'span', ['style' => 'text-decoration: underline;'], '[u]', '[/u]');
192 self::tagToBBCode($doc, 'span', ['style' => 'font-style: italic;'], '[i]', '[/i]');
193 self::tagToBBCode($doc, 'span', ['style' => 'font-weight: bold;'], '[b]', '[/b]');
195 /* self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[font=$1][size=$2][color=$3]', '[/color][/size][/font]');
196 self::node2BBCode($doc, 'font', array('size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[size=$1][color=$2]', '[/color][/size]');
197 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(.+)/'), '[font=$1][size=$2]', '[/size][/font]');
198 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'color'=>'/(.+)/'), '[font=$1][color=$3]', '[/color][/font]');
199 self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/'), '[font=$1]', '[/font]');
200 self::node2BBCode($doc, 'font', array('size'=>'/(\d+)/'), '[size=$1]', '[/size]');
201 self::node2BBCode($doc, 'font', array('color'=>'/(.+)/'), '[color=$1]', '[/color]');
204 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*font-family:\s*(.+?)[,;].*color:\s*(.+?)[,;].*/'), '[size=$1][font=$2][color=$3]', '[/color][/font][/size]');
205 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(\d+)[,;].*/'), '[size=$1]', '[/size]');
206 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*/'), '[size=$1]', '[/size]');
208 self::tagToBBCode($doc, 'span', ['style' => '/.*color:\s*(.+?)[,;].*/'], '[color="$1"]', '[/color]');
210 //self::node2BBCode($doc, 'span', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
211 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)pt.*/'), '[font=$1][size=$2]', '[/size][/font]');
212 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)px.*/'), '[font=$1][size=$2]', '[/size][/font]');
213 //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
214 // Importing the classes - interesting for importing of posts from third party networks that were exported from friendica
216 //self::node2BBCode($doc, 'span', array('class'=>'/([\w ]+)/'), '[class=$1]', '[/class]');
217 self::tagToBBCode($doc, 'span', ['class' => 'type-link'], '[class=type-link]', '[/class]');
218 self::tagToBBCode($doc, 'span', ['class' => 'type-video'], '[class=type-video]', '[/class]');
220 self::tagToBBCode($doc, 'strong', [], '[b]', '[/b]');
221 self::tagToBBCode($doc, 'em', [], '[i]', '[/i]');
222 self::tagToBBCode($doc, 'b', [], '[b]', '[/b]');
223 self::tagToBBCode($doc, 'i', [], '[i]', '[/i]');
224 self::tagToBBCode($doc, 'u', [], '[u]', '[/u]');
225 self::tagToBBCode($doc, 's', [], '[s]', '[/s]');
226 self::tagToBBCode($doc, 'del', [], '[s]', '[/s]');
227 self::tagToBBCode($doc, 'strike', [], '[s]', '[/s]');
229 self::tagToBBCode($doc, 'big', [], "[size=large]", "[/size]");
230 self::tagToBBCode($doc, 'small', [], "[size=small]", "[/size]");
232 self::tagToBBCode($doc, 'blockquote', [], '[quote]', '[/quote]');
234 self::tagToBBCode($doc, 'br', [], "\n", '');
236 self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal'], "\n", "");
237 self::tagToBBCode($doc, 'div', ['class' => 'MsoNormal'], "\r", "");
239 self::tagToBBCode($doc, 'span', [], "", "");
241 self::tagToBBCode($doc, 'span', [], "", "");
242 self::tagToBBCode($doc, 'pre', [], "", "");
244 self::tagToBBCode($doc, 'div', [], "\r", "\r");
245 self::tagToBBCode($doc, 'p', [], "\n", "\n");
247 self::tagToBBCode($doc, 'ul', [], "[list]", "[/list]");
248 self::tagToBBCode($doc, 'ol', [], "[list=1]", "[/list]");
249 self::tagToBBCode($doc, 'li', [], "[*]", "");
251 self::tagToBBCode($doc, 'hr', [], "[hr]", "");
253 self::tagToBBCode($doc, 'table', [], "", "");
254 self::tagToBBCode($doc, 'tr', [], "\n", "");
255 self::tagToBBCode($doc, 'td', [], "\t", "");
256 //self::node2BBCode($doc, 'table', array(), "[table]", "[/table]");
257 //self::node2BBCode($doc, 'th', array(), "[th]", "[/th]");
258 //self::node2BBCode($doc, 'tr', array(), "[tr]", "[/tr]");
259 //self::node2BBCode($doc, 'td', array(), "[td]", "[/td]");
260 //self::node2BBCode($doc, 'h1', array(), "\n\n[size=xx-large][b]", "[/b][/size]\n");
261 //self::node2BBCode($doc, 'h2', array(), "\n\n[size=x-large][b]", "[/b][/size]\n");
262 //self::node2BBCode($doc, 'h3', array(), "\n\n[size=large][b]", "[/b][/size]\n");
263 //self::node2BBCode($doc, 'h4', array(), "\n\n[size=medium][b]", "[/b][/size]\n");
264 //self::node2BBCode($doc, 'h5', array(), "\n\n[size=small][b]", "[/b][/size]\n");
265 //self::node2BBCode($doc, 'h6', array(), "\n\n[size=x-small][b]", "[/b][/size]\n");
267 self::tagToBBCode($doc, 'h1', [], "[h1]", "[/h1]");
268 self::tagToBBCode($doc, 'h2', [], "[h2]", "[/h2]");
269 self::tagToBBCode($doc, 'h3', [], "[h3]", "[/h3]");
270 self::tagToBBCode($doc, 'h4', [], "[h4]", "[/h4]");
271 self::tagToBBCode($doc, 'h5', [], "[h5]", "[/h5]");
272 self::tagToBBCode($doc, 'h6', [], "[h6]", "[/h6]");
274 self::tagToBBCode($doc, 'a', ['href' => '/mailto:(.+)/'], '[mail=$1]', '[/mail]');
275 self::tagToBBCode($doc, 'a', ['href' => '/(.+)/'], '[url=$1]', '[/url]');
277 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/', 'width' => '/(\d+)/', 'height' => '/(\d+)/'], '[img=$2x$3]$1',
279 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], '[img]$1', '[/img]');
282 self::tagToBBCode($doc, 'video', ['src' => '/(.+)/'], '[video]$1', '[/video]');
283 self::tagToBBCode($doc, 'audio', ['src' => '/(.+)/'], '[audio]$1', '[/audio]');
284 self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], '[iframe]$1', '[/iframe]');
286 self::tagToBBCode($doc, 'key', [], '[code]', '[/code]');
287 self::tagToBBCode($doc, 'code', [], '[code]', '[/code]');
289 $message = $doc->saveHTML();
291 // I'm removing something really disturbing
292 // Don't know exactly what it is
293 $message = str_replace(chr(194) . chr(160), ' ', $message);
295 $message = str_replace(" ", " ", $message);
297 // removing multiple DIVs
298 $message = preg_replace('=\r *\r=i', "\n", $message);
299 $message = str_replace("\r", "\n", $message);
301 Addon::callHooks('html2bbcode', $message);
303 $message = strip_tags($message);
305 $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
307 $message = str_replace(["<"], ["<"], $message);
309 // remove quotes if they don't make sense
310 $message = preg_replace('=\[/quote\][\s]*\[quote\]=i', "\n", $message);
312 $message = preg_replace('=\[quote\]\s*=i', "[quote]", $message);
313 $message = preg_replace('=\s*\[/quote\]=i', "[/quote]", $message);
316 $oldmessage = $message;
317 $message = str_replace("\n \n", "\n\n", $message);
318 } while ($oldmessage != $message);
321 $oldmessage = $message;
322 $message = str_replace("\n\n\n", "\n\n", $message);
323 } while ($oldmessage != $message);
326 $oldmessage = $message;
327 $message = str_replace(
349 } while ($message != $oldmessage);
351 $message = str_replace(
352 ['[b][b]', '[/b][/b]', '[i][i]', '[/i][/i]'], ['[b]', '[/b]', '[i]', '[/i]'], $message
355 // Handling Yahoo style of mails
356 $message = str_replace('[hr][b]From:[/b]', '[quote][b]From:[/b]', $message);
358 // Restore code blocks
359 $message = preg_replace_callback(
360 '#\[codeblock-([0-9]+)\]#iU',
361 function ($matches) use ($codeblocks) {
363 if (isset($codeblocks[intval($matches[1])])) {
364 $return = $codeblocks[$matches[1]];
371 $message = trim($message);
373 if ($basepath != '') {
374 $message = self::qualifyURLs($message, $basepath);
381 * @brief Sub function to complete incomplete URL
383 * @param array $matches Result of preg_replace_callback
384 * @param string $basepath Basepath that is used to complete the URL
386 * @return string The expanded URL
388 private static function qualifyURLsSub($matches, $basepath)
390 $base = parse_url($basepath);
391 unset($base['query']);
392 unset($base['fragment']);
397 $parts = array_merge($base, parse_url($url));
398 $url2 = Network::unparseURL($parts);
400 return str_replace($url, $url2, $link);
404 * @brief Complete incomplete URLs in BBCode
406 * @param string $body Body with URLs
407 * @param string $basepath Base path that is used to complete the URL
409 * @return string Body with expanded URLs
411 private static function qualifyURLs($body, $basepath)
413 $URLSearchString = "^\[\]";
415 $matches = ["/\[url\=([$URLSearchString]*)\].*?\[\/url\]/ism",
416 "/\[url\]([$URLSearchString]*)\[\/url\]/ism",
417 "/\[img\=[0-9]*x[0-9]*\](.*?)\[\/img\]/ism",
418 "/\[img\](.*?)\[\/img\]/ism",
419 "/\[zmg\=[0-9]*x[0-9]*\](.*?)\[\/img\]/ism",
420 "/\[zmg\](.*?)\[\/zmg\]/ism",
421 "/\[video\](.*?)\[\/video\]/ism",
422 "/\[audio\](.*?)\[\/audio\]/ism",
425 foreach ($matches as $match) {
426 $body = preg_replace_callback(
427 $match, function ($match) use ($basepath) {
428 return self::qualifyURLsSub($match, $basepath);
436 private static function breakLines($line, $level, $wraplength = 75)
438 if ($wraplength == 0) {
439 $wraplength = 2000000;
442 $wraplen = $wraplength - $level;
449 $subline = substr($line, 0, $wraplen);
451 $pos = strrpos($subline, ' ');
454 $pos = strpos($line, ' ');
457 if (($pos > 0) && strlen($line) > $wraplen) {
458 $newline = trim(substr($line, 0, $pos));
460 $newline = str_repeat(">", $level) . ' ' . $newline;
463 $newlines[] = $newline . " ";
464 $line = substr($line, $pos + 1);
466 } while ((strlen($line) > $wraplen) && !($oldline == $line));
469 $line = str_repeat(">", $level) . ' ' . $line;
474 return implode($newlines, "\n");
477 private static function quoteLevel($message, $wraplength = 75)
479 $lines = explode("\n", $message);
483 foreach ($lines as $line) {
486 while (strpos("*" . $line, '[quote]') > 0) {
488 $pos = strpos($line, '[quote]');
489 $line = substr($line, 0, $pos) . substr($line, $pos + 7);
495 while (strpos("*" . $line, '[/quote]') > 0) {
501 $pos = strpos($line, '[/quote]');
502 $line = substr($line, 0, $pos) . substr($line, $pos + 8);
505 if (!$startquote || ($line != '')) {
506 $newlines[] = self::breakLines($line, $currlevel, $wraplength);
510 return implode($newlines, "\n");
513 private static function collectURLs($message)
515 $pattern = '/<a.*?href="(.*?)".*?>(.*?)<\/a>/is';
516 preg_match_all($pattern, $message, $result, PREG_SET_ORDER);
519 foreach ($result as $treffer) {
522 // A list of some links that should be ignored
523 $list = ["/user/", "/tag/", "/group/", "/profile/", "/search?search=", "/search?tag=", "mailto:", "/u/", "/node/",
524 "//plus.google.com/", "//twitter.com/"];
525 foreach ($list as $listitem) {
526 if (strpos($treffer[1], $listitem) !== false) {
531 if ((strpos($treffer[1], "//twitter.com/") !== false) && (strpos($treffer[1], "/status/") !== false)) {
535 if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/posts") !== false)) {
539 if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/photos") !== false)) {
544 $urls[$treffer[1]] = $treffer[1];
551 public static function toPlaintext($html, $wraplength = 75, $compact = false)
553 $message = str_replace("\r", "", $html);
555 $doc = new DOMDocument();
556 $doc->preserveWhiteSpace = false;
558 $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8");
560 @$doc->loadHTML($message);
562 $xpath = new DOMXPath($doc);
563 $list = $xpath->query("//pre");
564 foreach ($list as $node) {
565 $node->nodeValue = str_replace("\n", "\r", $node->nodeValue);
568 $message = $doc->saveHTML();
569 $message = str_replace(["\n<", ">\n", "\r", "\n", "\xC3\x82\xC2\xA0"], ["<", ">", "<br>", " ", ""], $message);
570 $message = preg_replace('= [\s]*=i', " ", $message);
572 // Collecting all links
573 $urls = self::collectURLs($message);
575 @$doc->loadHTML($message);
577 self::tagToBBCode($doc, 'html', [], '', '');
578 self::tagToBBCode($doc, 'body', [], '', '');
580 // MyBB-Auszeichnungen
582 self::node2BBCode($doc, 'span', array('style'=>'text-decoration: underline;'), '_', '_');
583 self::node2BBCode($doc, 'span', array('style'=>'font-style: italic;'), '/', '/');
584 self::node2BBCode($doc, 'span', array('style'=>'font-weight: bold;'), '*', '*');
586 self::node2BBCode($doc, 'strong', array(), '*', '*');
587 self::node2BBCode($doc, 'b', array(), '*', '*');
588 self::node2BBCode($doc, 'i', array(), '/', '/');
589 self::node2BBCode($doc, 'u', array(), '_', '_');
593 self::tagToBBCode($doc, 'blockquote', [], "»", "«");
595 self::tagToBBCode($doc, 'blockquote', [], '[quote]', "[/quote]\n");
598 self::tagToBBCode($doc, 'br', [], "\n", '');
600 self::tagToBBCode($doc, 'span', [], "", "");
601 self::tagToBBCode($doc, 'pre', [], "", "");
602 self::tagToBBCode($doc, 'div', [], "\r", "\r");
603 self::tagToBBCode($doc, 'p', [], "\n", "\n");
605 //self::node2BBCode($doc, 'ul', array(), "\n[list]", "[/list]\n");
606 //self::node2BBCode($doc, 'ol', array(), "\n[list=1]", "[/list]\n");
607 self::tagToBBCode($doc, 'li', [], "\n* ", "\n");
609 self::tagToBBCode($doc, 'hr', [], "\n" . str_repeat("-", 70) . "\n", "");
611 self::tagToBBCode($doc, 'tr', [], "\n", "");
612 self::tagToBBCode($doc, 'td', [], "\t", "");
614 self::tagToBBCode($doc, 'h1', [], "\n\n*", "*\n");
615 self::tagToBBCode($doc, 'h2', [], "\n\n*", "*\n");
616 self::tagToBBCode($doc, 'h3', [], "\n\n*", "*\n");
617 self::tagToBBCode($doc, 'h4', [], "\n\n*", "*\n");
618 self::tagToBBCode($doc, 'h5', [], "\n\n*", "*\n");
619 self::tagToBBCode($doc, 'h6', [], "\n\n*", "*\n");
621 // Problem: there is no reliable way to detect if it is a link to a tag or profile
622 //self::node2BBCode($doc, 'a', array('href'=>'/(.+)/'), ' $1 ', ' ', true);
623 //self::node2BBCode($doc, 'a', array('href'=>'/(.+)/', 'rel'=>'oembed'), ' $1 ', '', true);
624 //self::node2BBCode($doc, 'img', array('alt'=>'/(.+)/'), '$1', '');
625 //self::node2BBCode($doc, 'img', array('title'=>'/(.+)/'), '$1', '');
626 //self::node2BBCode($doc, 'img', array(), '', '');
628 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], ' [img]$1', '[/img] ');
630 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], ' ', ' ');
633 self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], ' $1 ', '');
635 $message = $doc->saveHTML();
638 $message = str_replace("[img]", "", $message);
639 $message = str_replace("[/img]", "", $message);
642 // was ersetze ich da?
643 // Irgendein stoerrisches UTF-Zeug
644 $message = str_replace(chr(194) . chr(160), ' ', $message);
646 $message = str_replace(" ", " ", $message);
648 // Aufeinanderfolgende DIVs
649 $message = preg_replace('=\r *\r=i', "\n", $message);
650 $message = str_replace("\r", "\n", $message);
652 $message = strip_tags($message);
654 $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
656 if (!$compact && ($message != '')) {
657 foreach ($urls as $id => $url) {
658 if ($url != '' && strpos($message, $url) === false) {
659 $message .= "\n" . $url . ' ';
664 $message = str_replace("\n«", "«\n", $message);
665 $message = str_replace("»\n", "\n»", $message);
668 $oldmessage = $message;
669 $message = str_replace("\n\n\n", "\n\n", $message);
670 } while ($oldmessage != $message);
672 $message = self::quoteLevel(trim($message), $wraplength);
674 return trim($message);
678 * Converts provided HTML code to Markdown. The hardwrap parameter maximizes
679 * compatibility with Diaspora in spite of the Markdown standards.
681 * @param string $html
684 public static function toMarkdown($html)
686 $converter = new HtmlConverter(['hard_break' => true]);
687 $markdown = $converter->convert($html);