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