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