]> git.mxchange.org Git - friendica.git/blob - src/Content/Text/BBCode.php
friendica-5875 Uncaught Error: Call to undefined method Friendica\App::getCurlCode...
[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          * Processes [share] tags
863          *
864          * Note: Can produce a [bookmark] tag in the output
865          *
866          * @brief Processes [share] tags
867          * @param array    $share      preg_match_callback result array
868          * @param bool|int $simplehtml
869          * @return string
870          */
871         private static function convertShare($share, $simplehtml)
872         {
873                 $attributes = $share[2];
874
875                 $author = "";
876                 preg_match("/author='(.*?)'/ism", $attributes, $matches);
877                 if (x($matches, 1)) {
878                         $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
879                 }
880
881                 preg_match('/author="(.*?)"/ism', $attributes, $matches);
882                 if (x($matches, 1)) {
883                         $author = $matches[1];
884                 }
885
886                 $profile = "";
887                 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
888                 if (x($matches, 1)) {
889                         $profile = $matches[1];
890                 }
891
892                 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
893                 if (x($matches, 1)) {
894                         $profile = $matches[1];
895                 }
896
897                 $avatar = "";
898                 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
899                 if (x($matches, 1)) {
900                         $avatar = $matches[1];
901                 }
902
903                 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
904                 if (x($matches, 1)) {
905                         $avatar = $matches[1];
906                 }
907
908                 $link = "";
909                 preg_match("/link='(.*?)'/ism", $attributes, $matches);
910                 if (x($matches, 1)) {
911                         $link = $matches[1];
912                 }
913
914                 preg_match('/link="(.*?)"/ism', $attributes, $matches);
915                 if (x($matches, 1)) {
916                         $link = $matches[1];
917                 }
918
919                 $posted = "";
920
921                 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
922                 if (x($matches, 1)) {
923                         $posted = $matches[1];
924                 }
925
926                 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
927                 if (x($matches, 1)) {
928                         $posted = $matches[1];
929                 }
930
931                 // We only call this so that a previously unknown contact can be added.
932                 // This is important for the function "Model\Contact::getDetailsByURL()".
933                 // This function then can fetch an entry from the contact table.
934                 Contact::getIdForURL($profile, 0, true);
935
936                 $data = Contact::getDetailsByURL($profile);
937
938                 if (x($data, "name") && x($data, "addr")) {
939                         $userid_compact = $data["name"] . " (" . $data["addr"] . ")";
940                 } else {
941                         $userid_compact = Protocol::getAddrFromProfileUrl($profile, $author);
942                 }
943
944                 if (x($data, "addr")) {
945                         $userid = $data["addr"];
946                 } else {
947                         $userid = Protocol::formatMention($profile, $author);
948                 }
949
950                 if (x($data, "name")) {
951                         $author = $data["name"];
952                 }
953
954                 if (x($data, "micro")) {
955                         $avatar = $data["micro"];
956                 }
957
958                 $preshare = trim($share[1]);
959                 if ($preshare != "") {
960                         $preshare .= "<br />";
961                 }
962
963                 switch ($simplehtml) {
964                         case 1:
965                                 $text = $preshare . html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8') . ' <a href="' . $profile . '">' . $userid . "</a>: <br />»" . $share[3] . "«";
966                                 break;
967                         case 2:
968                                 $text = $preshare . html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8') . ' ' . $userid_compact . ": <br />" . $share[3];
969                                 break;
970                         case 3: // Diaspora
971                                 $headline = '<b>' . html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8') . $userid . ':</b><br />';
972
973                                 $text = trim($share[1]);
974
975                                 if ($text != "") {
976                                         $text .= "<hr />";
977                                 }
978
979                                 if (stripos(normalise_link($link), 'http://twitter.com/') === 0) {
980                                         $text .= '<br /><a href="' . $link . '">' . $link . '</a>';
981                                 } else {
982                                         $text .= $headline . '<blockquote>' . trim($share[3]) . "</blockquote><br />";
983
984                                         if ($link != "") {
985                                                 $text .= '<br /><a href="' . $link . '">[l]</a>';
986                                         }
987                                 }
988
989                                 break;
990                         case 4:
991                                 $headline = '<br /><b>' . html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8');
992                                 $headline .= L10n::t('<a href="%1$s" target="_blank">%2$s</a> %3$s', $link, $userid, $posted);
993                                 $headline .= ":</b><br />";
994
995                                 $text = trim($share[1]);
996
997                                 if ($text != "") {
998                                         $text .= "<hr />";
999                                 }
1000
1001                                 $text .= $headline . '<blockquote class="shared_content">' . trim($share[3]) . "</blockquote><br />";
1002
1003                                 break;
1004                         case 5:
1005                                 $text = $preshare . html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8') . ' ' . $userid_compact . ": <br />" . $share[3];
1006                                 break;
1007                         case 7: // statusnet/GNU Social
1008                                 $text = $preshare . html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8') . " @" . $userid_compact . ": " . $share[3];
1009                                 break;
1010                         case 8: // twitter
1011                                 $text = $preshare . "RT @" . $userid_compact . ": " . $share[3];
1012                                 break;
1013                         case 9: // Google+
1014                                 $text = $preshare . html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8') . ' ' . $userid_compact . ": <br />" . $share[3];
1015
1016                                 if ($link != "") {
1017                                         $text .= "<br /><br />" . $link;
1018                                 }
1019                                 break;
1020                         default:
1021                                 // Transforms quoted tweets in rich attachments to avoid nested tweets
1022                                 if (stripos(normalise_link($link), 'http://twitter.com/') === 0 && OEmbed::isAllowedURL($link)) {
1023                                         try {
1024                                                 $oembed = OEmbed::getHTML($link, $preshare);
1025                                         } catch (Exception $e) {
1026                                                 $oembed = sprintf('[bookmark=%s]%s[/bookmark]', $link, $preshare);
1027                                         }
1028
1029                                         $text = $preshare . $oembed;
1030                                 } else {
1031                                         $text = trim($share[1]) . "\n";
1032
1033                                         $avatar = ProxyUtils::proxifyUrl($avatar, false, ProxyUtils::SIZE_THUMB);
1034
1035                                         $tpl = get_markup_template('shared_content.tpl');
1036                                         $text .= replace_macros($tpl, [
1037                                                 '$profile' => $profile,
1038                                                 '$avatar' => $avatar,
1039                                                 '$author' => $author,
1040                                                 '$link' => $link,
1041                                                 '$posted' => $posted,
1042                                                 '$content' => trim($share[3])
1043                                         ]);
1044                                 }
1045                                 break;
1046                 }
1047
1048                 return $text;
1049         }
1050
1051         private static function removePictureLinksCallback($match)
1052         {
1053                 $text = Cache::get($match[1]);
1054
1055                 if (is_null($text)) {
1056                         $a = self::getApp();
1057
1058                         $stamp1 = microtime(true);
1059
1060                         $ch = @curl_init($match[1]);
1061                         @curl_setopt($ch, CURLOPT_NOBODY, true);
1062                         @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1063                         @curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
1064                         @curl_exec($ch);
1065                         $curl_info = @curl_getinfo($ch);
1066
1067                         $a->saveTimestamp($stamp1, "network");
1068
1069                         if (substr($curl_info["content_type"], 0, 6) == "image/") {
1070                                 $text = "[url=" . $match[1] . "]" . $match[1] . "[/url]";
1071                         } else {
1072                                 $text = "[url=" . $match[2] . "]" . $match[2] . "[/url]";
1073
1074                                 // if its not a picture then look if its a page that contains a picture link
1075                                 $body = Network::fetchUrl($match[1]);
1076
1077                                 $doc = new DOMDocument();
1078                                 @$doc->loadHTML($body);
1079                                 $xpath = new DOMXPath($doc);
1080                                 $list = $xpath->query("//meta[@name]");
1081                                 foreach ($list as $node) {
1082                                         $attr = [];
1083
1084                                         if ($node->attributes->length) {
1085                                                 foreach ($node->attributes as $attribute) {
1086                                                         $attr[$attribute->name] = $attribute->value;
1087                                                 }
1088                                         }
1089
1090                                         if (strtolower($attr["name"]) == "twitter:image") {
1091                                                 $text = "[url=" . $attr["content"] . "]" . $attr["content"] . "[/url]";
1092                                         }
1093                                 }
1094                         }
1095                         Cache::set($match[1], $text);
1096                 }
1097
1098                 return $text;
1099         }
1100
1101         private static function expandLinksCallback($match)
1102         {
1103                 if (($match[3] == "") || ($match[2] == $match[3]) || stristr($match[2], $match[3])) {
1104                         return ($match[1] . "[url]" . $match[2] . "[/url]");
1105                 } else {
1106                         return ($match[1] . $match[3] . " [url]" . $match[2] . "[/url]");
1107                 }
1108         }
1109
1110         private static function cleanPictureLinksCallback($match)
1111         {
1112                 $text = Cache::get($match[1]);
1113
1114                 if (is_null($text)) {
1115                         $a = self::getApp();
1116
1117                         $stamp1 = microtime(true);
1118
1119                         $ch = @curl_init($match[1]);
1120                         @curl_setopt($ch, CURLOPT_NOBODY, true);
1121                         @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1122                         @curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
1123                         @curl_exec($ch);
1124                         $curl_info = @curl_getinfo($ch);
1125
1126                         $a->saveTimestamp($stamp1, "network");
1127
1128                         // if its a link to a picture then embed this picture
1129                         if (substr($curl_info["content_type"], 0, 6) == "image/") {
1130                                 $text = "[img]" . $match[1] . "[/img]";
1131                         } else {
1132                                 $text = "[img]" . $match[2] . "[/img]";
1133
1134                                 // if its not a picture then look if its a page that contains a picture link
1135                                 $body = Network::fetchUrl($match[1]);
1136
1137                                 $doc = new DOMDocument();
1138                                 @$doc->loadHTML($body);
1139                                 $xpath = new DOMXPath($doc);
1140                                 $list = $xpath->query("//meta[@name]");
1141                                 foreach ($list as $node) {
1142                                         $attr = [];
1143                                         if ($node->attributes->length) {
1144                                                 foreach ($node->attributes as $attribute) {
1145                                                         $attr[$attribute->name] = $attribute->value;
1146                                                 }
1147                                         }
1148
1149                                         if (strtolower($attr["name"]) == "twitter:image") {
1150                                                 $text = "[img]" . $attr["content"] . "[/img]";
1151                                         }
1152                                 }
1153                         }
1154                         Cache::set($match[1], $text);
1155                 }
1156
1157                 return $text;
1158         }
1159
1160         public static function cleanPictureLinks($text)
1161         {
1162                 $return = preg_replace_callback("&\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]&Usi", 'self::cleanPictureLinksCallback', $text);
1163                 return $return;
1164         }
1165
1166         /**
1167          * @brief Converts a BBCode message to HTML message
1168          *
1169          * BBcode 2 HTML was written by WAY2WEB.net
1170          * extended to work with Mistpark/Friendica - Mike Macgirvin
1171          *
1172          * Simple HTML values meaning:
1173          * - 0: Friendica display
1174          * - 1: Unused
1175          * - 2: Used for Google+, Windows Phone push, Friendica API
1176          * - 3: Used before converting to Markdown in bb2diaspora.php
1177          * - 4: Used for WordPress, Libertree (before Markdown), pump.io and tumblr
1178          * - 5: Unused
1179          * - 6: Unused
1180          * - 7: Used for dfrn, OStatus
1181          * - 8: Used for WP backlink text setting
1182          *
1183          * @param string $text
1184          * @param bool   $try_oembed
1185          * @param int    $simple_html
1186          * @param bool   $for_plaintext
1187          * @return string
1188          */
1189         public static function convert($text, $try_oembed = true, $simple_html = false, $for_plaintext = false)
1190         {
1191                 $a = self::getApp();
1192
1193                 /*
1194                  * preg_match_callback function to replace potential Oembed tags with Oembed content
1195                  *
1196                  * $match[0] = [tag]$url[/tag] or [tag=$url]$title[/tag]
1197                  * $match[1] = $url
1198                  * $match[2] = $title or absent
1199                  */
1200                 $try_oembed_callback = function ($match)
1201                 {
1202                         $url = $match[1];
1203                         $title = defaults($match, 2, null);
1204
1205                         try {
1206                                 $return = OEmbed::getHTML($url, $title);
1207                         } catch (Exception $ex) {
1208                                 $return = $match[0];
1209                         }
1210
1211                         return $return;
1212                 };
1213
1214                 // Extracting multi-line code blocks before the whitespace processing
1215                 $codeblocks = [];
1216
1217                 $text = preg_replace_callback("#\[code(?:=([^\]]*))?\](.*?)\[\/code\]#is",
1218                         function ($matches) use (&$codeblocks) {
1219                                 $return = $matches[0];
1220                                 if (strpos($matches[2], "\n") !== false) {
1221                                         $return = '#codeblock-' . count($codeblocks) . '#';
1222
1223                                         $codeblocks[] =  '<pre><code class="language-' . trim($matches[1]) . '">' . trim($matches[2], "\n\r") . '</code></pre>';
1224                                 }
1225                                 return $return;
1226                         },
1227                         $text
1228                 );
1229
1230                 // Hide all [noparse] contained bbtags by spacefying them
1231                 // POSSIBLE BUG --> Will the 'preg' functions crash if there's an embedded image?
1232
1233                 $text = preg_replace_callback("/\[noparse\](.*?)\[\/noparse\]/ism", 'self::escapeNoparseCallback', $text);
1234                 $text = preg_replace_callback("/\[nobb\](.*?)\[\/nobb\]/ism", 'self::escapeNoparseCallback', $text);
1235                 $text = preg_replace_callback("/\[pre\](.*?)\[\/pre\]/ism", 'self::escapeNoparseCallback', $text);
1236
1237                 // Remove the abstract element. It is a non visible element.
1238                 $text = self::stripAbstract($text);
1239
1240                 // Move all spaces out of the tags
1241                 $text = preg_replace("/\[(\w*)\](\s*)/ism", '$2[$1]', $text);
1242                 $text = preg_replace("/(\s*)\[\/(\w*)\]/ism", '[/$2]$1', $text);
1243
1244                 // Extract the private images which use data urls since preg has issues with
1245                 // large data sizes. Stash them away while we do bbcode conversion, and then put them back
1246                 // in after we've done all the regex matching. We cannot use any preg functions to do this.
1247
1248                 $extracted = self::extractImagesFromItemBody($text);
1249                 $text = $extracted['body'];
1250                 $saved_image = $extracted['images'];
1251
1252                 // If we find any event code, turn it into an event.
1253                 // After we're finished processing the bbcode we'll
1254                 // replace all of the event code with a reformatted version.
1255
1256                 $ev = Event::fromBBCode($text);
1257
1258                 // Replace any html brackets with HTML Entities to prevent executing HTML or script
1259                 // Don't use strip_tags here because it breaks [url] search by replacing & with amp
1260
1261                 $text = str_replace("<", "&lt;", $text);
1262                 $text = str_replace(">", "&gt;", $text);
1263
1264                 // remove some newlines before the general conversion
1265                 $text = preg_replace("/\s?\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "[share$1]$2[/share]", $text);
1266                 $text = preg_replace("/\s?\[quote(.*?)\]\s?(.*?)\s?\[\/quote\]\s?/ism", "[quote$1]$2[/quote]", $text);
1267
1268                 $text = preg_replace("/\n\[code\]/ism", "[code]", $text);
1269                 $text = preg_replace("/\[\/code\]\n/ism", "[/code]", $text);
1270
1271                 // when the content is meant exporting to other systems then remove the avatar picture since this doesn't really look good on these systems
1272                 if (!$try_oembed) {
1273                         $text = preg_replace("/\[share(.*?)avatar\s?=\s?'.*?'\s?(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "\n[share$1$2]$3[/share]", $text);
1274                 }
1275
1276                 // Convert new line chars to html <br /> tags
1277
1278                 // nlbr seems to be hopelessly messed up
1279                 //      $Text = nl2br($Text);
1280
1281                 // We'll emulate it.
1282
1283                 $text = trim($text);
1284                 $text = str_replace("\r\n", "\n", $text);
1285
1286                 // removing multiplicated newlines
1287                 if (Config::get("system", "remove_multiplicated_lines")) {
1288                         $search = ["\n\n\n", "\n ", " \n", "[/quote]\n\n", "\n[/quote]", "[/li]\n", "\n[li]", "\n[ul]", "[/ul]\n", "\n\n[share ", "[/attachment]\n",
1289                                         "\n[h1]", "[/h1]\n", "\n[h2]", "[/h2]\n", "\n[h3]", "[/h3]\n", "\n[h4]", "[/h4]\n", "\n[h5]", "[/h5]\n", "\n[h6]", "[/h6]\n"];
1290                         $replace = ["\n\n", "\n", "\n", "[/quote]\n", "[/quote]", "[/li]", "[li]", "[ul]", "[/ul]", "\n[share ", "[/attachment]",
1291                                         "[h1]", "[/h1]", "[h2]", "[/h2]", "[h3]", "[/h3]", "[h4]", "[/h4]", "[h5]", "[/h5]", "[h6]", "[/h6]"];
1292                         do {
1293                                 $oldtext = $text;
1294                                 $text = str_replace($search, $replace, $text);
1295                         } while ($oldtext != $text);
1296                 }
1297
1298                 // Set up the parameters for a URL search string
1299                 $URLSearchString = "^\[\]";
1300                 // Set up the parameters for a MAIL search string
1301                 $MAILSearchString = $URLSearchString;
1302
1303                 // if the HTML is used to generate plain text, then don't do this search, but replace all URL of that kind to text
1304                 if (!$for_plaintext) {
1305                         // Autolink feature (thanks to http://code.seebz.net/p/autolink-php/)
1306                         // Currently disabled, since the function is too greedy
1307                         // $autolink_regex = "`([^\]\=\"']|^)(https?\://[^\s<]+[^\s<\.\)])`ism";
1308                         $autolink_regex = "/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism";
1309                         $text = preg_replace($autolink_regex, '$1[url]$2[/url]', $text);
1310                         if ($simple_html == 7) {
1311                                 $text = preg_replace_callback("/\[url\]([$URLSearchString]*)\[\/url\]/ism", 'self::convertUrlForOStatusCallback', $text);
1312                                 $text = preg_replace_callback("/\[url\=([$URLSearchString]*)\]([$URLSearchString]*)\[\/url\]/ism", 'self::convertUrlForOStatusCallback', $text);
1313                         }
1314                 } else {
1315                         $text = preg_replace("(\[url\]([$URLSearchString]*)\[\/url\])ism", " $1 ", $text);
1316                         $text = preg_replace_callback("&\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]&Usi", 'self::removePictureLinksCallback', $text);
1317                 }
1318
1319
1320                 // Handle attached links or videos
1321                 $text = self::convertAttachment($text, $simple_html, $try_oembed);
1322
1323                 $text = str_replace(["\r","\n"], ['<br />', '<br />'], $text);
1324
1325                 // Remove all hashtag addresses
1326                 if ((!$try_oembed || $simple_html) && !in_array($simple_html, [3, 7])) {
1327                         $text = preg_replace("/([#@!])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
1328                 } elseif ($simple_html == 3) {
1329                         // The ! is converted to @ since Diaspora only understands the @
1330                         $text = preg_replace("/([@!])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1331                                 '@<a href="$2">$3</a>',
1332                                 $text);
1333                 } elseif ($simple_html == 7) {
1334                         $text = preg_replace("/([@!])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1335                                 '$1<span class="vcard"><a href="$2" class="url" title="$3"><span class="fn nickname mention">$3</span></a></span>',
1336                                 $text);
1337                 } elseif (!$simple_html) {
1338                         $text = preg_replace("/([@!])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1339                                 '$1<a href="$2" class="userinfo mention" title="$3">$3</a>',
1340                                 $text);
1341                 }
1342
1343                 // Bookmarks in red - will be converted to bookmarks in friendica
1344                 $text = preg_replace("/#\^\[url\]([$URLSearchString]*)\[\/url\]/ism", '[bookmark=$1]$1[/bookmark]', $text);
1345                 $text = preg_replace("/#\^\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[bookmark=$1]$2[/bookmark]', $text);
1346                 $text = preg_replace("/#\[url\=[$URLSearchString]*\]\^\[\/url\]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/i",
1347                                         "[bookmark=$1]$2[/bookmark]", $text);
1348
1349                 if (in_array($simple_html, [2, 6, 7, 8, 9])) {
1350                         $text = preg_replace_callback("/([^#@!])\[url\=([^\]]*)\](.*?)\[\/url\]/ism", "self::expandLinksCallback", $text);
1351                         //$Text = preg_replace("/[^#@!]\[url\=([^\]]*)\](.*?)\[\/url\]/ism", ' $2 [url]$1[/url]', $Text);
1352                         $text = preg_replace("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", ' $2 [url]$1[/url]',$text);
1353                 }
1354
1355                 if ($simple_html == 5) {
1356                         $text = preg_replace("/[^#@!]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url]$1[/url]', $text);
1357                 }
1358
1359                 // Perform URL Search
1360                 if ($try_oembed) {
1361                         $text = preg_replace_callback("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $try_oembed_callback, $text);
1362                 }
1363
1364                 if ($simple_html == 5) {
1365                         $text = preg_replace("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", '[url]$1[/url]', $text);
1366                 } else {
1367                         $text = preg_replace("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $text);
1368                 }
1369
1370                 // Handle Diaspora posts
1371                 $text = preg_replace_callback(
1372                         "&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1373                         function ($match) {
1374                                 return "[url=" . System::baseUrl() . "/display/" . $match[1] . "]" . $match[2] . "[/url]";
1375                         }, $text
1376                 );
1377
1378                 $text = preg_replace_callback(
1379                         "&\[url=/people\?q\=(.*)\](.*)\[\/url\]&Usi",
1380                         function ($match) {
1381                                 return "[url=" . System::baseUrl() . "/search?search=%40" . $match[1] . "]" . $match[2] . "[/url]";
1382                         }, $text
1383                 );
1384
1385                 // Server independent link to posts and comments
1386                 // See issue: https://github.com/diaspora/diaspora_federation/issues/75
1387                 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1388                 $text = preg_replace($expression, System::baseUrl()."/display/$1", $text);
1389
1390                 $text = preg_replace("/([#])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1391                                         '$1<a href="' . System::baseUrl() . '/search?tag=$3" class="tag" title="$3">$3</a>', $text);
1392
1393                 $text = preg_replace("/\[url\=([$URLSearchString]*)\]#(.*?)\[\/url\]/ism",
1394                                         '#<a href="' . System::baseUrl() . '/search?tag=$2" class="tag" title="$2">$2</a>', $text);
1395
1396                 $text = preg_replace("/\[url\]([$URLSearchString]*)\[\/url\]/ism", '<a href="$1" target="_blank">$1</a>', $text);
1397                 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '<a href="$1" target="_blank">$2</a>', $text);
1398                 //$Text = preg_replace("/\[url\=([$URLSearchString]*)\]([$URLSearchString]*)\[\/url\]/ism", '<a href="$1" target="_blank">$2</a>', $Text);
1399
1400                 // Red compatibility, though the link can't be authenticated on Friendica
1401                 $text = preg_replace("/\[zrl\=([$URLSearchString]*)\](.*?)\[\/zrl\]/ism", '<a href="$1" target="_blank">$2</a>', $text);
1402
1403
1404                 // we may need to restrict this further if it picks up too many strays
1405                 // link acct:user@host to a webfinger profile redirector
1406
1407                 $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);
1408
1409                 // Perform MAIL Search
1410                 $text = preg_replace("/\[mail\]([$MAILSearchString]*)\[\/mail\]/", '<a href="mailto:$1">$1</a>', $text);
1411                 $text = preg_replace("/\[mail\=([$MAILSearchString]*)\](.*?)\[\/mail\]/", '<a href="mailto:$1">$2</a>', $text);
1412
1413                 // leave open the posibility of [map=something]
1414                 // this is replaced in prepare_body() which has knowledge of the item location
1415
1416                 if (strpos($text, '[/map]') !== false) {
1417                         $text = preg_replace_callback(
1418                                 "/\[map\](.*?)\[\/map\]/ism",
1419                                 function ($match) use ($simple_html) {
1420                                         return str_replace($match[0], '<p class="map">' . Map::byLocation($match[1], $simple_html) . '</p>', $match[0]);
1421                                 },
1422                                 $text
1423                         );
1424                 }
1425                 if (strpos($text, '[map=') !== false) {
1426                         $text = preg_replace_callback(
1427                                 "/\[map=(.*?)\]/ism",
1428                                 function ($match) use ($simple_html) {
1429                                         return str_replace($match[0], '<p class="map">' . Map::byCoordinates(str_replace('/', ' ', $match[1]), $simple_html) . '</p>', $match[0]);
1430                                 },
1431                                 $text
1432                         );
1433                 }
1434                 if (strpos($text, '[map]') !== false) {
1435                         $text = preg_replace("/\[map\]/", '<p class="map"></p>', $text);
1436                 }
1437
1438                 // Check for headers
1439                 $text = preg_replace("(\[h1\](.*?)\[\/h1\])ism", '<h1>$1</h1>', $text);
1440                 $text = preg_replace("(\[h2\](.*?)\[\/h2\])ism", '<h2>$1</h2>', $text);
1441                 $text = preg_replace("(\[h3\](.*?)\[\/h3\])ism", '<h3>$1</h3>', $text);
1442                 $text = preg_replace("(\[h4\](.*?)\[\/h4\])ism", '<h4>$1</h4>', $text);
1443                 $text = preg_replace("(\[h5\](.*?)\[\/h5\])ism", '<h5>$1</h5>', $text);
1444                 $text = preg_replace("(\[h6\](.*?)\[\/h6\])ism", '<h6>$1</h6>', $text);
1445
1446                 // Check for paragraph
1447                 $text = preg_replace("(\[p\](.*?)\[\/p\])ism", '<p>$1</p>', $text);
1448
1449                 // Check for bold text
1450                 $text = preg_replace("(\[b\](.*?)\[\/b\])ism", '<strong>$1</strong>', $text);
1451
1452                 // Check for Italics text
1453                 $text = preg_replace("(\[i\](.*?)\[\/i\])ism", '<em>$1</em>', $text);
1454
1455                 // Check for Underline text
1456                 $text = preg_replace("(\[u\](.*?)\[\/u\])ism", '<u>$1</u>', $text);
1457
1458                 // Check for strike-through text
1459                 $text = preg_replace("(\[s\](.*?)\[\/s\])ism", '<s>$1</s>', $text);
1460
1461                 // Check for over-line text
1462                 $text = preg_replace("(\[o\](.*?)\[\/o\])ism", '<span class="overline">$1</span>', $text);
1463
1464                 // Check for colored text
1465                 $text = preg_replace("(\[color=(.*?)\](.*?)\[\/color\])ism", "<span style=\"color: $1;\">$2</span>", $text);
1466
1467                 // Check for sized text
1468                 // [size=50] --> font-size: 50px (with the unit).
1469                 $text = preg_replace("(\[size=(\d*?)\](.*?)\[\/size\])ism", "<span style=\"font-size: $1px; line-height: initial;\">$2</span>", $text);
1470                 $text = preg_replace("(\[size=(.*?)\](.*?)\[\/size\])ism", "<span style=\"font-size: $1; line-height: initial;\">$2</span>", $text);
1471
1472                 // Check for centered text
1473                 $text = preg_replace("(\[center\](.*?)\[\/center\])ism", "<div style=\"text-align:center;\">$1</div>", $text);
1474
1475                 // Check for list text
1476                 $text = str_replace("[*]", "<li>", $text);
1477
1478                 // Check for style sheet commands
1479                 $text = preg_replace_callback(
1480                         "(\[style=(.*?)\](.*?)\[\/style\])ism",
1481                         function ($match) {
1482                                 return "<span style=\"" . HTML::sanitizeCSS($match[1]) . ";\">" . $match[2] . "</span>";
1483                         },
1484                         $text
1485                 );
1486
1487                 // Check for CSS classes
1488                 $text = preg_replace_callback(
1489                         "(\[class=(.*?)\](.*?)\[\/class\])ism",
1490                         function ($match) {
1491                                 return "<span class=\"" . HTML::sanitizeCSS($match[1]) . "\">" . $match[2] . "</span>";
1492                         },
1493                         $text
1494                 );
1495
1496                 // handle nested lists
1497                 $endlessloop = 0;
1498
1499                 while ((((strpos($text, "[/list]") !== false) && (strpos($text, "[list") !== false)) ||
1500                            ((strpos($text, "[/ol]") !== false) && (strpos($text, "[ol]") !== false)) ||
1501                            ((strpos($text, "[/ul]") !== false) && (strpos($text, "[ul]") !== false)) ||
1502                            ((strpos($text, "[/li]") !== false) && (strpos($text, "[li]") !== false))) && (++$endlessloop < 20)) {
1503                         $text = preg_replace("/\[list\](.*?)\[\/list\]/ism", '<ul class="listbullet" style="list-style-type: circle;">$1</ul>', $text);
1504                         $text = preg_replace("/\[list=\](.*?)\[\/list\]/ism", '<ul class="listnone" style="list-style-type: none;">$1</ul>', $text);
1505                         $text = preg_replace("/\[list=1\](.*?)\[\/list\]/ism", '<ul class="listdecimal" style="list-style-type: decimal;">$1</ul>', $text);
1506                         $text = preg_replace("/\[list=((?-i)i)\](.*?)\[\/list\]/ism", '<ul class="listlowerroman" style="list-style-type: lower-roman;">$2</ul>', $text);
1507                         $text = preg_replace("/\[list=((?-i)I)\](.*?)\[\/list\]/ism", '<ul class="listupperroman" style="list-style-type: upper-roman;">$2</ul>', $text);
1508                         $text = preg_replace("/\[list=((?-i)a)\](.*?)\[\/list\]/ism", '<ul class="listloweralpha" style="list-style-type: lower-alpha;">$2</ul>', $text);
1509                         $text = preg_replace("/\[list=((?-i)A)\](.*?)\[\/list\]/ism", '<ul class="listupperalpha" style="list-style-type: upper-alpha;">$2</ul>', $text);
1510                         $text = preg_replace("/\[ul\](.*?)\[\/ul\]/ism", '<ul class="listbullet" style="list-style-type: circle;">$1</ul>', $text);
1511                         $text = preg_replace("/\[ol\](.*?)\[\/ol\]/ism", '<ul class="listdecimal" style="list-style-type: decimal;">$1</ul>', $text);
1512                         $text = preg_replace("/\[li\](.*?)\[\/li\]/ism", '<li>$1</li>', $text);
1513                 }
1514
1515                 $text = preg_replace("/\[th\](.*?)\[\/th\]/sm", '<th>$1</th>', $text);
1516                 $text = preg_replace("/\[td\](.*?)\[\/td\]/sm", '<td>$1</td>', $text);
1517                 $text = preg_replace("/\[tr\](.*?)\[\/tr\]/sm", '<tr>$1</tr>', $text);
1518                 $text = preg_replace("/\[table\](.*?)\[\/table\]/sm", '<table>$1</table>', $text);
1519
1520                 $text = preg_replace("/\[table border=1\](.*?)\[\/table\]/sm", '<table border="1" >$1</table>', $text);
1521                 $text = preg_replace("/\[table border=0\](.*?)\[\/table\]/sm", '<table border="0" >$1</table>', $text);
1522
1523                 $text = str_replace('[hr]', '<hr />', $text);
1524
1525                 // This is actually executed in prepare_body()
1526
1527                 $text = str_replace('[nosmile]', '', $text);
1528
1529                 // Check for font change text
1530                 $text = preg_replace("/\[font=(.*?)\](.*?)\[\/font\]/sm", "<span style=\"font-family: $1;\">$2</span>", $text);
1531
1532                 // Declare the format for [code] layout
1533
1534                 $CodeLayout = '<code>$1</code>';
1535                 // Check for [code] text
1536                 $text = preg_replace("/\[code\](.*?)\[\/code\]/ism", "$CodeLayout", $text);
1537
1538                 // Declare the format for [spoiler] layout
1539                 $SpoilerLayout = '<blockquote class="spoiler">$1</blockquote>';
1540
1541                 // Check for [spoiler] text
1542                 // handle nested quotes
1543                 $endlessloop = 0;
1544                 while ((strpos($text, "[/spoiler]") !== false) && (strpos($text, "[spoiler]") !== false) && (++$endlessloop < 20)) {
1545                         $text = preg_replace("/\[spoiler\](.*?)\[\/spoiler\]/ism", "$SpoilerLayout", $text);
1546                 }
1547
1548                 // Check for [spoiler=Author] text
1549
1550                 $t_wrote = L10n::t('$1 wrote:');
1551
1552                 // handle nested quotes
1553                 $endlessloop = 0;
1554                 while ((strpos($text, "[/spoiler]")!== false)  && (strpos($text, "[spoiler=") !== false) && (++$endlessloop < 20)) {
1555                         $text = preg_replace("/\[spoiler=[\"\']*(.*?)[\"\']*\](.*?)\[\/spoiler\]/ism",
1556                                                  "<br /><strong class=".'"spoiler"'.">" . $t_wrote . "</strong><blockquote class=".'"spoiler"'.">$2</blockquote>",
1557                                                  $text);
1558                 }
1559
1560                 // Declare the format for [quote] layout
1561                 $QuoteLayout = '<blockquote>$1</blockquote>';
1562
1563                 // Check for [quote] text
1564                 // handle nested quotes
1565                 $endlessloop = 0;
1566                 while ((strpos($text, "[/quote]") !== false) && (strpos($text, "[quote]") !== false) && (++$endlessloop < 20)) {
1567                         $text = preg_replace("/\[quote\](.*?)\[\/quote\]/ism", "$QuoteLayout", $text);
1568                 }
1569
1570                 // Check for [quote=Author] text
1571
1572                 $t_wrote = L10n::t('$1 wrote:');
1573
1574                 // handle nested quotes
1575                 $endlessloop = 0;
1576                 while ((strpos($text, "[/quote]")!== false)  && (strpos($text, "[quote=") !== false) && (++$endlessloop < 20)) {
1577                         $text = preg_replace("/\[quote=[\"\']*(.*?)[\"\']*\](.*?)\[\/quote\]/ism",
1578                                                  "<p><strong class=".'"author"'.">" . $t_wrote . "</strong></p><blockquote>$2</blockquote>",
1579                                                  $text);
1580                 }
1581
1582
1583                 // [img=widthxheight]image source[/img]
1584                 $text = preg_replace_callback(
1585                         "/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism",
1586                         function ($matches) use ($simple_html) {
1587                                 if (strpos($matches[3], "data:image/") === 0) {
1588                                         return $matches[0];
1589                                 }
1590
1591                                 $matches[3] = self::proxyUrl($matches[3], $simple_html);
1592                                 return "[img=" . $matches[1] . "x" . $matches[2] . "]" . $matches[3] . "[/img]";
1593                         },
1594                         $text
1595                 );
1596
1597                 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '<img src="$3" style="width: $1px;" >', $text);
1598                 $text = preg_replace("/\[zmg\=([0-9]*)x([0-9]*)\](.*?)\[\/zmg\]/ism", '<img class="zrl" src="$3" style="width: $1px;" >', $text);
1599
1600                 $text = preg_replace_callback("/\[img\=([$URLSearchString]*)\](.*?)\[\/img\]/ism",
1601                         function ($matches) use ($simple_html) {
1602                                 $matches[1] = self::proxyUrl($matches[1], $simple_html);
1603                                 $matches[2] = htmlspecialchars($matches[2], ENT_COMPAT);
1604                                 return '<img src="' . $matches[1] . '" alt="' . $matches[2] . '">';
1605                         },
1606                         $text);
1607
1608                 // Images
1609                 // [img]pathtoimage[/img]
1610                 $text = preg_replace_callback(
1611                         "/\[img\](.*?)\[\/img\]/ism",
1612                         function ($matches) use ($simple_html) {
1613                                 if (strpos($matches[1], "data:image/") === 0) {
1614                                         return $matches[0];
1615                                 }
1616
1617                                 $matches[1] = self::proxyUrl($matches[1], $simple_html);
1618                                 return "[img]" . $matches[1] . "[/img]";
1619                         },
1620                         $text
1621                 );
1622
1623                 $text = preg_replace("/\[img\](.*?)\[\/img\]/ism", '<img src="$1" alt="' . L10n::t('Image/photo') . '" />', $text);
1624                 $text = preg_replace("/\[zmg\](.*?)\[\/zmg\]/ism", '<img src="$1" alt="' . L10n::t('Image/photo') . '" />', $text);
1625
1626                 // Shared content
1627                 $text = preg_replace_callback("/(.*?)\[share(.*?)\](.*?)\[\/share\]/ism",
1628                         function ($match) use ($simple_html) {
1629                                 return self::convertShare($match, $simple_html);
1630                         }, $text);
1631
1632                 $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);
1633                 $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);
1634                 //$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);
1635
1636                 // Try to Oembed
1637                 if ($try_oembed) {
1638                         $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);
1639                         $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);
1640
1641                         $text = preg_replace_callback("/\[video\](.*?)\[\/video\]/ism", $try_oembed_callback, $text);
1642                         $text = preg_replace_callback("/\[audio\](.*?)\[\/audio\]/ism", $try_oembed_callback, $text);
1643                 } else {
1644                         $text = preg_replace("/\[video\](.*?)\[\/video\]/ism",
1645                                                 '<a href="$1" target="_blank">$1</a>', $text);
1646                         $text = preg_replace("/\[audio\](.*?)\[\/audio\]/ism",
1647                                                 '<a href="$1" target="_blank">$1</a>', $text);
1648                 }
1649
1650                 // html5 video and audio
1651
1652
1653                 if ($try_oembed) {
1654                         $text = preg_replace("/\[iframe\](.*?)\[\/iframe\]/ism", '<iframe src="$1" width="' . $a->videowidth . '" height="' . $a->videoheight . '"><a href="$1">$1</a></iframe>', $text);
1655                 } else {
1656                         $text = preg_replace("/\[iframe\](.*?)\[\/iframe\]/ism", '<a href="$1">$1</a>', $text);
1657                 }
1658
1659                 // Youtube extensions
1660                 if ($try_oembed) {
1661                         $text = preg_replace_callback("/\[youtube\](https?:\/\/www.youtube.com\/watch\?v\=.*?)\[\/youtube\]/ism", $try_oembed_callback, $text);
1662                         $text = preg_replace_callback("/\[youtube\](www.youtube.com\/watch\?v\=.*?)\[\/youtube\]/ism", $try_oembed_callback, $text);
1663                         $text = preg_replace_callback("/\[youtube\](https?:\/\/youtu.be\/.*?)\[\/youtube\]/ism", $try_oembed_callback, $text);
1664                 }
1665
1666                 $text = preg_replace("/\[youtube\]https?:\/\/www.youtube.com\/watch\?v\=(.*?)\[\/youtube\]/ism", '[youtube]$1[/youtube]', $text);
1667                 $text = preg_replace("/\[youtube\]https?:\/\/www.youtube.com\/embed\/(.*?)\[\/youtube\]/ism", '[youtube]$1[/youtube]', $text);
1668                 $text = preg_replace("/\[youtube\]https?:\/\/youtu.be\/(.*?)\[\/youtube\]/ism", '[youtube]$1[/youtube]', $text);
1669
1670                 if ($try_oembed) {
1671                         $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);
1672                 } else {
1673                         $text = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
1674                                                 '<a href="https://www.youtube.com/watch?v=$1" target="_blank">https://www.youtube.com/watch?v=$1</a>', $text);
1675                 }
1676
1677                 if ($try_oembed) {
1678                         $text = preg_replace_callback("/\[vimeo\](https?:\/\/player.vimeo.com\/video\/[0-9]+).*?\[\/vimeo\]/ism", $try_oembed_callback, $text);
1679                         $text = preg_replace_callback("/\[vimeo\](https?:\/\/vimeo.com\/[0-9]+).*?\[\/vimeo\]/ism", $try_oembed_callback, $text);
1680                 }
1681
1682                 $text = preg_replace("/\[vimeo\]https?:\/\/player.vimeo.com\/video\/([0-9]+)(.*?)\[\/vimeo\]/ism", '[vimeo]$1[/vimeo]', $text);
1683                 $text = preg_replace("/\[vimeo\]https?:\/\/vimeo.com\/([0-9]+)(.*?)\[\/vimeo\]/ism", '[vimeo]$1[/vimeo]', $text);
1684
1685                 if ($try_oembed) {
1686                         $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);
1687                 } else {
1688                         $text = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
1689                                                 '<a href="https://vimeo.com/$1" target="_blank">https://vimeo.com/$1</a>', $text);
1690                 }
1691
1692                 // oembed tag
1693                 $text = OEmbed::BBCode2HTML($text);
1694
1695                 // Avoid triple linefeeds through oembed
1696                 $text = str_replace("<br style='clear:left'></span><br /><br />", "<br style='clear:left'></span><br />", $text);
1697
1698                 // If we found an event earlier, strip out all the event code and replace with a reformatted version.
1699                 // Replace the event-start section with the entire formatted event. The other bbcode is stripped.
1700                 // Summary (e.g. title) is required, earlier revisions only required description (in addition to
1701                 // start which is always required). Allow desc with a missing summary for compatibility.
1702
1703                 if ((x($ev, 'desc') || x($ev, 'summary')) && x($ev, 'start')) {
1704                         $sub = Event::getHTML($ev, $simple_html);
1705
1706                         $text = preg_replace("/\[event\-summary\](.*?)\[\/event\-summary\]/ism", '', $text);
1707                         $text = preg_replace("/\[event\-description\](.*?)\[\/event\-description\]/ism", '', $text);
1708                         $text = preg_replace("/\[event\-start\](.*?)\[\/event\-start\]/ism", $sub, $text);
1709                         $text = preg_replace("/\[event\-finish\](.*?)\[\/event\-finish\]/ism", '', $text);
1710                         $text = preg_replace("/\[event\-location\](.*?)\[\/event\-location\]/ism", '', $text);
1711                         $text = preg_replace("/\[event\-adjust\](.*?)\[\/event\-adjust\]/ism", '', $text);
1712                         $text = preg_replace("/\[event\-id\](.*?)\[\/event\-id\]/ism", '', $text);
1713                 }
1714
1715                 // Replace non graphical smilies for external posts
1716                 if ($simple_html) {
1717                         $text = Smilies::replace($text, false, true);
1718                 }
1719
1720                 // Replace inline code blocks
1721                 $text = preg_replace_callback("|(?!<br[^>]*>)<code>([^<]*)</code>(?!<br[^>]*>)|ism",
1722                         function ($match) use ($simple_html) {
1723                                 $return = '<key>' . $match[1] . '</key>';
1724                                 // Use <code> for Diaspora inline code blocks
1725                                 if ($simple_html === 3) {
1726                                         $return = '<code>' . $match[1] . '</code>';
1727                                 }
1728                                 return $return;
1729                         }
1730                 , $text);
1731
1732                 // Unhide all [noparse] contained bbtags unspacefying them
1733                 // and triming the [noparse] tag.
1734
1735                 $text = preg_replace_callback("/\[noparse\](.*?)\[\/noparse\]/ism", 'self::unescapeNoparseCallback', $text);
1736                 $text = preg_replace_callback("/\[nobb\](.*?)\[\/nobb\]/ism", 'self::unescapeNoparseCallback', $text);
1737                 $text = preg_replace_callback("/\[pre\](.*?)\[\/pre\]/ism", 'self::unescapeNoparseCallback', $text);
1738
1739                 /// @todo What is the meaning of these lines?
1740                 $text = preg_replace('/\[\&amp\;([#a-z0-9]+)\;\]/', '&$1;', $text);
1741                 $text = preg_replace('/\&\#039\;/', '\'', $text);
1742
1743                 // Currently deactivated, it made problems with " inside of alt texts.
1744                 //$text = preg_replace('/\&quot\;/', '"', $text);
1745
1746                 // fix any escaped ampersands that may have been converted into links
1747                 $text = preg_replace('/\<([^>]*?)(src|href)=(.*?)\&amp\;(.*?)\>/ism', '<$1$2=$3&$4>', $text);
1748
1749                 // sanitizes src attributes (http and redir URLs for displaying in a web page, cid used for inline images in emails)
1750                 $allowed_src_protocols = ['http', 'redir', 'cid'];
1751                 $text = preg_replace('#<([^>]*?)(src)="(?!' . implode('|', $allowed_src_protocols) . ')(.*?)"(.*?)>#ism',
1752                                          '<$1$2=""$4 data-original-src="$3" class="invalid-src" title="' . L10n::t('Invalid source protocol') . '">', $text);
1753
1754                 // sanitize href attributes (only whitelisted protocols URLs)
1755                 // default value for backward compatibility
1756                 $allowed_link_protocols = Config::get('system', 'allowed_link_protocols', ['ftp', 'mailto', 'gopher', 'cid']);
1757
1758                 // Always allowed protocol even if config isn't set or not including it
1759                 $allowed_link_protocols[] = 'http';
1760                 $allowed_link_protocols[] = 'redir/';
1761
1762                 $regex = '#<([^>]*?)(href)="(?!' . implode('|', $allowed_link_protocols) . ')(.*?)"(.*?)>#ism';
1763                 $text = preg_replace($regex, '<$1$2="javascript:void(0)"$4 data-original-href="$3" class="invalid-href" title="' . L10n::t('Invalid link protocol') . '">', $text);
1764
1765                 if ($saved_image) {
1766                         $text = self::interpolateSavedImagesIntoItemBody($text, $saved_image);
1767                 }
1768
1769                 // Restore code blocks
1770                 $text = preg_replace_callback('/#codeblock-([0-9]+)#/iU',
1771                         function ($matches) use ($codeblocks) {
1772                                 $return = $matches[0];
1773                                 if (isset($codeblocks[intval($matches[1])])) {
1774                                         $return = $codeblocks[$matches[1]];
1775                                 }
1776                                 return $return;
1777                         },
1778                         $text
1779                 );
1780
1781                 // Clean up the HTML by loading and saving the HTML with the DOM.
1782                 // Bad structured html can break a whole page.
1783                 // For performance reasons do it only with ativated item cache or at export.
1784                 if (!$try_oembed || (get_itemcachepath() != "")) {
1785                         $doc = new DOMDocument();
1786                         $doc->preserveWhiteSpace = false;
1787
1788                         $text = mb_convert_encoding($text, 'HTML-ENTITIES', "UTF-8");
1789
1790                         $doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">';
1791                         $encoding = '<?xml encoding="UTF-8">';
1792                         @$doc->loadHTML($encoding.$doctype."<html><body>".$text."</body></html>");
1793                         $doc->encoding = 'UTF-8';
1794                         $text = $doc->saveHTML();
1795                         $text = str_replace(["<html><body>", "</body></html>", $doctype, $encoding], ["", "", "", ""], $text);
1796
1797                         $text = str_replace('<br></li>', '</li>', $text);
1798
1799                         //$Text = mb_convert_encoding($Text, "UTF-8", 'HTML-ENTITIES');
1800                 }
1801
1802                 // Clean up some useless linebreaks in lists
1803                 //$Text = str_replace('<br /><ul', '<ul ', $Text);
1804                 //$Text = str_replace('</ul><br />', '</ul>', $Text);
1805                 //$Text = str_replace('</li><br />', '</li>', $Text);
1806                 //$Text = str_replace('<br /><li>', '<li>', $Text);
1807                 //$Text = str_replace('<br /><ul', '<ul ', $Text);
1808
1809                 Addon::callHooks('bbcode', $text);
1810
1811                 return trim($text);
1812         }
1813
1814         /**
1815          * @brief Strips the "abstract" tag from the provided text
1816          *
1817          * @param string $text The text with BBCode
1818          * @return string The same text - but without "abstract" element
1819          */
1820         public static function stripAbstract($text)
1821         {
1822                 $text = preg_replace("/[\s|\n]*\[abstract\].*?\[\/abstract\][\s|\n]*/ism", '', $text);
1823                 $text = preg_replace("/[\s|\n]*\[abstract=.*?\].*?\[\/abstract][\s|\n]*/ism", '', $text);
1824
1825                 return $text;
1826         }
1827
1828         /**
1829          * @brief Returns the value of the "abstract" element
1830          *
1831          * @param string $text The text that maybe contains the element
1832          * @param string $addon The addon for which the abstract is meant for
1833          * @return string The abstract
1834          */
1835         public static function getAbstract($text, $addon = "")
1836         {
1837                 $abstract = "";
1838                 $abstracts = [];
1839                 $addon = strtolower($addon);
1840
1841                 if (preg_match_all("/\[abstract=(.*?)\](.*?)\[\/abstract\]/ism", $text, $results, PREG_SET_ORDER)) {
1842                         foreach ($results AS $result) {
1843                                 $abstracts[strtolower($result[1])] = $result[2];
1844                         }
1845                 }
1846
1847                 if (isset($abstracts[$addon])) {
1848                         $abstract = $abstracts[$addon];
1849                 }
1850
1851                 if ($abstract == "" && preg_match("/\[abstract\](.*?)\[\/abstract\]/ism", $text, $result)) {
1852                         $abstract = $result[1];
1853                 }
1854
1855                 return $abstract;
1856         }
1857
1858         /**
1859          * @brief Callback function to replace a Friendica style mention in a mention for Diaspora
1860          *
1861          * @param array $match Matching values for the callback
1862          * @return string Replaced mention
1863          */
1864         private static function bbCodeMention2DiasporaCallback($match)
1865         {
1866                 $contact = Contact::getDetailsByURL($match[3]);
1867
1868                 if (empty($contact['addr'])) {
1869                         $contact = Probe::uri($match[3]);
1870                 }
1871
1872                 if (empty($contact['addr'])) {
1873                         return $match[0];
1874                 }
1875
1876                 $mention = '@{' . $match[2] . '; ' . $contact['addr'] . '}';
1877                 return $mention;
1878         }
1879
1880         /**
1881          * @brief Converts a BBCode text into Markdown
1882          *
1883          * This function converts a BBCode item body to be sent to Markdown-enabled
1884          * systems like Diaspora and Libertree
1885          *
1886          * @param string $text
1887          * @param bool   $for_diaspora Diaspora requires more changes than Libertree
1888          * @return string
1889          */
1890         public static function toMarkdown($text, $for_diaspora = true)
1891         {
1892                 $a = self::getApp();
1893
1894                 $original_text = $text;
1895
1896                 // Since Diaspora is creating a summary for links, this function removes them before posting
1897                 if ($for_diaspora) {
1898                         $text = self::removeShareInformation($text);
1899                 }
1900
1901                 /**
1902                  * Transform #tags, strip off the [url] and replace spaces with underscore
1903                  */
1904                 $url_search_string = "^\[\]";
1905                 $text = preg_replace_callback("/#\[url\=([$url_search_string]*)\](.*?)\[\/url\]/i",
1906                         function ($matches) {
1907                                 return '#' . str_replace(' ', '_', $matches[2]);
1908                         },
1909                         $text
1910                 );
1911
1912                 // Converting images with size parameters to simple images. Markdown doesn't know it.
1913                 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
1914
1915                 // Convert it to HTML - don't try oembed
1916                 if ($for_diaspora) {
1917                         $text = self::convert($text, false, 3);
1918
1919                         // Add all tags that maybe were removed
1920                         if (preg_match_all("/#\[url\=([$url_search_string]*)\](.*?)\[\/url\]/ism", $original_text, $tags)) {
1921                                 $tagline = "";
1922                                 foreach ($tags[2] as $tag) {
1923                                         $tag = html_entity_decode($tag, ENT_QUOTES, 'UTF-8');
1924                                         if (!strpos(html_entity_decode($text, ENT_QUOTES, 'UTF-8'), '#' . $tag)) {
1925                                                 $tagline .= '#' . $tag . ' ';
1926                                         }
1927                                 }
1928                                 $text = $text . " " . $tagline;
1929                         }
1930                 } else {
1931                         $text = self::convert($text, false, 4);
1932                 }
1933
1934                 // mask some special HTML chars from conversation to markdown
1935                 $text = str_replace(['&lt;', '&gt;', '&amp;'], ['&_lt_;', '&_gt_;', '&_amp_;'], $text);
1936
1937                 // If a link is followed by a quote then there should be a newline before it
1938                 // Maybe we should make this newline at every time before a quote.
1939                 $text = str_replace(["</a><blockquote>"], ["</a><br><blockquote>"], $text);
1940
1941                 $stamp1 = microtime(true);
1942
1943                 // Now convert HTML to Markdown
1944                 $text = HTML::toMarkdown($text);
1945
1946                 // unmask the special chars back to HTML
1947                 $text = str_replace(['&\_lt\_;', '&\_gt\_;', '&\_amp\_;'], ['&lt;', '&gt;', '&amp;'], $text);
1948
1949                 $a->saveTimestamp($stamp1, "parser");
1950
1951                 // Libertree has a problem with escaped hashtags.
1952                 $text = str_replace(['\#'], ['#'], $text);
1953
1954                 // Remove any leading or trailing whitespace, as this will mess up
1955                 // the Diaspora signature verification and cause the item to disappear
1956                 $text = trim($text);
1957
1958                 if ($for_diaspora) {
1959                         $url_search_string = "^\[\]";
1960                         $text = preg_replace_callback(
1961                                 "/([@]\[(.*?)\])\(([$url_search_string]*?)\)/ism",
1962                                 ['self', 'bbCodeMention2DiasporaCallback'],
1963                                 $text
1964                         );
1965                 }
1966
1967                 Addon::callHooks('bb2diaspora', $text);
1968
1969                 return $text;
1970         }
1971 }