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