]> git.mxchange.org Git - friendica.git/blob - include/bbcode.php
Merge pull request #4191 from MrPetovan/bug/4173-fix-oembed-iframe-url
[friendica.git] / include / bbcode.php
1 <?php
2
3 use Friendica\App;
4 use Friendica\Content\Smilies;
5 use Friendica\Content\OEmbed;
6 use Friendica\Core\Cache;
7 use Friendica\Core\System;
8 use Friendica\Core\Config;
9 use Friendica\Model\Contact;
10 use Friendica\Util\Map;
11
12 require_once 'include/event.php';
13 require_once 'mod/proxy.php';
14 require_once 'include/plaintext.php';
15
16 function bb_PictureCacheExt($matches) {
17         if (strpos($matches[3], "data:image/") === 0) {
18                 return $matches[0];
19         }
20
21         $matches[3] = proxy_url($matches[3]);
22         return "[img=" . $matches[1] . "x" . $matches[2] . "]" . $matches[3] . "[/img]";
23 }
24
25 function bb_PictureCache($matches) {
26         if (strpos($matches[1], "data:image/") === 0) {
27                 return $matches[0];
28         }
29
30         $matches[1] = proxy_url($matches[1]);
31         return "[img]" . $matches[1] . "[/img]";
32 }
33
34 function bb_map_coords($match) {
35         // the extra space in the following line is intentional
36         return str_replace($match[0], '<div class="map"  >' . Map::byCoordinates(str_replace('/', ' ', $match[1])) . '</div>', $match[0]);
37 }
38 function bb_map_location($match) {
39         // the extra space in the following line is intentional
40         return str_replace($match[0], '<div class="map"  >' . Map::byLocation($match[1]) . '</div>', $match[0]);
41 }
42
43 /**
44  * Processes [attachment] tags
45  *
46  * Note: Can produce a [bookmark] tag in the returned string
47  *
48  * @brief Processes [attachment] tags
49  * @param string $return
50  * @param bool|int $simplehtml
51  * @param bool $tryoembed
52  * @return string
53  */
54 function bb_attachment($return, $simplehtml = false, $tryoembed = true)
55 {
56         $data = get_attachment_data($return);
57         if (!$data) {
58                 return $return;
59         }
60
61         if (isset($data["title"])) {
62                 $data["title"] = strip_tags($data["title"]);
63                 $data["title"] = str_replace(array("http://", "https://"), "", $data["title"]);
64         }
65
66         if (((strpos($data["text"], "[img=") !== false) || (strpos($data["text"], "[img]") !== false) || Config::get('system', 'always_show_preview')) && ($data["image"] != "")) {
67                 $data["preview"] = $data["image"];
68                 $data["image"] = "";
69         }
70
71         $return = '';
72         if ($simplehtml == 7) {
73                 $return = style_url_for_mastodon($data["url"]);
74         } elseif (($simplehtml != 4) && ($simplehtml != 0)) {
75                 $return = sprintf('<a href="%s" target="_blank">%s</a><br>', $data["url"], $data["title"]);
76         } else {
77                 try {
78                         if ($tryoembed) {
79                                 $return = OEmbed::getHTML($data['url'], $data['title']);
80                         } else {
81                                 throw new Exception('OEmbed is disabled for this attachment.');
82                         }
83                 } catch (Exception $e) {
84                         if ($simplehtml != 4) {
85                                 $return = sprintf('<span class="type-%s">', $data["type"]);
86                         }
87
88                         if ($data["image"] != "") {
89                                 $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"]);
90                         } elseif ($data["preview"] != "") {
91                                 $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"]);
92                         }
93
94                         if (($data["type"] == "photo") && ($data["url"] != "") && ($data["image"] != "")) {
95                                 $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"]);
96                         } else {
97                                 $return .= sprintf('[bookmark=%s]%s[/bookmark]', $data['url'], $data['title']);
98                         }
99
100                         if (trim($data["description"]) != "") {
101                                 $return .= sprintf('<blockquote>%s</blockquote>', trim(bbcode($data["description"])));
102                         }
103
104                         if ($simplehtml != 4) {
105                                 $return .= '</span>';
106                         }
107                 }
108         }
109
110         return trim($data["text"] . ' ' . $return . ' ' . $data["after"]);
111 }
112
113 function bb_remove_share_information($Text, $plaintext = false, $nolink = false) {
114
115         $data = get_attachment_data($Text);
116
117         if (!$data) {
118                 return $Text;
119         } elseif ($nolink) {
120                 return $data["text"] . $data["after"];
121         }
122
123         $title = htmlentities($data["title"], ENT_QUOTES, 'UTF-8', false);
124         $text = htmlentities($data["text"], ENT_QUOTES, 'UTF-8', false);
125         if ($plaintext || (($title != "") && strstr($text, $title))) {
126                 $data["title"] = $data["url"];
127         } elseif (($text != "") && strstr($title, $text)) {
128                 $data["text"] = $data["title"];
129                 $data["title"] = $data["url"];
130         }
131
132         if (($data["text"] == "") && ($data["title"] != "") && ($data["url"] == "")) {
133                 return $data["title"] . $data["after"];
134         }
135
136         // If the link already is included in the post, don't add it again
137         if (($data["url"] != "") && strpos($data["text"], $data["url"])) {
138                 return $data["text"] . $data["after"];
139         }
140
141         $text = $data["text"];
142
143         if (($data["url"] != "") && ($data["title"] != "")) {
144                 $text .= "\n[url=" . $data["url"] . "]" . $data["title"] . "[/url]";
145         } elseif (($data["url"] != "")) {
146                 $text .= "\n" . $data["url"];
147         }
148
149         return $text . "\n" . $data["after"];
150 }
151
152 function bb_cleanstyle($st) {
153         return "<span style=\"" . cleancss($st[1]) . ";\">" . $st[2] . "</span>";
154 }
155
156 function bb_cleanclass($st) {
157         return "<span class=\"" . cleancss($st[1]) . "\">" . $st[2] . "</span>";
158 }
159
160 function cleancss($input) {
161
162         $cleaned = "";
163
164         $input = strtolower($input);
165
166         for ($i = 0; $i < strlen($input); $i++) {
167                 $char = substr($input, $i, 1);
168
169                 if (($char >= "a") && ($char <= "z")) {
170                         $cleaned .= $char;
171                 }
172
173                 if (!(strpos(" #;:0123456789-_.%", $char) === false)) {
174                         $cleaned .= $char;
175                 }
176         }
177
178         return $cleaned;
179 }
180
181 /**
182  * @brief Converts [url] BBCodes in a format that looks fine on Mastodon. (callback function)
183  * @param array $match Array with the matching values
184  * @return string reformatted link including HTML codes
185  */
186 function bb_style_url($match) {
187         $url = $match[1];
188
189         if (isset($match[2]) && ($match[1] != $match[2])) {
190                 return $match[0];
191         }
192
193         $parts = parse_url($url);
194         if (!isset($parts['scheme'])) {
195                 return $match[0];
196         }
197
198         return style_url_for_mastodon($url);
199 }
200
201 /**
202  * @brief Converts [url] BBCodes in a format that looks fine on Mastodon and GNU Social.
203  * @param string $url URL that is about to be reformatted
204  * @return string reformatted link including HTML codes
205  */
206 function style_url_for_mastodon($url) {
207         $styled_url = $url;
208
209         $parts = parse_url($url);
210         $scheme = $parts['scheme'].'://';
211         $styled_url = str_replace($scheme, '', $styled_url);
212
213         $html = '<a href="%s" class="attachment" rel="nofollow noopener" target="_blank">'.
214                  '<span class="invisible">%s</span>';
215
216         if (strlen($styled_url) > 30) {
217                 $html .= '<span class="ellipsis">%s</span>'.
218                         '<span class="invisible">%s</span></a>';
219
220                 $ellipsis = substr($styled_url, 0, 30);
221                 $rest = substr($styled_url, 30);
222                 return sprintf($html, $url, $scheme, $ellipsis, $rest);
223         } else {
224                 $html .= '%s</a>';
225                 return sprintf($html, $url, $scheme, $styled_url);
226         }
227 }
228
229 function stripcode_br_cb($s) {
230         return '[code]' . str_replace('<br />', '', $s[1]) . '[/code]';
231 }
232
233 /*
234  * [noparse][i]italic[/i][/noparse] turns into
235  * [noparse][ i ]italic[ /i ][/noparse],
236  * to hide them from parser.
237  */
238 function bb_spacefy($st) {
239         $whole_match = $st[0];
240         $captured = $st[1];
241         $spacefied = preg_replace("/\[(.*?)\]/", "[ $1 ]", $captured);
242         $new_str = str_replace($captured, $spacefied, $whole_match);
243         return $new_str;
244 }
245
246 /*
247  * The previously spacefied [noparse][ i ]italic[ /i ][/noparse],
248  * now turns back and the [noparse] tags are trimed
249  * returning [i]italic[/i]
250  */
251 function bb_unspacefy_and_trim($st) {
252         $captured = $st[1];
253         $unspacefied = preg_replace("/\[ (.*?)\ ]/", "[$1]", $captured);
254         return $unspacefied;
255 }
256
257 function bb_find_open_close($s, $open, $close, $occurence = 1) {
258         if ($occurence < 1) {
259                 $occurence = 1;
260         }
261
262         $start_pos = -1;
263         for ($i = 1; $i <= $occurence; $i++) {
264                 if ($start_pos !== false) {
265                         $start_pos = strpos($s, $open, $start_pos + 1);
266                 }
267         }
268
269         if ($start_pos === false) {
270                 return false;
271         }
272
273         $end_pos = strpos($s, $close, $start_pos);
274
275         if ($end_pos === false) {
276                 return false;
277         }
278
279         $res = array( 'start' => $start_pos, 'end' => $end_pos );
280
281         return $res;
282 }
283
284 function get_bb_tag_pos($s, $name, $occurence = 1) {
285         if ($occurence < 1) {
286                 $occurence = 1;
287         }
288
289         $start_open = -1;
290         for ($i = 1; $i <= $occurence; $i++) {
291                 if ($start_open !== false) {
292                         $start_open = strpos($s, '[' . $name, $start_open + 1); // allow [name= type tags
293                 }
294         }
295
296         if ($start_open === false) {
297                 return false;
298         }
299
300         $start_equal = strpos($s, '=', $start_open);
301         $start_close = strpos($s, ']', $start_open);
302
303         if ($start_close === false) {
304                 return false;
305         }
306
307         $start_close++;
308
309         $end_open = strpos($s, '[/' . $name . ']', $start_close);
310
311         if ($end_open === false) {
312                 return false;
313         }
314
315         $res = array(
316                 'start' => array(
317                         'open'  => $start_open,
318                         'close' => $start_close
319                 ),
320                 'end'   => array(
321                         'open'  => $end_open,
322                         'close' => $end_open + strlen('[/' . $name . ']')
323                 ),
324         );
325
326         if ($start_equal !== false) {
327                 $res['start']['equal'] = $start_equal + 1;
328         }
329
330         return $res;
331 }
332
333 function bb_tag_preg_replace($pattern, $replace, $name, $s) {
334
335         $string = $s;
336
337         $occurence = 1;
338         $pos = get_bb_tag_pos($string, $name, $occurence);
339         while ($pos !== false && $occurence < 1000) {
340                 $start = substr($string, 0, $pos['start']['open']);
341                 $subject = substr($string, $pos['start']['open'], $pos['end']['close'] - $pos['start']['open']);
342                 $end = substr($string, $pos['end']['close']);
343                 if ($end === false) {
344                         $end = '';
345                 }
346
347                 $subject = preg_replace($pattern, $replace, $subject);
348                 $string = $start . $subject . $end;
349
350                 $occurence++;
351                 $pos = get_bb_tag_pos($string, $name, $occurence);
352         }
353
354         return $string;
355 }
356
357 function bb_extract_images($body) {
358
359         $saved_image = array();
360         $orig_body = $body;
361         $new_body = '';
362
363         $cnt = 0;
364         $img_start = strpos($orig_body, '[img');
365         $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
366         $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
367         while (($img_st_close !== false) && ($img_end !== false)) {
368
369                 $img_st_close++; // make it point to AFTER the closing bracket
370                 $img_end += $img_start;
371
372                 if (! strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
373                         // This is an embedded image
374
375                         $saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close));
376                         $new_body = $new_body . substr($orig_body, 0, $img_start) . '[$#saved_image' . $cnt . '#$]';
377
378                         $cnt++;
379                 } else {
380                         $new_body = $new_body . substr($orig_body, 0, $img_end + strlen('[/img]'));
381                 }
382
383                 $orig_body = substr($orig_body, $img_end + strlen('[/img]'));
384
385                 if ($orig_body === false) {
386                         // in case the body ends on a closing image tag
387                         $orig_body = '';
388                 }
389
390                 $img_start = strpos($orig_body, '[img');
391                 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
392                 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
393         }
394
395         $new_body = $new_body . $orig_body;
396
397         return array('body' => $new_body, 'images' => $saved_image);
398 }
399
400 function bb_replace_images($body, $images) {
401
402         $newbody = $body;
403
404         $cnt = 0;
405         foreach ($images as $image) {
406                 // We're depending on the property of 'foreach' (specified on the PHP website) that
407                 // it loops over the array starting from the first element and going sequentially
408                 // to the last element
409                 $newbody = str_replace('[$#saved_image' . $cnt . '#$]', '<img src="' . proxy_url($image) .'" alt="' . t('Image/photo') . '" />', $newbody);
410                 $cnt++;
411         }
412
413         return $newbody;
414 }
415
416 /**
417  * Processes [share] tags
418  *
419  * Note: Can produce a [bookmark] tag in the output
420  *
421  * @brief Processes [share] tags
422  * @param array    $share      preg_match_callback result array
423  * @param bool|int $simplehtml
424  * @return string
425  */
426 function bb_ShareAttributes($share, $simplehtml)
427 {
428         $attributes = $share[2];
429
430         $author = "";
431         preg_match("/author='(.*?)'/ism", $attributes, $matches);
432         if (x($matches, 1)) {
433                 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
434         }
435
436         preg_match('/author="(.*?)"/ism', $attributes, $matches);
437         if (x($matches, 1)) {
438                 $author = $matches[1];
439         }
440
441         $profile = "";
442         preg_match("/profile='(.*?)'/ism", $attributes, $matches);
443         if (x($matches, 1)) {
444                 $profile = $matches[1];
445         }
446
447         preg_match('/profile="(.*?)"/ism', $attributes, $matches);
448         if (x($matches, 1)) {
449                 $profile = $matches[1];
450         }
451
452         $avatar = "";
453         preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
454         if (x($matches, 1)) {
455                 $avatar = $matches[1];
456         }
457
458         preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
459         if (x($matches, 1)) {
460                 $avatar = $matches[1];
461         }
462
463         $link = "";
464         preg_match("/link='(.*?)'/ism", $attributes, $matches);
465         if (x($matches, 1)) {
466                 $link = $matches[1];
467         }
468
469         preg_match('/link="(.*?)"/ism', $attributes, $matches);
470         if (x($matches, 1)) {
471                 $link = $matches[1];
472         }
473
474         $posted = "";
475
476         preg_match("/posted='(.*?)'/ism", $attributes, $matches);
477         if (x($matches, 1)) {
478                 $posted = $matches[1];
479         }
480
481         preg_match('/posted="(.*?)"/ism', $attributes, $matches);
482         if (x($matches, 1)) {
483                 $posted = $matches[1];
484         }
485
486         // We only call this so that a previously unknown contact can be added.
487         // This is important for the function "get_contact_details_by_url".
488         // This function then can fetch an entry from the contact table.
489         Contact::getIdForURL($profile, 0);
490
491         $data = Contact::getDetailsByURL($profile);
492
493         if (x($data, "name") && x($data, "addr")) {
494                 $userid_compact = $data["name"] . " (" . $data["addr"] . ")";
495         } else {
496                 $userid_compact = GetProfileUsername($profile, $author, true);
497         }
498
499         if (x($data, "addr")) {
500                 $userid = $data["addr"];
501         } else {
502                 $userid = GetProfileUsername($profile, $author, false);
503         }
504
505         if (x($data, "name")) {
506                 $author = $data["name"];
507         }
508
509         if (x($data, "micro")) {
510                 $avatar = $data["micro"];
511         }
512
513         $preshare = trim($share[1]);
514         if ($preshare != "") {
515                 $preshare .= "<br />";
516         }
517
518         switch ($simplehtml) {
519                 case 1:
520                         $text = $preshare . html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8') . ' <a href="' . $profile . '">' . $userid . "</a>: <br />»" . $share[3] . "«";
521                         break;
522                 case 2:
523                         $text = $preshare . html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8') . ' ' . $userid_compact . ": <br />" . $share[3];
524                         break;
525                 case 3: // Diaspora
526                         $headline .= '<b>' . html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8') . $userid . ':</b><br />';
527
528                         $text = trim($share[1]);
529
530                         if ($text != "") {
531                                 $text .= "<hr />";
532                         }
533
534                         if (stripos(normalise_link($link), 'http://twitter.com/') === 0) {
535                                 $text .= $headline . '<blockquote>' . trim($share[3]) . "</blockquote><br />";
536
537                                 if ($link != "") {
538                                         $text .= '<br /><a href="' . $link . '">[l]</a>';
539                                 }
540                         } else {
541                                 $text .= '<br /><a href="' . $link . '">' . $link . '</a>';
542                         }
543
544                         break;
545                 case 4:
546                         $headline .= '<br /><b>' . html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8');
547                         $headline .= t('<a href="%1$s" target="_blank">%2$s</a> %3$s', $link, $userid, $posted);
548                         $headline .= ":</b><br />";
549
550                         $text = trim($share[1]);
551
552                         if ($text != "") {
553                                 $text .= "<hr />";
554                         }
555
556                         $text .= $headline . '<blockquote class="shared_content">' . trim($share[3]) . "</blockquote><br />";
557
558                         break;
559                 case 5:
560                         $text = $preshare . html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8') . ' ' . $userid_compact . ": <br />" . $share[3];
561                         break;
562                 case 6: // app.net
563                         $text = $preshare . "&gt;&gt; @" . $userid_compact . ": <br />" . $share[3];
564                         break;
565                 case 7: // statusnet/GNU Social
566                         $text = $preshare . html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8') . " @" . $userid_compact . ": " . $share[3];
567                         break;
568                 case 8: // twitter
569                         $text = $preshare . "RT @" . $userid_compact . ": " . $share[3];
570                         break;
571                 case 9: // Google+/Facebook
572                         $text = $preshare . html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8') . ' ' . $userid_compact . ": <br />" . $share[3];
573
574                         if ($link != "") {
575                                 $text .= "<br /><br />" . $link;
576                         }
577                         break;
578                 default:
579                         // Transforms quoted tweets in rich attachments to avoid nested tweets
580                         if (stripos(normalise_link($link), 'http://twitter.com/') === 0 && OEmbed::isAllowedURL($link)) {
581                                 try {
582                                         $oembed = OEmbed::getHTML($link, $preshare);
583                                 } catch (Exception $e) {
584                                         $oembed = sprintf('[bookmark=%s]%s[/bookmark]', $link, $preshare);
585                                 }
586
587                                 $text = $preshare . $oembed;
588                         } else {
589                                 $text = trim($share[1]) . "\n";
590
591                                 $avatar = proxy_url($avatar, false, PROXY_SIZE_THUMB);
592
593                                 $tpl = get_markup_template('shared_content.tpl');
594                                 $text .= replace_macros($tpl, array(
595                                         '$profile' => $profile,
596                                         '$avatar' => $avatar,
597                                         '$author' => $author,
598                                         '$link' => $link,
599                                         '$posted' => $posted,
600                                         '$content' => trim($share[3])
601                                 ));
602                         }
603                         break;
604         }
605
606         return $text;
607 }
608
609 function GetProfileUsername($profile, $username, $compact = false, $getnetwork = false) {
610
611         $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1@twitter.com", $profile);
612         if ($twitter != $profile) {
613                 if ($getnetwork) {
614                         return NETWORK_TWITTER;
615                 } elseif ($compact) {
616                         return $twitter;
617                 } else {
618                         return ($username . " (" . $twitter . ")");
619                 }
620         }
621
622         $appnet = preg_replace("=https?://alpha.app.net/(.*)=ism", "$1@alpha.app.net", $profile);
623         if ($appnet != $profile) {
624                 if ($getnetwork) {
625                         return NETWORK_APPNET;
626                 } elseif ($compact) {
627                         return $appnet;
628                 } else {
629                         return ($username . " (" . $appnet . ")");
630                 }
631         }
632
633         $gplus = preg_replace("=https?://plus.google.com/(.*)=ism", "$1@plus.google.com", $profile);
634         if ($gplus != $profile) {
635                 if ($getnetwork) {
636                         return NETWORK_GPLUS;
637                 } elseif ($compact) {
638                         return ($gplususername . " (" . $username . ")");
639                 } else {
640                         return ($username . " (" . $gplus . ")");
641                 }
642         }
643
644         $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2@$1", $profile);
645         if ($friendica != $profile) {
646                 if ($getnetwork) {
647                         return NETWORK_DFRN;
648                 } elseif ($compact) {
649                         return $friendica;
650                 } else {
651                         return ($username . " (" . $friendica . ")");
652                 }
653         }
654
655         $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
656         if ($diaspora != $profile) {
657                 if ($getnetwork) {
658                         return NETWORK_DIASPORA;
659                 } elseif ($compact) {
660                         return $diaspora;
661                 } else {
662                         return ($username . " (" . $diaspora . ")");
663                 }
664         }
665
666         $red = preg_replace("=https?://(.*)/channel/(.*)=ism", "$2@$1", $profile);
667         if ($red != $profile) {
668                 if ($getnetwork) {
669                         // red is identified as Diaspora - friendica can't connect directly to it
670                         return NETWORK_DIASPORA;
671                 } elseif ($compact) {
672                         return $red;
673                 } else {
674                         return ($username . " (" . $red . ")");
675                 }
676         }
677
678         $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
679         if ($StatusnetHost != $profile) {
680                 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
681                 if ($StatusnetUser != $profile) {
682                         /// @TODO Some hosts run on https, not just http and sometimes http is disabled, let's support both here
683                         $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
684                         $user = json_decode($UserData);
685                         if ($user) {
686                                 if ($getnetwork) {
687                                         return NETWORK_STATUSNET;
688                                 } elseif ($compact) {
689                                         return ($user->screen_name . "@" . $StatusnetHost);
690                                 } else {
691                                         return ($username . " (" . $user->screen_name . "@" . $StatusnetHost . ")");
692                                 }
693                         }
694                 }
695         }
696
697         // pumpio (http://host.name/user)
698         $rest = preg_replace("=https?://([\.\w]+)/([\.\w]+)(.*)=ism", "$3", $profile);
699         if ($rest == "") {
700                 $pumpio = preg_replace("=https?://([\.\w]+)/([\.\w]+)(.*)=ism", "$2@$1", $profile);
701                 if ($pumpio != $profile) {
702                         if ($getnetwork) {
703                                 return NETWORK_PUMPIO;
704                         } elseif ($compact) {
705                                 return $pumpio;
706                         } else {
707                                 return ($username . " (" . $pumpio . ")");
708                         }
709                 }
710         }
711
712         return $username;
713 }
714
715 function bb_DiasporaLinks($match) {
716         return "[url=".System::baseUrl()."/display/".$match[1]."]".$match[2]."[/url]";
717 }
718
719 function bb_RemovePictureLinks($match) {
720         $text = Cache::get($match[1]);
721
722         if (is_null($text)) {
723                 $a = get_app();
724
725                 $stamp1 = microtime(true);
726
727                 $ch = @curl_init($match[1]);
728                 @curl_setopt($ch, CURLOPT_NOBODY, true);
729                 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
730                 @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
731                 @curl_exec($ch);
732                 $curl_info = @curl_getinfo($ch);
733
734                 $a->save_timestamp($stamp1, "network");
735
736                 if (substr($curl_info["content_type"], 0, 6) == "image/")
737                         $text = "[url=".$match[1]."]".$match[1]."[/url]";
738                 else {
739                         $text = "[url=".$match[2]."]".$match[2]."[/url]";
740
741                         // if its not a picture then look if its a page that contains a picture link
742                         require_once("include/network.php");
743
744                         $body = fetch_url($match[1]);
745
746                         $doc = new DOMDocument();
747                         @$doc->loadHTML($body);
748                         $xpath = new DomXPath($doc);
749                         $list = $xpath->query("//meta[@name]");
750                         foreach ($list as $node) {
751                                 $attr = array();
752
753                                 if ($node->attributes->length)
754                                         foreach ($node->attributes as $attribute)
755                                                 $attr[$attribute->name] = $attribute->value;
756
757                                 if (strtolower($attr["name"]) == "twitter:image")
758                                         $text = "[url=".$attr["content"]."]".$attr["content"]."[/url]";
759                         }
760                 }
761                 Cache::set($match[1],$text);
762         }
763
764         return $text;
765 }
766
767 function bb_expand_links($match) {
768         if (($match[3] == "") || ($match[2] == $match[3]) || stristr($match[2], $match[3])) {
769                 return ($match[1] . "[url]" . $match[2] . "[/url]");
770         } else {
771                 return ($match[1] . $match[3] . " [url]" . $match[2] . "[/url]");
772         }
773 }
774
775 function bb_CleanPictureLinksSub($match) {
776         $text = Cache::get($match[1]);
777
778         if (is_null($text)) {
779                 $a = get_app();
780
781                 $stamp1 = microtime(true);
782
783                 $ch = @curl_init($match[1]);
784                 @curl_setopt($ch, CURLOPT_NOBODY, true);
785                 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
786                 @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
787                 @curl_exec($ch);
788                 $curl_info = @curl_getinfo($ch);
789
790                 $a->save_timestamp($stamp1, "network");
791
792                 // if its a link to a picture then embed this picture
793                 if (substr($curl_info["content_type"], 0, 6) == "image/")
794                         $text = "[img]".$match[1]."[/img]";
795                 else {
796                         $text = "[img]".$match[2]."[/img]";
797
798                         // if its not a picture then look if its a page that contains a picture link
799                         require_once("include/network.php");
800
801                         $body = fetch_url($match[1]);
802
803                         $doc = new DOMDocument();
804                         @$doc->loadHTML($body);
805                         $xpath = new DomXPath($doc);
806                         $list = $xpath->query("//meta[@name]");
807                         foreach ($list as $node) {
808                                 $attr = array();
809
810                                 if ($node->attributes->length)
811                                         foreach ($node->attributes as $attribute)
812                                                 $attr[$attribute->name] = $attribute->value;
813
814                                 if (strtolower($attr["name"]) == "twitter:image")
815                                         $text = "[img]".$attr["content"]."[/img]";
816                         }
817                 }
818                 Cache::set($match[1],$text);
819         }
820
821         return $text;
822 }
823
824 function bb_CleanPictureLinks($text) {
825         $text = preg_replace_callback("&\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]&Usi", 'bb_CleanPictureLinksSub', $text);
826         return $text;
827 }
828
829 function bb_highlight($match) {
830         if (in_array(strtolower($match[1]), ['php', 'css', 'mysql', 'sql', 'abap', 'diff', 'html', 'perl', 'ruby',
831                 'vbscript', 'avrc', 'dtd', 'java', 'xml', 'cpp', 'python', 'javascript', 'js', 'sh'])) {
832                 return text_highlight($match[2], strtolower($match[1]));
833         }
834         return $match[0];
835 }
836
837 /**
838  * @brief Converts a BBCode message to HTML message
839  *
840  * BBcode 2 HTML was written by WAY2WEB.net
841  * extended to work with Mistpark/Friendica - Mike Macgirvin
842  *
843  * Simple HTML values meaning:
844  * - 0: Friendica display
845  * - 1: Unused
846  * - 2: Used for Facebook, Google+, Windows Phone push, Friendica API
847  * - 3: Used before converting to Markdown in bb2diaspora.php
848  * - 4: Used for WordPress, Libertree (before Markdown), pump.io and tumblr
849  * - 5: Unused
850  * - 6: Used for Appnet
851  * - 7: Used for dfrn, OStatus
852  * - 8: Used for WP backlink text setting
853  *
854  * @staticvar array $allowed_src_protocols
855  * @param string $Text
856  * @param bool $preserve_nl
857  * @param bool $tryoembed
858  * @param int $simplehtml
859  * @param bool $forplaintext
860  * @return string
861  */
862 function bbcode($Text, $preserve_nl = false, $tryoembed = true, $simplehtml = false, $forplaintext = false)
863 {
864         $a = get_app();
865
866         /*
867          * preg_match_callback function to replace potential Oembed tags with Oembed content
868          *
869          * $match[0] = [tag]$url[/tag] or [tag=$url]$title[/tag]
870          * $match[1] = $url
871          * $match[2] = $title or absent
872          */
873         $tryoembed_callback = function ($match)
874         {
875                 $url = $match[1];
876                 $title = defaults($match, 2, null);
877
878                 try {
879                         $return = OEmbed::getHTML($url, $title);
880                 } catch (Exception $ex) {
881                         $return = $match[0];
882                 }
883
884                 return $return;
885         };
886
887         // Hide all [noparse] contained bbtags by spacefying them
888         // POSSIBLE BUG --> Will the 'preg' functions crash if there's an embedded image?
889
890         $Text = preg_replace_callback("/\[noparse\](.*?)\[\/noparse\]/ism", 'bb_spacefy', $Text);
891         $Text = preg_replace_callback("/\[nobb\](.*?)\[\/nobb\]/ism", 'bb_spacefy', $Text);
892         $Text = preg_replace_callback("/\[pre\](.*?)\[\/pre\]/ism", 'bb_spacefy', $Text);
893
894         // Remove the abstract element. It is a non visible element.
895         $Text = remove_abstract($Text);
896
897         // Move all spaces out of the tags
898         $Text = preg_replace("/\[(\w*)\](\s*)/ism", '$2[$1]', $Text);
899         $Text = preg_replace("/(\s*)\[\/(\w*)\]/ism", '[/$2]$1', $Text);
900
901         // Extract the private images which use data urls since preg has issues with
902         // large data sizes. Stash them away while we do bbcode conversion, and then put them back
903         // in after we've done all the regex matching. We cannot use any preg functions to do this.
904
905         $extracted = bb_extract_images($Text);
906         $Text = $extracted['body'];
907         $saved_image = $extracted['images'];
908
909         // If we find any event code, turn it into an event.
910         // After we're finished processing the bbcode we'll
911         // replace all of the event code with a reformatted version.
912
913         $ev = bbtoevent($Text);
914
915         // Replace any html brackets with HTML Entities to prevent executing HTML or script
916         // Don't use strip_tags here because it breaks [url] search by replacing & with amp
917
918         $Text = str_replace("<", "&lt;", $Text);
919         $Text = str_replace(">", "&gt;", $Text);
920
921         // remove some newlines before the general conversion
922         $Text = preg_replace("/\s?\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "[share$1]$2[/share]", $Text);
923         $Text = preg_replace("/\s?\[quote(.*?)\]\s?(.*?)\s?\[\/quote\]\s?/ism", "[quote$1]$2[/quote]", $Text);
924
925         $Text = preg_replace("/\n\[code\]/ism", "[code]", $Text);
926         $Text = preg_replace("/\[\/code\]\n/ism", "[/code]", $Text);
927
928         // when the content is meant exporting to other systems then remove the avatar picture since this doesn't really look good on these systems
929         if (!$tryoembed) {
930                 $Text = preg_replace("/\[share(.*?)avatar\s?=\s?'.*?'\s?(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "\n[share$1$2]$3[/share]", $Text);
931         }
932
933         // Check for [code] text here, before the linefeeds are messed with.
934         // The highlighter will unescape and re-escape the content.
935         if (strpos($Text, '[code=') !== false) {
936                 $Text = preg_replace_callback("/\[code=(.*?)\](.*?)\[\/code\]/ism", 'bb_highlight', $Text);
937         }
938         // Convert new line chars to html <br /> tags
939
940         // nlbr seems to be hopelessly messed up
941         //      $Text = nl2br($Text);
942
943         // We'll emulate it.
944
945         $Text = trim($Text);
946         $Text = str_replace("\r\n", "\n", $Text);
947
948         // removing multiplicated newlines
949         if (Config::get("system", "remove_multiplicated_lines")) {
950                 $search = array("\n\n\n", "\n ", " \n", "[/quote]\n\n", "\n[/quote]", "[/li]\n", "\n[li]", "\n[ul]", "[/ul]\n", "\n\n[share ", "[/attachment]\n",
951                                 "\n[h1]", "[/h1]\n", "\n[h2]", "[/h2]\n", "\n[h3]", "[/h3]\n", "\n[h4]", "[/h4]\n", "\n[h5]", "[/h5]\n", "\n[h6]", "[/h6]\n");
952                 $replace = array("\n\n", "\n", "\n", "[/quote]\n", "[/quote]", "[/li]", "[li]", "[ul]", "[/ul]", "\n[share ", "[/attachment]",
953                                 "[h1]", "[/h1]", "[h2]", "[/h2]", "[h3]", "[/h3]", "[h4]", "[/h4]", "[h5]", "[/h5]", "[h6]", "[/h6]");
954                 do {
955                         $oldtext = $Text;
956                         $Text = str_replace($search, $replace, $Text);
957                 } while ($oldtext != $Text);
958         }
959
960         // Handle attached links or videos
961         $Text = bb_attachment($Text, $simplehtml, $tryoembed);
962
963         $Text = str_replace(array("\r","\n"), array('<br />', '<br />'), $Text);
964
965         if ($preserve_nl) {
966                 $Text = str_replace(array("\n", "\r"), array('', ''), $Text);
967         }
968
969         // Set up the parameters for a URL search string
970         $URLSearchString = "^\[\]";
971         // Set up the parameters for a MAIL search string
972         $MAILSearchString = $URLSearchString;
973
974         // Remove all hashtag addresses
975         if ((!$tryoembed || $simplehtml) && !in_array($simplehtml, array(3, 7))) {
976                 $Text = preg_replace("/([#@!])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
977         } elseif ($simplehtml == 3) {
978                 $Text = preg_replace("/([@!])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
979                         '$1<a href="$2">$3</a>',
980                         $Text);
981         } elseif ($simplehtml == 7) {
982                 $Text = preg_replace("/([@!])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
983                         '$1<span class="vcard"><a href="$2" class="url" title="$3"><span class="fn nickname mention">$3</span></a></span>',
984                         $Text);
985         } elseif (!$simplehtml) {
986                 $Text = preg_replace("/([@!])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
987                         '$1<a href="$2" class="userinfo mention" title="$3">$3</a>',
988                         $Text);
989         }
990
991         // Bookmarks in red - will be converted to bookmarks in friendica
992         $Text = preg_replace("/#\^\[url\]([$URLSearchString]*)\[\/url\]/ism", '[bookmark=$1]$1[/bookmark]', $Text);
993         $Text = preg_replace("/#\^\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[bookmark=$1]$2[/bookmark]', $Text);
994         $Text = preg_replace("/#\[url\=[$URLSearchString]*\]\^\[\/url\]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/i",
995                                 "[bookmark=$1]$2[/bookmark]", $Text);
996
997         if (in_array($simplehtml, array(2, 6, 7, 8, 9))) {
998                 $Text = preg_replace_callback("/([^#@!])\[url\=([^\]]*)\](.*?)\[\/url\]/ism", "bb_expand_links", $Text);
999                 //$Text = preg_replace("/[^#@!]\[url\=([^\]]*)\](.*?)\[\/url\]/ism", ' $2 [url]$1[/url]', $Text);
1000                 $Text = preg_replace("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", ' $2 [url]$1[/url]',$Text);
1001         }
1002
1003         if ($simplehtml == 5) {
1004                 $Text = preg_replace("/[^#@!]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url]$1[/url]', $Text);
1005         }
1006
1007         // Perform URL Search
1008         if ($tryoembed) {
1009                 $Text = preg_replace_callback("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $tryoembed_callback, $Text);
1010         }
1011
1012         if ($simplehtml == 5) {
1013                 $Text = preg_replace("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", '[url]$1[/url]', $Text);
1014         } else {
1015                 $Text = preg_replace("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $Text);
1016         }
1017
1018         // Handle Diaspora posts
1019         $Text = preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi", 'bb_DiasporaLinks', $Text);
1020
1021         // Server independent link to posts and comments
1022         // See issue: https://github.com/diaspora/diaspora_federation/issues/75
1023         $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1024         $Text = preg_replace($expression, System::baseUrl()."/display/$1", $Text);
1025
1026         // if the HTML is used to generate plain text, then don't do this search, but replace all URL of that kind to text
1027 //      if ($simplehtml != 7) {
1028                 if (!$forplaintext) {
1029                         if ($simplehtml != 7) {
1030                                 $Text = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1<a href="$2" target="_blank">$2</a>', $Text);
1031                         } else {
1032                                 $Text = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url]$2[/url]', $Text);
1033
1034                                 $Text = preg_replace_callback("/\[url\]([$URLSearchString]*)\[\/url\]/ism", 'bb_style_url', $Text);
1035                                 $Text = preg_replace_callback("/\[url\=([$URLSearchString]*)\]([$URLSearchString]*)\[\/url\]/ism", 'bb_style_url', $Text);
1036                         }
1037                 } else {
1038                         $Text = preg_replace("(\[url\]([$URLSearchString]*)\[\/url\])ism", " $1 ", $Text);
1039                         $Text = preg_replace_callback("&\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]&Usi", 'bb_RemovePictureLinks', $Text);
1040                 }
1041 //      }
1042
1043         if ($tryoembed) {
1044                 $Text = preg_replace_callback("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $tryoembed_callback, $Text);
1045         }
1046
1047         $Text = preg_replace("/([#])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1048                                 '$1<a href="$2" class="tag" title="$3">$3</a>', $Text);
1049
1050         $Text = preg_replace("/\[url\]([$URLSearchString]*)\[\/url\]/ism", '<a href="$1" target="_blank">$1</a>', $Text);
1051         $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '<a href="$1" target="_blank">$2</a>', $Text);
1052         //$Text = preg_replace("/\[url\=([$URLSearchString]*)\]([$URLSearchString]*)\[\/url\]/ism", '<a href="$1" target="_blank">$2</a>', $Text);
1053
1054         // Red compatibility, though the link can't be authenticated on Friendica
1055         $Text = preg_replace("/\[zrl\=([$URLSearchString]*)\](.*?)\[\/zrl\]/ism", '<a href="$1" target="_blank">$2</a>', $Text);
1056
1057
1058         // we may need to restrict this further if it picks up too many strays
1059         // link acct:user@host to a webfinger profile redirector
1060
1061         $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);
1062
1063         // Perform MAIL Search
1064         $Text = preg_replace("/\[mail\]([$MAILSearchString]*)\[\/mail\]/", '<a href="mailto:$1">$1</a>', $Text);
1065         $Text = preg_replace("/\[mail\=([$MAILSearchString]*)\](.*?)\[\/mail\]/", '<a href="mailto:$1">$2</a>', $Text);
1066
1067         // leave open the posibility of [map=something]
1068         // this is replaced in prepare_body() which has knowledge of the item location
1069
1070         if (strpos($Text, '[/map]') !== false) {
1071                 $Text = preg_replace_callback("/\[map\](.*?)\[\/map\]/ism", 'bb_map_location', $Text);
1072         }
1073         if (strpos($Text, '[map=') !== false) {
1074                 $Text = preg_replace_callback("/\[map=(.*?)\]/ism", 'bb_map_coords', $Text);
1075         }
1076         if (strpos($Text, '[map]') !== false) {
1077                 $Text = preg_replace("/\[map\]/", '<div class="map"></div>', $Text);
1078         }
1079
1080         // Check for headers
1081         $Text = preg_replace("(\[h1\](.*?)\[\/h1\])ism", '<h1>$1</h1>', $Text);
1082         $Text = preg_replace("(\[h2\](.*?)\[\/h2\])ism", '<h2>$1</h2>', $Text);
1083         $Text = preg_replace("(\[h3\](.*?)\[\/h3\])ism", '<h3>$1</h3>', $Text);
1084         $Text = preg_replace("(\[h4\](.*?)\[\/h4\])ism", '<h4>$1</h4>', $Text);
1085         $Text = preg_replace("(\[h5\](.*?)\[\/h5\])ism", '<h5>$1</h5>', $Text);
1086         $Text = preg_replace("(\[h6\](.*?)\[\/h6\])ism", '<h6>$1</h6>', $Text);
1087
1088         // Check for paragraph
1089         $Text = preg_replace("(\[p\](.*?)\[\/p\])ism", '<p>$1</p>', $Text);
1090
1091         // Check for bold text
1092         $Text = preg_replace("(\[b\](.*?)\[\/b\])ism", '<strong>$1</strong>', $Text);
1093
1094         // Check for Italics text
1095         $Text = preg_replace("(\[i\](.*?)\[\/i\])ism", '<em>$1</em>', $Text);
1096
1097         // Check for Underline text
1098         $Text = preg_replace("(\[u\](.*?)\[\/u\])ism", '<u>$1</u>', $Text);
1099
1100         // Check for strike-through text
1101         $Text = preg_replace("(\[s\](.*?)\[\/s\])ism", '<strike>$1</strike>', $Text);
1102
1103         // Check for over-line text
1104         $Text = preg_replace("(\[o\](.*?)\[\/o\])ism", '<span class="overline">$1</span>', $Text);
1105
1106         // Check for colored text
1107         $Text = preg_replace("(\[color=(.*?)\](.*?)\[\/color\])ism", "<span style=\"color: $1;\">$2</span>", $Text);
1108
1109         // Check for sized text
1110         // [size=50] --> font-size: 50px (with the unit).
1111         $Text = preg_replace("(\[size=(\d*?)\](.*?)\[\/size\])ism", "<span style=\"font-size: $1px; line-height: initial;\">$2</span>", $Text);
1112         $Text = preg_replace("(\[size=(.*?)\](.*?)\[\/size\])ism", "<span style=\"font-size: $1; line-height: initial;\">$2</span>", $Text);
1113
1114         // Check for centered text
1115         $Text = preg_replace("(\[center\](.*?)\[\/center\])ism", "<div style=\"text-align:center;\">$1</div>", $Text);
1116
1117         // Check for list text
1118         $Text = str_replace("[*]", "<li>", $Text);
1119
1120         // Check for style sheet commands
1121         $Text = preg_replace_callback("(\[style=(.*?)\](.*?)\[\/style\])ism", "bb_cleanstyle", $Text);
1122
1123         // Check for CSS classes
1124         $Text = preg_replace_callback("(\[class=(.*?)\](.*?)\[\/class\])ism", "bb_cleanclass", $Text);
1125
1126         // handle nested lists
1127         $endlessloop = 0;
1128
1129         while ((((strpos($Text, "[/list]") !== false) && (strpos($Text, "[list") !== false)) ||
1130                ((strpos($Text, "[/ol]") !== false) && (strpos($Text, "[ol]") !== false)) ||
1131                ((strpos($Text, "[/ul]") !== false) && (strpos($Text, "[ul]") !== false)) ||
1132                ((strpos($Text, "[/li]") !== false) && (strpos($Text, "[li]") !== false))) && (++$endlessloop < 20)) {
1133                 $Text = preg_replace("/\[list\](.*?)\[\/list\]/ism", '<ul class="listbullet" style="list-style-type: circle;">$1</ul>', $Text);
1134                 $Text = preg_replace("/\[list=\](.*?)\[\/list\]/ism", '<ul class="listnone" style="list-style-type: none;">$1</ul>', $Text);
1135                 $Text = preg_replace("/\[list=1\](.*?)\[\/list\]/ism", '<ul class="listdecimal" style="list-style-type: decimal;">$1</ul>', $Text);
1136                 $Text = preg_replace("/\[list=((?-i)i)\](.*?)\[\/list\]/ism", '<ul class="listlowerroman" style="list-style-type: lower-roman;">$2</ul>', $Text);
1137                 $Text = preg_replace("/\[list=((?-i)I)\](.*?)\[\/list\]/ism", '<ul class="listupperroman" style="list-style-type: upper-roman;">$2</ul>', $Text);
1138                 $Text = preg_replace("/\[list=((?-i)a)\](.*?)\[\/list\]/ism", '<ul class="listloweralpha" style="list-style-type: lower-alpha;">$2</ul>', $Text);
1139                 $Text = preg_replace("/\[list=((?-i)A)\](.*?)\[\/list\]/ism", '<ul class="listupperalpha" style="list-style-type: upper-alpha;">$2</ul>', $Text);
1140                 $Text = preg_replace("/\[ul\](.*?)\[\/ul\]/ism", '<ul class="listbullet" style="list-style-type: circle;">$1</ul>', $Text);
1141                 $Text = preg_replace("/\[ol\](.*?)\[\/ol\]/ism", '<ul class="listdecimal" style="list-style-type: decimal;">$1</ul>', $Text);
1142                 $Text = preg_replace("/\[li\](.*?)\[\/li\]/ism", '<li>$1</li>', $Text);
1143         }
1144
1145         $Text = preg_replace("/\[th\](.*?)\[\/th\]/sm", '<th>$1</th>', $Text);
1146         $Text = preg_replace("/\[td\](.*?)\[\/td\]/sm", '<td>$1</td>', $Text);
1147         $Text = preg_replace("/\[tr\](.*?)\[\/tr\]/sm", '<tr>$1</tr>', $Text);
1148         $Text = preg_replace("/\[table\](.*?)\[\/table\]/sm", '<table>$1</table>', $Text);
1149
1150         $Text = preg_replace("/\[table border=1\](.*?)\[\/table\]/sm", '<table border="1" >$1</table>', $Text);
1151         $Text = preg_replace("/\[table border=0\](.*?)\[\/table\]/sm", '<table border="0" >$1</table>', $Text);
1152
1153         $Text = str_replace('[hr]', '<hr />', $Text);
1154
1155         // This is actually executed in prepare_body()
1156
1157         $Text = str_replace('[nosmile]', '', $Text);
1158
1159         // Check for font change text
1160         $Text = preg_replace("/\[font=(.*?)\](.*?)\[\/font\]/sm", "<span style=\"font-family: $1;\">$2</span>", $Text);
1161
1162         // Declare the format for [code] layout
1163
1164 //      $Text = preg_replace_callback("/\[code\](.*?)\[\/code\]/ism", 'stripcode_br_cb', $Text);
1165
1166         $CodeLayout = '<code>$1</code>';
1167         // Check for [code] text
1168         $Text = preg_replace("/\[code\](.*?)\[\/code\]/ism", "$CodeLayout", $Text);
1169
1170         // Declare the format for [spoiler] layout
1171         $SpoilerLayout = '<blockquote class="spoiler">$1</blockquote>';
1172
1173         // Check for [spoiler] text
1174         // handle nested quotes
1175         $endlessloop = 0;
1176         while ((strpos($Text, "[/spoiler]") !== false) && (strpos($Text, "[spoiler]") !== false) && (++$endlessloop < 20)) {
1177                 $Text = preg_replace("/\[spoiler\](.*?)\[\/spoiler\]/ism", "$SpoilerLayout", $Text);
1178         }
1179
1180         // Check for [spoiler=Author] text
1181
1182         $t_wrote = t('$1 wrote:');
1183
1184         // handle nested quotes
1185         $endlessloop = 0;
1186         while ((strpos($Text, "[/spoiler]")!== false)  && (strpos($Text, "[spoiler=") !== false) && (++$endlessloop < 20)) {
1187                 $Text = preg_replace("/\[spoiler=[\"\']*(.*?)[\"\']*\](.*?)\[\/spoiler\]/ism",
1188                                      "<br /><strong class=".'"spoiler"'.">" . $t_wrote . "</strong><blockquote class=".'"spoiler"'.">$2</blockquote>",
1189                                      $Text);
1190         }
1191
1192         // Declare the format for [quote] layout
1193         $QuoteLayout = '<blockquote>$1</blockquote>';
1194
1195         // Check for [quote] text
1196         // handle nested quotes
1197         $endlessloop = 0;
1198         while ((strpos($Text, "[/quote]") !== false) && (strpos($Text, "[quote]") !== false) && (++$endlessloop < 20)) {
1199                 $Text = preg_replace("/\[quote\](.*?)\[\/quote\]/ism", "$QuoteLayout", $Text);
1200         }
1201
1202         // Check for [quote=Author] text
1203
1204         $t_wrote = t('$1 wrote:');
1205
1206         // handle nested quotes
1207         $endlessloop = 0;
1208         while ((strpos($Text, "[/quote]")!== false)  && (strpos($Text, "[quote=") !== false) && (++$endlessloop < 20)) {
1209                 $Text = preg_replace("/\[quote=[\"\']*(.*?)[\"\']*\](.*?)\[\/quote\]/ism",
1210                                      "<br /><strong class=".'"author"'.">" . $t_wrote . "</strong><blockquote>$2</blockquote>",
1211                                      $Text);
1212         }
1213
1214
1215         // [img=widthxheight]image source[/img]
1216         $Text = preg_replace_callback("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", 'bb_PictureCacheExt', $Text);
1217
1218         $Text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '<img src="$3" style="width: $1px;" >', $Text);
1219         $Text = preg_replace("/\[zmg\=([0-9]*)x([0-9]*)\](.*?)\[\/zmg\]/ism", '<img class="zrl" src="$3" style="width: $1px;" >', $Text);
1220
1221         // Images
1222         // [img]pathtoimage[/img]
1223         $Text = preg_replace_callback("/\[img\](.*?)\[\/img\]/ism", 'bb_PictureCache', $Text);
1224
1225         $Text = preg_replace("/\[img\](.*?)\[\/img\]/ism", '<img src="$1" alt="' . t('Image/photo') . '" />', $Text);
1226         $Text = preg_replace("/\[zmg\](.*?)\[\/zmg\]/ism", '<img src="$1" alt="' . t('Image/photo') . '" />', $Text);
1227
1228         // Shared content
1229         $Text = preg_replace_callback("/(.*?)\[share(.*?)\](.*?)\[\/share\]/ism",
1230                 function ($match) use ($simplehtml) {
1231                         return bb_ShareAttributes($match, $simplehtml);
1232                 }, $Text);
1233
1234         $Text = preg_replace("/\[crypt\](.*?)\[\/crypt\]/ism", '<br/><img src="' .System::baseUrl() . '/images/lock_icon.gif" alt="' . t('Encrypted content') . '" title="' . t('Encrypted content') . '" /><br />', $Text);
1235         $Text = preg_replace("/\[crypt(.*?)\](.*?)\[\/crypt\]/ism", '<br/><img src="' .System::baseUrl() . '/images/lock_icon.gif" alt="' . t('Encrypted content') . '" title="' . '$1' . ' ' . t('Encrypted content') . '" /><br />', $Text);
1236         //$Text = preg_replace("/\[crypt=(.*?)\](.*?)\[\/crypt\]/ism", '<br/><img src="' .System::baseUrl() . '/images/lock_icon.gif" alt="' . t('Encrypted content') . '" title="' . '$1' . ' ' . t('Encrypted content') . '" /><br />', $Text);
1237
1238         // Try to Oembed
1239         if ($tryoembed) {
1240                 $Text = preg_replace("/\[video\](.*?\.(ogg|ogv|oga|ogm|webm|mp4))\[\/video\]/ism", '<video src="$1" controls="controls" width="' . $a->videowidth . '" height="' . $a->videoheight . '"><a href="$1">$1</a></video>', $Text);
1241                 $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);
1242
1243                 $Text = preg_replace_callback("/\[video\](.*?)\[\/video\]/ism", $tryoembed_callback, $Text);
1244                 $Text = preg_replace_callback("/\[audio\](.*?)\[\/audio\]/ism", $tryoembed_callback, $Text);
1245         } else {
1246                 $Text = preg_replace("/\[video\](.*?)\[\/video\]/",
1247                                         '<a href="$1" target="_blank">$1</a>', $Text);
1248                 $Text = preg_replace("/\[audio\](.*?)\[\/audio\]/",
1249                                         '<a href="$1" target="_blank">$1</a>', $Text);
1250         }
1251
1252         // html5 video and audio
1253
1254
1255         if ($tryoembed) {
1256                 $Text = preg_replace("/\[iframe\](.*?)\[\/iframe\]/ism", '<iframe src="$1" width="' . $a->videowidth . '" height="' . $a->videoheight . '"><a href="$1">$1</a></iframe>', $Text);
1257         } else {
1258                 $Text = preg_replace("/\[iframe\](.*?)\[\/iframe\]/ism", '<a href="$1">$1</a>', $Text);
1259         }
1260
1261         // Youtube extensions
1262         if ($tryoembed) {
1263                 $Text = preg_replace_callback("/\[youtube\](https?:\/\/www.youtube.com\/watch\?v\=.*?)\[\/youtube\]/ism", $tryoembed_callback, $Text);
1264                 $Text = preg_replace_callback("/\[youtube\](www.youtube.com\/watch\?v\=.*?)\[\/youtube\]/ism", $tryoembed_callback, $Text);
1265                 $Text = preg_replace_callback("/\[youtube\](https?:\/\/youtu.be\/.*?)\[\/youtube\]/ism", $tryoembed_callback, $Text);
1266         }
1267
1268         $Text = preg_replace("/\[youtube\]https?:\/\/www.youtube.com\/watch\?v\=(.*?)\[\/youtube\]/ism", '[youtube]$1[/youtube]', $Text);
1269         $Text = preg_replace("/\[youtube\]https?:\/\/www.youtube.com\/embed\/(.*?)\[\/youtube\]/ism", '[youtube]$1[/youtube]', $Text);
1270         $Text = preg_replace("/\[youtube\]https?:\/\/youtu.be\/(.*?)\[\/youtube\]/ism", '[youtube]$1[/youtube]', $Text);
1271
1272         if ($tryoembed) {
1273                 $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);
1274         } else {
1275                 $Text = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
1276                                         '<a href="https://www.youtube.com/watch?v=$1" target="_blank">https://www.youtube.com/watch?v=$1</a>', $Text);
1277         }
1278
1279         if ($tryoembed) {
1280                 $Text = preg_replace_callback("/\[vimeo\](https?:\/\/player.vimeo.com\/video\/[0-9]+).*?\[\/vimeo\]/ism", $tryoembed_callback, $Text);
1281                 $Text = preg_replace_callback("/\[vimeo\](https?:\/\/vimeo.com\/[0-9]+).*?\[\/vimeo\]/ism", $tryoembed_callback, $Text);
1282         }
1283
1284         $Text = preg_replace("/\[vimeo\]https?:\/\/player.vimeo.com\/video\/([0-9]+)(.*?)\[\/vimeo\]/ism", '[vimeo]$1[/vimeo]', $Text);
1285         $Text = preg_replace("/\[vimeo\]https?:\/\/vimeo.com\/([0-9]+)(.*?)\[\/vimeo\]/ism", '[vimeo]$1[/vimeo]', $Text);
1286
1287         if ($tryoembed) {
1288                 $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);
1289         } else {
1290                 $Text = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
1291                                         '<a href="https://vimeo.com/$1" target="_blank">https://vimeo.com/$1</a>', $Text);
1292         }
1293
1294 //      $Text = preg_replace("/\[youtube\](.*?)\[\/youtube\]/", '<object width="425" height="350" type="application/x-shockwave-flash" data="http://www.youtube.com/v/$1" ><param name="movie" value="http://www.youtube.com/v/$1"></param><!--[if IE]><embed src="http://www.youtube.com/v/$1" type="application/x-shockwave-flash" width="425" height="350" /><![endif]--></object>', $Text);
1295
1296         // oembed tag
1297         $Text = OEmbed::BBCode2HTML($Text);
1298
1299         // Avoid triple linefeeds through oembed
1300         $Text = str_replace("<br style='clear:left'></span><br /><br />", "<br style='clear:left'></span><br />", $Text);
1301
1302         // If we found an event earlier, strip out all the event code and replace with a reformatted version.
1303         // Replace the event-start section with the entire formatted event. The other bbcode is stripped.
1304         // Summary (e.g. title) is required, earlier revisions only required description (in addition to
1305         // start which is always required). Allow desc with a missing summary for compatibility.
1306
1307         if ((x($ev, 'desc') || x($ev, 'summary')) && x($ev, 'start')) {
1308                 $sub = format_event_html($ev, $simplehtml);
1309
1310                 $Text = preg_replace("/\[event\-summary\](.*?)\[\/event\-summary\]/ism", '', $Text);
1311                 $Text = preg_replace("/\[event\-description\](.*?)\[\/event\-description\]/ism", '', $Text);
1312                 $Text = preg_replace("/\[event\-start\](.*?)\[\/event\-start\]/ism", $sub, $Text);
1313                 $Text = preg_replace("/\[event\-finish\](.*?)\[\/event\-finish\]/ism", '', $Text);
1314                 $Text = preg_replace("/\[event\-location\](.*?)\[\/event\-location\]/ism", '', $Text);
1315                 $Text = preg_replace("/\[event\-adjust\](.*?)\[\/event\-adjust\]/ism", '', $Text);
1316                 $Text = preg_replace("/\[event\-id\](.*?)\[\/event\-id\]/ism", '', $Text);
1317         }
1318
1319         // Replace non graphical smilies for external posts
1320         if ($simplehtml) {
1321                 $Text = Smilies::replace($Text, false, true);
1322         }
1323
1324         // Replace inline code blocks
1325         $Text = preg_replace_callback("|(?!<br[^>]*>)<code>([^<]*)</code>(?!<br[^>]*>)|ism",
1326                 function ($match) use ($simplehtml) {
1327                         $return = '<key>' . $match[1] . '</key>';
1328                         // Use <code> for Diaspora inline code blocks
1329                         if ($simplehtml === 3) {
1330                                 $return = '<code>' . $match[1] . '</code>';
1331                         }
1332                         return $return;
1333                 }
1334         , $Text);
1335
1336         // Unhide all [noparse] contained bbtags unspacefying them
1337         // and triming the [noparse] tag.
1338
1339         $Text = preg_replace_callback("/\[noparse\](.*?)\[\/noparse\]/ism", 'bb_unspacefy_and_trim', $Text);
1340         $Text = preg_replace_callback("/\[nobb\](.*?)\[\/nobb\]/ism", 'bb_unspacefy_and_trim', $Text);
1341         $Text = preg_replace_callback("/\[pre\](.*?)\[\/pre\]/ism", 'bb_unspacefy_and_trim', $Text);
1342
1343
1344         $Text = preg_replace('/\[\&amp\;([#a-z0-9]+)\;\]/', '&$1;', $Text);
1345         $Text = preg_replace('/\&\#039\;/', '\'', $Text);
1346         $Text = preg_replace('/\&quot\;/', '"', $Text);
1347
1348         // fix any escaped ampersands that may have been converted into links
1349         $Text = preg_replace('/\<([^>]*?)(src|href)=(.*?)\&amp\;(.*?)\>/ism', '<$1$2=$3&$4>', $Text);
1350
1351         // sanitizes src attributes (http and redir URLs for displaying in a web page, cid used for inline images in emails)
1352         static $allowed_src_protocols = array('http', 'redir', 'cid');
1353         $Text = preg_replace('#<([^>]*?)(src)="(?!' . implode('|', $allowed_src_protocols) . ')(.*?)"(.*?)>#ism',
1354                              '<$1$2=""$4 class="invalid-src" title="' . t('Invalid source protocol') . '">', $Text);
1355
1356         // sanitize href attributes (only whitelisted protocols URLs)
1357         // default value for backward compatibility
1358         $allowed_link_protocols = Config::get('system', 'allowed_link_protocols', array('ftp', 'mailto', 'gopher', 'cid'));
1359
1360         // Always allowed protocol even if config isn't set or not including it
1361         $allowed_link_protocols[] = 'http';
1362         $allowed_link_protocols[] = 'redir/';
1363
1364         $regex = '#<([^>]*?)(href)="(?!' . implode('|', $allowed_link_protocols) . ')(.*?)"(.*?)>#ism';
1365         $Text = preg_replace($regex, '<$1$2="javascript:void(0)"$4 class="invalid-href" title="' . t('Invalid link protocol') . '">', $Text);
1366
1367         if ($saved_image) {
1368                 $Text = bb_replace_images($Text, $saved_image);
1369         }
1370
1371         // Clean up the HTML by loading and saving the HTML with the DOM.
1372         // Bad structured html can break a whole page.
1373         // For performance reasons do it only with ativated item cache or at export.
1374         if (!$tryoembed || (get_itemcachepath() != "")) {
1375                 $doc = new DOMDocument();
1376                 $doc->preserveWhiteSpace = false;
1377
1378                 $Text = mb_convert_encoding($Text, 'HTML-ENTITIES', "UTF-8");
1379
1380                 $doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">';
1381                 $encoding = '<?xml encoding="UTF-8">';
1382                 @$doc->loadHTML($encoding.$doctype."<html><body>".$Text."</body></html>");
1383                 $doc->encoding = 'UTF-8';
1384                 $Text = $doc->saveHTML();
1385                 $Text = str_replace(array("<html><body>", "</body></html>", $doctype, $encoding), array("", "", "", ""), $Text);
1386
1387                 $Text = str_replace('<br></li>', '</li>', $Text);
1388
1389                 //$Text = mb_convert_encoding($Text, "UTF-8", 'HTML-ENTITIES');
1390         }
1391
1392         // Clean up some useless linebreaks in lists
1393         //$Text = str_replace('<br /><ul', '<ul ', $Text);
1394         //$Text = str_replace('</ul><br />', '</ul>', $Text);
1395         //$Text = str_replace('</li><br />', '</li>', $Text);
1396         //$Text = str_replace('<br /><li>', '<li>', $Text);
1397         //$Text = str_replace('<br /><ul', '<ul ', $Text);
1398
1399         call_hooks('bbcode', $Text);
1400
1401         return trim($Text);
1402 }
1403
1404 /**
1405  * @brief Removes the "abstract" element from the text
1406  *
1407  * @param string $text The text with BBCode
1408  * @return string The same text - but without "abstract" element
1409  */
1410 function remove_abstract($text) {
1411         $text = preg_replace("/[\s|\n]*\[abstract\].*?\[\/abstract\][\s|\n]*/ism", '', $text);
1412         $text = preg_replace("/[\s|\n]*\[abstract=.*?\].*?\[\/abstract][\s|\n]*/ism", '', $text);
1413
1414         return $text;
1415 }
1416
1417 /**
1418  * @brief Returns the value of the "abstract" element
1419  *
1420  * @param string $text The text that maybe contains the element
1421  * @param string $addon The addon for which the abstract is meant for
1422  * @return string The abstract
1423  */
1424 function fetch_abstract($text, $addon = "") {
1425         $abstract = "";
1426         $abstracts = array();
1427         $addon = strtolower($addon);
1428
1429         if (preg_match_all("/\[abstract=(.*?)\](.*?)\[\/abstract\]/ism",$text, $results, PREG_SET_ORDER))
1430                 foreach ($results AS $result)
1431                         $abstracts[strtolower($result[1])] = $result[2];
1432
1433         if (isset($abstracts[$addon]))
1434                 $abstract = $abstracts[$addon];
1435
1436         if ($abstract == "")
1437                 if (preg_match("/\[abstract\](.*?)\[\/abstract\]/ism",$text, $result))
1438                         $abstract = $result[1];
1439
1440         return $abstract;
1441 }