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