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