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