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