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