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