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