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