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