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