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