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