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