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