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