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