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