]> git.mxchange.org Git - friendica.git/blob - include/bbcode.php
Improving performance measuring for the bbcode parser.
[friendica.git] / include / bbcode.php
1 <?php
2 require_once("include/oembed.php");
3 require_once('include/event.php');
4
5 function bb_attachment($Text, $plaintext = false, $tryoembed = true) {
6         $Text = preg_replace_callback("/(.*?)\[attachment(.*?)\](.*?)\[\/attachment\]/ism",
7                 function ($match) use ($plaintext){
8
9                         $attributes = $match[2];
10
11                         $type = "";
12                         preg_match("/type='(.*?)'/ism", $attributes, $matches);
13                         if ($matches[1] != "")
14                                 $type = strtolower($matches[1]);
15
16                         preg_match('/type="(.*?)"/ism', $attributes, $matches);
17                         if ($matches[1] != "")
18                                 $type = strtolower($matches[1]);
19
20                         if ($type == "")
21                                 return($match[0]);
22
23                         if (!in_array($type, array("link", "audio", "video")))
24                                 return($match[0]);
25
26                         $url = "";
27                         preg_match("/url='(.*?)'/ism", $attributes, $matches);
28                         if ($matches[1] != "")
29                                 $url = $matches[1];
30
31                         preg_match('/url="(.*?)"/ism', $attributes, $matches);
32                         if ($matches[1] != "")
33                                 $url = $matches[1];
34
35                         $title = "";
36                         preg_match("/title='(.*?)'/ism", $attributes, $matches);
37                         if ($matches[1] != "")
38                                 $title = $matches[1];
39
40                         preg_match('/title="(.*?)"/ism', $attributes, $matches);
41                         if ($matches[1] != "")
42                                 $title = $matches[1];
43
44                         //$title = htmlentities($title, ENT_QUOTES, 'UTF-8', false);
45                         $title = bbcode(html_entity_decode($title), false, false, true);
46                         $title = str_replace(array("[", "]"), array("&#91;", "&#93;"), $title);
47
48                         $image = "";
49                         if ($type != "video") {
50                                 preg_match("/image='(.*?)'/ism", $attributes, $matches);
51                                 if ($matches[1] != "")
52                                         $image = $matches[1];
53
54                                 preg_match('/image="(.*?)"/ism', $attributes, $matches);
55                                 if ($matches[1] != "")
56                                         $image = $matches[1];
57                         }
58
59                         $preview = "";
60                         if ($type != "video") {
61                                 preg_match("/preview='(.*?)'/ism", $attributes, $matches);
62                                 if ($matches[1] != "")
63                                         $preview = $matches[1];
64
65                                 preg_match('/preview="(.*?)"/ism', $attributes, $matches);
66                                 if ($matches[1] != "")
67                                         $preview = $matches[1];
68                         }
69
70                         if (((strpos($match[1], "[img=") !== false) OR (strpos($match[1], "[img]") !== false)) AND ($image != "")) {
71                                 $preview = $image;
72                                 $image = "";
73                         }
74
75                         if ($plaintext)
76                                 $text = sprintf('<a href="%s" target="_blank">%s</a><br>', $url, $title);
77                         else {
78                                 $text = sprintf('<span class="type-%s">', $type);
79
80                                 $bookmark = array(sprintf('[bookmark=%s]%s[/bookmark]', $url, $title), $url, $title);
81                                 if ($tryoembed)
82                                         $oembed = tryoembed($bookmark);
83                                 else
84                                         $oembed = $bookmark[0];
85
86                                 if (($image != "") AND !strstr(strtolower($oembed), "<img "))
87                                         $text .= sprintf('<a href="%s" target="_blank"><img src="%s" alt="" title="%s" class="attachment-image" /></a><br />', $url, $image, $title);
88                                 elseif (($preview != "") AND !strstr(strtolower($oembed), "<img "))
89                                         $text .= sprintf('<a href="%s" target="_blank"><img src="%s" alt="" title="%s" class="attachment-preview" /></a><br />', $url, $preview, $title);
90
91                                 $text .= $oembed;
92
93                                 $text .= sprintf('<blockquote>%s</blockquote></span>', trim($match[3]));
94                         }
95
96                         return($match[1].$text);
97                 },$Text);
98
99         return($Text);
100 }
101
102 function bb_rearrange_share($shared) {
103         if (!in_array(strtolower($shared[2]), array("type-link", "type-audio", "type-video")))
104                 return($shared[0]);
105
106         if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
107                 return($shared[0]);
108
109         $type = substr(trim(strtolower($shared[2])), 5);
110
111         $title = "";
112         $url = "";
113         $preview = "";
114         $description = "";
115
116         if (isset($bookmark[2][0]))
117                 $title = $bookmark[2][0];
118
119         if (isset($bookmark[1][0]))
120                 $url = $bookmark[1][0];
121
122         $cleanedshare = trim($shared[3]);
123         $cleanedshare = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $cleanedshare);
124         preg_match("/\[img\](.*?)\[\/img\]/ism", $cleanedshare, $matches);
125
126         if ($matches)
127                 $preview = trim($matches[1]);
128
129         preg_match("/\[quote\](.*?)\[\/quote\]/ism", $cleanedshare, $matches);
130         if ($matches)
131                 $description = trim($matches[1]);
132
133         $url = str_replace(array("[", "]"), array("&#91;", "&#93;"), htmlentities($url, ENT_QUOTES, 'UTF-8', false));
134         $title = str_replace(array("[", "]"), array("&#91;", "&#93;"), htmlentities($title, ENT_QUOTES, 'UTF-8', false));
135         $preview = str_replace(array("[", "]"), array("&#91;", "&#93;"), htmlentities($preview, ENT_QUOTES, 'UTF-8', false));
136
137         $Text = trim($shared[1])."\n[attachment type='".$type."'";
138
139         if ($url != "")
140                 $Text .= " url='".$url."'";
141         if ($title != "")
142                 $Text .= " title='".$title."'";
143         if ($preview != "") {
144                 require_once("include/Photo.php");
145                 $picturedata = get_photo_info($preview);
146
147                 if (count($picturedata) > 0) {
148                         // if the preview picture is larger than 500 pixels then show it in a larger mode
149                         // But only, if the picture isn't higher than large (To prevent huge posts)
150                         if (($picturedata[0] >= 500) AND ($picturedata[0] >= $picturedata[1]))
151                                 $Text .= " image='".$preview."'";
152                         else
153                                 $Text .= " preview='".$preview."'";
154                 } else
155                         $Text .= " preview='".$preview."'";
156         }
157         $Text .= "]".$description."[/attachment]";
158
159         return($Text);
160 }
161
162 function bb_remove_share_information($Text, $plaintext = false, $nolink = false) {
163         $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism",
164                 function ($match) use ($plaintext, $nolink){
165                         return(bb_cleanup_share($match, $plaintext, $nolink));
166                 },$Text);
167         return($Text);
168 }
169
170 function bb_cleanup_share($shared, $plaintext, $nolink) {
171         $shared[1] = trim($shared[1]);
172
173         if (!in_array($shared[2], array("type-link", "type-video")))
174                 return($shared[0]);
175
176         if ($plaintext)
177                 $shared[3] = preg_replace("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism","[bookmark=$1]$1[/bookmark]", $shared[3]);
178
179         if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
180                 return($shared[0]);
181
182         if ($nolink)
183                 return($shared[1]);
184
185         $title = "";
186         $link = "";
187
188         if (isset($bookmark[2][0]))
189                 $title = $bookmark[2][0];
190
191         if (isset($bookmark[1][0]))
192                 $link = $bookmark[1][0];
193
194         if (($shared[1] != "") AND (strpos($title, $shared[1]) !== false))
195                 $shared[1] = $title;
196
197         if (($title != "") AND ((strpos($shared[1],$title) !== false) OR
198                 (similar_text($shared[1],$title) / strlen($title)) > 0.9))
199                 $title = "";
200
201 //        if (strpos($shared[1],$link) !== false)
202 //                $link = "";
203
204         $text = trim($shared[1]);
205
206         if (($text == "") AND ($title != "") AND ($link == ""))
207                 $text .= "\n\n".trim($title);
208
209         // If the link already is included in the post, don't add it again
210         if (($link != "") AND strpos($text, $link))
211                 return(trim($text));
212
213         if (($link != "") AND ($title != ""))
214                 $text .= "\n[url=".trim($link)."]".trim($title)."[/url]";
215         elseif (($link != ""))
216                 $text .= "\n".trim($link);
217
218         return(trim($text));
219 }
220
221
222 function bb_cleanstyle($st) {
223   return "<span style=\"".cleancss($st[1]).";\">".$st[2]."</span>";
224 }
225
226 function bb_cleanclass($st) {
227   return "<span class=\"".cleancss($st[1])."\">".$st[2]."</span>";
228 }
229
230 function cleancss($input) {
231
232         $cleaned = "";
233
234         $input = strtolower($input);
235
236         for ($i = 0; $i < strlen($input); $i++) {
237                 $char = substr($input, $i, 1);
238
239                 if (($char >= "a") and ($char <= "z"))
240                         $cleaned .= $char;
241
242                 if (!(strpos(" #;:0123456789-_", $char) === false))
243                         $cleaned .= $char;
244         }
245
246         return($cleaned);
247 }
248
249 function stripcode_br_cb($s) {
250         return '[code]' . str_replace('<br />', '', $s[1]) . '[/code]';
251 }
252
253 function tryoembed($match){
254         //$url = ((count($match)==2)?$match[1]:$match[2]);
255         $url = $match[1];
256
257         // Always embed the SSL version
258         $url = str_replace(array("http://www.youtube.com/", "http://player.vimeo.com/"),
259                                 array("https://www.youtube.com/", "https://player.vimeo.com/"), $url);
260
261         //logger("tryoembed: $url");
262
263         $o = oembed_fetch_url($url);
264
265         if (isset($match[2]))
266                 $o->title = $match[2];
267
268         if ($o->type=="error") return $match[0];
269
270         $html = oembed_format_object($o);
271         return $html; //oembed_iframe($html,$o->width,$o->height);
272
273 }
274
275 // [noparse][i]italic[/i][/noparse] turns into
276 // [noparse][ i ]italic[ /i ][/noparse],
277 // to hide them from parser.
278
279 function bb_spacefy($st) {
280   $whole_match = $st[0];
281   $captured = $st[1];
282   $spacefied = preg_replace("/\[(.*?)\]/", "[ $1 ]", $captured);
283   $new_str = str_replace($captured, $spacefied, $whole_match);
284   return $new_str;
285 }
286
287 // The previously spacefied [noparse][ i ]italic[ /i ][/noparse],
288 // now turns back and the [noparse] tags are trimed
289 // returning [i]italic[/i]
290
291 function bb_unspacefy_and_trim($st) {
292   $whole_match = $st[0];
293   $captured = $st[1];
294   $unspacefied = preg_replace("/\[ (.*?)\ ]/", "[$1]", $captured);
295   return $unspacefied;
296 }
297
298 function bb_find_open_close($s, $open, $close, $occurance = 1) {
299
300         if($occurance < 1)
301                 $occurance = 1;
302
303         $start_pos = -1;
304         for($i = 1; $i <= $occurance; $i++) {
305                 if( $start_pos !== false)
306                         $start_pos = strpos($s, $open, $start_pos + 1);
307         }
308
309         if( $start_pos === false)
310                 return false;
311
312         $end_pos = strpos($s, $close, $start_pos);
313
314         if( $end_pos === false)
315                 return false;
316
317         $res = array( 'start' => $start_pos, 'end' => $end_pos );
318
319         return $res;
320 }
321
322 function get_bb_tag_pos($s, $name, $occurance = 1) {
323
324         if($occurance < 1)
325                 $occurance = 1;
326
327         $start_open = -1;
328         for($i = 1; $i <= $occurance; $i++) {
329                 if( $start_open !== false)
330                         $start_open = strpos($s, '[' . $name, $start_open + 1); // allow [name= type tags
331         }
332
333         if( $start_open === false)
334                 return false;
335
336         $start_equal = strpos($s, '=', $start_open);
337         $start_close = strpos($s, ']', $start_open);
338
339         if( $start_close === false)
340                 return false;
341
342         $start_close++;
343
344         $end_open = strpos($s, '[/' . $name . ']', $start_close);
345
346         if( $end_open === false)
347                 return false;
348
349         $res = array( 'start' => array('open' => $start_open, 'close' => $start_close),
350                       'end' => array('open' => $end_open, 'close' => $end_open + strlen('[/' . $name . ']')) );
351         if( $start_equal !== false)
352                 $res['start']['equal'] = $start_equal + 1;
353
354         return $res;
355 }
356
357 function bb_tag_preg_replace($pattern, $replace, $name, $s) {
358
359         $string = $s;
360
361         $occurance = 1;
362         $pos = get_bb_tag_pos($string, $name, $occurance);
363         while($pos !== false && $occurance < 1000) {
364
365                 $start = substr($string, 0, $pos['start']['open']);
366                 $subject = substr($string, $pos['start']['open'], $pos['end']['close'] - $pos['start']['open']);
367                 $end = substr($string, $pos['end']['close']);
368                 if($end === false)
369                         $end = '';
370
371                 $subject = preg_replace($pattern, $replace, $subject);
372                 $string = $start . $subject . $end;
373
374                 $occurance++;
375                 $pos = get_bb_tag_pos($string, $name, $occurance);
376         }
377
378         return $string;
379 }
380
381 if(! function_exists('bb_extract_images')) {
382 function bb_extract_images($body) {
383
384         $saved_image = array();
385         $orig_body = $body;
386         $new_body = '';
387
388         $cnt = 0;
389         $img_start = strpos($orig_body, '[img');
390         $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
391         $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
392         while(($img_st_close !== false) && ($img_end !== false)) {
393
394                 $img_st_close++; // make it point to AFTER the closing bracket
395                 $img_end += $img_start;
396
397                 if(! strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
398                         // This is an embedded image
399
400                         $saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close));
401                         $new_body = $new_body . substr($orig_body, 0, $img_start) . '[$#saved_image' . $cnt . '#$]';
402
403                         $cnt++;
404                 }
405                 else
406                         $new_body = $new_body . substr($orig_body, 0, $img_end + strlen('[/img]'));
407
408                 $orig_body = substr($orig_body, $img_end + strlen('[/img]'));
409
410                 if($orig_body === false) // in case the body ends on a closing image tag
411                         $orig_body = '';
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="' . $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         // relative dates only make sense when they aren't cached
484         if ($itemcache == "") {
485                 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
486                 if ($matches[1] != "")
487                         $posted = $matches[1];
488
489                 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
490                 if ($matches[1] != "")
491                         $posted = $matches[1];
492
493                 $reldate = (($posted) ? " " . relative_date($posted) : '');
494         }
495
496         $userid = GetProfileUsername($profile,$author, false);
497         $userid_compact = GetProfileUsername($profile,$author, true);
498
499         $preshare = trim($share[1]);
500
501         if ($preshare != "")
502                 $preshare .= "<br /><br />";
503
504         switch ($simplehtml) {
505                 case 1:
506                         $text = $preshare.html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8').' <a href="'.$profile.'">'.$userid."</a>: <br />»".$share[3]."«";
507                         break;
508                 case 2:
509                         $text = $preshare.html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8').' '.$userid_compact.": <br />".$share[3];
510                         break;
511                 case 3: // Diaspora
512                         $headline = '<div class="shared_header">';
513                         $headline .= '<span><b>'.html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8').$userid.':</b></span>';
514                         $headline .= "</div>";
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 class="shared_content">'.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                         $headline = trim($share[1]).'<div class="shared_header">';
564                         if ($avatar != "")
565                                 $headline .= '<img src="'.$avatar.'" height="32" width="32" >';
566
567                         $headline .= sprintf(t('<span><a href="%s" target="_blank">%s</a> wrote the following <a href="%s" target="_blank">post</a>'.$reldate.':</span>'), $profile, $author, $link);
568                         $headline .= "</div>";
569                         $text = $headline.'<blockquote class="shared_content">'.trim($share[3])."</blockquote>";
570                         break;
571         }
572         return($text);
573 }
574
575 function GetProfileUsername($profile, $username, $compact = false, $getnetwork = false) {
576
577         $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1@twitter.com", $profile);
578         if ($twitter != $profile) {
579                 if ($getnetwork)
580                         return(NETWORK_TWITTER);
581                 elseif ($compact)
582                         return($twitter);
583                 else
584                         return($username." (".$twitter.")");
585         }
586
587         $appnet = preg_replace("=https?://alpha.app.net/(.*)=ism", "$1@alpha.app.net", $profile);
588         if ($appnet != $profile) {
589                 if ($getnetwork)
590                         return(NETWORK_APPNET);
591                 elseif ($compact)
592                         return($appnet);
593                 else
594                         return($username." (".$appnet.")");
595         }
596
597         $gplus = preg_replace("=https?://plus.google.com/(.*)=ism", "$1@plus.google.com", $profile);
598         if ($gplus != $profile) {
599                 if ($getnetwork)
600                         return(NETWORK_GPLUS);
601                 elseif ($compact)
602                         return($gplususername." (".$username.")");
603                 else
604                         return($username." (".$gplus.")");
605         }
606
607         $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2@$1", $profile);
608         if ($friendica != $profile) {
609                 if ($getnetwork)
610                         return(NETWORK_DFRN);
611                 elseif ($compact)
612                         return($friendica);
613                 else
614                         return($username." (".$friendica.")");
615         }
616
617         $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
618         if ($diaspora != $profile) {
619                 if ($getnetwork)
620                         return(NETWORK_DIASPORA);
621                 elseif ($compact)
622                         return($diaspora);
623                 else
624                         return($username." (".$diaspora.")");
625         }
626
627         $red = preg_replace("=https?://(.*)/channel/(.*)=ism", "$2@$1", $profile);
628         if ($red != $profile) {
629                 if ($getnetwork)
630                         // red is identified as Diaspora - friendica can't connect directly to it
631                         return(NETWORK_DIASPORA);
632                 elseif ($compact)
633                         return($red);
634                 else
635                         return($username." (".$red.")");
636         }
637
638         $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
639         if ($StatusnetHost != $profile) {
640                 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
641                 if ($StatusnetUser != $profile) {
642                         $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
643                         $user = json_decode($UserData);
644                         if ($user) {
645                                 if ($getnetwork)
646                                         return(NETWORK_STATUSNET);
647                                 elseif ($compact)
648                                         return($user->screen_name."@".$StatusnetHost);
649                                 else
650                                         return($username." (".$user->screen_name."@".$StatusnetHost.")");
651                         }
652                 }
653         }
654
655         // pumpio (http://host.name/user)
656         $rest = preg_replace("=https?://([\.\w]+)/([\.\w]+)(.*)=ism", "$3", $profile);
657         if ($rest == "") {
658                 $pumpio = preg_replace("=https?://([\.\w]+)/([\.\w]+)(.*)=ism", "$2@$1", $profile);
659                 if ($pumpio != $profile) {
660                         if ($getnetwork)
661                                 return(NETWORK_PUMPIO);
662                         elseif ($compact)
663                                 return($pumpio);
664                         else
665                                 return($username." (".$pumpio.")");
666                 }
667         }
668
669         return($username);
670 }
671
672 function bb_DiasporaLinks($match) {
673         $a = get_app();
674
675         return "[url=".$a->get_baseurl()."/display/".$match[1]."]".$match[2]."[/url]";
676 }
677
678 function bb_RemovePictureLinks($match) {
679         $text = Cache::get($match[1]);
680
681         if(is_null($text)){
682                 $a = get_app();
683
684                 $ch = @curl_init($match[1]);
685                 @curl_setopt($ch, CURLOPT_NOBODY, true);
686                 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
687                 @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
688                 @curl_exec($ch);
689                 $curl_info = @curl_getinfo($ch);
690
691                 if (substr($curl_info["content_type"], 0, 6) == "image/")
692                         $text = "[url=".$match[1]."]".$match[1]."[/url]";
693                 else {
694                         $text = "[url=".$match[2]."]".$match[2]."[/url]";
695
696                         // if its not a picture then look if its a page that contains a picture link
697                         require_once("include/network.php");
698
699                         $body = fetch_url($match[1]);
700
701                         $doc = new DOMDocument();
702                         @$doc->loadHTML($body);
703                         $xpath = new DomXPath($doc);
704                         $list = $xpath->query("//meta[@name]");
705                         foreach ($list as $node) {
706                                 $attr = array();
707
708                                 if ($node->attributes->length)
709                                         foreach ($node->attributes as $attribute)
710                                                 $attr[$attribute->name] = $attribute->value;
711
712                                 if (strtolower($attr["name"]) == "twitter:image")
713                                         $text = "[url=".$attr["content"]."]".$attr["content"]."[/url]";
714                         }
715                 }
716                 Cache::set($match[1],$text);
717         }
718         return($text);
719 }
720
721 function bb_expand_links($match) {
722         if (($match[3] == "") OR ($match[2] == $match[3]) OR stristr($match[2], $match[3]))
723                 return ($match[1]."[url]".$match[2]."[/url]");
724         else
725                 return ($match[1].$match[3]." [url]".$match[2]."[/url]");
726 }
727
728 function bb_CleanPictureLinksSub($match) {
729         $text = Cache::get($match[1]);
730
731         if(is_null($text)){
732                 $a = get_app();
733
734                 $ch = @curl_init($match[1]);
735                 @curl_setopt($ch, CURLOPT_NOBODY, true);
736                 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
737                 @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
738                 @curl_exec($ch);
739                 $curl_info = @curl_getinfo($ch);
740
741                 // if its a link to a picture then embed this picture
742                 if (substr($curl_info["content_type"], 0, 6) == "image/")
743                         $text = "[img]".$match[1]."[/img]";
744                 else {
745                         $text = "[img]".$match[2]."[/img]";
746
747                         // if its not a picture then look if its a page that contains a picture link
748                         require_once("include/network.php");
749
750                         $body = fetch_url($match[1]);
751
752                         $doc = new DOMDocument();
753                         @$doc->loadHTML($body);
754                         $xpath = new DomXPath($doc);
755                         $list = $xpath->query("//meta[@name]");
756                         foreach ($list as $node) {
757                                 $attr = array();
758
759                                 if ($node->attributes->length)
760                                         foreach ($node->attributes as $attribute)
761                                                 $attr[$attribute->name] = $attribute->value;
762
763                                 if (strtolower($attr["name"]) == "twitter:image")
764                                         $text = "[img]".$attr["content"]."[/img]";
765                         }
766                 }
767                 Cache::set($match[1],$text);
768         }
769         return($text);
770 }
771
772 function bb_CleanPictureLinks($text) {
773         $text = preg_replace_callback("&\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]&Usi", 'bb_CleanPictureLinksSub', $text);
774         return ($text);
775 }
776
777         // BBcode 2 HTML was written by WAY2WEB.net
778         // extended to work with Mistpark/Friendica - Mike Macgirvin
779
780 function bbcode($Text,$preserve_nl = false, $tryoembed = true, $simplehtml = false, $forplaintext = false) {
781
782         $stamp1 = microtime(true);
783
784         $a = get_app();
785
786         // Hide all [noparse] contained bbtags by spacefying them
787         // POSSIBLE BUG --> Will the 'preg' functions crash if there's an embedded image?
788
789         $Text = preg_replace_callback("/\[noparse\](.*?)\[\/noparse\]/ism", 'bb_spacefy',$Text);
790         $Text = preg_replace_callback("/\[nobb\](.*?)\[\/nobb\]/ism", 'bb_spacefy',$Text);
791         $Text = preg_replace_callback("/\[pre\](.*?)\[\/pre\]/ism", 'bb_spacefy',$Text);
792
793
794         // Move all spaces out of the tags
795         $Text = preg_replace("/\[(\w*)\](\s*)/ism", '$2[$1]', $Text);
796         $Text = preg_replace("/(\s*)\[\/(\w*)\]/ism", '[/$2]$1', $Text);
797
798         // Extract the private images which use data urls since preg has issues with
799         // large data sizes. Stash them away while we do bbcode conversion, and then put them back
800         // in after we've done all the regex matching. We cannot use any preg functions to do this.
801
802         $extracted = bb_extract_images($Text);
803         $Text = $extracted['body'];
804         $saved_image = $extracted['images'];
805
806         // If we find any event code, turn it into an event.
807         // After we're finished processing the bbcode we'll
808         // replace all of the event code with a reformatted version.
809
810         $ev = bbtoevent($Text);
811
812
813         // Replace any html brackets with HTML Entities to prevent executing HTML or script
814         // Don't use strip_tags here because it breaks [url] search by replacing & with amp
815
816         $Text = str_replace("<", "&lt;", $Text);
817         $Text = str_replace(">", "&gt;", $Text);
818
819         // remove some newlines before the general conversion
820         $Text = preg_replace("/\s?\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","[share$1]$2[/share]",$Text);
821         $Text = preg_replace("/\s?\[quote(.*?)\]\s?(.*?)\s?\[\/quote\]\s?/ism","[quote$1]$2[/quote]",$Text);
822
823         $Text = preg_replace("/\n\[code\]/ism", "[code]", $Text);
824         $Text = preg_replace("/\[\/code\]\n/ism", "[/code]", $Text);
825
826         // Rearrange shares to attachments
827         $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism", "bb_rearrange_share",$Text);
828
829         // when the content is meant exporting to other systems then remove the avatar picture since this doesn't really look good on these systems
830         if (!$tryoembed)
831                 $Text = preg_replace("/\[share(.*?)avatar\s?=\s?'.*?'\s?(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","\n[share$1$2]$3[/share]",$Text);
832
833         // Convert new line chars to html <br /> tags
834
835         // nlbr seems to be hopelessly messed up
836         //      $Text = nl2br($Text);
837
838         // We'll emulate it.
839
840         $Text = trim($Text);
841         $Text = str_replace("\r\n","\n", $Text);
842
843         // removing multiplicated newlines
844         if (get_config("system", "remove_multiplicated_lines")) {
845                 $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",
846                                 "\n[h1]", "[/h1]\n", "\n[h2]", "[/h2]\n", "\n[h3]", "[/h3]\n", "\n[h4]", "[/h4]\n", "\n[h5]", "[/h5]\n", "\n[h6]", "[/h6]\n");
847                 $replace = array("\n\n", "\n", "\n", "[/quote]\n", "[/quote]", "[/li]", "[li]", "[ul]", "[/ul]", "\n[share ", "[/attachment]",
848                                 "[h1]", "[/h1]", "[h2]", "[/h2]", "[h3]", "[/h3]", "[h4]", "[/h4]", "[h5]", "[/h5]", "[h6]", "[/h6]");
849                 do {
850                         $oldtext = $Text;
851                         $Text = str_replace($search, $replace, $Text);
852                 } while ($oldtext != $Text);
853         }
854
855         $a->save_timestamp($stamp1, "parser");
856
857         // Handle attached links or videos
858         $Text = bb_attachment($Text, ($simplehtml != 4) AND ($simplehtml != 0), $tryoembed);
859
860         $stamp1 = microtime(true);
861
862         $Text = str_replace(array("\r","\n"), array('<br />','<br />'), $Text);
863
864         if($preserve_nl)
865                 $Text = str_replace(array("\n","\r"), array('',''),$Text);
866
867         // Set up the parameters for a URL search string
868         $URLSearchString = "^\[\]";
869         // Set up the parameters for a MAIL search string
870         $MAILSearchString = $URLSearchString;
871
872         // Remove all hashtag addresses
873         if (!$tryoembed OR $simplehtml)
874                 $Text = preg_replace("/([#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
875
876         // Bookmarks in red - will be converted to bookmarks in friendica
877         $Text = preg_replace("/#\^\[url\]([$URLSearchString]*)\[\/url\]/ism", '[bookmark=$1]$1[/bookmark]', $Text);
878         $Text = preg_replace("/#\^\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[bookmark=$1]$2[/bookmark]', $Text);
879         $Text = preg_replace("/#\[url\=[$URLSearchString]*\]\^\[\/url\]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/i",
880                                 "[bookmark=$1]$2[/bookmark]", $Text);
881
882         if (in_array($simplehtml, array(2, 6, 7, 8, 9))) {
883                 $Text = preg_replace_callback("/([^#@])\[url\=([^\]]*)\](.*?)\[\/url\]/ism","bb_expand_links",$Text);
884                 //$Text = preg_replace("/[^#@]\[url\=([^\]]*)\](.*?)\[\/url\]/ism",' $2 [url]$1[/url]',$Text);
885                 $Text = preg_replace("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",' $2 [url]$1[/url]',$Text);
886         }
887
888         if ($simplehtml == 5)
889                 $Text = preg_replace("/[^#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url]$1[/url]', $Text);
890
891         $a->save_timestamp($stamp1, "parser");
892
893         // Perform URL Search
894         if ($tryoembed)
895                 $Text = preg_replace_callback("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",'tryoembed',$Text);
896
897         $stamp1 = microtime(true);
898
899         if ($simplehtml == 5)
900                 $Text = preg_replace("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",'[url]$1[/url]',$Text);
901         else
902                 $Text = preg_replace("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$Text);
903
904         // Handle Diaspora posts
905         $Text = preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi", 'bb_DiasporaLinks', $Text);
906
907         $a->save_timestamp($stamp1, "parser");
908
909         // if the HTML is used to generate plain text, then don't do this search, but replace all URL of that kind to text
910         if (!$forplaintext)
911                 $Text = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1<a href="$2" target="_blank">$2</a>', $Text);
912         else {
913                 $Text = preg_replace("(\[url\]([$URLSearchString]*)\[\/url\])ism"," $1 ",$Text);
914                 $Text = preg_replace_callback("&\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]&Usi", 'bb_RemovePictureLinks', $Text);
915         }
916
917         if ($tryoembed)
918                 $Text = preg_replace_callback("/\[url\]([$URLSearchString]*)\[\/url\]/ism",'tryoembed',$Text);
919
920         $stamp1 = microtime(true);
921
922         $Text = preg_replace("/\[url\]([$URLSearchString]*)\[\/url\]/ism", '<a href="$1" target="_blank">$1</a>', $Text);
923         $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '<a href="$1" target="_blank">$2</a>', $Text);
924         //$Text = preg_replace("/\[url\=([$URLSearchString]*)\]([$URLSearchString]*)\[\/url\]/ism", '<a href="$1" target="_blank">$2</a>', $Text);
925
926         // Red compatibility, though the link can't be authenticated on Friendica
927         $Text = preg_replace("/\[zrl\=([$URLSearchString]*)\](.*?)\[\/zrl\]/ism", '<a href="$1" target="_blank">$2</a>', $Text);
928
929
930         // we may need to restrict this further if it picks up too many strays
931         // link acct:user@host to a webfinger profile redirector
932
933         $Text = preg_replace('/acct:(.*?)@(.*?)([ ,])/', '<a href="' . $a->get_baseurl() . '/acctlink?addr=' . "$1@$2" 
934                 . '" target="extlink" >acct:' . "$1@$2$3" . '</a>',$Text);
935
936         // Perform MAIL Search
937         $Text = preg_replace("/\[mail\]([$MAILSearchString]*)\[\/mail\]/", '<a href="mailto:$1">$1</a>', $Text);
938         $Text = preg_replace("/\[mail\=([$MAILSearchString]*)\](.*?)\[\/mail\]/", '<a href="mailto:$1">$2</a>', $Text);
939
940         // Check for headers
941         $Text = preg_replace("(\[h1\](.*?)\[\/h1\])ism",'<h1>$1</h1>',$Text);
942         $Text = preg_replace("(\[h2\](.*?)\[\/h2\])ism",'<h2>$1</h2>',$Text);
943         $Text = preg_replace("(\[h3\](.*?)\[\/h3\])ism",'<h3>$1</h3>',$Text);
944         $Text = preg_replace("(\[h4\](.*?)\[\/h4\])ism",'<h4>$1</h4>',$Text);
945         $Text = preg_replace("(\[h5\](.*?)\[\/h5\])ism",'<h5>$1</h5>',$Text);
946         $Text = preg_replace("(\[h6\](.*?)\[\/h6\])ism",'<h6>$1</h6>',$Text);
947
948         // Check for bold text
949         $Text = preg_replace("(\[b\](.*?)\[\/b\])ism",'<strong>$1</strong>',$Text);
950
951         // Check for Italics text
952         $Text = preg_replace("(\[i\](.*?)\[\/i\])ism",'<em>$1</em>',$Text);
953
954         // Check for Underline text
955         $Text = preg_replace("(\[u\](.*?)\[\/u\])ism",'<u>$1</u>',$Text);
956
957         // Check for strike-through text
958         $Text = preg_replace("(\[s\](.*?)\[\/s\])ism",'<strike>$1</strike>',$Text);
959
960         // Check for over-line text
961         $Text = preg_replace("(\[o\](.*?)\[\/o\])ism",'<span class="overline">$1</span>',$Text);
962
963         // Check for colored text
964         $Text = preg_replace("(\[color=(.*?)\](.*?)\[\/color\])ism","<span style=\"color: $1;\">$2</span>",$Text);
965
966         // Check for sized text
967         // [size=50] --> font-size: 50px (with the unit).
968         $Text = preg_replace("(\[size=(\d*?)\](.*?)\[\/size\])ism","<span style=\"font-size: $1px; line-height: initial;\">$2</span>",$Text);
969         $Text = preg_replace("(\[size=(.*?)\](.*?)\[\/size\])ism","<span style=\"font-size: $1; line-height: initial;\">$2</span>",$Text);
970
971         // Check for centered text
972         $Text = preg_replace("(\[center\](.*?)\[\/center\])ism","<div style=\"text-align:center;\">$1</div>",$Text);
973
974         // Check for list text
975         $Text = str_replace("[*]", "<li>", $Text);
976
977         // Check for style sheet commands
978         $Text = preg_replace_callback("(\[style=(.*?)\](.*?)\[\/style\])ism","bb_cleanstyle",$Text);
979
980         // Check for CSS classes
981         $Text = preg_replace_callback("(\[class=(.*?)\](.*?)\[\/class\])ism","bb_cleanclass",$Text);
982
983         // handle nested lists
984         $endlessloop = 0;
985
986         while ((((strpos($Text, "[/list]") !== false) && (strpos($Text, "[list") !== false)) ||
987                ((strpos($Text, "[/ol]") !== false) && (strpos($Text, "[ol]") !== false)) || 
988                ((strpos($Text, "[/ul]") !== false) && (strpos($Text, "[ul]") !== false)) || 
989                ((strpos($Text, "[/li]") !== false) && (strpos($Text, "[li]") !== false))) && (++$endlessloop < 20)) {
990                 $Text = preg_replace("/\[list\](.*?)\[\/list\]/ism", '<ul class="listbullet" style="list-style-type: circle;">$1</ul>' ,$Text);
991                 $Text = preg_replace("/\[list=\](.*?)\[\/list\]/ism", '<ul class="listnone" style="list-style-type: none;">$1</ul>' ,$Text);
992                 $Text = preg_replace("/\[list=1\](.*?)\[\/list\]/ism", '<ul class="listdecimal" style="list-style-type: decimal;">$1</ul>' ,$Text);
993                 $Text = preg_replace("/\[list=((?-i)i)\](.*?)\[\/list\]/ism",'<ul class="listlowerroman" style="list-style-type: lower-roman;">$2</ul>' ,$Text);
994                 $Text = preg_replace("/\[list=((?-i)I)\](.*?)\[\/list\]/ism", '<ul class="listupperroman" style="list-style-type: upper-roman;">$2</ul>' ,$Text);
995                 $Text = preg_replace("/\[list=((?-i)a)\](.*?)\[\/list\]/ism", '<ul class="listloweralpha" style="list-style-type: lower-alpha;">$2</ul>' ,$Text);
996                 $Text = preg_replace("/\[list=((?-i)A)\](.*?)\[\/list\]/ism", '<ul class="listupperalpha" style="list-style-type: upper-alpha;">$2</ul>' ,$Text);
997                 $Text = preg_replace("/\[ul\](.*?)\[\/ul\]/ism", '<ul class="listbullet" style="list-style-type: circle;">$1</ul>' ,$Text);
998                 $Text = preg_replace("/\[ol\](.*?)\[\/ol\]/ism", '<ul class="listdecimal" style="list-style-type: decimal;">$1</ul>' ,$Text);
999                 $Text = preg_replace("/\[li\](.*?)\[\/li\]/ism", '<li>$1</li>' ,$Text);
1000         }
1001
1002         $Text = preg_replace("/\[th\](.*?)\[\/th\]/sm", '<th>$1</th>' ,$Text);
1003         $Text = preg_replace("/\[td\](.*?)\[\/td\]/sm", '<td>$1</td>' ,$Text);
1004         $Text = preg_replace("/\[tr\](.*?)\[\/tr\]/sm", '<tr>$1</tr>' ,$Text);
1005         $Text = preg_replace("/\[table\](.*?)\[\/table\]/sm", '<table>$1</table>' ,$Text);
1006
1007         $Text = preg_replace("/\[table border=1\](.*?)\[\/table\]/sm", '<table border="1" >$1</table>' ,$Text);
1008         $Text = preg_replace("/\[table border=0\](.*?)\[\/table\]/sm", '<table border="0" >$1</table>' ,$Text);
1009
1010         $Text = str_replace('[hr]','<hr />', $Text);
1011
1012         // This is actually executed in prepare_body()
1013
1014         $Text = str_replace('[nosmile]','',$Text);
1015
1016         // Check for font change text
1017         $Text = preg_replace("/\[font=(.*?)\](.*?)\[\/font\]/sm","<span style=\"font-family: $1;\">$2</span>",$Text);
1018
1019         // Declare the format for [code] layout
1020
1021 //      $Text = preg_replace_callback("/\[code\](.*?)\[\/code\]/ism",'stripcode_br_cb',$Text);
1022
1023         $CodeLayout = '<code>$1</code>';
1024         // Check for [code] text
1025         $Text = preg_replace("/\[code\](.*?)\[\/code\]/ism","$CodeLayout", $Text);
1026
1027         // Declare the format for [spoiler] layout
1028         $SpoilerLayout = '<blockquote class="spoiler">$1</blockquote>';
1029
1030         // Check for [spoiler] text
1031         // handle nested quotes
1032         $endlessloop = 0;
1033         while ((strpos($Text, "[/spoiler]") !== false) and (strpos($Text, "[spoiler]") !== false) and (++$endlessloop < 20))
1034                 $Text = preg_replace("/\[spoiler\](.*?)\[\/spoiler\]/ism","$SpoilerLayout", $Text);
1035
1036         // Check for [spoiler=Author] text
1037
1038         $t_wrote = t('$1 wrote:');
1039
1040         // handle nested quotes
1041         $endlessloop = 0;
1042         while ((strpos($Text, "[/spoiler]")!== false)  and (strpos($Text, "[spoiler=") !== false) and (++$endlessloop < 20))
1043                 $Text = preg_replace("/\[spoiler=[\"\']*(.*?)[\"\']*\](.*?)\[\/spoiler\]/ism",
1044                                      "<br /><strong class=".'"spoiler"'.">" . $t_wrote . "</strong><blockquote class=".'"spoiler"'.">$2</blockquote>",
1045                                      $Text);
1046
1047         // Declare the format for [quote] layout
1048         $QuoteLayout = '<blockquote>$1</blockquote>';
1049
1050         // Check for [quote] text
1051         // handle nested quotes
1052         $endlessloop = 0;
1053         while ((strpos($Text, "[/quote]") !== false) and (strpos($Text, "[quote]") !== false) and (++$endlessloop < 20))
1054                 $Text = preg_replace("/\[quote\](.*?)\[\/quote\]/ism","$QuoteLayout", $Text);
1055
1056         // Check for [quote=Author] text
1057
1058         $t_wrote = t('$1 wrote:');
1059
1060         // handle nested quotes
1061         $endlessloop = 0;
1062         while ((strpos($Text, "[/quote]")!== false)  and (strpos($Text, "[quote=") !== false) and (++$endlessloop < 20))
1063                 $Text = preg_replace("/\[quote=[\"\']*(.*?)[\"\']*\](.*?)\[\/quote\]/ism",
1064                                      "<br /><strong class=".'"author"'.">" . $t_wrote . "</strong><blockquote>$2</blockquote>",
1065                                      $Text);
1066
1067         // [img=widthxheight]image source[/img]
1068         //$Text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '<img src="$3" style="height: $2px; width: $1px;" >', $Text);
1069         $Text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '<img src="$3" style="width: $1px;" >', $Text);
1070         $Text = preg_replace("/\[zmg\=([0-9]*)x([0-9]*)\](.*?)\[\/zmg\]/ism", '<img class="zrl" src="$3" style="width: $1px;" >', $Text);
1071
1072         // Images
1073         // [img]pathtoimage[/img]
1074         $Text = preg_replace("/\[img\](.*?)\[\/img\]/ism", '<img src="$1" alt="' . t('Image/photo') . '" />', $Text);
1075         $Text = preg_replace("/\[zmg\](.*?)\[\/zmg\]/ism", '<img src="$1" alt="' . t('Image/photo') . '" />', $Text);
1076
1077         // Shared content
1078         $Text = preg_replace_callback("/(.*?)\[share(.*?)\](.*?)\[\/share\]/ism",
1079                 function ($match) use ($simplehtml){
1080                         return(bb_ShareAttributes($match, $simplehtml));
1081                 },$Text);
1082
1083         $Text = preg_replace("/\[crypt\](.*?)\[\/crypt\]/ism",'<br/><img src="' .$a->get_baseurl() . '/images/lock_icon.gif" alt="' . t('Encrypted content') . '" title="' . t('Encrypted content') . '" /><br />', $Text);
1084         $Text = preg_replace("/\[crypt(.*?)\](.*?)\[\/crypt\]/ism",'<br/><img src="' .$a->get_baseurl() . '/images/lock_icon.gif" alt="' . t('Encrypted content') . '" title="' . '$1' . ' ' . t('Encrypted content') . '" /><br />', $Text);
1085         //$Text = preg_replace("/\[crypt=(.*?)\](.*?)\[\/crypt\]/ism",'<br/><img src="' .$a->get_baseurl() . '/images/lock_icon.gif" alt="' . t('Encrypted content') . '" title="' . '$1' . ' ' . t('Encrypted content') . '" /><br />', $Text);
1086
1087
1088         // Try to Oembed
1089         if ($tryoembed) {
1090                 $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);
1091                 $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);
1092
1093                 $a->save_timestamp($stamp1, "parser");
1094
1095                 $Text = preg_replace_callback("/\[video\](.*?)\[\/video\]/ism", 'tryoembed', $Text);
1096                 $Text = preg_replace_callback("/\[audio\](.*?)\[\/audio\]/ism", 'tryoembed', $Text);
1097
1098                 $stamp1 = microtime(true);
1099
1100         } else {
1101                 $Text = preg_replace("/\[video\](.*?)\[\/video\]/",
1102                                         '<a href="$1" target="_blank">$1</a>', $Text);
1103                 $Text = preg_replace("/\[audio\](.*?)\[\/audio\]/",
1104                                         '<a href="$1" target="_blank">$1</a>', $Text);
1105         }
1106
1107         // html5 video and audio
1108
1109
1110         if ($tryoembed)
1111                 $Text = preg_replace("/\[iframe\](.*?)\[\/iframe\]/ism", '<iframe src="$1" width="' . $a->videowidth . '" height="' . $a->videoheight . '"><a href="$1">$1</a></iframe>', $Text);
1112         else
1113                 $Text = preg_replace("/\[iframe\](.*?)\[\/iframe\]/ism", '<a href="$1">$1</a>', $Text);
1114
1115         // Youtube extensions
1116         if ($tryoembed) {
1117                 $a->save_timestamp($stamp1, "parser");
1118
1119                 $Text = preg_replace_callback("/\[youtube\](https?:\/\/www.youtube.com\/watch\?v\=.*?)\[\/youtube\]/ism", 'tryoembed', $Text);
1120                 $Text = preg_replace_callback("/\[youtube\](www.youtube.com\/watch\?v\=.*?)\[\/youtube\]/ism", 'tryoembed', $Text);
1121                 $Text = preg_replace_callback("/\[youtube\](https?:\/\/youtu.be\/.*?)\[\/youtube\]/ism",'tryoembed',$Text);
1122
1123                 $stamp1 = microtime(true);
1124         }
1125
1126         $Text = preg_replace("/\[youtube\]https?:\/\/www.youtube.com\/watch\?v\=(.*?)\[\/youtube\]/ism",'[youtube]$1[/youtube]',$Text);
1127         $Text = preg_replace("/\[youtube\]https?:\/\/www.youtube.com\/embed\/(.*?)\[\/youtube\]/ism",'[youtube]$1[/youtube]',$Text);
1128         $Text = preg_replace("/\[youtube\]https?:\/\/youtu.be\/(.*?)\[\/youtube\]/ism",'[youtube]$1[/youtube]',$Text);
1129
1130         if ($tryoembed)
1131                 $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);
1132         else
1133                 $Text = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
1134                                         '<a href="https://www.youtube.com/watch?v=$1" target="_blank">https://www.youtube.com/watch?v=$1</a>', $Text);
1135
1136         if ($tryoembed) {
1137                 $a->save_timestamp($stamp1, "parser");
1138
1139                 $Text = preg_replace_callback("/\[vimeo\](https?:\/\/player.vimeo.com\/video\/[0-9]+).*?\[\/vimeo\]/ism",'tryoembed',$Text);
1140                 $Text = preg_replace_callback("/\[vimeo\](https?:\/\/vimeo.com\/[0-9]+).*?\[\/vimeo\]/ism",'tryoembed',$Text);
1141
1142                 $stamp1 = microtime(true);
1143         }
1144
1145         $Text = preg_replace("/\[vimeo\]https?:\/\/player.vimeo.com\/video\/([0-9]+)(.*?)\[\/vimeo\]/ism",'[vimeo]$1[/vimeo]',$Text); 
1146         $Text = preg_replace("/\[vimeo\]https?:\/\/vimeo.com\/([0-9]+)(.*?)\[\/vimeo\]/ism",'[vimeo]$1[/vimeo]',$Text);
1147
1148         if ($tryoembed)
1149                 $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);
1150         else
1151                 $Text = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
1152                                         '<a href="https://vimeo.com/$1" target="_blank">https://vimeo.com/$1</a>', $Text);
1153
1154 //      $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);
1155
1156         $a->save_timestamp($stamp1, "parser");
1157
1158         // oembed tag
1159         $Text = oembed_bbcode2html($Text);
1160
1161         $stamp1 = microtime(true);
1162
1163         // Avoid triple linefeeds through oembed
1164         $Text = str_replace("<br style='clear:left'></span><br /><br />", "<br style='clear:left'></span><br />", $Text);
1165
1166         // If we found an event earlier, strip out all the event code and replace with a reformatted version.
1167         // Replace the event-start section with the entire formatted event. The other bbcode is stripped.
1168         // Summary (e.g. title) is required, earlier revisions only required description (in addition to 
1169         // start which is always required). Allow desc with a missing summary for compatibility.
1170
1171         if((x($ev,'desc') || x($ev,'summary')) && x($ev,'start')) {
1172                 $sub = format_event_html($ev);
1173
1174                 $Text = preg_replace("/\[event\-summary\](.*?)\[\/event\-summary\]/ism",'',$Text);
1175                 $Text = preg_replace("/\[event\-description\](.*?)\[\/event\-description\]/ism",'',$Text);
1176                 $Text = preg_replace("/\[event\-start\](.*?)\[\/event\-start\]/ism",$sub,$Text); 
1177                 $Text = preg_replace("/\[event\-finish\](.*?)\[\/event\-finish\]/ism",'',$Text);
1178                 $Text = preg_replace("/\[event\-location\](.*?)\[\/event\-location\]/ism",'',$Text);
1179                 $Text = preg_replace("/\[event\-adjust\](.*?)\[\/event\-adjust\]/ism",'',$Text);
1180         }
1181
1182         // Unhide all [noparse] contained bbtags unspacefying them 
1183         // and triming the [noparse] tag.
1184
1185         $Text = preg_replace_callback("/\[noparse\](.*?)\[\/noparse\]/ism", 'bb_unspacefy_and_trim',$Text);
1186         $Text = preg_replace_callback("/\[nobb\](.*?)\[\/nobb\]/ism", 'bb_unspacefy_and_trim',$Text);
1187         $Text = preg_replace_callback("/\[pre\](.*?)\[\/pre\]/ism", 'bb_unspacefy_and_trim',$Text);
1188
1189
1190         $Text = preg_replace('/\[\&amp\;([#a-z0-9]+)\;\]/','&$1;',$Text);
1191         $Text = preg_replace('/\&\#039\;/','\'',$Text);
1192         $Text = preg_replace('/\&quot\;/','"',$Text);
1193
1194         // fix any escaped ampersands that may have been converted into links
1195         $Text = preg_replace("/\<([^>]*?)(src|href)=(.*?)\&amp\;(.*?)\>/ism",'<$1$2=$3&$4>',$Text);
1196         $Text = preg_replace("/\<([^>]*?)(src|href)=\"(?!http|ftp|mailto|cid)(.*?)\>/ism",'<$1$2="">',$Text);
1197
1198         if($saved_image)
1199                 $Text = bb_replace_images($Text, $saved_image);
1200
1201         // Clean up the HTML by loading and saving the HTML with the DOM.
1202         // Bad structured html can break a whole page.
1203         // For performance reasons do it only with ativated item cache or at export.
1204         if (!$tryoembed OR (get_itemcachepath() != "")) {
1205                 $doc = new DOMDocument();
1206                 $doc->preserveWhiteSpace = false;
1207
1208                 $Text = mb_convert_encoding($Text, 'HTML-ENTITIES', "UTF-8");
1209
1210                 $doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">';
1211                 $encoding = '<?xml encoding="UTF-8">';
1212                 @$doc->loadHTML($encoding.$doctype."<html><body>".$Text."</body></html>");
1213                 $doc->encoding = 'UTF-8';
1214                 $Text = $doc->saveHTML();
1215                 $Text = str_replace(array("<html><body>", "</body></html>", $doctype, $encoding), array("", "", "", ""), $Text);
1216
1217                 $Text = str_replace('<br></li>','</li>', $Text);
1218
1219                 //$Text = mb_convert_encoding($Text, "UTF-8", 'HTML-ENTITIES');
1220         }
1221
1222         // Clean up some useless linebreaks in lists
1223         //$Text = str_replace('<br /><ul','<ul ', $Text);
1224         //$Text = str_replace('</ul><br />','</ul>', $Text);
1225         //$Text = str_replace('</li><br />','</li>', $Text);
1226         //$Text = str_replace('<br /><li>','<li>', $Text);
1227         //      $Text = str_replace('<br /><ul','<ul ', $Text);
1228
1229         call_hooks('bbcode',$Text);
1230
1231         $a->save_timestamp($stamp1, "parser");
1232
1233         return trim($Text);
1234 }
1235 ?>