]> git.mxchange.org Git - friendica.git/blob - src/Content/Text/HTML.php
Merge pull request #8909 from MrPetovan/task/ex_auth
[friendica.git] / src / Content / Text / HTML.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Content\Text;
23
24 use DOMDocument;
25 use DOMXPath;
26 use Friendica\Content\Widget\ContactBlock;
27 use Friendica\Core\Hook;
28 use Friendica\Core\Renderer;
29 use Friendica\Core\Search;
30 use Friendica\DI;
31 use Friendica\Model\Contact;
32 use Friendica\Util\Network;
33 use Friendica\Util\Strings;
34 use Friendica\Util\XML;
35 use League\HTMLToMarkdown\HtmlConverter;
36
37 class HTML
38 {
39         public static function sanitizeCSS($input)
40         {
41                 $cleaned = "";
42
43                 $input = strtolower($input);
44
45                 for ($i = 0; $i < strlen($input); $i++) {
46                         $char = substr($input, $i, 1);
47
48                         if (($char >= "a") && ($char <= "z")) {
49                                 $cleaned .= $char;
50                         }
51
52                         if (!(strpos(" #;:0123456789-_.%", $char) === false)) {
53                                 $cleaned .= $char;
54                         }
55                 }
56
57                 return $cleaned;
58         }
59
60         /**
61          * Search all instances of a specific HTML tag node in the provided DOM document and replaces them with BBCode text nodes.
62          *
63          * @see HTML::tagToBBCodeSub()
64          */
65         private static function tagToBBCode(DOMDocument $doc, string $tag, array $attributes, string $startbb, string $endbb, bool $ignoreChildren = false)
66         {
67                 do {
68                         $done = self::tagToBBCodeSub($doc, $tag, $attributes, $startbb, $endbb, $ignoreChildren);
69                 } while ($done);
70         }
71
72         /**
73          * Search the first specific HTML tag node in the provided DOM document and replaces it with BBCode text nodes.
74          *
75          * @param DOMDocument $doc
76          * @param string      $tag            HTML tag name
77          * @param array       $attributes     Array of attributes to match and optionally use the value from
78          * @param string      $startbb        BBCode tag opening
79          * @param string      $endbb          BBCode tag closing
80          * @param bool        $ignoreChildren If set to false, the HTML tag children will be appended as text inside the BBCode tag
81          *                                    Otherwise, they will be entirely ignored. Useful for simple BBCode that draw their
82          *                                    inner value from an attribute value and disregard the tag children.
83          * @return bool Whether a replacement was done
84          */
85         private static function tagToBBCodeSub(DOMDocument $doc, string $tag, array $attributes, string $startbb, string $endbb, bool $ignoreChildren = false)
86         {
87                 $savestart = str_replace('$', '\x01', $startbb);
88                 $replace = false;
89
90                 $xpath = new DOMXPath($doc);
91
92                 /** @var \DOMNode[] $list */
93                 $list = $xpath->query("//" . $tag);
94                 foreach ($list as $node) {
95                         $attr = [];
96                         if ($node->attributes->length) {
97                                 foreach ($node->attributes as $attribute) {
98                                         $attr[$attribute->name] = $attribute->value;
99                                 }
100                         }
101
102                         $replace = true;
103
104                         $startbb = $savestart;
105
106                         $i = 0;
107
108                         foreach ($attributes as $attribute => $value) {
109                                 $startbb = str_replace('\x01' . ++$i, '$1', $startbb);
110                                 if (strpos('*' . $startbb, '$1') > 0) {
111                                         if ($replace && (@$attr[$attribute] != '')) {
112                                                 $startbb = preg_replace($value, $startbb, $attr[$attribute], -1, $count);
113
114                                                 // If nothing could be changed
115                                                 if ($count == 0) {
116                                                         $replace = false;
117                                                 }
118                                         } else {
119                                                 $replace = false;
120                                         }
121                                 } else {
122                                         if (@$attr[$attribute] != $value) {
123                                                 $replace = false;
124                                         }
125                                 }
126                         }
127
128                         if ($replace) {
129                                 $StartCode = $doc->createTextNode($startbb);
130                                 $EndCode = $doc->createTextNode($endbb);
131
132                                 $node->parentNode->insertBefore($StartCode, $node);
133
134                                 if (!$ignoreChildren && $node->hasChildNodes()) {
135                                         /** @var \DOMNode $child */
136                                         foreach ($node->childNodes as $key => $child) {
137                                                 /* Remove empty text nodes at the start or at the end of the children list */
138                                                 if ($key > 0 && $key < $node->childNodes->length - 1 || $child->nodeName != '#text' || trim($child->nodeValue)) {
139                                                         $newNode = $child->cloneNode(true);
140                                                         $node->parentNode->insertBefore($newNode, $node);
141                                                 }
142                                         }
143                                 }
144
145                                 $node->parentNode->insertBefore($EndCode, $node);
146                                 $node->parentNode->removeChild($node);
147                         }
148                 }
149
150                 return $replace;
151         }
152
153         /**
154          * Converter for HTML to BBCode
155          *
156          * Made by: ike@piratenpartei.de
157          * Originally made for the syncom project: http://wiki.piratenpartei.de/Syncom
158          *                    https://github.com/annando/Syncom
159          *
160          * @param string $message
161          * @param string $basepath
162          * @return string
163          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
164          */
165         public static function toBBCode($message, $basepath = '')
166         {
167                 $message = str_replace("\r", "", $message);
168
169                 $message = Strings::performWithEscapedBlocks($message, '#<pre><code.*</code></pre>#iUs', function ($message) {
170                         $message = str_replace(
171                                 [
172                                         "<li><p>",
173                                         "</p></li>",
174                                 ],
175                                 [
176                                         "<li>",
177                                         "</li>",
178                                 ],
179                                 $message
180                         );
181
182                         // remove namespaces
183                         $message = preg_replace('=<(\w+):(.+?)>=', '<removeme>', $message);
184                         $message = preg_replace('=</(\w+):(.+?)>=', '</removeme>', $message);
185
186                         $doc = new DOMDocument();
187                         $doc->preserveWhiteSpace = false;
188
189                         $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8");
190
191                         @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
192
193                         XML::deleteNode($doc, 'style');
194                         XML::deleteNode($doc, 'head');
195                         XML::deleteNode($doc, 'title');
196                         XML::deleteNode($doc, 'meta');
197                         XML::deleteNode($doc, 'xml');
198                         XML::deleteNode($doc, 'removeme');
199
200                         $xpath = new DomXPath($doc);
201                         $list = $xpath->query("//pre");
202                         foreach ($list as $node) {
203                                 // Ensure to escape unescaped & - they will otherwise raise a warning
204                                 $safe_value = preg_replace('/&(?!\w+;)/', '&amp;', $node->nodeValue);
205                                 $node->nodeValue = str_replace("\n", "\r", $safe_value);
206                         }
207
208                         $message = $doc->saveHTML();
209                         $message = str_replace(["\n<", ">\n", "\r", "\n", "\xC3\x82\xC2\xA0"], ["<", ">", "<br />", " ", ""], $message);
210                         $message = preg_replace('= [\s]*=i', " ", $message);
211
212                         @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
213
214                         self::tagToBBCode($doc, 'html', [], "", "");
215                         self::tagToBBCode($doc, 'body', [], "", "");
216
217                         // Outlook-Quote - Variant 1
218                         self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal', 'style' => 'margin-left:35.4pt'], '[quote]', '[/quote]');
219
220                         // Outlook-Quote - Variant 2
221                         self::tagToBBCode(
222                                 $doc,
223                                 'div',
224                                 ['style' => 'border:none;border-left:solid blue 1.5pt;padding:0cm 0cm 0cm 4.0pt'],
225                                 '[quote]',
226                                 '[/quote]'
227                         );
228
229                         // MyBB-Stuff
230                         self::tagToBBCode($doc, 'span', ['style' => 'text-decoration: underline;'], '[u]', '[/u]');
231                         self::tagToBBCode($doc, 'span', ['style' => 'font-style: italic;'], '[i]', '[/i]');
232                         self::tagToBBCode($doc, 'span', ['style' => 'font-weight: bold;'], '[b]', '[/b]');
233
234                         /* self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[font=$1][size=$2][color=$3]', '[/color][/size][/font]');
235                           self::node2BBCode($doc, 'font', array('size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[size=$1][color=$2]', '[/color][/size]');
236                           self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(.+)/'), '[font=$1][size=$2]', '[/size][/font]');
237                           self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/', 'color'=>'/(.+)/'), '[font=$1][color=$3]', '[/color][/font]');
238                           self::node2BBCode($doc, 'font', array('face'=>'/([\w ]+)/'), '[font=$1]', '[/font]');
239                           self::node2BBCode($doc, 'font', array('size'=>'/(\d+)/'), '[size=$1]', '[/size]');
240                           self::node2BBCode($doc, 'font', array('color'=>'/(.+)/'), '[color=$1]', '[/color]');
241                          */
242                         // Untested
243                         //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*font-family:\s*(.+?)[,;].*color:\s*(.+?)[,;].*/'), '[size=$1][font=$2][color=$3]', '[/color][/font][/size]');
244                         //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(\d+)[,;].*/'), '[size=$1]', '[/size]');
245                         //self::node2BBCode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*/'), '[size=$1]', '[/size]');
246
247                         self::tagToBBCode($doc, 'span', ['style' => '/.*color:\s*(.+?)[,;].*/'], '[color="$1"]', '[/color]');
248
249                         //self::node2BBCode($doc, 'span', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
250                         //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)pt.*/'), '[font=$1][size=$2]', '[/size][/font]');
251                         //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)px.*/'), '[font=$1][size=$2]', '[/size][/font]');
252                         //self::node2BBCode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
253                         // Importing the classes - interesting for importing of posts from third party networks that were exported from friendica
254                         // Test
255                         //self::node2BBCode($doc, 'span', array('class'=>'/([\w ]+)/'), '[class=$1]', '[/class]');
256                         self::tagToBBCode($doc, 'span', ['class' => 'type-link'], '[class=type-link]', '[/class]');
257                         self::tagToBBCode($doc, 'span', ['class' => 'type-video'], '[class=type-video]', '[/class]');
258
259                         self::tagToBBCode($doc, 'strong', [], '[b]', '[/b]');
260                         self::tagToBBCode($doc, 'em', [], '[i]', '[/i]');
261                         self::tagToBBCode($doc, 'b', [], '[b]', '[/b]');
262                         self::tagToBBCode($doc, 'i', [], '[i]', '[/i]');
263                         self::tagToBBCode($doc, 'u', [], '[u]', '[/u]');
264                         self::tagToBBCode($doc, 's', [], '[s]', '[/s]');
265                         self::tagToBBCode($doc, 'del', [], '[s]', '[/s]');
266                         self::tagToBBCode($doc, 'strike', [], '[s]', '[/s]');
267
268                         self::tagToBBCode($doc, 'big', [], "[size=large]", "[/size]");
269                         self::tagToBBCode($doc, 'small', [], "[size=small]", "[/size]");
270
271                         self::tagToBBCode($doc, 'blockquote', [], '[quote]', '[/quote]');
272
273                         self::tagToBBCode($doc, 'br', [], "\n", '');
274
275                         self::tagToBBCode($doc, 'p', ['class' => 'MsoNormal'], "\n", "");
276                         self::tagToBBCode($doc, 'div', ['class' => 'MsoNormal'], "\r", "");
277
278                         self::tagToBBCode($doc, 'span', [], "", "");
279
280                         self::tagToBBCode($doc, 'span', [], "", "");
281                         self::tagToBBCode($doc, 'pre', [], "", "");
282
283                         self::tagToBBCode($doc, 'div', [], "\r", "\r");
284                         self::tagToBBCode($doc, 'p', [], "\n", "\n");
285
286                         self::tagToBBCode($doc, 'ul', [], "[list]", "[/list]");
287                         self::tagToBBCode($doc, 'ol', [], "[list=1]", "[/list]");
288                         self::tagToBBCode($doc, 'li', [], "[*]", "");
289
290                         self::tagToBBCode($doc, 'hr', [], "[hr]", "");
291
292                         self::tagToBBCode($doc, 'table', [], "[table]", "[/table]");
293                         self::tagToBBCode($doc, 'th', [], "[th]", "[/th]");
294                         self::tagToBBCode($doc, 'tr', [], "[tr]", "[/tr]");
295                         self::tagToBBCode($doc, 'td', [], "[td]", "[/td]");
296
297                         self::tagToBBCode($doc, 'h1', [], "[h1]", "[/h1]");
298                         self::tagToBBCode($doc, 'h2', [], "[h2]", "[/h2]");
299                         self::tagToBBCode($doc, 'h3', [], "[h3]", "[/h3]");
300                         self::tagToBBCode($doc, 'h4', [], "[h4]", "[/h4]");
301                         self::tagToBBCode($doc, 'h5', [], "[h5]", "[/h5]");
302                         self::tagToBBCode($doc, 'h6', [], "[h6]", "[/h6]");
303
304                         self::tagToBBCode($doc, 'a', ['href' => '/mailto:(.+)/'], '[mail=$1]', '[/mail]');
305                         self::tagToBBCode($doc, 'a', ['href' => '/(.+)/'], '[url=$1]', '[/url]');
306
307                         self::tagToBBCode($doc, 'img', ['src' => '/(.+)/', 'alt' => '/(.+)/'], '[img=$1]$2', '[/img]', true);
308                         self::tagToBBCode($doc, 'img', ['src' => '/(.+)/', 'width' => '/(\d+)/', 'height' => '/(\d+)/'], '[img=$2x$3]$1', '[/img]', true);
309                         self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], '[img]$1', '[/img]', true);
310
311
312                         self::tagToBBCode($doc, 'video', ['src' => '/(.+)/'], '[video]$1', '[/video]', true);
313                         self::tagToBBCode($doc, 'audio', ['src' => '/(.+)/'], '[audio]$1', '[/audio]', true);
314                         self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], '[iframe]$1', '[/iframe]', true);
315
316                         self::tagToBBCode($doc, 'key', [], '[code]', '[/code]');
317                         self::tagToBBCode($doc, 'code', [], '[code]', '[/code]');
318
319                         $message = $doc->saveHTML();
320
321                         // I'm removing something really disturbing
322                         // Don't know exactly what it is
323                         $message = str_replace(chr(194) . chr(160), ' ', $message);
324
325                         $message = str_replace("&nbsp;", " ", $message);
326
327                         // removing multiple DIVs
328                         $message = preg_replace('=\r *\r=i', "\n", $message);
329                         $message = str_replace("\r", "\n", $message);
330
331                         Hook::callAll('html2bbcode', $message);
332
333                         $message = strip_tags($message);
334
335                         $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
336
337                         // remove quotes if they don't make sense
338                         $message = preg_replace('=\[/quote\][\s]*\[quote\]=i', "\n", $message);
339
340                         $message = preg_replace('=\[quote\]\s*=i', "[quote]", $message);
341                         $message = preg_replace('=\s*\[/quote\]=i', "[/quote]", $message);
342
343                         do {
344                                 $oldmessage = $message;
345                                 $message = str_replace("\n \n", "\n\n", $message);
346                         } while ($oldmessage != $message);
347
348                         do {
349                                 $oldmessage = $message;
350                                 $message = str_replace("\n\n\n", "\n\n", $message);
351                         } while ($oldmessage != $message);
352
353                         do {
354                                 $oldmessage = $message;
355                                 $message = str_replace(
356                                         [
357                                                 "[/size]\n\n",
358                                                 "\n[hr]",
359                                                 "[hr]\n",
360                                                 "\n[list",
361                                                 "[/list]\n",
362                                                 "\n[/",
363                                                 "[list]\n",
364                                                 "[list=1]\n",
365                                                 "\n[*]"],
366                                         [
367                                                 "[/size]\n",
368                                                 "[hr]",
369                                                 "[hr]",
370                                                 "[list",
371                                                 "[/list]",
372                                                 "[/",
373                                                 "[list]",
374                                                 "[list=1]",
375                                                 "[*]"],
376                                         $message
377                                 );
378                         } while ($message != $oldmessage);
379
380                         $message = str_replace(
381                                 ['[b][b]', '[/b][/b]', '[i][i]', '[/i][/i]'],
382                                 ['[b]', '[/b]', '[i]', '[/i]'],
383                                 $message
384                         );
385
386                         // Handling Yahoo style of mails
387                         $message = str_replace('[hr][b]From:[/b]', '[quote][b]From:[/b]', $message);
388
389                         return $message;
390                 });
391
392                 $message = preg_replace_callback(
393                         '#<pre><code(?: class="language-([^"]*)")?>(.*)</code></pre>#iUs',
394                         function ($matches) {
395                                 $prefix = '[code]';
396                                 if ($matches[1] != '') {
397                                         $prefix = '[code=' . $matches[1] . ']';
398                                 }
399
400                                 return $prefix . PHP_EOL . trim($matches[2]) . PHP_EOL . '[/code]';
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          * 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          * 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("\n", $newlines);
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("\n", $newlines);
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          * 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' => DI::l10n()->t('Loading more entries...'),
803                         'end' => DI::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 = DI::app();
819
820                 return ContactBlock::getHTML($a->profile);
821         }
822
823         /**
824          * 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' => Contact::getThumb($contact),
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' ? DI::l10n()->t('Save') : DI::l10n()->t('Follow');
897
898                 $values = [
899                         '$s'            => $s,
900                         '$q'            => urlencode($s),
901                         '$id'           => $id,
902                         '$search_label' => DI::l10n()->t('Search'),
903                         '$save_label'   => $save_label,
904                         '$search_hint'  => DI::l10n()->t('@name, !forum, #tags, content'),
905                         '$mode'         => $mode,
906                         '$return_url'   => urlencode(Search::getSearchPath($s)),
907                 ];
908
909                 if (!$aside) {
910                         $values['$search_options'] = [
911                                 'fulltext' => DI::l10n()->t('Full Text'),
912                                 'tags'     => DI::l10n()->t('Tags'),
913                                 'contacts' => DI::l10n()->t('Contacts')
914                         ];
915
916                         if (DI::config()->get('system', 'poco_local_search')) {
917                                 $values['$searchoption']['forums'] = DI::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" rel="noopener noreferrer">$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' => DI::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 }