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