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