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