]> git.mxchange.org Git - friendica.git/blob - src/Content/Text/HTML.php
Merge pull request #6697 from annando/memory-jsonld
[friendica.git] / src / Content / Text / HTML.php
1 <?php
2 /**
3  * @file src/Content/Text/HTML.php
4  */
5
6 namespace Friendica\Content\Text;
7
8 use DOMDocument;
9 use DOMXPath;
10 use Friendica\Content\Widget\ContactBlock;
11 use Friendica\Core\Hook;
12 use Friendica\Core\L10n;
13 use Friendica\Core\Config;
14 use Friendica\Core\Renderer;
15 use Friendica\Model\Contact;
16 use Friendica\Util\Network;
17 use Friendica\Util\Proxy as ProxyUtils;
18 use Friendica\Util\Strings;
19 use Friendica\Util\XML;
20 use League\HTMLToMarkdown\HtmlConverter;
21
22 class HTML
23 {
24         public static function sanitizeCSS($input)
25         {
26                 $cleaned = "";
27
28                 $input = strtolower($input);
29
30                 for ($i = 0; $i < strlen($input); $i++) {
31                         $char = substr($input, $i, 1);
32
33                         if (($char >= "a") && ($char <= "z")) {
34                                 $cleaned .= $char;
35                         }
36
37                         if (!(strpos(" #;:0123456789-_.%", $char) === false)) {
38                                 $cleaned .= $char;
39                         }
40                 }
41
42                 return $cleaned;
43         }
44
45         private static function tagToBBCode(DOMDocument $doc, $tag, $attributes, $startbb, $endbb)
46         {
47                 do {
48                         $done = self::tagToBBCodeSub($doc, $tag, $attributes, $startbb, $endbb);
49                 } while ($done);
50         }
51
52         private static function tagToBBCodeSub(DOMDocument $doc, $tag, $attributes, $startbb, $endbb)
53         {
54                 $savestart = str_replace('$', '\x01', $startbb);
55                 $replace = false;
56
57                 $xpath = new DOMXPath($doc);
58
59                 $list = $xpath->query("//" . $tag);
60                 foreach ($list as $node) {
61                         $attr = [];
62                         if ($node->attributes->length) {
63                                 foreach ($node->attributes as $attribute) {
64                                         $attr[$attribute->name] = $attribute->value;
65                                 }
66                         }
67
68                         $replace = true;
69
70                         $startbb = $savestart;
71
72                         $i = 0;
73
74                         foreach ($attributes as $attribute => $value) {
75                                 $startbb = str_replace('\x01' . ++$i, '$1', $startbb);
76                                 if (strpos('*' . $startbb, '$1') > 0) {
77                                         if ($replace && (@$attr[$attribute] != '')) {
78                                                 $startbb = preg_replace($value, $startbb, $attr[$attribute], -1, $count);
79
80                                                 // If nothing could be changed
81                                                 if ($count == 0) {
82                                                         $replace = false;
83                                                 }
84                                         } else {
85                                                 $replace = false;
86                                         }
87                                 } else {
88                                         if (@$attr[$attribute] != $value) {
89                                                 $replace = false;
90                                         }
91                                 }
92                         }
93
94                         if ($replace) {
95                                 $StartCode = $doc->createTextNode($startbb);
96                                 $EndCode = $doc->createTextNode($endbb);
97
98                                 $node->parentNode->insertBefore($StartCode, $node);
99
100                                 if ($node->hasChildNodes()) {
101                                         foreach ($node->childNodes as $child) {
102                                                 $newNode = $child->cloneNode(true);
103                                                 $node->parentNode->insertBefore($newNode, $node);
104                                         }
105                                 }
106
107                                 $node->parentNode->insertBefore($EndCode, $node);
108                                 $node->parentNode->removeChild($node);
109                         }
110                 }
111
112                 return $replace;
113         }
114
115         /**
116          * Made by: ike@piratenpartei.de
117          * Originally made for the syncom project: http://wiki.piratenpartei.de/Syncom
118          *                    https://github.com/annando/Syncom
119          *
120          * @brief Converter for HTML to BBCode
121          * @param string $message
122          * @param string $basepath
123          * @return string
124          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
125          */
126         public static function toBBCode($message, $basepath = '')
127         {
128                 $message = str_replace("\r", "", $message);
129
130                 // Removing code blocks before the whitespace removal processing below
131                 $codeblocks = [];
132                 $message = preg_replace_callback(
133                         '#<pre><code(?: class="language-([^"]*)")?>(.*)</code></pre>#iUs',
134                         function ($matches) use (&$codeblocks) {
135                                 $return = '[codeblock-' . count($codeblocks) . ']';
136
137                                 $prefix = '[code]';
138                                 if ($matches[1] != '') {
139                                         $prefix = '[code=' . $matches[1] . ']';
140                                 }
141
142                                 $codeblocks[] = $prefix . PHP_EOL . trim($matches[2]) . PHP_EOL . '[/code]';
143                                 return $return;
144                         },
145                         $message
146                 );
147
148                 $message = str_replace(
149                         [
150                                 "<li><p>",
151                                 "</p></li>",
152                         ],
153                         [
154                                 "<li>",
155                                 "</li>",
156                         ],
157                         $message
158                 );
159
160                 // remove namespaces
161                 $message = preg_replace('=<(\w+):(.+?)>=', '<removeme>', $message);
162                 $message = preg_replace('=</(\w+):(.+?)>=', '</removeme>', $message);
163
164                 $doc = new DOMDocument();
165                 $doc->preserveWhiteSpace = false;
166
167                 $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8");
168
169                 @$doc->loadHTML($message);
170
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');
177
178                 $xpath = new DomXPath($doc);
179                 $list = $xpath->query("//pre");
180                 foreach ($list as $node) {
181                         // Ensure to escape unescaped & - they will otherwise raise a warning
182                         $safe_value = preg_replace('/&(?!\w+;)/', '&amp;', $node->nodeValue);
183                         $node->nodeValue = str_replace("\n", "\r", $safe_value);
184                 }
185
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);
190
191                 self::tagToBBCode($doc, 'html', [], "", "");
192                 self::tagToBBCode($doc, 'body', [], "", "");
193
194                 // Outlook-Quote - Variant 1
195                 self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal', 'style' => 'margin-left:35.4pt'], '[quote]', '[/quote]');
196
197                 // Outlook-Quote - Variant 2
198                 self::tagToBBCode(
199                         $doc,
200                         'div',
201                         ['style' => 'border:none;border-left:solid blue 1.5pt;padding:0cm 0cm 0cm 4.0pt'],
202                         '[quote]',
203                         '[/quote]'
204                 );
205
206                 // MyBB-Stuff
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]');
210
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]');
218                  */
219                 // Untested
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]');
223
224                 self::tagToBBCode($doc, 'span', ['style' => '/.*color:\s*(.+?)[,;].*/'], '[color="$1"]', '[/color]');
225
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
231                 // Test
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]');
235
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]');
244
245                 self::tagToBBCode($doc, 'big', [], "[size=large]", "[/size]");
246                 self::tagToBBCode($doc, 'small', [], "[size=small]", "[/size]");
247
248                 self::tagToBBCode($doc, 'blockquote', [], '[quote]', '[/quote]');
249
250                 self::tagToBBCode($doc, 'br', [], "\n", '');
251
252                 self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal'], "\n", "");
253                 self::tagToBBCode($doc, 'div', ['class' => 'MsoNormal'], "\r", "");
254
255                 self::tagToBBCode($doc, 'span', [], "", "");
256
257                 self::tagToBBCode($doc, 'span', [], "", "");
258                 self::tagToBBCode($doc, 'pre', [], "", "");
259
260                 self::tagToBBCode($doc, 'div', [], "\r", "\r");
261                 self::tagToBBCode($doc, 'p', [], "\n", "\n");
262
263                 self::tagToBBCode($doc, 'ul', [], "[list]", "[/list]");
264                 self::tagToBBCode($doc, 'ol', [], "[list=1]", "[/list]");
265                 self::tagToBBCode($doc, 'li', [], "[*]", "");
266
267                 self::tagToBBCode($doc, 'hr', [], "[hr]", "");
268
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");
282
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]");
289
290                 self::tagToBBCode($doc, 'a', ['href' => '/mailto:(.+)/'], '[mail=$1]', '[/mail]');
291                 self::tagToBBCode($doc, 'a', ['href' => '/(.+)/'], '[url=$1]', '[/url]');
292
293                 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/', 'width' => '/(\d+)/', 'height' => '/(\d+)/'], '[img=$2x$3]$1', '[/img]');
294                 self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], '[img]$1', '[/img]');
295
296
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]');
300
301                 self::tagToBBCode($doc, 'key', [], '[code]', '[/code]');
302                 self::tagToBBCode($doc, 'code', [], '[code]', '[/code]');
303
304                 $message = $doc->saveHTML();
305
306                 // I'm removing something really disturbing
307                 // Don't know exactly what it is
308                 $message = str_replace(chr(194) . chr(160), ' ', $message);
309
310                 $message = str_replace("&nbsp;", " ", $message);
311
312                 // removing multiple DIVs
313                 $message = preg_replace('=\r *\r=i', "\n", $message);
314                 $message = str_replace("\r", "\n", $message);
315
316                 Hook::callAll('html2bbcode', $message);
317
318                 $message = strip_tags($message);
319
320                 $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
321
322                 $message = str_replace(["<"], ["&lt;"], $message);
323
324                 // remove quotes if they don't make sense
325                 $message = preg_replace('=\[/quote\][\s]*\[quote\]=i', "\n", $message);
326
327                 $message = preg_replace('=\[quote\]\s*=i', "[quote]", $message);
328                 $message = preg_replace('=\s*\[/quote\]=i', "[/quote]", $message);
329
330                 do {
331                         $oldmessage = $message;
332                         $message = str_replace("\n \n", "\n\n", $message);
333                 } while ($oldmessage != $message);
334
335                 do {
336                         $oldmessage = $message;
337                         $message = str_replace("\n\n\n", "\n\n", $message);
338                 } while ($oldmessage != $message);
339
340                 do {
341                         $oldmessage = $message;
342                         $message = str_replace(
343                                 [
344                                 "[/size]\n\n",
345                                 "\n[hr]",
346                                 "[hr]\n",
347                                 "\n[list",
348                                 "[/list]\n",
349                                 "\n[/",
350                                 "[list]\n",
351                                 "[list=1]\n",
352                                 "\n[*]"],
353                                 [
354                                 "[/size]\n",
355                                 "[hr]",
356                                 "[hr]",
357                                 "[list",
358                                 "[/list]",
359                                 "[/",
360                                 "[list]",
361                                 "[list=1]",
362                                 "[*]"],
363                                 $message
364                         );
365                 } while ($message != $oldmessage);
366
367                 $message = str_replace(
368                         ['[b][b]', '[/b][/b]', '[i][i]', '[/i][/i]'],
369                         ['[b]', '[/b]', '[i]', '[/i]'],
370                         $message
371                 );
372
373                 // Handling Yahoo style of mails
374                 $message = str_replace('[hr][b]From:[/b]', '[quote][b]From:[/b]', $message);
375
376                 // Restore code blocks
377                 $message = preg_replace_callback(
378                         '#\[codeblock-([0-9]+)\]#iU',
379                         function ($matches) use ($codeblocks) {
380                                 $return = '';
381                                 if (isset($codeblocks[intval($matches[1])])) {
382                                         $return = $codeblocks[$matches[1]];
383                                 }
384                                 return $return;
385                         },
386                         $message
387                 );
388
389                 $message = trim($message);
390
391                 if ($basepath != '') {
392                         $message = self::qualifyURLs($message, $basepath);
393                 }
394
395                 return $message;
396         }
397
398         /**
399          * @brief Sub function to complete incomplete URL
400          *
401          * @param array  $matches  Result of preg_replace_callback
402          * @param string $basepath Basepath that is used to complete the URL
403          *
404          * @return string The expanded URL
405          */
406         private static function qualifyURLsSub($matches, $basepath)
407         {
408                 $base = parse_url($basepath);
409                 unset($base['query']);
410                 unset($base['fragment']);
411
412                 $link = $matches[0];
413                 $url = $matches[1];
414
415                 $parts = array_merge($base, parse_url($url));
416                 $url2 = Network::unparseURL($parts);
417
418                 return str_replace($url, $url2, $link);
419         }
420
421         /**
422          * @brief Complete incomplete URLs in BBCode
423          *
424          * @param string $body     Body with URLs
425          * @param string $basepath Base path that is used to complete the URL
426          *
427          * @return string Body with expanded URLs
428          */
429         private static function qualifyURLs($body, $basepath)
430         {
431                 $URLSearchString = "^\[\]";
432
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",
441                 ];
442
443                 foreach ($matches as $match) {
444                         $body = preg_replace_callback(
445                                 $match,
446                                 function ($match) use ($basepath) {
447                                         return self::qualifyURLsSub($match, $basepath);
448                                 },
449                                 $body
450                         );
451                 }
452                 return $body;
453         }
454
455         private static function breakLines($line, $level, $wraplength = 75)
456         {
457                 if ($wraplength == 0) {
458                         $wraplength = 2000000;
459                 }
460
461                 $wraplen = $wraplength - $level;
462
463                 $newlines = [];
464
465                 do {
466                         $oldline = $line;
467
468                         $subline = substr($line, 0, $wraplen);
469
470                         $pos = strrpos($subline, ' ');
471
472                         if ($pos == 0) {
473                                 $pos = strpos($line, ' ');
474                         }
475
476                         if (($pos > 0) && strlen($line) > $wraplen) {
477                                 $newline = trim(substr($line, 0, $pos));
478                                 if ($level > 0) {
479                                         $newline = str_repeat(">", $level) . ' ' . $newline;
480                                 }
481
482                                 $newlines[] = $newline . " ";
483                                 $line = substr($line, $pos + 1);
484                         }
485                 } while ((strlen($line) > $wraplen) && !($oldline == $line));
486
487                 if ($level > 0) {
488                         $line = str_repeat(">", $level) . ' ' . $line;
489                 }
490
491                 $newlines[] = $line;
492
493                 return implode($newlines, "\n");
494         }
495
496         private static function quoteLevel($message, $wraplength = 75)
497         {
498                 $lines = explode("\n", $message);
499
500                 $newlines = [];
501                 $level = 0;
502                 foreach ($lines as $line) {
503                         $line = trim($line);
504                         $startquote = false;
505                         while (strpos("*" . $line, '[quote]') > 0) {
506                                 $level++;
507                                 $pos = strpos($line, '[quote]');
508                                 $line = substr($line, 0, $pos) . substr($line, $pos + 7);
509                                 $startquote = true;
510                         }
511
512                         $currlevel = $level;
513
514                         while (strpos("*" . $line, '[/quote]') > 0) {
515                                 $level--;
516                                 if ($level < 0) {
517                                         $level = 0;
518                                 }
519
520                                 $pos = strpos($line, '[/quote]');
521                                 $line = substr($line, 0, $pos) . substr($line, $pos + 8);
522                         }
523
524                         if (!$startquote || ($line != '')) {
525                                 $newlines[] = self::breakLines($line, $currlevel, $wraplength);
526                         }
527                 }
528
529                 return implode($newlines, "\n");
530         }
531
532         private static function collectURLs($message)
533         {
534                 $pattern = '/<a.*?href="(.*?)".*?>(.*?)<\/a>/is';
535                 preg_match_all($pattern, $message, $result, PREG_SET_ORDER);
536
537                 $urls = [];
538                 foreach ($result as $treffer) {
539                         $ignore = false;
540
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) {
546                                         $ignore = true;
547                                 }
548                         }
549
550                         if ((strpos($treffer[1], "//twitter.com/") !== false) && (strpos($treffer[1], "/status/") !== false)) {
551                                 $ignore = false;
552                         }
553
554                         if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/posts") !== false)) {
555                                 $ignore = false;
556                         }
557
558                         if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/photos") !== false)) {
559                                 $ignore = false;
560                         }
561
562                         if (!$ignore) {
563                                 $urls[$treffer[1]] = $treffer[1];
564                         }
565                 }
566
567                 return $urls;
568         }
569
570         public static function toPlaintext($html, $wraplength = 75, $compact = false)
571         {
572                 $message = str_replace("\r", "", $html);
573
574                 $doc = new DOMDocument();
575                 $doc->preserveWhiteSpace = false;
576
577                 $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8");
578
579                 @$doc->loadHTML($message);
580
581                 $xpath = new DOMXPath($doc);
582                 $list = $xpath->query("//pre");
583                 foreach ($list as $node) {
584                         $node->nodeValue = str_replace("\n", "\r", $node->nodeValue);
585                 }
586
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);
590
591                 // Collecting all links
592                 $urls = self::collectURLs($message);
593
594                 @$doc->loadHTML($message);
595
596                 self::tagToBBCode($doc, 'html', [], '', '');
597                 self::tagToBBCode($doc, 'body', [], '', '');
598
599                 // MyBB-Auszeichnungen
600                 /*
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;'), '*', '*');
604
605                   self::node2BBCode($doc, 'strong', array(), '*', '*');
606                   self::node2BBCode($doc, 'b', array(), '*', '*');
607                   self::node2BBCode($doc, 'i', array(), '/', '/');
608                   self::node2BBCode($doc, 'u', array(), '_', '_');
609                  */
610
611                 if ($compact) {
612                         self::tagToBBCode($doc, 'blockquote', [], "»", "«");
613                 } else {
614                         self::tagToBBCode($doc, 'blockquote', [], '[quote]', "[/quote]\n");
615                 }
616
617                 self::tagToBBCode($doc, 'br', [], "\n", '');
618
619                 self::tagToBBCode($doc, 'span', [], "", "");
620                 self::tagToBBCode($doc, 'pre', [], "", "");
621                 self::tagToBBCode($doc, 'div', [], "\r", "\r");
622                 self::tagToBBCode($doc, 'p', [], "\n", "\n");
623
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");
627
628                 self::tagToBBCode($doc, 'hr', [], "\n" . str_repeat("-", 70) . "\n", "");
629
630                 self::tagToBBCode($doc, 'tr', [], "\n", "");
631                 self::tagToBBCode($doc, 'td', [], "\t", "");
632
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");
639
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(), '', '');
646                 if (!$compact) {
647                         self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], ' [img]$1', '[/img] ');
648                 } else {
649                         self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], ' ', ' ');
650                 }
651
652                 self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], ' $1 ', '');
653
654                 $message = $doc->saveHTML();
655
656                 if (!$compact) {
657                         $message = str_replace("[img]", "", $message);
658                         $message = str_replace("[/img]", "", $message);
659                 }
660
661                 // was ersetze ich da?
662                 // Irgendein stoerrisches UTF-Zeug
663                 $message = str_replace(chr(194) . chr(160), ' ', $message);
664
665                 $message = str_replace("&nbsp;", " ", $message);
666
667                 // Aufeinanderfolgende DIVs
668                 $message = preg_replace('=\r *\r=i', "\n", $message);
669                 $message = str_replace("\r", "\n", $message);
670
671                 $message = strip_tags($message);
672
673                 $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
674
675                 if (!$compact && ($message != '')) {
676                         foreach ($urls as $id => $url) {
677                                 if ($url != '' && strpos($message, $url) === false) {
678                                         $message .= "\n" . $url . ' ';
679                                 }
680                         }
681                 }
682
683                 $message = str_replace("\n«", "«\n", $message);
684                 $message = str_replace("»\n", "\n»", $message);
685
686                 do {
687                         $oldmessage = $message;
688                         $message = str_replace("\n\n\n", "\n\n", $message);
689                 } while ($oldmessage != $message);
690
691                 $message = self::quoteLevel(trim($message), $wraplength);
692
693                 return trim($message);
694         }
695
696         /**
697          * Converts provided HTML code to Markdown. The hardwrap parameter maximizes
698          * compatibility with Diaspora in spite of the Markdown standards.
699          *
700          * @param string $html
701          * @return string
702          */
703         public static function toMarkdown($html)
704         {
705                 $converter = new HtmlConverter(['hard_break' => true]);
706                 $markdown = $converter->convert($html);
707
708                 return $markdown;
709         }
710
711         /**
712          * @brief Convert video HTML to BBCode tags
713          *
714          * @param string $s
715          * @return string
716          */
717         public static function toBBCodeVideo($s)
718         {
719                 $s = preg_replace(
720                         '#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
721                         '[youtube]$2[/youtube]',
722                         $s
723                 );
724         
725                 $s = preg_replace(
726                         '#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
727                         '[youtube]$2[/youtube]',
728                         $s
729                 );
730         
731                 $s = preg_replace(
732                         '#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
733                         '[vimeo]$2[/vimeo]',
734                         $s
735                 );
736         
737                 return $s;
738         }
739         
740         /**
741          * transform link href and img src from relative to absolute
742          *
743          * @param string $text
744          * @param string $base base url
745          * @return string
746          */
747         public static function relToAbs($text, $base)
748         {
749                 if (empty($base)) {
750                         return $text;
751                 }
752         
753                 $base = rtrim($base, '/');
754         
755                 $base2 = $base . "/";
756         
757                 // Replace links
758                 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
759                 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
760                 $text = preg_replace($pattern, $replace, $text);
761         
762                 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
763                 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
764                 $text = preg_replace($pattern, $replace, $text);
765         
766                 // Replace images
767                 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
768                 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
769                 $text = preg_replace($pattern, $replace, $text);
770         
771                 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
772                 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
773                 $text = preg_replace($pattern, $replace, $text);
774         
775         
776                 // Done
777                 return $text;
778         }
779
780         /**
781          * return div element with class 'clear'
782          * @return string
783          * @deprecated
784          */
785         public static function clearDiv()
786         {
787                 return '<div class="clear"></div>';
788         }
789
790         /**
791          * Loader for infinite scrolling
792          *
793          * @return string html for loader
794          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
795          */
796         public static function scrollLoader()
797         {
798                 $tpl = Renderer::getMarkupTemplate("scroll_loader.tpl");
799                 return Renderer::replaceMacros($tpl, [
800                         'wait' => L10n::t('Loading more entries...'),
801                         'end' => L10n::t('The end')
802                 ]);
803         }
804
805         /**
806          * Get html for contact block.
807          *
808          * @deprecated since version 2019.03
809          * @see ContactBlock::getHTML()
810          * @return string
811          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
812          * @throws \ImagickException
813          */
814         public static function contactBlock()
815         {
816                 $a = \get_app();
817
818                 return ContactBlock::getHTML($a->profile);
819         }
820
821         /**
822          * @brief Format contacts as picture links or as text links
823          *
824          * @param array   $contact  Array with contacts which contains an array with
825          *                          int 'id' => The ID of the contact
826          *                          int 'uid' => The user ID of the user who owns this data
827          *                          string 'name' => The name of the contact
828          *                          string 'url' => The url to the profile page of the contact
829          *                          string 'addr' => The webbie of the contact (e.g.) username@friendica.com
830          *                          string 'network' => The network to which the contact belongs to
831          *                          string 'thumb' => The contact picture
832          *                          string 'click' => js code which is performed when clicking on the contact
833          * @param boolean $redirect If true try to use the redir url if it's possible
834          * @param string  $class    CSS class for the
835          * @param boolean $textmode If true display the contacts as text links
836          *                          if false display the contacts as picture links
837          * @return string Formatted html
838          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
839          * @throws \ImagickException
840          */
841         public static function micropro($contact, $redirect = false, $class = '', $textmode = false)
842         {
843                 // Use the contact URL if no address is available
844                 if (empty($contact['addr'])) {
845                         $contact["addr"] = $contact["url"];
846                 }
847
848                 $url = $contact['url'];
849                 $sparkle = '';
850                 $redir = false;
851
852                 if ($redirect) {
853                         $url = Contact::magicLink($contact['url']);
854                         if (strpos($url, 'redir/') === 0) {
855                                 $sparkle = ' sparkle';
856                         }
857                 }
858
859                 // If there is some js available we don't need the url
860                 if (!empty($contact['click'])) {
861                         $url = '';
862                 }
863
864                 return Renderer::replaceMacros(Renderer::getMarkupTemplate(($textmode)?'micropro_txt.tpl':'micropro_img.tpl'), [
865                         '$click' => defaults($contact, 'click', ''),
866                         '$class' => $class,
867                         '$url' => $url,
868                         '$photo' => ProxyUtils::proxifyUrl($contact['thumb'], false, ProxyUtils::SIZE_THUMB),
869                         '$name' => $contact['name'],
870                         'title' => $contact['name'] . ' [' . $contact['addr'] . ']',
871                         '$parkle' => $sparkle,
872                         '$redir' => $redir
873                 ]);
874         }
875
876         /**
877          * Search box.
878          *
879          * @param string $s     Search query.
880          * @param string $id    HTML id
881          * @param string $url   Search url.
882          * @param bool   $aside Display the search widgit aside.
883          *
884          * @return string Formatted HTML.
885          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
886          */
887         public static function search($s, $id = 'search-box', $url = 'search', $aside = true)
888         {
889                 $mode = 'text';
890
891                 if (strpos($s, '#') === 0) {
892                         $mode = 'tag';
893                 }
894                 $save_label = $mode === 'text' ? L10n::t('Save') : L10n::t('Follow');
895
896                 $values = [
897                                 '$s' => $s,
898                                 '$id' => $id,
899                                 '$action_url' => $url,
900                                 '$search_label' => L10n::t('Search'),
901                                 '$save_label' => $save_label,
902                                 '$savedsearch' => 'savedsearch',
903                                 '$search_hint' => L10n::t('@name, !forum, #tags, content'),
904                                 '$mode' => $mode
905                         ];
906
907                 if (!$aside) {
908                         $values['$searchoption'] = [
909                                                 L10n::t("Full Text"),
910                                                 L10n::t("Tags"),
911                                                 L10n::t("Contacts")];
912
913                         if (Config::get('system', 'poco_local_search')) {
914                                 $values['$searchoption'][] = L10n::t("Forums");
915                         }
916                 }
917
918                 return Renderer::replaceMacros(Renderer::getMarkupTemplate('searchbox.tpl'), $values);
919         }
920
921         /**
922          * Replace naked text hyperlink with HTML formatted hyperlink
923          *
924          * @param string $s
925          * @return string
926          */
927         public static function toLink($s)
928         {
929                 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank">$1</a>', $s);
930                 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&amp\;(.*?)\>/ism", '<$1$2=$3&$4>', $s);
931                 return $s;
932         }
933
934         /**
935          * Given a HTML text and a set of filtering reasons, adds a content hiding header with the provided reasons
936          *
937          * Reasons are expected to have been translated already.
938          *
939          * @param string $html
940          * @param array  $reasons
941          * @return string
942          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
943          */
944         public static function applyContentFilter($html, array $reasons)
945         {
946                 if (count($reasons)) {
947                         $tpl = Renderer::getMarkupTemplate('wall/content_filter.tpl');
948                         $html = Renderer::replaceMacros($tpl, [
949                                 '$reasons'   => $reasons,
950                                 '$rnd'       => Strings::getRandomHex(8),
951                                 '$openclose' => L10n::t('Click to open/close'),
952                                 '$html'      => $html
953                         ]);
954                 }
955
956                 return $html;
957         }
958
959         /**
960          * replace html amp entity with amp char
961          * @param string $s
962          * @return string
963          */
964         public static function unamp($s)
965         {
966                 return str_replace('&amp;', '&', $s);
967         }
968 }