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