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