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