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