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