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