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