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