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