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