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