]> git.mxchange.org Git - friendica.git/blob - src/Content/Text/BBCode.php
Merge pull request #13635 from gudzpoz/emojis-please
[friendica.git] / src / Content / Text / BBCode.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
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 Exception;
27 use Friendica\Content\ContactSelector;
28 use Friendica\Content\Item;
29 use Friendica\Content\OEmbed;
30 use Friendica\Content\PageInfo;
31 use Friendica\Content\Smilies;
32 use Friendica\Core\Hook;
33 use Friendica\Core\Logger;
34 use Friendica\Core\Protocol;
35 use Friendica\Core\Renderer;
36 use Friendica\DI;
37 use Friendica\Model\Contact;
38 use Friendica\Model\Event;
39 use Friendica\Model\Post;
40 use Friendica\Model\Tag;
41 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
42 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
43 use Friendica\Util\Map;
44 use Friendica\Util\ParseUrl;
45 use Friendica\Util\Proxy;
46 use Friendica\Util\Strings;
47 use Friendica\Util\XML;
48
49 class BBCode
50 {
51         // Update this value to the current date whenever changes are made to BBCode::convert
52         const VERSION = '2021-07-28';
53
54         const INTERNAL     = 0;
55         const EXTERNAL     = 1;
56         const MASTODON_API = 2;
57         const DIASPORA     = 3;
58         const CONNECTORS   = 4;
59         const TWITTER_API  = 5;
60         const NPF          = 6;
61         const OSTATUS      = 7;
62         const TWITTER      = 8;
63         const BACKLINK     = 8;
64         const ACTIVITYPUB  = 9;
65         const BLUESKY      = 10;
66
67         const SHARED_ANCHOR = '<hr class="shared-anchor">';
68         const TOP_ANCHOR    = '<br class="top-anchor">';
69         const BOTTOM_ANCHOR = '<br class="button-anchor">';
70
71         const PREVIEW_NONE     = 0;
72         const PREVIEW_NO_IMAGE = 1;
73         const PREVIEW_LARGE    = 2;
74         const PREVIEW_SMALL    = 3;
75
76         /**
77          * Fetches attachment data that were generated with the "attachment" element
78          *
79          * @param string $body Message body
80          * @return array
81          *                     'type' -> Message type ('link', 'video', 'photo')
82          *                     'text' -> Text before the shared message
83          *                     'after' -> Text after the shared message
84          *                     'image' -> Preview image of the message
85          *                     'url' -> Url to the attached message
86          *                     'title' -> Title of the attachment
87          *                     'description' -> Description of the attachment
88          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
89          */
90         public static function getAttachmentData(string $body): array
91         {
92                 DI::profiler()->startRecording('rendering');
93                 $data = [
94                         'type'          => '',
95                         'text'          => '',
96                         'after'         => '',
97                         'image'         => null,
98                         'url'           => '',
99                         'author_name'   => '',
100                         'author_url'    => '',
101                         'provider_name' => '',
102                         'provider_url'  => '',
103                         'title'         => '',
104                         'description'   => '',
105                 ];
106
107                 if (!preg_match("/(.*)\[attachment(.*?)\](.*?)\[\/attachment\](.*)/ism", $body, $match)) {
108                         DI::profiler()->stopRecording();
109                         return [];
110                 }
111
112                 $attributes = $match[2];
113
114                 $data['text'] = trim($match[1]);
115
116                 foreach (['type', 'url', 'title', 'image', 'preview', 'publisher_name', 'publisher_url', 'author_name', 'author_url'] as $field) {
117                         preg_match('/' . preg_quote($field, '/') . '=("|\')(.*?)\1/ism', $attributes, $matches);
118                         $value = $matches[2] ?? '';
119
120                         if ($value != '') {
121                                 switch ($field) {
122                                         case 'publisher_name':
123                                                 $data['provider_name'] = html_entity_decode($value, ENT_QUOTES, 'UTF-8');
124                                                 break;
125
126                                         case 'publisher_url':
127                                                 $data['provider_url'] = html_entity_decode($value, ENT_QUOTES, 'UTF-8');
128                                                 break;
129
130                                         case 'author_name':
131                                                 $data['author_name'] = html_entity_decode($value, ENT_QUOTES, 'UTF-8');
132                                                 if ($data['provider_name'] == $data['author_name']) {
133                                                         $data['author_name'] = '';
134                                                 }
135                                                 break;
136
137                                         case 'author_url':
138                                                 $data['author_url'] = html_entity_decode($value, ENT_QUOTES, 'UTF-8');
139                                                 if ($data['provider_url'] == $data['author_url']) {
140                                                         $data['author_url'] = '';
141                                                 }
142                                                 break;
143
144                                         case 'title':
145                                                 $value = self::toPlaintext(html_entity_decode($value, ENT_QUOTES, 'UTF-8'));
146                                                 $value = html_entity_decode($value, ENT_QUOTES, 'UTF-8');
147                                                 $value = str_replace(['[', ']'], ['&#91;', '&#93;'], $value);
148                                                 $data['title'] = $value;
149
150                                         default:
151                                                 $data[$field] = html_entity_decode($value, ENT_QUOTES, 'UTF-8');
152                                                 break;
153                                 }
154                         }
155                 }
156
157                 if (!in_array($data['type'], ['link', 'audio', 'photo', 'video'])) {
158                         DI::profiler()->stopRecording();
159                         return [];
160                 }
161
162                 $data['description'] = trim($match[3]);
163
164                 $data['after'] = trim($match[4]);
165
166                 $parts = parse_url($data['url']);
167                 if (!empty($parts['scheme']) && !empty($parts['host'])) {
168                         if (empty($data['provider_name'])) {
169                                 $data['provider_name'] = $parts['host'];
170                         }
171                         if (empty($data['provider_url']) || empty(parse_url($data['provider_url'], PHP_URL_SCHEME))) {
172                                 $data['provider_url'] = $parts['scheme'] . '://' . $parts['host'];
173
174                                 if (!empty($parts['port'])) {
175                                         $data['provider_url'] .= ':' . $parts['port'];
176                                 }
177                         }
178                 }
179
180                 DI::profiler()->stopRecording();
181                 return $data;
182         }
183
184         /**
185          * Remove [attachment] BBCode and replaces it with a regular [url]
186          *
187          * @param string  $body
188          * @param boolean $no_link_desc No link description
189          * @return string with replaced body
190          */
191         public static function replaceAttachment(string $body, bool $no_link_desc = false): string
192         {
193                 return preg_replace_callback(
194                         "/\s*\[attachment (.*?)\](.*?)\[\/attachment\]\s*/ism",
195                         function ($match) use ($body, $no_link_desc) {
196                                 $attach_data = self::getAttachmentData($match[0]);
197                                 if (empty($attach_data['url'])) {
198                                         return $match[0];
199                                 } elseif (strpos(str_replace($match[0], '', $body), $attach_data['url']) !== false) {
200                                         return '';
201                                 } elseif (empty($attach_data['title']) || $no_link_desc) {
202                                         return " \n[url]" . $attach_data['url'] . "[/url]\n";
203                                 } else {
204                                         return " \n[url=" . $attach_data['url'] . ']' . $attach_data['title'] . "[/url]\n";
205                                 }
206                         },
207                         $body
208                 );
209         }
210
211         /**
212          * Remove [attachment] BBCode
213          *
214          * @param string  $body
215          * @return string with removed attachment
216          */
217         public static function removeAttachment(string $body): string
218         {
219                 return trim(preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $body));
220         }
221
222         /**
223          * Converts a BBCode text into plaintext
224          *
225          * @param string $text
226          * @param bool $keep_urls Whether to keep URLs in the resulting plaintext
227          * @return string
228          */
229         public static function toPlaintext(string $text, bool $keep_urls = true): string
230         {
231                 DI::profiler()->startRecording('rendering');
232                 // Remove pictures in advance to avoid unneeded proxy calls
233                 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", ' ', $text);
234                 $text = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", ' $2 ', $text);
235                 $text = preg_replace("/\[img.*?\[\/img\]/ism", ' ', $text);
236
237                 // Remove attachment
238                 $text = self::replaceAttachment($text);
239
240                 $naked_text = HTML::toPlaintext(self::convert($text, false, self::EXTERNAL, true), 0, !$keep_urls);
241
242                 DI::profiler()->stopRecording();
243                 return $naked_text;
244         }
245
246         /**
247          * Converts text into a format that can be used for the channel search and the language detection.
248          *
249          * @param string $text
250          * @param integer $uri_id
251          * @return string
252          */
253         public static function toSearchText(string $text, int $uri_id): string
254         {
255                 // Removes attachments
256                 $text = self::removeAttachment($text);
257
258                 // Add images because of possible alt texts
259                 if (!empty($uri_id)) {
260                         $text = Post\Media::addAttachmentsToBody($uri_id, $text, [Post\Media::IMAGE]);
261                 }
262
263                 if (empty($text)) {
264                         return '';
265                 }
266
267                 // Remove links without a link description
268                 $text = preg_replace("~\[url\=.*\]https?:.*\[\/url\]~", ' ', $text);
269
270                 // Remove pictures
271                 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", ' ', $text);
272
273                 // Replace picture with the alt description
274                 $text = preg_replace("/\[img\=.*?\](.*?)\[\/img\]/ism", ' $1 ', $text);
275
276                 // Remove the other pictures
277                 $text = preg_replace("/\[img.*?\[\/img\]/ism", ' ', $text);
278
279                 // Removes mentions, remove links from hashtags
280                 $text = preg_replace('/[@!]\[url\=.*?\].*?\[\/url\]/ism', ' ', $text);
281                 $text = preg_replace('/[#]\[url\=.*?\](.*?)\[\/url\]/ism', ' #$1 ', $text);
282                 $text = preg_replace('/[@!#]?\[url.*?\[\/url\]/ism', ' ', $text);
283                 $text = preg_replace("/\[url=[^\[\]]*\](.*)\[\/url\]/Usi", ' $1 ', $text);
284
285                 // Convert it to plain text
286                 $text = self::toPlaintext($text, false);
287
288                 // Remove possibly remaining links
289                 $text = preg_replace(Strings::autoLinkRegEx(), '', $text);
290
291                 // Remove all unneeded white space
292                 do {
293                         $oldtext = $text;
294                         $text = str_replace(['  ', "\n", "\r", '"', '_'], ' ', $text);
295                 } while ($oldtext != $text);
296
297                 return trim($text);
298         }
299
300         private static function proxyUrl(string $image, int $simplehtml = self::INTERNAL, int $uriid = 0, string $size = ''): string
301         {
302                 // Only send proxied pictures to API and for internal display
303                 if (!in_array($simplehtml, [self::INTERNAL, self::MASTODON_API, self::TWITTER_API])) {
304                         return $image;
305                 } elseif ($uriid > 0) {
306                         return Post\Link::getByLink($uriid, $image, $size);
307                 } else {
308                         return Proxy::proxifyUrl($image, $size);
309                 }
310         }
311
312         /**
313          * Truncates imported message body string length to max_import_size
314          *
315          * The purpose of this function is to apply system message length limits to
316          * imported messages without including any embedded photos in the length
317          *
318          * @param string $body
319          * @return string
320          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
321          */
322         public static function limitBodySize(string $body): string
323         {
324                 DI::profiler()->startRecording('rendering');
325                 $maxlen = DI::config()->get('config', 'max_import_size', 0);
326
327                 // If the length of the body, including the embedded images, is smaller
328                 // than the maximum, then don't waste time looking for the images
329                 if ($maxlen && (strlen($body) > $maxlen)) {
330
331                         Logger::info('the total body length exceeds the limit', ['maxlen' => $maxlen, 'body_len' => strlen($body)]);
332
333                         $orig_body = $body;
334                         $new_body = '';
335                         $textlen = 0;
336
337                         $img_start = strpos($orig_body, '[img');
338                         $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
339                         $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
340                         while (($img_st_close !== false) && ($img_end !== false)) {
341
342                                 $img_st_close++; // make it point to AFTER the closing bracket
343                                 $img_end += $img_start;
344                                 $img_end += strlen('[/img]');
345
346                                 if (!strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
347                                         // This is an embedded image
348
349                                         if (($textlen + $img_start) > $maxlen) {
350                                                 if ($textlen < $maxlen) {
351                                                         Logger::debug('the limit happens before an embedded image');
352                                                         $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
353                                                         $textlen = $maxlen;
354                                                 }
355                                         } else {
356                                                 $new_body = $new_body . substr($orig_body, 0, $img_start);
357                                                 $textlen += $img_start;
358                                         }
359
360                                         $new_body = $new_body . substr($orig_body, $img_start, $img_end - $img_start);
361                                 } else {
362
363                                         if (($textlen + $img_end) > $maxlen) {
364                                                 if ($textlen < $maxlen) {
365                                                         Logger::debug('the limit happens before the end of a non-embedded image');
366                                                         $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
367                                                         $textlen = $maxlen;
368                                                 }
369                                         } else {
370                                                 $new_body = $new_body . substr($orig_body, 0, $img_end);
371                                                 $textlen += $img_end;
372                                         }
373                                 }
374                                 $orig_body = substr($orig_body, $img_end);
375
376                                 if ($orig_body === false) {
377                                         // in case the body ends on a closing image tag
378                                         $orig_body = '';
379                                 }
380
381                                 $img_start = strpos($orig_body, '[img');
382                                 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
383                                 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
384                         }
385
386                         if (($textlen + strlen($orig_body)) > $maxlen) {
387                                 if ($textlen < $maxlen) {
388                                         Logger::debug('the limit happens after the end of the last image');
389                                         $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
390                                 }
391                         } else {
392                                 Logger::debug('the text size with embedded images extracted did not violate the limit');
393                                 $new_body = $new_body . $orig_body;
394                         }
395
396                         DI::profiler()->stopRecording();
397                         return $new_body;
398                 } else {
399                         DI::profiler()->stopRecording();
400                         return $body;
401                 }
402         }
403
404         /**
405          * Processes [attachment] tags
406          *
407          * Note: Can produce a [bookmark] tag in the returned string
408          *
409          * @param string  $text
410          * @param integer $simplehtml
411          * @param bool    $tryoembed
412          * @param array   $data
413          * @param int     $uriid
414          * @return string
415          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
416          */
417         public static function convertAttachment(string $text, int $simplehtml = self::INTERNAL, bool $tryoembed = true, array $data = [], int $uriid = 0, int $preview_mode = self::PREVIEW_LARGE): string
418         {
419                 DI::profiler()->startRecording('rendering');
420                 $data = $data ?: self::getAttachmentData($text);
421                 if (empty($data) || empty($data['url'])) {
422                         DI::profiler()->stopRecording();
423                         return $text;
424                 }
425
426                 if (isset($data['title'])) {
427                         $data['title'] = strip_tags($data['title']);
428                         $data['title'] = str_replace(['http://', 'https://'], '', $data['title']);
429                 } else {
430                         $data['title'] = '';
431                 }
432
433                 if (((strpos($data['text'], '[img=') !== false) || (strpos($data['text'], '[img]') !== false) || DI::config()->get('system', 'always_show_preview')) && !empty($data['image'])) {
434                         $data['preview'] = $data['image'];
435                         $data['image'] = '';
436                 }
437
438                 $return = '';
439                 try {
440                         if ($tryoembed && OEmbed::isAllowedURL($data['url'])) {
441                                 $return = OEmbed::getHTML($data['url'], $data['title']);
442                         } else {
443                                 throw new Exception('OEmbed is disabled for this attachment.');
444                         }
445                 } catch (Exception $e) {
446                         $data['title'] = ($data['title'] ?? '') ?: $data['url'];
447
448                         if ($simplehtml != self::CONNECTORS) {
449                                 $return = sprintf('<div class="type-%s">', $data['type']);
450                         }
451
452                         if ($preview_mode == self::PREVIEW_NO_IMAGE) {
453                                 unset($data['image']);
454                                 unset($data['preview']);
455                         }
456
457                         if (!empty($data['title']) && !empty($data['url'])) {
458                                 $preview_class = $preview_mode == self::PREVIEW_LARGE ? 'attachment-image' : 'attachment-preview';
459                                 if (!empty($data['image']) && empty($data['text']) && ($data['type'] == 'photo')) {
460                                         $return .= sprintf('<a href="%s" target="_blank" rel="noopener noreferrer"><img src="%s" alt="" title="%s" class="' . $preview_class . '" /></a>', $data['url'], self::proxyUrl($data['image'], $simplehtml, $uriid), $data['title']);
461                                 } else {
462                                         if (!empty($data['image'])) {
463                                                 $return .= sprintf('<a href="%s" target="_blank" rel="noopener noreferrer"><img src="%s" alt="" title="%s" class="' . $preview_class . '" /></a><br>', $data['url'], self::proxyUrl($data['image'], $simplehtml, $uriid), $data['title']);
464                                         } elseif (!empty($data['preview'])) {
465                                                 $return .= sprintf('<a href="%s" target="_blank" rel="noopener noreferrer"><img src="%s" alt="" title="%s" class="attachment-preview" /></a><br>', $data['url'], self::proxyUrl($data['preview'], $simplehtml, $uriid), $data['title']);
466                                         }
467                                         $return .= sprintf('<h4><a href="%s" target="_blank" rel="noopener noreferrer">%s</a></h4>', $data['url'], $data['title']);
468                                 }
469                         }
470
471                         if (!empty($data['description']) && $data['description'] != $data['title']) {
472                                 // Sanitize the HTML
473                                 $return .= sprintf('<blockquote>%s</blockquote>', trim(HTML::purify($data['description'])));
474                         }
475
476                         if (!empty($data['provider_url']) && !empty($data['provider_name'])) {
477                                 if (!empty($data['author_name'])) {
478                                         $return .= sprintf('<sup><a href="%s" target="_blank" rel="noopener noreferrer">%s (%s)</a></sup>', $data['provider_url'], $data['author_name'], $data['provider_name']);
479                                 } else {
480                                         $return .= sprintf('<sup><a href="%s" target="_blank" rel="noopener noreferrer">%s</a></sup>', $data['provider_url'], $data['provider_name']);
481                                 }
482                         }
483
484                         if ($simplehtml != self::CONNECTORS) {
485                                 $return .= '</div>';
486                         }
487                 }
488
489                 DI::profiler()->stopRecording();
490                 return trim(($data['text'] ?? '') . ' ' . $return . ' ' . ($data['after'] ?? ''));
491         }
492
493         public static function removeShareInformation(string $text, bool $plaintext = false, bool $nolink = false): string
494         {
495                 DI::profiler()->startRecording('rendering');
496                 $data = self::getAttachmentData($text);
497
498                 if (!$data) {
499                         DI::profiler()->stopRecording();
500                         return $text;
501                 } elseif ($nolink) {
502                         DI::profiler()->stopRecording();
503                         return $data['text'] . ($data['after'] ?? '');
504                 }
505
506                 $title = htmlentities($data['title'] ?? '', ENT_QUOTES, 'UTF-8', false);
507                 $text = htmlentities($data['text'], ENT_QUOTES, 'UTF-8', false);
508                 if ($plaintext || (($title != '') && strstr($text, $title))) {
509                         $data['title'] = $data['url'];
510                 } elseif (($text != '') && strstr($title, $text)) {
511                         $data['text'] = $data['title'];
512                         $data['title'] = $data['url'];
513                 }
514
515                 if (empty($data['text']) && !empty($data['title']) && empty($data['url'])) {
516                         DI::profiler()->stopRecording();
517                         return $data['title'] . $data['after'];
518                 }
519
520                 // If the link already is included in the post, don't add it again
521                 if (!empty($data['url']) && strpos($data['text'], $data['url'])) {
522                         DI::profiler()->stopRecording();
523                         return $data['text'] . $data['after'];
524                 }
525
526                 $text = $data['text'];
527
528                 if (!empty($data['url']) && !empty($data['title'])) {
529                         $text .= "\n[url=" . $data['url'] . ']' . $data['title'] . '[/url]';
530                 } elseif (!empty($data['url'])) {
531                         $text .= "\n[url]" . $data['url'] . '[/url]';
532                 }
533
534                 DI::profiler()->stopRecording();
535                 return $text . "\n" . $data['after'];
536         }
537
538         /**
539          * Converts [url] BBCodes in a format that looks fine on Mastodon. (callback function)
540          *
541          * @param array $match Array with the matching values
542          * @return string reformatted link including HTML codes
543          */
544         private static function convertUrlForActivityPubCallback(array $match): string
545         {
546                 $url = $match[1];
547
548                 if (isset($match[2]) && ($match[1] != $match[2])) {
549                         return $match[0];
550                 }
551
552                 $parts = parse_url($url);
553                 if (!isset($parts['scheme'])) {
554                         return $match[0];
555                 }
556
557                 return self::convertUrlForActivityPub($url);
558         }
559
560         /**
561          * Converts [url] BBCodes in a format that looks fine on ActivityPub systems.
562          *
563          * @param string $url URL that is about to be reformatted
564          * @return string reformatted link including HTML codes
565          */
566         private static function convertUrlForActivityPub(string $url): string
567         {
568                 return sprintf('<a href="%s" target="_blank" rel="noopener noreferrer">%s</a>', $url, Strings::getStyledURL($url));
569         }
570
571         /*
572          * [noparse][i]italic[/i][/noparse] turns into
573          * [noparse][ i ]italic[ /i ][/noparse],
574          * to hide them from parser.
575          *
576          * @param array $match
577          * @return string
578          */
579         private static function escapeNoparseCallback(array $match): string
580         {
581                 $whole_match = $match[0];
582                 $captured = $match[1];
583                 $spacefied = preg_replace("/\[(.*?)\]/", "[ $1 ]", $captured);
584                 $new_str = str_replace($captured, $spacefied, $whole_match);
585                 return $new_str;
586         }
587
588         /*
589          * The previously spacefied [noparse][ i ]italic[ /i ][/noparse],
590          * now turns back and the [noparse] tags are trimmed
591          * returning [i]italic[/i]
592          *
593          * @param array $match
594          * @return string
595          */
596         private static function unescapeNoparseCallback(array $match): string
597         {
598                 $captured = $match[1];
599                 $unspacefied = preg_replace("/\[ (.*?)\ ]/", "[$1]", $captured);
600                 return $unspacefied;
601         }
602
603         /**
604          * Returns the bracket character positions of a set of opening and closing BBCode tags, optionally skipping first
605          * occurrences
606          *
607          * @param string $text        Text to search
608          * @param string $name        Tag name
609          * @param int    $occurrences Number of first occurrences to skip
610          * @return boolean|array
611          */
612         public static function getTagPosition(string $text, string $name, int $occurrences = 0)
613         {
614                 DI::profiler()->startRecording('rendering');
615                 if ($occurrences < 0) {
616                         $occurrences = 0;
617                 }
618
619                 $start_open = -1;
620                 for ($i = 0; $i <= $occurrences; $i++) {
621                         if ($start_open !== false) {
622                                 $start_open = strpos($text, '[' . $name, $start_open + 1); // allow [name= type tags
623                         }
624                 }
625
626                 if ($start_open === false) {
627                         DI::profiler()->stopRecording();
628                         return false;
629                 }
630
631                 $start_equal = strpos($text, '=', $start_open);
632                 $start_close = strpos($text, ']', $start_open);
633
634                 if ($start_close === false) {
635                         DI::profiler()->stopRecording();
636                         return false;
637                 }
638
639                 $start_close++;
640
641                 $end_open = strpos($text, '[/' . $name . ']', $start_close);
642
643                 if ($end_open === false) {
644                         DI::profiler()->stopRecording();
645                         return false;
646                 }
647
648                 $res = [
649                         'start' => [
650                                 'open' => $start_open,
651                                 'close' => $start_close
652                         ],
653                         'end' => [
654                                 'open' => $end_open,
655                                 'close' => $end_open + strlen('[/' . $name . ']')
656                         ],
657                 ];
658
659                 if ($start_equal !== false) {
660                         $res['start']['equal'] = $start_equal + 1;
661                 }
662
663                 DI::profiler()->stopRecording();
664                 return $res;
665         }
666
667         /**
668          * Performs a preg_replace within the boundaries of all named BBCode tags in a text
669          *
670          * @param string $pattern Preg pattern string
671          * @param string $replace Preg replace string
672          * @param string $name    BBCode tag name
673          * @param string $text    Text to search
674          * @return string
675          */
676         public static function pregReplaceInTag(string $pattern, string $replace, string $name, string $text): string
677         {
678                 DI::profiler()->startRecording('rendering');
679                 $occurrences = 0;
680                 $pos = self::getTagPosition($text, $name, $occurrences);
681                 while ($pos !== false && $occurrences++ < 1000) {
682                         $start = substr($text, 0, $pos['start']['open']);
683                         $subject = substr($text, $pos['start']['open'], $pos['end']['close'] - $pos['start']['open']);
684                         $end = substr($text, $pos['end']['close']);
685                         if ($end === false) {
686                                 $end = '';
687                         }
688
689                         $subject = preg_replace($pattern, $replace, $subject);
690                         $text = $start . $subject . $end;
691
692                         $pos = self::getTagPosition($text, $name, $occurrences);
693                 }
694
695                 DI::profiler()->stopRecording();
696                 return $text;
697         }
698
699         private static function extractImagesFromItemBody(string $body): array
700         {
701                 $saved_image = [];
702                 $orig_body = $body;
703                 $new_body = '';
704
705                 $cnt = 0;
706                 $img_start = strpos($orig_body, '[img');
707                 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
708                 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
709                 while (($img_st_close !== false) && ($img_end !== false)) {
710                         $img_st_close++; // make it point to AFTER the closing bracket
711                         $img_end += $img_start;
712
713                         if (!strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
714                                 // This is an embedded image
715                                 $saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close));
716                                 $new_body = $new_body . substr($orig_body, 0, $img_start) . '[$#saved_image' . $cnt . '#$]';
717
718                                 $cnt++;
719                         } else {
720                                 $new_body = $new_body . substr($orig_body, 0, $img_end + strlen('[/img]'));
721                         }
722
723                         $orig_body = substr($orig_body, $img_end + strlen('[/img]'));
724
725                         if ($orig_body === false) {
726                                 // in case the body ends on a closing image tag
727                                 $orig_body = '';
728                         }
729
730                         $img_start = strpos($orig_body, '[img');
731                         $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
732                         $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
733                 }
734
735                 $new_body = $new_body . $orig_body;
736
737                 return ['body' => $new_body, 'images' => $saved_image];
738         }
739
740         private static function interpolateSavedImagesIntoItemBody(int $uriid, string $body, array $images): string
741         {
742                 $newbody = $body;
743
744                 $cnt = 0;
745                 foreach ($images as $image) {
746                         // We're depending on the property of 'foreach' (specified on the PHP website) that
747                         // it loops over the array starting from the first element and going sequentially
748                         // to the last element
749                         $newbody = str_replace(
750                                 '[$#saved_image' . $cnt . '#$]',
751                                 '<img src="' . self::proxyUrl($image, self::INTERNAL, $uriid) . '" alt="' . DI::l10n()->t('Image/photo') . '" />',
752                                 $newbody
753                         );
754                         $cnt++;
755                 }
756
757                 return $newbody;
758         }
759
760         /**
761          * @param string $text A BBCode string
762          * @return array Empty array if no share tag is present or the following array, missing attributes end up empty strings:
763          *               - comment   : Text before the opening share tag
764          *               - shared    : Text inside the share tags
765          *               - author    : (Optional) Display name of the shared author
766          *               - profile   : (Optional) Profile page URL of the shared author
767          *               - avatar    : (Optional) Profile picture URL of the shared author
768          *               - link      : (Optional) Canonical URL of the shared post
769          *               - posted    : (Optional) Date the shared post was initially posted ("Y-m-d H:i:s" in GMT)
770          *               - message_id: (Optional) Shared post URI if any
771          *               - guid      : (Optional) Shared post GUID if any
772          */
773         public static function fetchShareAttributes(string $text): array
774         {
775                 DI::profiler()->startRecording('rendering');
776                 if (preg_match('~(.*?)\[share](.*)\[/share]~ism', $text, $matches)) {
777                         DI::profiler()->stopRecording();
778                         return [
779                                 'author'     => '',
780                                 'profile'    => '',
781                                 'avatar'     => '',
782                                 'link'       => '',
783                                 'posted'     => '',
784                                 'guid'       => '',
785                                 'message_id' => trim($matches[2]),
786                                 'comment'    => trim($matches[1]),
787                                 'shared'     => '',
788                         ];
789                 }
790                 // See Issue https://github.com/friendica/friendica/issues/10454
791                 // Hashtags in usernames are expanded to links. This here is a quick fix.
792                 $text = preg_replace('~([@!#])\[url=.*?](.*?)\[/url]~ism', '$1$2', $text);
793
794                 if (!preg_match('~(.*?)\[share(.*?)](.*)\[/share]~ism', $text, $matches)) {
795                         DI::profiler()->stopRecording();
796                         return [];
797                 }
798
799                 $attributes = self::extractShareAttributes($matches[2]);
800
801                 $attributes['comment'] = trim($matches[1]);
802                 $attributes['shared'] = trim($matches[3]);
803
804                 DI::profiler()->stopRecording();
805                 return $attributes;
806         }
807
808         /**
809          * @see BBCode::fetchShareAttributes()
810          * @param string $shareString Internal opening share tag string matched by the regular expression
811          * @return array A fixed attribute array where missing attribute are represented by empty strings
812          */
813         private static function extractShareAttributes(string $shareString): array
814         {
815                 $attributes = [];
816                 foreach (['author', 'profile', 'avatar', 'link', 'posted', 'guid', 'message_id'] as $field) {
817                         preg_match("/$field=(['\"])(.+?)\\1/ism", $shareString, $matches);
818                         $attributes[$field] = html_entity_decode($matches[2] ?? '', ENT_QUOTES, 'UTF-8');
819                 }
820
821                 return $attributes;
822         }
823
824         /**
825          * Remove the share block
826          *
827          * @param string $body
828          * @return string
829          */
830         public static function removeSharedData(string $body): string
831         {
832                 return trim(preg_replace("/\s*\[share.*?\].*?\[\/share\]\s*/ism", '', $body));
833         }
834
835         /**
836          * This function converts a [share] block to text according to a provided callback function whose signature is:
837          *
838          * function(array $attributes, array $author_contact, string $content, boolean $is_quote_share): string
839          *
840          * Where:
841          * - $attributes is an array of attributes of the [share] block itself. Missing keys will be completed by the contact
842          * data lookup
843          * - $author_contact is a contact record array
844          * - $content is the inner content of the [share] block
845          * - $is_quote_share indicates whether there's any content before the [share] block
846          * - Return value is the string that should replace the [share] block in the provided text
847          *
848          * This function is intended to be used by addon connector to format a share block like the target network is expecting it.
849          *
850          * @param  string   $text     A BBCode string
851          * @param  callable $callback
852          * @return string The BBCode string with all [share] blocks replaced
853          */
854         public static function convertShare(string $text, callable $callback, int $uriid = 0): string
855         {
856                 DI::profiler()->startRecording('rendering');
857                 $return = preg_replace_callback(
858                         '~(.*?)\[share(.*?)](.*)\[/share]~ism',
859                         function ($match) use ($callback, $uriid) {
860                                 $attributes = self::extractShareAttributes($match[2]);
861
862                                 $author_contact = Contact::getByURL($attributes['profile'], false, ['id', 'url', 'addr', 'name', 'micro']);
863                                 $author_contact['url'] = ($author_contact['url'] ?? $attributes['profile']);
864                                 $author_contact['addr'] = ($author_contact['addr'] ?? '');
865
866                                 $attributes['author']   = ($author_contact['name']  ?? '') ?: $attributes['author'];
867                                 $attributes['avatar']   = ($author_contact['micro'] ?? '') ?: $attributes['avatar'];
868                                 $attributes['profile']  = ($author_contact['url']   ?? '') ?: $attributes['profile'];
869
870                                 if (!empty($author_contact['id'])) {
871                                         $attributes['avatar'] = Contact::getAvatarUrlForId($author_contact['id'], Proxy::SIZE_THUMB);
872                                 } elseif ($attributes['avatar']) {
873                                         $attributes['avatar'] = self::proxyUrl($attributes['avatar'], self::INTERNAL, $uriid, Proxy::SIZE_THUMB);
874                                 }
875
876                                 $content = preg_replace(Strings::autoLinkRegEx(), '<a href="$1">$1</a>', $match[3]);
877
878                                 return $match[1] . $callback($attributes, $author_contact, $content, trim($match[1]) != '');
879                         },
880                         $text
881                 );
882
883                 DI::profiler()->stopRecording();
884                 return trim($return);
885         }
886
887         /**
888          * Convert complex IMG and ZMG elements
889          *
890          * @param [type] $text
891          * @param integer $simplehtml
892          * @param integer $uriid
893          * @return string
894          */
895         private static function convertImages(string $text, int $simplehtml, int $uriid = 0): string
896         {
897                 DI::profiler()->startRecording('rendering');
898                 $return = preg_replace_callback(
899                         "/\[[zi]mg(.*?)\]([^\[\]]*)\[\/[zi]mg\]/ism",
900                         function ($match) use ($simplehtml, $uriid) {
901                                 $attribute_string = $match[1];
902                                 $attributes = [];
903                                 foreach (['alt', 'width', 'height'] as $field) {
904                                         preg_match("/$field=(['\"])(.+?)\\1/ism", $attribute_string, $matches);
905                                         $attributes[$field] = html_entity_decode($matches[2] ?? '', ENT_QUOTES, 'UTF-8');
906                                 }
907
908                                 $img_str = '<img src="' . self::proxyUrl($match[2], $simplehtml, $uriid) . '"';
909                                 foreach ($attributes as $key => $value) {
910                                         if (!empty($value)) {
911                                                 $img_str .= ' ' . $key . '="' . htmlspecialchars($value, ENT_COMPAT) . '"';
912                                         }
913                                 }
914                                 return $img_str . '>';
915                         },
916                         $text
917                 );
918
919                 DI::profiler()->stopRecording();
920                 return $return;
921         }
922
923         /**
924          * Default [share] tag conversion callback
925          *
926          * Note: Can produce a [bookmark] tag in the output
927          *
928          * @see BBCode::convertShare()
929          * @param array   $attributes     [share] block attribute values
930          * @param array   $author_contact Contact row of the shared author
931          * @param string  $content        Inner content of the [share] block
932          * @param boolean $is_quote_share Whether there is content before the [share] block
933          * @param integer $simplehtml     Mysterious integer value depending on the target network/formatting style
934          * @return string
935          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
936          */
937         private static function convertShareCallback(array $attributes, array $author_contact, string $content, bool $is_quote_share, int $simplehtml): string
938         {
939                 DI::profiler()->startRecording('rendering');
940                 $mention = $attributes['author'] . ' (' . ($author_contact['addr'] ?? '') . ')';
941
942                 switch ($simplehtml) {
943                         case self::MASTODON_API:
944                         case self::TWITTER_API:
945                                 $text = ($is_quote_share ? '<br>' : '') .
946                                         '<b><a href="' . $attributes['link'] . '">' . html_entity_decode('&#x2672;', ENT_QUOTES, 'UTF-8') . ' ' . $author_contact['addr'] . "</a>:</b><br>\n" .
947                                         '<blockquote class="shared_content" dir="auto">' . $content . '</blockquote>';
948                                 break;
949                         case self::DIASPORA:
950                                 if (stripos(Strings::normaliseLink($attributes['link']), 'http://twitter.com/') === 0) {
951                                         $text = ($is_quote_share ? '<hr />' : '') . '<p><a href="' . $attributes['link'] . '">' . $attributes['link'] . '</a></p>' . "\n";
952                                 } else {
953                                         $headline = '<p><b>♲ <a href="' . $attributes['profile'] . '">' . $attributes['author'] . '</a>:</b></p>' . "\n";
954
955                                         if (!empty($attributes['posted']) && !empty($attributes['link'])) {
956                                                 $headline = '<p><b>♲ <a href="' . $attributes['profile'] . '">' . $attributes['author'] . '</a></b> - <a href="' . $attributes['link'] . '">' . $attributes['posted'] . ' GMT</a></p>' . "\n";
957                                         }
958
959                                         $text = ($is_quote_share ? '<hr />' : '') . $headline . '<blockquote>' . trim($content) . '</blockquote>' . "\n";
960
961                                         if (empty($attributes['posted']) && !empty($attributes['link'])) {
962                                                 $text .= '<p><a href="' . $attributes['link'] . '">[Source]</a></p>' . "\n";
963                                         }
964                                 }
965
966                                 break;
967                         case self::CONNECTORS:
968                                 $headline = '<p><b>' . html_entity_decode('&#x2672; ', ENT_QUOTES, 'UTF-8');
969                                 $headline .= DI::l10n()->t('<a href="%1$s" target="_blank" rel="noopener noreferrer">%2$s</a> %3$s', $attributes['link'], $mention, $attributes['posted']);
970                                 $headline .= ':</b></p>' . "\n";
971
972                                 $text = ($is_quote_share ? '<hr />' : '') . $headline . '<blockquote class="shared_content" dir="auto">' . trim($content) . '</blockquote>' . "\n";
973
974                                 break;
975                         case self::OSTATUS:
976                                 $text = ($is_quote_share ? '<br>' : '') . '<p>' . html_entity_decode('&#x2672; ', ENT_QUOTES, 'UTF-8') . ' @' . $author_contact['addr'] . ': ' . $content . '</p>' . "\n";
977                                 break;
978                         case self::ACTIVITYPUB:
979                                 $author = '@<span class="vcard"><a href="' . $author_contact['url'] . '" class="url u-url mention" title="' . $author_contact['addr'] . '"><span class="fn nickname mention">' . $author_contact['addr'] . '</span></a>:</span>';
980                                 $text = '<div><a href="' . $attributes['link'] . '">' . html_entity_decode('&#x2672;', ENT_QUOTES, 'UTF-8') . '</a> ' . $author . '<blockquote>' . $content . '</blockquote></div>' . "\n";
981                                 break;
982                         default:
983                                 $text = ($is_quote_share ? "\n" : '');
984
985                                 $contact = Contact::getByURL($attributes['profile'], false, ['network']);
986                                 $network = $contact['network'] ?? Protocol::PHANTOM;
987
988                                 $tpl = Renderer::getMarkupTemplate('shared_content.tpl');
989                                 $text .= self::SHARED_ANCHOR . Renderer::replaceMacros($tpl, [
990                                         '$profile'      => $attributes['profile'],
991                                         '$avatar'       => $attributes['avatar'],
992                                         '$author'       => $attributes['author'],
993                                         '$link'         => $attributes['link'],
994                                         '$link_title'   => DI::l10n()->t('Link to source'),
995                                         '$posted'       => $attributes['posted'],
996                                         '$guid'         => $attributes['guid'],
997                                         '$network_name' => ContactSelector::networkToName($network, $attributes['profile']),
998                                         '$network_icon' => ContactSelector::networkToIcon($network, $attributes['profile']),
999                                         '$content'      => self::TOP_ANCHOR . self::setMentions(trim($content), 0, $network) . self::BOTTOM_ANCHOR,
1000                                 ]);
1001                                 break;
1002                 }
1003
1004                 return $text;
1005         }
1006
1007         private static function removePictureLinksCallback(array $match): string
1008         {
1009                 $cache_key = 'remove:' . $match[1];
1010                 $text = DI::cache()->get($cache_key);
1011
1012                 if (is_null($text)) {
1013                         $curlResult = DI::httpClient()->head($match[1], [HttpClientOptions::TIMEOUT => DI::config()->get('system', 'xrd_timeout')]);
1014                         if ($curlResult->isSuccess()) {
1015                                 $mimetype = $curlResult->getHeader('Content-Type')[0] ?? '';
1016                         } else {
1017                                 $mimetype = '';
1018                         }
1019
1020                         if (substr($mimetype, 0, 6) == 'image/') {
1021                                 $text = '[url=' . $match[1] . ']' . $match[1] . '[/url]';
1022                         } else {
1023                                 $text = '[url=' . $match[2] . ']' . $match[2] . '[/url]';
1024
1025                                 // if its not a picture then look if its a page that contains a picture link
1026                                 $body = DI::httpClient()->fetch($match[1], HttpClientAccept::HTML, 0);
1027                                 if (empty($body)) {
1028                                         DI::cache()->set($cache_key, $text);
1029                                         return $text;
1030                                 }
1031
1032                                 $doc = new DOMDocument();
1033                                 @$doc->loadHTML($body);
1034                                 $xpath = new DOMXPath($doc);
1035                                 $list = $xpath->query('//meta[@name]');
1036                                 foreach ($list as $node) {
1037                                         $attr = [];
1038
1039                                         if ($node->attributes->length) {
1040                                                 foreach ($node->attributes as $attribute) {
1041                                                         $attr[$attribute->name] = $attribute->value;
1042                                                 }
1043                                         }
1044
1045                                         if (strtolower($attr['name']) == 'twitter:image') {
1046                                                 $text = '[url=' . $attr['content'] . ']' . $attr['content'] . '[/url]';
1047                                         }
1048                                 }
1049                         }
1050                         DI::cache()->set($cache_key, $text);
1051                 }
1052
1053                 return $text;
1054         }
1055
1056         /**
1057          * Callback: Expands links from given $match array
1058          *
1059          * @param array $match Array with link match
1060          * @return string BBCode
1061          */
1062         private static function expandLinksCallback(array $match): string
1063         {
1064                 if (($match[3] == '') || ($match[2] == $match[3]) || stristr($match[2], $match[3])) {
1065                         return ($match[1] . '[url]' . $match[2] . '[/url]');
1066                 } else {
1067                         return ($match[1] . $match[3] . ' [url]' . $match[2] . '[/url]');
1068                 }
1069         }
1070
1071         /**
1072          * Callback: Cleans picture links
1073          *
1074          * @param array $match Array with link match
1075          * @return string BBCode
1076          */
1077         private static function cleanPictureLinksCallback(array $match): string
1078         {
1079                 // When the picture link is the own photo path then we can avoid fetching the link
1080                 $own_photo_url = preg_quote(Strings::normaliseLink(DI::baseUrl()) . '/photos/');
1081                 if (preg_match('|' . $own_photo_url . '.*?/image/|', Strings::normaliseLink($match[1]))) {
1082                         if (!empty($match[3])) {
1083                                 $text = '[img=' . str_replace('-1.', '-0.', $match[2]) . ']' . $match[3] . '[/img]';
1084                         } else {
1085                                 $text = '[img]' . str_replace('-1.', '-0.', $match[2]) . '[/img]';
1086                         }
1087                         return $text;
1088                 }
1089
1090                 $cache_key = 'clean:' . $match[1];
1091                 $text = DI::cache()->get($cache_key);
1092                 if (!is_null($text)) {
1093                         return $text;
1094                 }
1095
1096                 $curlResult = DI::httpClient()->head($match[1], [HttpClientOptions::TIMEOUT => DI::config()->get('system', 'xrd_timeout')]);
1097                 if ($curlResult->isSuccess()) {
1098                         $mimetype = $curlResult->getHeader('Content-Type')[0] ?? '';
1099                 } else {
1100                         $mimetype = '';
1101                 }
1102
1103                 // if its a link to a picture then embed this picture
1104                 if (substr($mimetype, 0, 6) == 'image/') {
1105                         $text = '[img]' . $match[1] . '[/img]';
1106                 } else {
1107                         if (!empty($match[3])) {
1108                                 $text = '[img=' . $match[2] . ']' . $match[3] . '[/img]';
1109                         } else {
1110                                 $text = '[img]' . $match[2] . '[/img]';
1111                         }
1112
1113                         // if its not a picture then look if its a page that contains a picture link
1114                         $body = DI::httpClient()->fetch($match[1], HttpClientAccept::HTML, 0);
1115                         if (empty($body)) {
1116                                 DI::cache()->set($cache_key, $text);
1117                                 return $text;
1118                         }
1119
1120                         $doc = new DOMDocument();
1121                         @$doc->loadHTML($body);
1122                         $xpath = new DOMXPath($doc);
1123                         $list = $xpath->query('//meta[@name]');
1124                         foreach ($list as $node) {
1125                                 $attr = [];
1126                                 if ($node->attributes->length) {
1127                                         foreach ($node->attributes as $attribute) {
1128                                                 $attr[$attribute->name] = $attribute->value;
1129                                         }
1130                                 }
1131
1132                                 if (strtolower($attr['name']) == "twitter:image") {
1133                                         if (!empty($match[3])) {
1134                                                 $text = "[img=" . $attr['content'] . "]" . $match[3] . "[/img]";
1135                                         } else {
1136                                                 $text = "[img]" . $attr['content'] . "[/img]";
1137                                         }
1138                                 }
1139                         }
1140                 }
1141                 DI::cache()->set($cache_key, $text);
1142
1143                 return $text;
1144         }
1145
1146         /**
1147          * Cleans picture links
1148          *
1149          * @param string $text HTML/BBCode string
1150          * @return string Cleaned HTML/BBCode
1151          */
1152         public static function cleanPictureLinks(string $text): string
1153         {
1154                 DI::profiler()->startRecording('rendering');
1155                 $return = preg_replace_callback("&\[url=([^\[\]]*)\]\[img=(.*)\](.*)\[\/img\]\[\/url\]&Usi", [self::class, 'cleanPictureLinksCallback'], $text);
1156                 $return = preg_replace_callback("&\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]&Usi", [self::class, 'cleanPictureLinksCallback'], $return);
1157                 DI::profiler()->stopRecording();
1158                 return $return;
1159         }
1160
1161         /**
1162          * Removes links
1163          *
1164          * @param string $text HTML/BBCode string
1165          * @return string Cleaned HTML/BBCode
1166          */
1167         public static function removeLinks(string $bbcode): string
1168         {
1169                 DI::profiler()->startRecording('rendering');
1170                 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", ' ', $bbcode);
1171                 $bbcode = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", ' $1 ', $bbcode);
1172                 $bbcode = preg_replace("/\[img.*?\[\/img\]/ism", ' ', $bbcode);
1173
1174                 $bbcode = preg_replace('/[@!#]\[url\=.*?\].*?\[\/url\]/ism', '', $bbcode);
1175                 $bbcode = preg_replace("/\[url=[^\[\]]*\](.*)\[\/url\]/Usi", ' $1 ', $bbcode);
1176                 $bbcode = preg_replace('/[@!#]?\[url.*?\[\/url\]/ism', '', $bbcode);
1177                 DI::profiler()->stopRecording();
1178                 return $bbcode;
1179         }
1180
1181         /**
1182          * Replace names in mentions with nicknames
1183          *
1184          * @param string $body HTML/BBCode
1185          * @return string Body with replaced mentions
1186          */
1187         public static function setMentionsToNicknames(string $body): string
1188         {
1189                 DI::profiler()->startRecording('rendering');
1190                 $regexp = "/([@!])\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1191                 $body = preg_replace_callback($regexp, [self::class, 'mentionCallback'], $body);
1192                 DI::profiler()->stopRecording();
1193                 return $body;
1194         }
1195
1196         /**
1197          * Callback function to replace a Friendica style mention in a mention with the nickname
1198          *
1199          * @param array $match Matching values for the callback
1200          * @return string Replaced mention or empty string
1201          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1202          */
1203         private static function mentionCallback(array $match): string
1204         {
1205                 if (empty($match[2])) {
1206                         return '';
1207                 }
1208
1209                 $data = Contact::getByURL($match[2], false, ['url', 'nick']);
1210                 if (empty($data['nick'])) {
1211                         return $match[0];
1212                 }
1213
1214                 return $match[1] . '[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
1215         }
1216
1217         /**
1218          * Normalize links to Youtube and Vimeo to a unified format.
1219          *
1220          * @param string $text
1221          * @return string
1222          */
1223         private static function normalizeVideoLinks(string $text): string
1224         {
1225                 $text = preg_replace("/\[youtube\]https?:\/\/www.youtube.com\/watch\?v\=(.*?)\[\/youtube\]/ism", '[youtube]$1[/youtube]', $text);
1226                 $text = preg_replace("/\[youtube\]https?:\/\/www.youtube.com\/embed\/(.*?)\[\/youtube\]/ism", '[youtube]$1[/youtube]', $text);
1227                 $text = preg_replace("/\[youtube\]https?:\/\/www.youtube.com\/shorts\/(.*?)\[\/youtube\]/ism", '[youtube]$1[/youtube]', $text);
1228                 $text = preg_replace("/\[youtube\]https?:\/\/youtu.be\/(.*?)\[\/youtube\]/ism", '[youtube]$1[/youtube]', $text);
1229
1230                 $text = preg_replace("/\[vimeo\]https?:\/\/player.vimeo.com\/video\/([0-9]+)(.*?)\[\/vimeo\]/ism", '[vimeo]$1[/vimeo]', $text);
1231                 $text = preg_replace("/\[vimeo\]https?:\/\/vimeo.com\/([0-9]+)(.*?)\[\/vimeo\]/ism", '[vimeo]$1[/vimeo]', $text);
1232
1233                 return $text;
1234         }
1235
1236         /**
1237          * Expand Youtube and Vimeo links to
1238          *
1239          * @param string $text
1240          * @return string
1241          */
1242         public static function expandVideoLinks(string $text): string
1243         {
1244                 $text = self::normalizeVideoLinks($text);
1245                 $text = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism", '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $text);
1246                 $text = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism", '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $text);
1247
1248                 return $text;
1249         }
1250
1251         /**
1252          * Converts a BBCode message for a given URI-ID to a HTML message
1253          *
1254          * BBcode 2 HTML was written by WAY2WEB.net
1255          * extended to work with Mistpark/Friendica - Mike Macgirvin
1256          *
1257          * Simple HTML values meaning:
1258          * - 0: Friendica display
1259          * - 1: Unused
1260          * - 2: Used for Windows Phone push, Friendica API
1261          * - 3: Used before converting to Markdown in bb2diaspora.php
1262          * - 4: Used for WordPress, Libertree (before Markdown), pump.io and tumblr
1263          * - 5: Unused
1264          * - 6: Unused
1265          * - 7: Used for dfrn, OStatus
1266          * - 8: Used for Twitter, WP backlink text setting
1267          * - 9: ActivityPub
1268          *
1269          * @param int    $uriid
1270          * @param string $text
1271          * @param int    $simple_html
1272          * @return string
1273          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1274          */
1275         public static function convertForUriId(int $uriid = null, string $text = null, int $simple_html = self::INTERNAL): string
1276         {
1277                 $try_oembed = ($simple_html == self::INTERNAL);
1278
1279                 return self::convert($text ?? '', $try_oembed, $simple_html, false, $uriid ?? 0);
1280         }
1281
1282         /**
1283          * Converts a BBCode message to HTML message
1284          *
1285          * BBcode 2 HTML was written by WAY2WEB.net
1286          * extended to work with Mistpark/Friendica - Mike Macgirvin
1287          *
1288          * Simple HTML values meaning:
1289          * - 0: Friendica display
1290          * - 1: Unused
1291          * - 2: Used for Windows Phone push, Friendica API
1292          * - 3: Used before converting to Markdown in bb2diaspora.php
1293          * - 4: Used for WordPress, Libertree (before Markdown), pump.io and tumblr
1294          * - 5: Unused
1295          * - 6: Unused
1296          * - 7: Used for dfrn, OStatus
1297          * - 8: Used for Twitter, WP backlink text setting
1298          * - 9: ActivityPub
1299          *
1300          * @param string $text
1301          * @param bool   $try_oembed
1302          * @param int    $simple_html
1303          * @param bool   $for_plaintext
1304          * @param int    $uriid
1305          * @return string Converted code or empty string
1306          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1307          */
1308         public static function convert(string $text = null, bool $try_oembed = true, int $simple_html = self::INTERNAL, bool $for_plaintext = false, int $uriid = 0): string
1309         {
1310                 // Accounting for null default column values
1311                 if (is_null($text) || $text === '') {
1312                         return '';
1313                 }
1314
1315                 DI::profiler()->startRecording('rendering');
1316
1317                 Hook::callAll('bbcode', $text);
1318
1319                 $a = DI::app();
1320
1321                 $text = self::performWithEscapedTags($text, ['code'], function ($text) use ($try_oembed, $simple_html, $for_plaintext, $a, $uriid) {
1322                         $text = self::performWithEscapedTags($text, ['noparse', 'nobb', 'pre'], function ($text) use ($try_oembed, $simple_html, $for_plaintext, $a, $uriid) {
1323                                 /*
1324                                  * preg_match_callback function to replace potential Oembed tags with Oembed content
1325                                  *
1326                                  * $match[0] = [tag]$url[/tag] or [tag=$url]$title[/tag]
1327                                  * $match[1] = $url
1328                                  * $match[2] = $title or absent
1329                                  */
1330                                 $try_oembed_callback = function (array $match) {
1331                                         $url = $match[1];
1332                                         $title = $match[2] ?? '';
1333
1334                                         try {
1335                                                 $return = OEmbed::getHTML($url, $title);
1336                                         } catch (Exception $ex) {
1337                                                 $return = $match[0];
1338                                         }
1339
1340                                         return $return;
1341                                 };
1342
1343                                 // Remove the abstract element. It is a non visible element.
1344                                 $text = self::stripAbstract($text);
1345
1346                                 // Line ending normalisation
1347                                 $text = str_replace("\r\n", "\n", $text);
1348
1349                                 // Move new lines outside of tags
1350                                 $text = preg_replace("#\[(\w*)](\n*)#ism", '$2[$1]', $text);
1351                                 $text = preg_replace("#(\n*)\[/(\w*)]#ism", '[/$2]$1', $text);
1352
1353                                 // Extract the private images which use data urls since preg has issues with
1354                                 // large data sizes. Stash them away while we do bbcode conversion, and then put them back
1355                                 // in after we've done all the regex matching. We cannot use any preg functions to do this.
1356
1357                                 $extracted = self::extractImagesFromItemBody($text);
1358                                 $text = $extracted['body'];
1359                                 $saved_image = $extracted['images'];
1360
1361                                 // If we find any event code, turn it into an event.
1362                                 // After we're finished processing the bbcode we'll
1363                                 // replace all of the event code with a reformatted version.
1364
1365                                 $ev = Event::fromBBCode($text);
1366
1367                                 // Replace any html brackets with HTML Entities to prevent executing HTML or script
1368                                 // Don't use strip_tags here because it breaks [url] search by replacing & with amp
1369
1370                                 $text = str_replace("<", "&lt;", $text);
1371                                 $text = str_replace(">", "&gt;", $text);
1372
1373                                 // remove some newlines before the general conversion
1374                                 $text = preg_replace("/\s?\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "\n[share$1]$2[/share]\n", $text);
1375                                 $text = preg_replace("/\s?\[quote(.*?)\]\s?(.*?)\s?\[\/quote\]\s?/ism", "\n[quote$1]$2[/quote]\n", $text);
1376
1377                                 // when the content is meant exporting to other systems then remove the avatar picture since this doesn't really look good on these systems
1378                                 if (!$try_oembed) {
1379                                         $text = preg_replace("/\[share(.*?)avatar\s?=\s?'.*?'\s?(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "\n[share$1$2]$3[/share]", $text);
1380                                 }
1381
1382                                 // Remove linefeeds inside of the table elements. See issue #6799
1383                                 $search = [
1384                                         "\n[th]", "[th]\n", " [th]", "\n[/th]", "[/th]\n", "[/th] ",
1385                                         "\n[td]", "[td]\n", " [td]", "\n[/td]", "[/td]\n", "[/td] ",
1386                                         "\n[tr]", "[tr]\n", " [tr]", "[tr] ", "\n[/tr]", "[/tr]\n", " [/tr]", "[/tr] ",
1387                                         "\n[hr]", "[hr]\n", " [hr]", "[hr] ",
1388                                         "\n[attachment ", " [attachment ", "\n[/attachment]", "[/attachment]\n", " [/attachment]", "[/attachment] ",
1389                                         "[table]\n", "[table] ", " [table]", "\n[/table]", " [/table]", "[/table] ",
1390                                         " \n", "\t\n", "[/li]\n", "\n[li]", "\n[*]",
1391                                 ];
1392                                 $replace = [
1393                                         "[th]", "[th]", "[th]", "[/th]", "[/th]", "[/th]",
1394                                         "[td]", "[td]", "[td]", "[/td]", "[/td]", "[/td]",
1395                                         "[tr]", "[tr]", "[tr]", "[tr]", "[/tr]", "[/tr]", "[/tr]", "[/tr]",
1396                                         "[hr]", "[hr]", "[hr]", "[hr]",
1397                                         "[attachment ", "[attachment ", "[/attachment]", "[/attachment]", "[/attachment]", "[/attachment]",
1398                                         "[table]", "[table]", "[table]", "[/table]", "[/table]", "[/table]",
1399                                         "\n", "\n", "[/li]", "[li]", "[*]",
1400                                 ];
1401                                 do {
1402                                         $oldtext = $text;
1403                                         $text = str_replace($search, $replace, $text);
1404                                 } while ($oldtext != $text);
1405
1406                                 // Replace these here only once
1407                                 $search = ["\n[table]", "[/table]\n"];
1408                                 $replace = ["[table]", "[/table]"];
1409                                 $text = str_replace($search, $replace, $text);
1410
1411                                 // Trim new lines regardless of the system.remove_multiplicated_lines config value
1412                                 $text = trim($text, "\n");
1413
1414                                 // removing multiplicated newlines
1415                                 if (DI::config()->get('system', 'remove_multiplicated_lines')) {
1416                                         $search = [
1417                                                 "\n\n\n", "[/quote]\n\n", "\n[/quote]", "\n[ul]", "[/ul]\n", "\n[ol]", "[/ol]\n", "\n\n[share ", "[/attachment]\n",
1418                                                 "\n[h1]", "[/h1]\n", "\n[h2]", "[/h2]\n", "\n[h3]", "[/h3]\n", "\n[h4]", "[/h4]\n", "\n[h5]", "[/h5]\n", "\n[h6]", "[/h6]\n"
1419                                         ];
1420                                         $replace = [
1421                                                 "\n\n", "[/quote]\n", "[/quote]", "[ul]", "[/ul]", "[ol]", "[/ol]", "\n[share ", "[/attachment]",
1422                                                 "[h1]", "[/h1]", "[h2]", "[/h2]", "[h3]", "[/h3]", "[h4]", "[/h4]", "[h5]", "[/h5]", "[h6]", "[/h6]"
1423                                         ];
1424                                         do {
1425                                                 $oldtext = $text;
1426                                                 $text = str_replace($search, $replace, $text);
1427                                         } while ($oldtext != $text);
1428                                 }
1429
1430                                 /// @todo Have a closer look at the different html modes
1431                                 // Handle attached links or videos
1432                                 if ($simple_html == self::NPF) {
1433                                         $text = self::removeAttachment($text);
1434                                 } elseif (in_array($simple_html, [self::MASTODON_API, self::TWITTER_API, self::ACTIVITYPUB])) {
1435                                         $text = self::replaceAttachment($text);
1436                                 } elseif (!in_array($simple_html, [self::INTERNAL, self::EXTERNAL, self::CONNECTORS])) {
1437                                         $text = self::replaceAttachment($text, true);
1438                                 } else {
1439                                         $text = self::convertAttachment($text, $simple_html, $try_oembed, [], $uriid);
1440                                 }
1441
1442                                 $nosmile = strpos($text, '[nosmile]') !== false;
1443                                 $text = str_replace('[nosmile]', '', $text);
1444
1445                                 // Replace non graphical smilies for external posts
1446                                 if (!$nosmile) {
1447                                         $text = self::performWithEscapedTags($text, ['img'], function ($text) use ($simple_html, $for_plaintext) {
1448                                                 return Smilies::replace($text, ($simple_html != self::INTERNAL) || $for_plaintext);
1449                                         });
1450                                 }
1451
1452                                 // leave open the possibility of [map=something]
1453                                 // this is replaced in Item::prepareBody() which has knowledge of the item location
1454                                 if (strpos($text, '[/map]') !== false) {
1455                                         $text = preg_replace_callback(
1456                                                 "/\[map\](.*?)\[\/map\]/ism",
1457                                                 function ($match) use ($simple_html) {
1458                                                         return str_replace($match[0], '<p class="map">' . Map::byLocation($match[1], $simple_html) . '</p>', $match[0]);
1459                                                 },
1460                                                 $text
1461                                         );
1462                                 }
1463
1464                                 if (strpos($text, '[map=') !== false) {
1465                                         $text = preg_replace_callback(
1466                                                 "/\[map=(.*?)\]/ism",
1467                                                 function ($match) use ($simple_html) {
1468                                                         return str_replace($match[0], '<p class="map">' . Map::byCoordinates(str_replace('/', ' ', $match[1]), $simple_html) . '</p>', $match[0]);
1469                                                 },
1470                                                 $text
1471                                         );
1472                                 }
1473
1474                                 if (strpos($text, '[map]') !== false) {
1475                                         $text = preg_replace("/\[map\]/", '<p class="map"></p>', $text);
1476                                 }
1477
1478                                 // Check for headers
1479
1480                                 if ($simple_html == self::INTERNAL) {
1481                                         //Ensure to always start with <h4> if possible
1482                                         $heading_count = 0;
1483                                         for ($level = 6; $level > 0; $level--) {
1484                                                 if (preg_match("(\[h$level\].*?\[\/h$level\])ism", $text)) {
1485                                                         $heading_count++;
1486                                                 }
1487                                         }
1488                                         if ($heading_count > 0) {
1489                                                 $heading = min($heading_count + 3, 6);
1490                                                 for ($level = 6; $level > 0; $level--) {
1491                                                         if (preg_match("(\[h$level\].*?\[\/h$level\])ism", $text)) {
1492                                                                 $text = preg_replace("(\[h$level\](.*?)\[\/h$level\])ism", "</p><h$heading>$1</h$heading><p>", $text);
1493                                                                 $heading--;
1494                                                         }
1495                                                 }
1496                                         }
1497                                 } else {
1498                                         $text = preg_replace("(\[h1\](.*?)\[\/h1\])ism", '</p><h1>$1</h1><p>', $text);
1499                                         $text = preg_replace("(\[h2\](.*?)\[\/h2\])ism", '</p><h2>$1</h2><p>', $text);
1500                                         $text = preg_replace("(\[h3\](.*?)\[\/h3\])ism", '</p><h3>$1</h3><p>', $text);
1501                                         $text = preg_replace("(\[h4\](.*?)\[\/h4\])ism", '</p><h4>$1</h4><p>', $text);
1502                                         $text = preg_replace("(\[h5\](.*?)\[\/h5\])ism", '</p><h5>$1</h5><p>', $text);
1503                                         $text = preg_replace("(\[h6\](.*?)\[\/h6\])ism", '</p><h6>$1</h6><p>', $text);
1504                                 }
1505
1506                                 // Check for paragraph
1507                                 $text = preg_replace("(\[p\](.*?)\[\/p\])ism", '<p>$1</p>', $text);
1508
1509                                 // Check for bold text
1510                                 $text = preg_replace("(\[b\](.*?)\[\/b\])ism", '<strong>$1</strong>', $text);
1511
1512                                 // Check for Italics text
1513                                 $text = preg_replace("(\[i\](.*?)\[\/i\])ism", '<em>$1</em>', $text);
1514
1515                                 // Check for Underline text
1516                                 $text = preg_replace("(\[u\](.*?)\[\/u\])ism", '<u>$1</u>', $text);
1517
1518                                 // Check for strike-through text
1519                                 $text = preg_replace("(\[s\](.*?)\[\/s\])ism", '<s>$1</s>', $text);
1520
1521                                 // Check for over-line text
1522                                 $text = preg_replace("(\[o\](.*?)\[\/o\])ism", '<span class="overline">$1</span>', $text);
1523
1524                                 // Check for colored text
1525                                 $text = preg_replace("(\[color=(.*?)\](.*?)\[\/color\])ism", "<span style=\"color: $1;\">$2</span>", $text);
1526
1527                                 // Check for sized text
1528                                 // [size=50] --> font-size: 50px (with the unit).
1529                                 if ($simple_html != self::DIASPORA) {
1530                                         $text = preg_replace("(\[size=(\d*?)\](.*?)\[\/size\])ism", '<span style="font-size:$1px;line-height:normal;">$2</span>', $text);
1531                                         $text = preg_replace("(\[size=(.*?)\](.*?)\[\/size\])ism", '<span style="font-size:$1;line-height:normal;">$2</span>', $text);
1532                                 } else {
1533                                         // Issue 2199: Diaspora doesn't interpret the construct above, nor the <small> or <big> element
1534                                         $text = preg_replace("(\[size=(.*?)\](.*?)\[\/size\])ism", "$2", $text);
1535                                 }
1536
1537
1538                                 // Check for centered text
1539                                 $text = preg_replace("(\[center\](.*?)\[\/center\])ism", '<div style="text-align:center;">$1</div>', $text);
1540
1541                                 // Check for list text
1542                                 $text = str_replace("[*]", "<li>", $text);
1543
1544                                 // Check for block-level custom CSS
1545                                 $text = preg_replace('#(?<=^|\n)\[style=(.*?)](.*?)\[/style](?:\n|$)#ism', '<div style="$1">$2</div>', $text);
1546
1547                                 // Check for inline custom CSS
1548                                 $text = preg_replace("(\[style=(.*?)\](.*?)\[\/style\])ism", '<span style="$1">$2</span>', $text);
1549
1550                                 // Mastodon Emoji (internal tag, do not document for users)
1551                                 if ($simple_html == self::MASTODON_API) {
1552                                         $text = preg_replace("(\[emoji=(.*?)](.*?)\[/emoji])ism", '$2', $text);
1553                                 } else {
1554                                         $text = preg_replace("(\[emoji=(.*?)](.*?)\[/emoji])ism", '<span class="mastodon emoji"><img src="$1" alt="$2" title="$2"/></span>', $text);
1555                                 }
1556
1557                                 // Check for CSS classes
1558                                 // @deprecated since 2021.12, left for backward-compatibility reasons
1559                                 $text = preg_replace("(\[class=(.*?)\](.*?)\[\/class\])ism", '<span class="$1">$2</span>', $text);
1560                                 // Add HTML new lines
1561                                 $text = str_replace("\n\n", '</p><p>', $text);
1562                                 $text = str_replace("\n", '<br>', $text);
1563
1564                                 // handle nested lists
1565                                 $endlessloop = 0;
1566
1567                                 while ((((strpos($text, "[/list]") !== false) && (strpos($text, "[list") !== false)) ||
1568                                         ((strpos($text, "[/ol]") !== false) && (strpos($text, "[ol]") !== false)) ||
1569                                         ((strpos($text, "[/ul]") !== false) && (strpos($text, "[ul]") !== false)) ||
1570                                         ((strpos($text, "[/li]") !== false) && (strpos($text, "[li]") !== false))) && (++$endlessloop < 20)) {
1571                                         $text = preg_replace("/\[list\](.*?)\[\/list\]/ism", '</p><ul class="listbullet" style="list-style-type: circle;">$1</ul><p>', $text);
1572                                         $text = preg_replace("/\[list=\](.*?)\[\/list\]/ism", '</p><ul class="listnone" style="list-style-type: none;">$1</ul><p>', $text);
1573                                         $text = preg_replace("/\[list=1\](.*?)\[\/list\]/ism", '</p><ul class="listdecimal" style="list-style-type: decimal;">$1</ul><p>', $text);
1574                                         $text = preg_replace("/\[list=((?-i)i)\](.*?)\[\/list\]/ism", '</p><ul class="listlowerroman" style="list-style-type: lower-roman;">$2</ul><p>', $text);
1575                                         $text = preg_replace("/\[list=((?-i)I)\](.*?)\[\/list\]/ism", '</p><ul class="listupperroman" style="list-style-type: upper-roman;">$2</ul><p>', $text);
1576                                         $text = preg_replace("/\[list=((?-i)a)\](.*?)\[\/list\]/ism", '</p><ul class="listloweralpha" style="list-style-type: lower-alpha;">$2</ul><p>', $text);
1577                                         $text = preg_replace("/\[list=((?-i)A)\](.*?)\[\/list\]/ism", '</p><ul class="listupperalpha" style="list-style-type: upper-alpha;">$2</ul><p>', $text);
1578                                         $text = preg_replace("/\[ul\](.*?)\[\/ul\]/ism", '</p><ul>$1</ul><p>', $text);
1579                                         $text = preg_replace("/\[ol\](.*?)\[\/ol\]/ism", '</p><ol>$1</ol><p>', $text);
1580                                         $text = preg_replace("/\[li\](.*?)\[\/li\]/ism", '<li>$1</li>', $text);
1581                                 }
1582
1583                                 $text = preg_replace("/\[th\](.*?)\[\/th\]/sm", '<th>$1</th>', $text);
1584                                 $text = preg_replace("/\[td\](.*?)\[\/td\]/sm", '<td>$1</td>', $text);
1585                                 $text = preg_replace("/\[tr\](.*?)\[\/tr\]/sm", '<tr>$1</tr>', $text);
1586                                 $text = preg_replace("/\[table\](.*?)\[\/table\]/sm", '</p><table>$1</table><p>', $text);
1587
1588                                 $text = preg_replace("/\[table border=1\](.*?)\[\/table\]/sm", '</p><table border="1" >$1</table><p>', $text);
1589                                 $text = preg_replace("/\[table border=0\](.*?)\[\/table\]/sm", '</p><table border="0" >$1</table><p>', $text);
1590
1591                                 $text = str_replace('[hr]', '</p><hr /><p>', $text);
1592
1593                                 if (!$for_plaintext) {
1594                                         $text = self::performWithEscapedTags($text, ['url', 'img', 'audio', 'video', 'youtube', 'vimeo', 'share', 'attachment', 'iframe', 'bookmark'], function ($text) {
1595                                                 return preg_replace(Strings::autoLinkRegEx(), '[url]$1[/url]', $text);
1596                                         });
1597                                 }
1598
1599                                 // Check for font change text
1600                                 $text = preg_replace("/\[font=(.*?)\](.*?)\[\/font\]/sm", "<span style=\"font-family: $1;\">$2</span>", $text);
1601
1602                                 // Declare the format for [spoiler] layout
1603                                 $SpoilerLayout = '<details class="spoiler"><summary>' . DI::l10n()->t('Click to open/close') . '</summary>$1</details>';
1604
1605                                 // Check for [spoiler] text
1606                                 // handle nested quotes
1607                                 $endlessloop = 0;
1608                                 while ((strpos($text, "[/spoiler]") !== false) && (strpos($text, "[spoiler]") !== false) && (++$endlessloop < 20)) {
1609                                         $text = preg_replace("/\[spoiler\](.*?)\[\/spoiler\]/ism", $SpoilerLayout, $text);
1610                                 }
1611
1612                                 // Check for [spoiler=Title] text
1613
1614                                 // handle nested quotes
1615                                 $endlessloop = 0;
1616                                 while ((strpos($text, "[/spoiler]") !== false)  && (strpos($text, "[spoiler=") !== false) && (++$endlessloop < 20)) {
1617                                         $text = preg_replace(
1618                                                 "/\[spoiler=[\"\']*(.*?)[\"\']*\](.*?)\[\/spoiler\]/ism",
1619                                                 '<details class="spoiler"><summary>$1</summary>$2</details>',
1620                                                 $text
1621                                         );
1622                                 }
1623
1624                                 // Declare the format for [quote] layout
1625                                 $QuoteLayout = '</p><blockquote>$1</blockquote><p>';
1626
1627                                 // Check for [quote] text
1628                                 // handle nested quotes
1629                                 $endlessloop = 0;
1630                                 while ((strpos($text, "[/quote]") !== false) && (strpos($text, "[quote]") !== false) && (++$endlessloop < 20)) {
1631                                         $text = preg_replace("/\[quote\](.*?)\[\/quote\]/ism", "$QuoteLayout", $text);
1632                                 }
1633
1634                                 // Check for [quote=Author] text
1635
1636                                 $t_wrote = DI::l10n()->t('$1 wrote:');
1637
1638                                 // handle nested quotes
1639                                 $endlessloop = 0;
1640                                 while ((strpos($text, "[/quote]") !== false)  && (strpos($text, "[quote=") !== false) && (++$endlessloop < 20)) {
1641                                         $text = preg_replace(
1642                                                 "/\[quote=[\"\']*(.*?)[\"\']*\](.*?)\[\/quote\]/ism",
1643                                                 "<p><strong class=" . '"author"' . ">" . $t_wrote . "</strong></p><blockquote>$2</blockquote>",
1644                                                 $text
1645                                         );
1646                                 }
1647
1648
1649                                 // [img=widthxheight]image source[/img]
1650                                 $text = preg_replace_callback(
1651                                         "/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism",
1652                                         function ($matches) use ($simple_html, $uriid) {
1653                                                 if (strpos($matches[3], "data:image/") === 0) {
1654                                                         return $matches[0];
1655                                                 }
1656
1657                                                 $matches[3] = self::proxyUrl($matches[3], $simple_html, $uriid);
1658                                                 return "[img=" . $matches[1] . "x" . $matches[2] . "]" . $matches[3] . "[/img]";
1659                                         },
1660                                         $text
1661                                 );
1662
1663                                 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '<img src="$3" style="width: $1px;" >', $text);
1664                                 $text = preg_replace("/\[zmg\=([0-9]*)x([0-9]*)\](.*?)\[\/zmg\]/ism", '<img class="zrl" src="$3" style="width: $1px;" >', $text);
1665
1666                                 $text = preg_replace_callback(
1667                                         "/\[[iz]mg\=(.*?)\](.*?)\[\/[iz]mg\]/ism",
1668                                         function ($matches) use ($simple_html, $uriid) {
1669                                                 $matches[1] = self::proxyUrl($matches[1], $simple_html, $uriid);
1670                                                 $alt = htmlspecialchars($matches[2], ENT_COMPAT);
1671                                                 // Fix for Markdown problems with Diaspora, see issue #12701
1672                                                 if (($simple_html != self::DIASPORA) || strpos($matches[2], '"') === false) {
1673                                                         return '<img src="' . $matches[1] . '" alt="' . $alt . '" title="' . $alt . '">';
1674                                                 } else {
1675                                                         return '<img src="' . $matches[1] . '" alt="' . $alt . '">';
1676                                                 }
1677                                         },
1678                                         $text
1679                                 );
1680
1681                                 // Images
1682                                 // [img]pathtoimage[/img]
1683                                 $text = preg_replace_callback(
1684                                         "/\[[iz]mg\](.*?)\[\/[iz]mg\]/ism",
1685                                         function ($matches) use ($simple_html, $uriid) {
1686                                                 if (strpos($matches[1], "data:image/") === 0) {
1687                                                         return $matches[0];
1688                                                 }
1689
1690                                                 $matches[1] = self::proxyUrl($matches[1], $simple_html, $uriid);
1691                                                 return "[img]" . $matches[1] . "[/img]";
1692                                         },
1693                                         $text
1694                                 );
1695
1696                                 $text = preg_replace("/\[img\](.*?)\[\/img\]/ism", '<img src="$1" alt="' . DI::l10n()->t('Image/photo') . '" />', $text);
1697                                 $text = preg_replace("/\[zmg\](.*?)\[\/zmg\]/ism", '<img src="$1" alt="' . DI::l10n()->t('Image/photo') . '" />', $text);
1698
1699                                 $text = self::convertImages($text, $simple_html, $uriid);
1700
1701                                 $text = preg_replace("/\[crypt\](.*?)\[\/crypt\]/ism", '<br><img src="' . DI::baseUrl() . '/images/lock_icon.gif" alt="' . DI::l10n()->t('Encrypted content') . '" title="' . DI::l10n()->t('Encrypted content') . '" /><br>', $text);
1702                                 $text = preg_replace("/\[crypt(.*?)\](.*?)\[\/crypt\]/ism", '<br><img src="' . DI::baseUrl() . '/images/lock_icon.gif" alt="' . DI::l10n()->t('Encrypted content') . '" title="' . '$1' . ' ' . DI::l10n()->t('Encrypted content') . '" /><br>', $text);
1703                                 //$text = preg_replace("/\[crypt=(.*?)\](.*?)\[\/crypt\]/ism", '<br><img src="' .DI::baseUrl() . '/images/lock_icon.gif" alt="' . DI::l10n()->t('Encrypted content') . '" title="' . '$1' . ' ' . DI::l10n()->t('Encrypted content') . '" /><br>', $text);
1704
1705                                 // Simplify "video" element
1706                                 $text = preg_replace('(\[video[^\]]*?\ssrc\s?=\s?([^\s\]]+)[^\]]*?\].*?\[/video\])ism', '[video]$1[/video]', $text);
1707
1708                                 if ($simple_html == self::NPF) {
1709                                         $text = preg_replace(
1710                                                 "/\[video\](.*?)\[\/video\]/ism",
1711                                                 '</p><video src="$1" controls width="100%" height="auto">$1</video><p>',
1712                                                 $text
1713                                         );
1714                                         $text = preg_replace(
1715                                                 "/\[audio\](.*?)\[\/audio\]/ism",
1716                                                 '</p><audio src="$1" controls>$1">$1</audio><p>',
1717                                                 $text
1718                                         );
1719                                 } elseif ($try_oembed) {
1720                                         // html5 video and audio
1721                                         $text = preg_replace(
1722                                                 "/\[video\](.*?\.(ogg|ogv|oga|ogm|webm|mp4).*?)\[\/video\]/ism",
1723                                                 '<video src="$1" controls width="100%" height="auto"><a href="$1">$1</a></video>',
1724                                                 $text
1725                                         );
1726
1727                                         $text = preg_replace_callback("/\[video\](.*?)\[\/video\]/ism", $try_oembed_callback, $text);
1728                                         $text = preg_replace_callback("/\[audio\](.*?)\[\/audio\]/ism", $try_oembed_callback, $text);
1729
1730                                         $text = preg_replace(
1731                                                 "/\[video\](.*?)\[\/video\]/ism",
1732                                                 '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>',
1733                                                 $text
1734                                         );
1735                                         $text = preg_replace("/\[audio\](.*?)\[\/audio\]/ism", '<audio src="$1" controls><a href="$1">$1</a></audio>', $text);
1736                                 } else {
1737                                         $text = preg_replace(
1738                                                 "/\[video\](.*?)\[\/video\]/ism",
1739                                                 '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>',
1740                                                 $text
1741                                         );
1742                                         $text = preg_replace(
1743                                                 "/\[audio\](.*?)\[\/audio\]/ism",
1744                                                 '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>',
1745                                                 $text
1746                                         );
1747                                 }
1748
1749                                 // Backward compatibility, [iframe] support has been removed in version 2020.12
1750                                 $text = preg_replace("/\[iframe\](.*?)\[\/iframe\]/ism", '<a href="$1">$1</a>', $text);
1751
1752                                 $text = self::normalizeVideoLinks($text);
1753
1754                                 // Youtube extensions
1755                                 if ($try_oembed) {
1756                                         $text = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism", '<iframe width="' . $a->getThemeInfoValue('videowidth') . '" height="' . $a->getThemeInfoValue('videoheight') . '" src="https://www.youtube.com/embed/$1" frameborder="0" ></iframe>', $text);
1757                                 } else {
1758                                         $text = preg_replace(
1759                                                 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
1760                                                 '<a href="https://www.youtube.com/watch?v=$1" target="_blank" rel="noopener noreferrer">https://www.youtube.com/watch?v=$1</a>',
1761                                                 $text
1762                                         );
1763                                 }
1764
1765                                 // Vimeo extensions
1766                                 if ($try_oembed) {
1767                                         $text = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism", '<iframe width="' . $a->getThemeInfoValue('videowidth') . '" height="' . $a->getThemeInfoValue('videoheight') . '" src="https://player.vimeo.com/video/$1" frameborder="0" ></iframe>', $text);
1768                                 } else {
1769                                         $text = preg_replace(
1770                                                 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
1771                                                 '<a href="https://vimeo.com/$1" target="_blank" rel="noopener noreferrer">https://vimeo.com/$1</a>',
1772                                                 $text
1773                                         );
1774                                 }
1775
1776                                 // oembed tag
1777                                 $text = OEmbed::BBCode2HTML($text);
1778
1779                                 // Avoid triple linefeeds through oembed
1780                                 $text = str_replace("<br style='clear:left'></span><br><br>", "<br style='clear:left'></span><br>", $text);
1781
1782                                 // If we found an event earlier, strip out all the event code and replace with a reformatted version.
1783                                 // Replace the event-start section with the entire formatted event. The other bbcode is stripped.
1784                                 // Summary (e.g. title) is required, earlier revisions only required description (in addition to
1785                                 // start which is always required). Allow desc with a missing summary for compatibility.
1786
1787                                 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
1788                                         $sub = Event::getHTML($ev, $simple_html, $uriid);
1789
1790                                         $text = preg_replace("/\[event\-summary\](.*?)\[\/event\-summary\]/ism", '', $text);
1791                                         $text = preg_replace("/\[event\-description\](.*?)\[\/event\-description\]/ism", '', $text);
1792                                         $text = preg_replace("/\[event\-start\](.*?)\[\/event\-start\]/ism", $sub, $text);
1793                                         $text = preg_replace("/\[event\-finish\](.*?)\[\/event\-finish\]/ism", '', $text);
1794                                         $text = preg_replace("/\[event\-location\](.*?)\[\/event\-location\]/ism", '', $text);
1795                                         $text = preg_replace("/\[event\-id\](.*?)\[\/event\-id\]/ism", '', $text);
1796                                 }
1797
1798                                 if (!$for_plaintext && DI::config()->get('system', 'big_emojis') && ($simple_html != self::DIASPORA) && Smilies::isEmojiPost($text)) {
1799                                         $text = '<span style="font-size: xx-large; line-height: normal;">' . $text . '</span>';
1800                                 }
1801
1802                                 // Handle mentions and hashtag links
1803                                 if ($simple_html == self::DIASPORA) {
1804                                         // The ! is converted to @ since Diaspora only understands the @
1805                                         $text = preg_replace(
1806                                                 "/([@!])\[url\=(.*?)\](.*?)\[\/url\]/ism",
1807                                                 '@<a href="$2">$3</a>',
1808                                                 $text
1809                                         );
1810                                 } elseif (in_array($simple_html, [self::OSTATUS, self::ACTIVITYPUB])) {
1811                                         $text = preg_replace(
1812                                                 "/([@!])\[url\=(.*?)\](.*?)\[\/url\]/ism",
1813                                                 '<span class="h-card"><a href="$2" class="u-url mention">$1<span>$3</span></a></span>',
1814                                                 $text
1815                                         );
1816                                         $text = preg_replace(
1817                                                 "/([#])\[url\=(.*?)\](.*?)\[\/url\]/ism",
1818                                                 '<a href="$2" class="mention hashtag" rel="tag">$1<span>$3</span></a>',
1819                                                 $text
1820                                         );
1821                                 } elseif (in_array($simple_html, [self::INTERNAL, self::EXTERNAL, self::TWITTER_API])) {
1822                                         $text = preg_replace(
1823                                                 "/([@!])\[url\=(.*?)\](.*?)\[\/url\]/ism",
1824                                                 '<bdi>$1<a href="$2" class="userinfo mention" title="$3">$3</a></bdi>',
1825                                                 $text
1826                                         );
1827                                 } elseif ($simple_html == self::MASTODON_API) {
1828                                         $text = preg_replace(
1829                                                 "/([@!])\[url\=(.*?)\](.*?)\[\/url\]/ism",
1830                                                 '<a class="u-url mention status-link" href="$2" rel="nofollow noopener noreferrer" target="_blank" title="$3">$1<span>$3</span></a>',
1831                                                 $text
1832                                         );
1833                                         $text = preg_replace(
1834                                                 "/([#])\[url\=(.*?)\](.*?)\[\/url\]/ism",
1835                                                 '<a class="mention hashtag status-link" href="$2" rel="tag">$1<span>$3</span></a>',
1836                                                 $text
1837                                         );
1838                                 } else {
1839                                         $text = preg_replace("/([#@!])\[url\=(.*?)\](.*?)\[\/url\]/ism", '$1$3', $text);
1840                                 }
1841
1842                                 if (!$for_plaintext) {
1843                                         if (in_array($simple_html, [self::OSTATUS, self::MASTODON_API, self::TWITTER_API, self::ACTIVITYPUB])) {
1844                                                 $text = preg_replace_callback("/\[url\](.*?)\[\/url\]/ism", [self::class, 'convertUrlForActivityPubCallback'], $text);
1845                                                 $text = preg_replace_callback("/\[url\=(.*?)\](.*?)\[\/url\]/ism", [self::class, 'convertUrlForActivityPubCallback'], $text);
1846                                         }
1847                                 } else {
1848                                         $text = preg_replace("(\[url\](.*?)\[\/url\])ism", " $1 ", $text);
1849                                         $text = preg_replace_callback("&\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]&Usi", [self::class, 'removePictureLinksCallback'], $text);
1850                                 }
1851
1852                                 // Bookmarks in red - will be converted to bookmarks in friendica
1853                                 $text = preg_replace("/#\^\[url\](.*?)\[\/url\]/ism", '[bookmark=$1]$1[/bookmark]', $text);
1854                                 $text = preg_replace("/#\^\[url\=(.*?)\](.*?)\[\/url\]/ism", '[bookmark=$1]$2[/bookmark]', $text);
1855                                 $text = preg_replace(
1856                                         "/#\[url\=.*?\]\^\[\/url\]\[url\=(.*?)\](.*?)\[\/url\]/i",
1857                                         "[bookmark=$1]$2[/bookmark]",
1858                                         $text
1859                                 );
1860
1861                                 if (in_array($simple_html, [self::OSTATUS, self::TWITTER, self::BLUESKY])) {
1862                                         $text = preg_replace_callback("/([^#@!])\[url\=([^\]]*)\](.*?)\[\/url\]/ism", [self::class, 'expandLinksCallback'], $text);
1863                                         //$text = preg_replace("/[^#@!]\[url\=([^\]]*)\](.*?)\[\/url\]/ism", ' $2 [url]$1[/url]', $text);
1864                                         $text = preg_replace("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", ' $2 [url]$1[/url]', $text);
1865                                 }
1866
1867                                 // Perform URL Search
1868                                 if ($try_oembed) {
1869                                         $text = preg_replace_callback("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $try_oembed_callback, $text);
1870                                 }
1871
1872                                 $text = preg_replace("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $text);
1873
1874                                 // Handle Diaspora posts
1875                                 $text = preg_replace_callback(
1876                                         "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1877                                         function ($match) {
1878                                                 return "[url=" . DI::baseUrl() . "/display/" . $match[1] . "]" . $match[2] . "[/url]";
1879                                         },
1880                                         $text
1881                                 );
1882
1883                                 $text = preg_replace_callback(
1884                                         "&\[url=/people\?q\=(.*)\](.*)\[\/url\]&Usi",
1885                                         function ($match) {
1886                                                 return "[url=" . DI::baseUrl() . "/search?search=%40" . $match[1] . "]" . $match[2] . "[/url]";
1887                                         },
1888                                         $text
1889                                 );
1890
1891                                 // Server independent link to posts and comments
1892                                 // See issue: https://github.com/diaspora/diaspora_federation/issues/75
1893                                 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1894                                 $text = preg_replace($expression, DI::baseUrl() . "/display/$1", $text);
1895
1896                                 /* Tag conversion
1897                                  * Supports:
1898                                  * - #[url=<anything>]<term>[/url]
1899                                  * - [url=<anything>]#<term>[/url]
1900                                  */
1901                                 self::performWithEscapedTags($text, ['url', 'share'], function ($text) use ($simple_html) {
1902                                         $text = preg_replace_callback("/(?:#\[url\=[^\[\]]*\]|\[url\=[^\[\]]*\]#)(.*?)\[\/url\]/ism", function ($matches) use ($simple_html) {
1903                                                 if ($simple_html == self::ACTIVITYPUB) {
1904                                                         return '<a href="' . DI::baseUrl() . '/search?tag=' . rawurlencode($matches[1])
1905                                                                 . '" data-tag="' . XML::escape($matches[1]) . '" rel="tag ugc">#'
1906                                                                 . XML::escape($matches[1]) . '</a>';
1907                                                 } else {
1908                                                         return '#<a href="' . DI::baseUrl() . '/search?tag=' . rawurlencode($matches[1])
1909                                                                 . '" class="tag" rel="tag" title="' . XML::escape($matches[1]) . '">'
1910                                                                 . XML::escape($matches[1]) . '</a>';
1911                                                 }
1912                                         }, $text);
1913                                         return $text;
1914                                 });
1915
1916                                 // We need no target="_blank" rel="noopener noreferrer" for local links
1917                                 // convert links start with DI::baseUrl() as local link without the target="_blank" rel="noopener noreferrer" attribute
1918                                 $escapedBaseUrl = preg_quote(DI::baseUrl(), '/');
1919                                 $text = preg_replace("/\[url\](" . $escapedBaseUrl . ".*?)\[\/url\]/ism", '<a href="$1">$1</a>', $text);
1920                                 $text = preg_replace("/\[url\=(" . $escapedBaseUrl . ".*?)\](.*?)\[\/url\]/ism", '<a href="$1">$2</a>', $text);
1921
1922                                 $text = preg_replace("/\[url\](.*?)\[\/url\]/ism", '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>', $text);
1923                                 $text = preg_replace("/\[url\=(.*?)\](.*?)\[\/url\]/ism", '<a href="$1" target="_blank" rel="noopener noreferrer">$2</a>', $text);
1924
1925                                 // Red compatibility, though the link can't be authenticated on Friendica
1926                                 $text = preg_replace("/\[zrl\=(.*?)\](.*?)\[\/zrl\]/ism", '<a href="$1" target="_blank" rel="noopener noreferrer">$2</a>', $text);
1927
1928
1929                                 // we may need to restrict this further if it picks up too many strays
1930                                 // link acct:user@host to a webfinger profile redirector
1931
1932                                 $text = preg_replace('/acct:([^@]+)@((?!\-)(?:[a-zA-Z\d\-]{0,62}[a-zA-Z\d]\.){1,126}(?!\d+)[a-zA-Z\d]{1,63})/', '<a href="' . DI::baseUrl() . '/acctlink?addr=$1@$2" target="extlink">acct:$1@$2</a>', $text);
1933
1934                                 // Perform MAIL Search
1935                                 $text = preg_replace("/\[mail\](.*?)\[\/mail\]/", '<a href="mailto:$1">$1</a>', $text);
1936                                 $text = preg_replace("/\[mail\=(.*?)\](.*?)\[\/mail\]/", '<a href="mailto:$1">$2</a>', $text);
1937
1938                                 /// @todo What is the meaning of these lines?
1939                                 $text = preg_replace('/\[\&amp\;([#a-z0-9]+)\;\]/', '&$1;', $text);
1940                                 $text = preg_replace('/\&\#039\;/', '\'', $text);
1941
1942                                 // Currently deactivated, it made problems with " inside of alt texts.
1943                                 //$text = preg_replace('/\&quot\;/', '"', $text);
1944
1945                                 // fix any escaped ampersands that may have been converted into links
1946                                 $text = preg_replace('/\<([^>]*?)(src|href)=(.*?)\&amp\;(.*?)\>/ism', '<$1$2=$3&$4>', $text);
1947
1948                                 // sanitizes src attributes (http and redir URLs for displaying in a web page, cid used for inline images in emails)
1949                                 $allowed_src_protocols = ['//', 'http://', 'https://', 'contact/redir/', 'cid:'];
1950
1951                                 array_walk($allowed_src_protocols, function (&$value) {
1952                                         $value = preg_quote($value, '#');
1953                                 });
1954
1955                                 $text = preg_replace(
1956                                         '#<([^>]*?)(src)="(?!' . implode('|', $allowed_src_protocols) . ')(.*?)"(.*?)>#ism',
1957                                         '<$1$2=""$4 data-original-src="$3" class="invalid-src" title="' . DI::l10n()->t('Invalid source protocol') . '">',
1958                                         $text
1959                                 );
1960
1961                                 // sanitize href attributes (only allowlisted protocols URLs)
1962                                 // default value for backward compatibility
1963                                 $allowed_link_protocols = DI::config()->get('system', 'allowed_link_protocols', []);
1964
1965                                 // Always allowed protocol even if config isn't set or not including it
1966                                 $allowed_link_protocols[] = '//';
1967                                 $allowed_link_protocols[] = 'http://';
1968                                 $allowed_link_protocols[] = 'https://';
1969                                 $allowed_link_protocols[] = 'contact/redir/';
1970
1971                                 array_walk($allowed_link_protocols, function (&$value) {
1972                                         $value = preg_quote($value, '#');
1973                                 });
1974
1975                                 $regex = '#<([^>]*?)(href)="(?!' . implode('|', $allowed_link_protocols) . ')(.*?)"(.*?)>#ism';
1976                                 $text = preg_replace($regex, '<$1$2="javascript:void(0)"$4 data-original-href="$3" class="invalid-href" title="' . DI::l10n()->t('Invalid link protocol') . '">', $text);
1977
1978                                 // Shared content
1979                                 $text = self::convertShare(
1980                                         $text,
1981                                         function (array $attributes, array $author_contact, $content, $is_quote_share) use ($simple_html) {
1982                                                 return self::convertShareCallback($attributes, $author_contact, $content, $is_quote_share, $simple_html);
1983                                         },
1984                                         $uriid
1985                                 );
1986
1987                                 $text = self::interpolateSavedImagesIntoItemBody($uriid, $text, $saved_image);
1988
1989                                 return $text;
1990                         }); // Escaped noparse, nobb, pre
1991
1992                         // Remove escaping tags and replace new lines that remain
1993                         $text = preg_replace_callback('/\[(noparse|nobb)](.*?)\[\/\1]/ism', function ($match) {
1994                                 return str_replace("\n", "<br>", $match[2]);
1995                         }, $text);
1996
1997                         // Additionally, [pre] tags preserve spaces
1998                         $text = preg_replace_callback("/\[pre\](.*?)\[\/pre\]/ism", function ($match) {
1999                                 return str_replace([' ', "\n"], ['&nbsp;', "<br>"], htmlentities($match[1], ENT_NOQUOTES, 'UTF-8'));
2000                         }, $text);
2001
2002                         return $text;
2003                 }); // Escaped code
2004
2005                 $text = preg_replace_callback(
2006                         "#\[code(?:=([^\]]*))?\](.*?)\[\/code\]#ism",
2007                         function ($matches) {
2008                                 if (strpos($matches[2], "\n") !== false) {
2009                                         $return = '<pre><code class="language-' . trim($matches[1]) . '">' . htmlentities(trim($matches[2], "\n\r"), ENT_NOQUOTES, 'UTF-8') . '</code></pre>';
2010                                 } else {
2011                                         $return = '<code>' . htmlentities($matches[2], ENT_NOQUOTES, 'UTF-8') . '</code>';
2012                                 }
2013
2014                                 return $return;
2015                         },
2016                         $text
2017                 );
2018
2019                 // Default iframe allowed domains/path
2020                 $allowedIframeDomains = [
2021                         DI::baseUrl()->getHost()
2022                                 . (DI::baseUrl()->getPath() ? '/' . DI::baseUrl()->getPath() : '')
2023                                 . '/oembed/', # The path part has to change with the source in Content\Oembed::iframe
2024                         'www.youtube.com/embed/',
2025                         'player.vimeo.com/video/',
2026                 ];
2027
2028                 $allowedIframeDomains = array_merge(
2029                         $allowedIframeDomains,
2030                         DI::config()->get('system', 'allowed_oembed') ?
2031                                 explode(',', DI::config()->get('system', 'allowed_oembed'))
2032                                 : []
2033                 );
2034
2035                 if (strpos($text, '<p>') !== false || strpos($text, '</p>') !== false) {
2036                         $text = '<p>' . $text . '</p>';
2037                 }
2038
2039                 $text = HTML::purify($text, $allowedIframeDomains);
2040                 DI::profiler()->stopRecording();
2041
2042                 return trim($text);
2043         }
2044
2045         /**
2046          * Strips the "abstract" tag from the provided text
2047          *
2048          * @param string $text The text with BBCode
2049          * @return string The same text - but without "abstract" element
2050          */
2051         public static function stripAbstract(string $text): string
2052         {
2053                 DI::profiler()->startRecording('rendering');
2054
2055                 $text = self::performWithEscapedTags($text, ['code', 'noparse', 'nobb', 'pre'], function ($text) {
2056                         $text = preg_replace("/[\s|\n]*\[abstract\].*?\[\/abstract\][\s|\n]*/ism", ' ', $text);
2057                         $text = preg_replace("/[\s|\n]*\[abstract=.*?\].*?\[\/abstract][\s|\n]*/ism", ' ', $text);
2058                         return $text;
2059                 });
2060
2061                 DI::profiler()->stopRecording();
2062                 return $text;
2063         }
2064
2065         /**
2066          * Returns the value of the "abstract" element
2067          *
2068          * @param string $text  The text that maybe contains the element
2069          * @param string $addon The addon for which the abstract is meant for
2070          * @return string The abstract
2071          */
2072         public static function getAbstract(string $text, string $addon = ''): string
2073         {
2074                 DI::profiler()->startRecording('rendering');
2075                 $addon = strtolower($addon);
2076
2077                 $abstract = self::performWithEscapedTags($text, ['code', 'noparse', 'nobb', 'pre'], function ($text) use ($addon) {
2078                         if ($addon && preg_match('#\[abstract=' . preg_quote($addon, '#') . '](.*?)\[/abstract]#ism', $text, $matches)) {
2079                                 return $matches[1];
2080                         }
2081
2082                         if (preg_match("#\[abstract](.*?)\[/abstract]#ism", $text, $matches)) {
2083                                 return $matches[1];
2084                         }
2085
2086                         return '';
2087                 });
2088
2089                 DI::profiler()->stopRecording();
2090                 return $abstract;
2091         }
2092
2093         /**
2094          * Callback function to replace a Friendica style mention in a mention for Diaspora
2095          *
2096          * @param array $match Matching values for the callback
2097          *                     [1] = Mention type (! or @)
2098          *                     [2] = Name
2099          *                     [3] = Address
2100          * @return string Replaced mention
2101          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2102          * @throws \ImagickException
2103          */
2104         private static function bbCodeMention2DiasporaCallback(array $match): string
2105         {
2106                 $contact = Contact::getByURL($match[3], false, ['addr']);
2107                 if (empty($contact['addr'])) {
2108                         return $match[0];
2109                 }
2110
2111                 $mention = $match[1] . '{' . $match[2] . '; ' . $contact['addr'] . '}';
2112                 return $mention;
2113         }
2114
2115         /**
2116          * Converts a BBCode text into Markdown
2117          *
2118          * This function converts a BBCode item body to be sent to Markdown-enabled
2119          * systems like Diaspora and Libertree
2120          *
2121          * @param string $text
2122          * @param bool   $for_diaspora Diaspora requires more changes than Libertree
2123          * @return string
2124          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2125          */
2126         public static function toMarkdown(string $text, bool $for_diaspora = true): string
2127         {
2128                 DI::profiler()->startRecording('rendering');
2129                 $original_text = $text;
2130
2131                 // Since Diaspora is creating a summary for links, this function removes them before posting
2132                 if ($for_diaspora) {
2133                         $text = self::removeShareInformation($text);
2134                 }
2135
2136                 /**
2137                  * Transform #tags, strip off the [url] and replace spaces with underscore
2138                  */
2139                 $url_search_string = "^\[\]";
2140                 $text = preg_replace_callback(
2141                         "/#\[url\=([$url_search_string]*)\](.*?)\[\/url\]/i",
2142                         function ($matches) {
2143                                 return '#' . str_replace(' ', '_', $matches[2]);
2144                         },
2145                         $text
2146                 );
2147
2148                 // Converting images with size parameters to simple images. Markdown doesn't know it.
2149                 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2150
2151                 // Convert it to HTML - don't try oembed
2152                 if ($for_diaspora) {
2153                         $text = self::convertForUriId(0, $text, self::DIASPORA);
2154
2155                         // Add all tags that maybe were removed
2156                         if (preg_match_all("/#\[url\=([$url_search_string]*)\](.*?)\[\/url\]/ism", $original_text, $tags)) {
2157                                 $tagline = '';
2158                                 foreach ($tags[2] as $tag) {
2159                                         $tag = html_entity_decode($tag, ENT_QUOTES, 'UTF-8');
2160                                         if (!strpos(html_entity_decode($text, ENT_QUOTES, 'UTF-8'), '#' . $tag)) {
2161                                                 $tagline .= '#' . $tag . ' ';
2162                                         }
2163                                 }
2164                                 $text = $text . ' ' . $tagline;
2165                         }
2166                 } else {
2167                         $text = self::convertForUriId(0, $text, self::CONNECTORS);
2168                 }
2169
2170                 // If a link is followed by a quote then there should be a newline before it
2171                 // Maybe we should make this newline at every time before a quote.
2172                 $text = str_replace(['</a><blockquote>'], ['</a><br><blockquote>'], $text);
2173
2174                 // Now convert HTML to Markdown
2175                 $text = HTML::toMarkdown($text);
2176
2177                 // Libertree has a problem with escaped hashtags.
2178                 $text = str_replace(['\#'], ['#'], $text);
2179
2180                 // Remove any leading or trailing whitespace, as this will mess up
2181                 // the Diaspora signature verification and cause the item to disappear
2182                 $text = trim($text);
2183
2184                 if ($for_diaspora) {
2185                         $url_search_string = "^\[\]";
2186                         $text = preg_replace_callback(
2187                                 "/([@!])\[(.*?)\]\(([$url_search_string]*?)\)/ism",
2188                                 [self::class, 'bbCodeMention2DiasporaCallback'],
2189                                 $text
2190                         );
2191                 }
2192
2193                 Hook::callAll('bb2diaspora', $text);
2194
2195                 DI::profiler()->stopRecording();
2196                 return $text;
2197         }
2198
2199         /**
2200          * Pull out all #hashtags and @person tags from $string.
2201          *
2202          * We also get @person@domain.com - which would make
2203          * the regex quite complicated as tags can also
2204          * end a sentence. So we'll run through our results
2205          * and strip the period from any tags which end with one.
2206          * Returns array of tags found, or empty array.
2207          *
2208          * @param string $string Post content
2209          * @return array List of tag and person names
2210          */
2211         public static function getTags(string $string): array
2212         {
2213                 DI::profiler()->startRecording('rendering');
2214                 $ret = [];
2215
2216                 self::performWithEscapedTags($string, ['noparse', 'pre', 'code', 'img', 'attachment'], function ($string) use (&$ret) {
2217                         // Convert hashtag links to hashtags
2218                         $string = preg_replace('/#\[url\=([^\[\]]*)\](.*?)\[\/url\]/ism', '#$2 ', $string);
2219
2220                         // Force line feeds at bbtags
2221                         $string = str_replace(['[', ']'], ["\n[", "]\n"], $string);
2222
2223                         // ignore anything in a bbtag
2224                         $string = preg_replace('/\[(.*?)\]/sm', '', $string);
2225
2226                         // Match full names against @tags including the space between first and last
2227                         // We will look these up afterward to see if they are full names or not recognisable.
2228
2229                         if (preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/', $string, $matches)) {
2230                                 foreach ($matches[1] as $match) {
2231                                         if (strstr($match, ']')) {
2232                                                 // we might be inside a bbcode color tag - leave it alone
2233                                                 continue;
2234                                         }
2235
2236                                         if (substr($match, -1, 1) === '.') {
2237                                                 $ret[] = substr($match, 0, -1);
2238                                         } else {
2239                                                 $ret[] = $match;
2240                                         }
2241                                 }
2242                         }
2243
2244                         // Otherwise pull out single word tags. These can be @nickname, @first_last
2245                         // and #hash tags.
2246
2247                         if (preg_match_all('/([!#@][^\^ \x0D\x0A,;:?\']*[^\^ \x0D\x0A,;:?!\'.])/', $string, $matches)) {
2248                                 foreach ($matches[1] as $match) {
2249                                         if (strstr($match, ']')) {
2250                                                 // we might be inside a bbcode color tag - leave it alone
2251                                                 continue;
2252                                         }
2253
2254                                         // try not to catch url fragments
2255                                         if (strpos($string, $match) && preg_match('/[a-zA-z0-9\/]/', substr($string, strpos($string, $match) - 1, 1))) {
2256                                                 continue;
2257                                         }
2258
2259                                         $ret[] = $match;
2260                                 }
2261                         }
2262                 });
2263
2264                 DI::profiler()->stopRecording();
2265                 return array_unique($ret);
2266         }
2267
2268         /**
2269          * Expand tags to URLs, checks the tag is at the start of a line or preceded by a non-word character
2270          *
2271          * @param string $body HTML/BBCode
2272          * @return string body with expanded tags
2273          */
2274         public static function expandTags(string $body): string
2275         {
2276                 return preg_replace_callback(
2277                         "/(?<=\W|^)([!#@])([^\^ \x0D\x0A,;:?'\"]*[^\^ \x0D\x0A,;:?!'\".])/",
2278                         function (array $match) {
2279                                 switch ($match[1]) {
2280                                         case '!':
2281                                         case '@':
2282                                                 $contact = Contact::getByURL($match[2]);
2283                                                 if (!empty($contact)) {
2284                                                         return $match[1] . '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
2285                                                 } else {
2286                                                         return $match[1] . $match[2];
2287                                                 }
2288                                                 break;
2289
2290                                         case '#':
2291                                         default:
2292                                                 return $match[1] . '[url=' . DI::baseUrl() . '/search?tag=' . $match[2] . ']' . $match[2] . '[/url]';
2293                                 }
2294                         },
2295                         $body
2296                 );
2297         }
2298
2299         /**
2300          * Perform a custom function on a text after having escaped blocks enclosed in the provided tag list.
2301          *
2302          * @param string   $text HTML/BBCode
2303          * @param array    $tagList A list of tag names, e.g ['noparse', 'nobb', 'pre']
2304          * @param callable $callback
2305          * @return string
2306          * @see Strings::performWithEscapedBlocks
2307          */
2308         public static function performWithEscapedTags(string $text, array $tagList, callable $callback): string
2309         {
2310                 $tagList = array_map('preg_quote', $tagList);
2311
2312                 return Strings::performWithEscapedBlocks($text, '#\[(?:' . implode('|', $tagList) . ').*?\[/(?:' . implode('|', $tagList) . ')]#ism', $callback);
2313         }
2314
2315         /**
2316          * Replaces mentions in the provided message body in BBCode links for the provided user and network if any
2317          *
2318          * @param string $body HTML/BBCode
2319          * @param int $profile_uid Profile user id
2320          * @param string $network Network name
2321          * @return string HTML/BBCode with inserted images
2322          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2323          * @throws \ImagickException
2324          */
2325         public static function setMentions(string $body, $profile_uid = 0, $network = '')
2326         {
2327                 DI::profiler()->startRecording('rendering');
2328                 $body = self::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) use ($profile_uid, $network) {
2329                         $tags = self::getTags($body);
2330
2331                         $tagged = [];
2332
2333                         foreach ($tags as $tag) {
2334                                 $tag_type = substr($tag, 0, 1);
2335
2336                                 if ($tag_type == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
2337                                         continue;
2338                                 }
2339
2340                                 /*
2341                                  * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
2342                                  * Robert Johnson should be first in the $tags array
2343                                  */
2344                                 foreach ($tagged as $nextTag) {
2345                                         if (stristr($nextTag, $tag . ' ')) {
2346                                                 continue 2;
2347                                         }
2348                                 }
2349
2350                                 if (($success = Item::replaceTag($body, $profile_uid, $tag, $network)) && $success['replaced']) {
2351                                         $tagged[] = $tag;
2352                                 }
2353                         }
2354
2355                         return $body;
2356                 });
2357
2358                 DI::profiler()->stopRecording();
2359                 return $body;
2360         }
2361
2362         /**
2363          * @param string      $author  Author display name
2364          * @param string      $profile Author profile URL
2365          * @param string      $avatar  Author profile picture URL
2366          * @param string      $link    Post source URL
2367          * @param string      $posted  Post created date
2368          * @param string|null $guid    Post guid (if any)
2369          * @param string|null $uri     Post uri (if any)
2370          * @return string
2371          * @TODO Rewrite to handle over whole record array
2372          */
2373         public static function getShareOpeningTag(string $author, string $profile, string $avatar, string $link, string $posted, string $guid = null, string $uri = null): string
2374         {
2375                 DI::profiler()->startRecording('rendering');
2376                 $header = "[share author='" . str_replace(["'", "[", "]"], ["&#x27;", "&#x5B;", "&#x5D;"], $author) .
2377                         "' profile='" . str_replace(["'", "[", "]"], ["&#x27;", "&#x5B;", "&#x5D;"], $profile) .
2378                         "' avatar='" . str_replace(["'", "[", "]"], ["&#x27;", "&#x5B;", "&#x5D;"], $avatar) .
2379                         "' link='" . str_replace(["'", "[", "]"], ["&#x27;", "&#x5B;", "&#x5D;"], $link) .
2380                         "' posted='" . str_replace(["'", "[", "]"], ["&#x27;", "&#x5B;", "&#x5D;"], $posted);
2381
2382                 if ($guid) {
2383                         $header .= "' guid='" . str_replace(["'", "[", "]"], ["&#x27;", "&#x5B;", "&#x5D;"], $guid);
2384                 }
2385
2386                 if ($uri) {
2387                         $header .= "' message_id='" . str_replace(["'", "[", "]"], ["&#x27;", "&#x5B;", "&#x5D;"], $uri);
2388                 }
2389
2390                 $header  .= "']";
2391
2392                 DI::profiler()->stopRecording();
2393                 return $header;
2394         }
2395
2396         /**
2397          * Returns the BBCode relevant to embed the provided URL in a post body.
2398          * For media type, it will return [img], [video] and [audio] tags.
2399          * For regular web pages, it will either output a [bookmark] tag if title and description were provided,
2400          * an [attachment] tag or a simple [url] tag depending on $tryAttachment.
2401          *
2402          * @param string      $url
2403          * @param bool        $tryAttachment
2404          * @param string|null $title
2405          * @param string|null $description
2406          * @param string|null $tags
2407          * @return string
2408          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2409          * @see ParseUrl::getSiteinfoCached
2410          */
2411         public static function embedURL(string $url, bool $tryAttachment = true, string $title = null, string $description = null, string $tags = null): string
2412         {
2413                 DI::profiler()->startRecording('rendering');
2414                 DI::logger()->info($url);
2415
2416                 // If there is already some content information submitted we don't
2417                 // need to parse the url for content.
2418                 if (!empty($title) && !empty($description)) {
2419                         $title = str_replace(["\r", "\n"], ['', ''], $title);
2420
2421                         $description = '[quote]' . trim($description) . '[/quote]' . "\n";
2422
2423                         $str_tags = '';
2424                         if (!empty($tags)) {
2425                                 $arr_tags = ParseUrl::convertTagsToArray($tags);
2426                                 if (count($arr_tags)) {
2427                                         $str_tags = "\n" . implode(' ', $arr_tags) . "\n";
2428                                 }
2429                         }
2430
2431                         $result = sprintf('[bookmark=%s]%s[/bookmark]%s', $url, ($title) ? $title : $url, $description) . $str_tags;
2432
2433                         DI::logger()->info('(unparsed): returns: ' . $result);
2434
2435                         DI::profiler()->stopRecording();
2436                         return $result;
2437                 }
2438
2439                 $siteinfo = ParseUrl::getSiteinfoCached($url);
2440
2441                 if (in_array($siteinfo['type'], ['image', 'video', 'audio'])) {
2442                         switch ($siteinfo['type']) {
2443                                 case 'video':
2444                                         $bbcode = "\n" . '[video]' . $url . '[/video]' . "\n";
2445                                         break;
2446                                 case 'audio':
2447                                         $bbcode = "\n" . '[audio]' . $url . '[/audio]' . "\n";
2448                                         break;
2449                                 default:
2450                                         $bbcode = "\n" . '[img]' . $url . '[/img]' . "\n";
2451                                         break;
2452                         }
2453
2454                         DI::profiler()->stopRecording();
2455                         return $bbcode;
2456                 }
2457
2458                 unset($siteinfo['keywords']);
2459
2460                 // Bypass attachment if parse url for a comment
2461                 if (!$tryAttachment) {
2462                         DI::profiler()->stopRecording();
2463                         return "\n" . '[url=' . $url . ']' . ($siteinfo['title'] ?? $url) . '[/url]';
2464                 }
2465
2466                 // Format it as BBCode attachment
2467                 $bbcode = "\n" . PageInfo::getFooterFromData($siteinfo);
2468                 DI::profiler()->stopRecording();
2469                 return $bbcode;
2470         }
2471 }