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