]> git.mxchange.org Git - friendica.git/blob - include/bbcode.php
b3f6aa826b6938390b4b94c62ecf0cd773ed1cfe
[friendica.git] / include / bbcode.php
1 <?php
2
3 require_once("include/oembed.php");
4 require_once('include/event.php');
5
6 function cleancss($input) {
7
8         $cleaned = "";
9
10         $input = strtolower($input);
11
12         for ($i = 0; $i < strlen($input); $i++) {
13                 $char = substr($input, $i, 1);
14
15                 if (($char >= "a") and ($char <= "z"))
16                         $cleaned .= $char;
17
18                 if (!(strpos(" #;:0123456789", $char) === false))
19                         $cleaned .= $char;
20         }
21
22         return($cleaned);
23 }
24
25 function stripcode_br_cb($s) {
26         return '[code]' . str_replace('<br />', '', $s[1]) . '[/code]';
27 }
28
29 function tryoembed($match){
30         $url = ((count($match)==2)?$match[1]:$match[2]);
31 //      logger("tryoembed: $url");
32
33         $o = oembed_fetch_url($url);
34
35         //echo "<pre>"; var_dump($match, $url, $o); killme();
36
37         if ($o->type=="error") return $match[0];
38
39         $html = oembed_format_object($o);
40         return $html; //oembed_iframe($html,$o->width,$o->height);
41
42 }
43
44 // [noparse][i]italic[/i][/noparse] turns into
45 // [noparse][ i ]italic[ /i ][/noparse],
46 // to hide them from parser.
47
48 function bb_spacefy($st) {
49   $whole_match = $st[0];
50   $captured = $st[1];
51   $spacefied = preg_replace("/\[(.*?)\]/", "[ $1 ]", $captured);
52   $new_str = str_replace($captured, $spacefied, $whole_match);
53   return $new_str;
54 }
55
56 // The previously spacefied [noparse][ i ]italic[ /i ][/noparse],
57 // now turns back and the [noparse] tags are trimed
58 // returning [i]italic[/i]
59
60 function bb_unspacefy_and_trim($st) {
61   $whole_match = $st[0];
62   $captured = $st[1];
63   $unspacefied = preg_replace("/\[ (.*?)\ ]/", "[$1]", $captured);
64   return $unspacefied;
65 }
66
67 function bb_find_open_close($s, $open, $close, $occurance = 1) {
68
69         if($occurance < 1)
70                 $occurance = 1;
71
72         $start_pos = -1;
73         for($i = 1; $i <= $occurance; $i++) {
74                 if( $start_pos !== false)
75                         $start_pos = strpos($s, $open, $start_pos + 1);
76         }
77
78         if( $start_pos === false)
79                 return false;
80
81         $end_pos = strpos($s, $close, $start_pos);
82
83         if( $end_pos === false)
84                 return false;
85
86         $res = array( 'start' => $start_pos, 'end' => $end_pos );
87
88         return $res;
89 }
90
91 function get_bb_tag_pos($s, $name, $occurance = 1) {
92
93         if($occurance < 1)
94                 $occurance = 1;
95
96         $start_open = -1;
97         for($i = 1; $i <= $occurance; $i++) {
98                 if( $start_open !== false)
99                         $start_open = strpos($s, '[' . $name, $start_open + 1); // allow [name= type tags
100         }
101
102         if( $start_open === false)
103                 return false;
104
105         $start_equal = strpos($s, '=', $start_open);
106         $start_close = strpos($s, ']', $start_open);
107
108         if( $start_close === false)
109                 return false;
110
111         $start_close++;
112
113         $end_open = strpos($s, '[/' . $name . ']', $start_close);
114
115         if( $end_open === false)
116                 return false;
117
118         $res = array( 'start' => array('open' => $start_open, 'close' => $start_close),
119                       'end' => array('open' => $end_open, 'close' => $end_open + strlen('[/' . $name . ']')) );
120         if( $start_equal !== false)
121                 $res['start']['equal'] = $start_equal + 1;
122
123         return $res;
124 }
125
126 function bb_tag_preg_replace($pattern, $replace, $name, $s) {
127
128         $string = $s;
129
130         $occurance = 1;
131         $pos = get_bb_tag_pos($string, $name, $occurance);
132         while($pos !== false && $occurance < 1000) {
133
134                 $start = substr($string, 0, $pos['start']['open']);
135                 $subject = substr($string, $pos['start']['open'], $pos['end']['close'] - $pos['start']['open']);
136                 $end = substr($string, $pos['end']['close']);
137                 if($end === false)
138                         $end = '';
139
140                 $subject = preg_replace($pattern, $replace, $subject);
141                 $string = $start . $subject . $end;
142
143                 $occurance++;
144                 $pos = get_bb_tag_pos($string, $name, $occurance);
145         }
146
147         return $string;
148 }
149
150 if(! function_exists('bb_extract_images')) {
151 function bb_extract_images($body) {
152
153         $saved_image = array();
154         $orig_body = $body;
155         $new_body = '';
156
157         $cnt = 0;
158         $img_start = strpos($orig_body, '[img');
159         $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
160         $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
161         while(($img_st_close !== false) && ($img_end !== false)) {
162
163                 $img_st_close++; // make it point to AFTER the closing bracket
164                 $img_end += $img_start;
165
166                 if(! strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
167                         // This is an embedded image
168
169                         $saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close));
170                         $new_body = $new_body . substr($orig_body, 0, $img_start) . '[$#saved_image' . $cnt . '#$]';
171
172                         $cnt++;
173                 }
174                 else
175                         $new_body = $new_body . substr($orig_body, 0, $img_end + strlen('[/img]'));
176
177                 $orig_body = substr($orig_body, $img_end + strlen('[/img]'));
178
179                 if($orig_body === false) // in case the body ends on a closing image tag
180                         $orig_body = '';
181
182                 $img_start = strpos($orig_body, '[img');
183                 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
184                 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
185         }
186
187         $new_body = $new_body . $orig_body;
188
189         return array('body' => $new_body, 'images' => $saved_image);
190 }}
191
192 if(! function_exists('bb_replace_images')) {
193 function bb_replace_images($body, $images) {
194
195         $newbody = $body;
196
197         $cnt = 0;
198         foreach($images as $image) {
199                 // We're depending on the property of 'foreach' (specified on the PHP website) that
200                 // it loops over the array starting from the first element and going sequentially
201                 // to the last element
202                 $newbody = str_replace('[$#saved_image' . $cnt . '#$]', '<img src="' . $image .'" alt="' . t('Image/photo') . '" />', $newbody);
203                 $cnt++;
204         }
205
206         return $newbody;
207 }}
208
209 function bb_ShareAttributes($match) {
210
211         $attributes = $match[1];
212
213         $author = "";
214         preg_match("/author='(.*?)'/ism", $attributes, $matches);
215         if ($matches[1] != "")
216                 $author = $matches[1];
217
218         preg_match('/author="(.*?)"/ism', $attributes, $matches);
219         if ($matches[1] != "")
220                 $author = $matches[1];
221
222         $link = "";
223         preg_match("/link='(.*?)'/ism", $attributes, $matches);
224         if ($matches[1] != "")
225                 $link = $matches[1];
226
227         preg_match('/link="(.*?)"/ism', $attributes, $matches);
228         if ($matches[1] != "")
229                 $link = $matches[1];
230
231         $avatar = "";
232         preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
233         if ($matches[1] != "")
234                 $avatar = $matches[1];
235
236         preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
237         if ($matches[1] != "")
238                 $avatar = $matches[1];
239
240         $profile = "";
241         preg_match("/profile='(.*?)'/ism", $attributes, $matches);
242         if ($matches[1] != "")
243                 $profile = $matches[1];
244
245         preg_match('/profile="(.*?)"/ism', $attributes, $matches);
246         if ($matches[1] != "")
247                 $profile = $matches[1];
248
249         $headline = '<div class="shared_header">';
250
251         if ($avatar != "")
252                 $headline .= '<img src="'.$avatar.'" height="32" width="32" >';
253
254         $headline .= sprintf(t('<span><a href="%s">%s</a> wrote the following <a href="%s">post</a>:</span>'), $profile, $author, $link);
255
256         $headline .= "</div>";
257
258         $text = "<br />".$headline.'<blockquote class="shared_content">'.trim($match[2])."</blockquote>";
259
260         return($text);
261 }
262
263         // BBcode 2 HTML was written by WAY2WEB.net
264         // extended to work with Mistpark/Friendica - Mike Macgirvin
265
266 function bbcode($Text,$preserve_nl = false, $tryoembed = true) {
267
268         $a = get_app();
269
270         // Hide all [noparse] contained bbtags by spacefying them
271         // POSSIBLE BUG --> Will the 'preg' functions crash if there's an embedded image?
272
273         $Text = preg_replace_callback("/\[noparse\](.*?)\[\/noparse\]/ism", 'bb_spacefy',$Text);
274         $Text = preg_replace_callback("/\[nobb\](.*?)\[\/nobb\]/ism", 'bb_spacefy',$Text);
275         $Text = preg_replace_callback("/\[pre\](.*?)\[\/pre\]/ism", 'bb_spacefy',$Text);
276
277
278         // Move all spaces out of the tags
279         $Text = preg_replace("/\[(\w*)\](\s*)/ism", '$2[$1]', $Text);
280         $Text = preg_replace("/(\s*)\[\/(\w*)\]/ism", '[/$2]$1', $Text);
281
282         // Extract the private images which use data url's since preg has issues with
283         // large data sizes. Stash them away while we do bbcode conversion, and then put them back
284         // in after we've done all the regex matching. We cannot use any preg functions to do this.
285
286         $extracted = bb_extract_images($Text);
287         $Text = $extracted['body'];
288         $saved_image = $extracted['images'];
289
290         // If we find any event code, turn it into an event.
291         // After we're finished processing the bbcode we'll
292         // replace all of the event code with a reformatted version.
293
294         $ev = bbtoevent($Text);
295
296
297         // Replace any html brackets with HTML Entities to prevent executing HTML or script
298         // Don't use strip_tags here because it breaks [url] search by replacing & with amp
299
300         $Text = str_replace("<", "&lt;", $Text);
301         $Text = str_replace(">", "&gt;", $Text);
302
303         // remove some newlines before the general conversion
304         $Text = preg_replace("/\s?\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","[share$1]$2[/share]",$Text);
305
306         // when the content is meant exporting to other systems then remove the avatar picture since this doesn't really look good on these systems
307         if (!$tryoembed)
308                 $Text = preg_replace("/\[share(.*?)avatar\s?=\s?'.*?'\s?(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","\n[share$1$2]$3[/share]",$Text);
309
310         // Convert new line chars to html <br /> tags
311
312         // nlbr seems to be hopelessly messed up
313         //      $Text = nl2br($Text);
314
315         // We'll emulate it.
316
317         $Text = str_replace("\r\n","\n", $Text);
318         $Text = str_replace(array("\r","\n"), array('<br />','<br />'), $Text);
319
320         if($preserve_nl)
321                 $Text = str_replace(array("\n","\r"), array('',''),$Text);
322
323
324
325         // Set up the parameters for a URL search string
326         $URLSearchString = "^\[\]";
327         // Set up the parameters for a MAIL search string
328         $MAILSearchString = $URLSearchString;
329
330
331         // Perform URL Search
332
333         $Text = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1<a href="$2" target="external-link">$2</a>', $Text);
334
335         if ($tryoembed)
336                 $Text = preg_replace_callback("/\[bookmark\=([^\]]*)\].*?\[\/bookmark\]/ism",'tryoembed',$Text);
337
338         $Text = preg_replace("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$Text);
339
340         if ($tryoembed)
341                 $Text = preg_replace_callback("/\[url\]([$URLSearchString]*)\[\/url\]/ism",'tryoembed',$Text);
342
343         $Text = preg_replace("/\[url\]([$URLSearchString]*)\[\/url\]/ism", '<a href="$1" target="external-link">$1</a>', $Text);
344         $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '<a href="$1" target="external-link">$2</a>', $Text);
345         //$Text = preg_replace("/\[url\=([$URLSearchString]*)\]([$URLSearchString]*)\[\/url\]/ism", '<a href="$1" target="_blank">$2</a>', $Text);
346
347         // we may need to restrict this further if it picks up too many strays
348         // link acct:user@host to a webfinger profile redirector
349
350         $Text = preg_replace('/acct:(.*?)@(.*?)([ ,])/', '<a href="' . $a->get_baseurl() . '/acctlink?addr=' . "$1@$2" 
351                 . '" target="extlink" >acct:' . "$1@$2$3" . '</a>',$Text);
352
353         // Perform MAIL Search
354         $Text = preg_replace("/\[mail\]([$MAILSearchString]*)\[\/mail\]/", '<a href="mailto:$1">$1</a>', $Text);
355         $Text = preg_replace("/\[mail\=([$MAILSearchString]*)\](.*?)\[\/mail\]/", '<a href="mailto:$1">$2</a>', $Text);
356
357         // Check for bold text
358         $Text = preg_replace("(\[b\](.*?)\[\/b\])ism",'<strong>$1</strong>',$Text);
359
360         // Check for Italics text
361         $Text = preg_replace("(\[i\](.*?)\[\/i\])ism",'<em>$1</em>',$Text);
362
363         // Check for Underline text
364         $Text = preg_replace("(\[u\](.*?)\[\/u\])ism",'<u>$1</u>',$Text);
365
366         // Check for strike-through text
367         $Text = preg_replace("(\[s\](.*?)\[\/s\])ism",'<strike>$1</strike>',$Text);
368
369         // Check for over-line text
370         $Text = preg_replace("(\[o\](.*?)\[\/o\])ism",'<span class="overline">$1</span>',$Text);
371
372         // Check for colored text
373         $Text = preg_replace("(\[color=(.*?)\](.*?)\[\/color\])ism","<span style=\"color: $1;\">$2</span>",$Text);
374
375         // Check for sized text
376         // [size=50] --> font-size: 50px (with the unit).
377         $Text = preg_replace("(\[size=(\d*?)\](.*?)\[\/size\])ism","<span style=\"font-size: $1px;\">$2</span>",$Text);
378         $Text = preg_replace("(\[size=(.*?)\](.*?)\[\/size\])ism","<span style=\"font-size: $1;\">$2</span>",$Text);
379
380         // Check for centered text
381         $Text = preg_replace("(\[center\](.*?)\[\/center\])ism","<div style=\"text-align:center;\">$1</div>",$Text);
382
383         // Check for list text
384         $Text = str_replace("[*]", "<li>", $Text);
385
386         // Check for style sheet commands
387         $Text = preg_replace("(\[style=(.*?)\](.*?)\[\/style\])ism","<span style=\"$1;\">$2</span>",$Text);
388
389         // Check for CSS classes
390         $Text = preg_replace("(\[class=(.*?)\](.*?)\[\/class\])ism","<span class=\"$1\">$2</span>",$Text);
391
392         // handle nested lists
393         $endlessloop = 0;
394
395         while ((((strpos($Text, "[/list]") !== false) && (strpos($Text, "[list") !== false)) ||
396                ((strpos($Text, "[/ol]") !== false) && (strpos($Text, "[ol]") !== false)) || 
397                ((strpos($Text, "[/ul]") !== false) && (strpos($Text, "[ul]") !== false)) || 
398                ((strpos($Text, "[/li]") !== false) && (strpos($Text, "[li]") !== false))) && (++$endlessloop < 20)) {
399                 $Text = preg_replace("/\[list\](.*?)\[\/list\]/ism", '<ul class="listbullet" style="list-style-type: circle;">$1</ul>' ,$Text);
400                 $Text = preg_replace("/\[list=\](.*?)\[\/list\]/ism", '<ul class="listnone" style="list-style-type: none;">$1</ul>' ,$Text);
401                 $Text = preg_replace("/\[list=1\](.*?)\[\/list\]/ism", '<ul class="listdecimal" style="list-style-type: decimal;">$1</ul>' ,$Text);
402                 $Text = preg_replace("/\[list=((?-i)i)\](.*?)\[\/list\]/ism",'<ul class="listlowerroman" style="list-style-type: lower-roman;">$2</ul>' ,$Text);
403                 $Text = preg_replace("/\[list=((?-i)I)\](.*?)\[\/list\]/ism", '<ul class="listupperroman" style="list-style-type: upper-roman;">$2</ul>' ,$Text);
404                 $Text = preg_replace("/\[list=((?-i)a)\](.*?)\[\/list\]/ism", '<ul class="listloweralpha" style="list-style-type: lower-alpha;">$2</ul>' ,$Text);
405                 $Text = preg_replace("/\[list=((?-i)A)\](.*?)\[\/list\]/ism", '<ul class="listupperalpha" style="list-style-type: upper-alpha;">$2</ul>' ,$Text);
406                 $Text = preg_replace("/\[ul\](.*?)\[\/ul\]/ism", '<ul class="listbullet" style="list-style-type: circle;">$1</ul>' ,$Text);
407                 $Text = preg_replace("/\[ol\](.*?)\[\/ol\]/ism", '<ul class="listdecimal" style="list-style-type: decimal;">$1</ul>' ,$Text);
408                 $Text = preg_replace("/\[li\](.*?)\[\/li\]/ism", '<li>$1</li>' ,$Text);
409         }
410
411         $Text = preg_replace("/\[th\](.*?)\[\/th\]/sm", '<th>$1</th>' ,$Text);
412         $Text = preg_replace("/\[td\](.*?)\[\/td\]/sm", '<td>$1</td>' ,$Text);
413         $Text = preg_replace("/\[tr\](.*?)\[\/tr\]/sm", '<tr>$1</tr>' ,$Text);
414         $Text = preg_replace("/\[table\](.*?)\[\/table\]/sm", '<table>$1</table>' ,$Text);
415
416         $Text = preg_replace("/\[table border=1\](.*?)\[\/table\]/sm", '<table border="1" >$1</table>' ,$Text);
417         $Text = preg_replace("/\[table border=0\](.*?)\[\/table\]/sm", '<table border="0" >$1</table>' ,$Text);
418
419         $Text = str_replace('[hr]','<hr />', $Text);
420
421         // This is actually executed in prepare_body()
422
423         $Text = str_replace('[nosmile]','',$Text);
424
425         // Check for font change text
426         $Text = preg_replace("/\[font=(.*?)\](.*?)\[\/font\]/sm","<span style=\"font-family: $1;\">$2</span>",$Text);
427
428         // Declare the format for [code] layout
429
430 //      $Text = preg_replace_callback("/\[code\](.*?)\[\/code\]/ism",'stripcode_br_cb',$Text);
431
432         $CodeLayout = '<code>$1</code>';
433         // Check for [code] text
434         $Text = preg_replace("/\[code\](.*?)\[\/code\]/ism","$CodeLayout", $Text);
435
436         // Declare the format for [spoiler] layout
437         $SpoilerLayout = '<blockquote class="spoiler">$1</blockquote>';
438
439         // Check for [spoiler] text
440         // handle nested quotes
441         $endlessloop = 0;
442         while ((strpos($Text, "[/spoiler]") !== false) and (strpos($Text, "[spoiler]") !== false) and (++$endlessloop < 20))
443                 $Text = preg_replace("/\[spoiler\](.*?)\[\/spoiler\]/ism","$SpoilerLayout", $Text);
444
445         // Check for [spoiler=Author] text
446
447         $t_wrote = t('$1 wrote:');
448
449         // handle nested quotes
450         $endlessloop = 0;
451         while ((strpos($Text, "[/spoiler]")!== false)  and (strpos($Text, "[spoiler=") !== false) and (++$endlessloop < 20))
452                 $Text = preg_replace("/\[spoiler=[\"\']*(.*?)[\"\']*\](.*?)\[\/spoiler\]/ism",
453                                      "<br /><strong class=".'"spoiler"'.">" . $t_wrote . "</strong><blockquote class=".'"spoiler"'.">$2</blockquote>",
454                                      $Text);
455
456         // Declare the format for [quote] layout
457         $QuoteLayout = '<blockquote>$1</blockquote>';
458
459         // Check for [quote] text
460         // handle nested quotes
461         $endlessloop = 0;
462         while ((strpos($Text, "[/quote]") !== false) and (strpos($Text, "[quote]") !== false) and (++$endlessloop < 20))
463                 $Text = preg_replace("/\[quote\](.*?)\[\/quote\]/ism","$QuoteLayout", $Text);
464
465         // Check for [quote=Author] text
466
467         $t_wrote = t('$1 wrote:');
468
469         // handle nested quotes
470         $endlessloop = 0;
471         while ((strpos($Text, "[/quote]")!== false)  and (strpos($Text, "[quote=") !== false) and (++$endlessloop < 20))
472                 $Text = preg_replace("/\[quote=[\"\']*(.*?)[\"\']*\](.*?)\[\/quote\]/ism",
473                                      "<br /><strong class=".'"author"'.">" . $t_wrote . "</strong><blockquote>$2</blockquote>",
474                                      $Text);
475
476         // [img=widthxheight]image source[/img]
477         //$Text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '<img src="$3" style="height: $2px; width: $1px;" >', $Text);
478         $Text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '<img src="$3" style="width: $1px;" >', $Text);
479
480         // Images
481         // [img]pathtoimage[/img]
482         $Text = preg_replace("/\[img\](.*?)\[\/img\]/ism", '<img src="$1" alt="' . t('Image/photo') . '" />', $Text);
483
484         // Shared content
485         $Text = preg_replace_callback("/\[share(.*?)\](.*?)\[\/share\]/ism","bb_ShareAttributes",$Text);
486
487         $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);
488         $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);
489
490
491         // Try to Oembed
492         if ($tryoembed) {
493                 $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);
494                 $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);
495
496                 $Text = preg_replace_callback("/\[video\](.*?)\[\/video\]/ism", 'tryoembed', $Text);
497                 $Text = preg_replace_callback("/\[audio\](.*?)\[\/audio\]/ism", 'tryoembed', $Text);
498         } else {
499                 $Text = preg_replace("/\[video\](.*?)\[\/video\]/", '$1', $Text);
500                 $Text = preg_replace("/\[audio\](.*?)\[\/audio\]/", '$1', $Text);
501         }
502
503         // html5 video and audio
504
505
506         if ($tryoembed)
507                 $Text = preg_replace("/\[iframe\](.*?)\[\/iframe\]/ism", '<iframe src="$1" width="' . $a->videowidth . '" height="' . $a->videoheight . '"><a href="$1">$1</a></iframe>', $Text);
508         else
509                 $Text = preg_replace("/\[iframe\](.*?)\[\/iframe\]/ism", '<a href="$1">$1</a>', $Text);
510
511         // Youtube extensions
512         if ($tryoembed) {
513                 $Text = preg_replace_callback("/\[youtube\](https?:\/\/www.youtube.com\/watch\?v\=.*?)\[\/youtube\]/ism", 'tryoembed', $Text);        
514                 $Text = preg_replace_callback("/\[youtube\](www.youtube.com\/watch\?v\=.*?)\[\/youtube\]/ism", 'tryoembed', $Text);        
515                 $Text = preg_replace_callback("/\[youtube\](https?:\/\/youtu.be\/.*?)\[\/youtube\]/ism",'tryoembed',$Text); 
516         }
517
518         $Text = preg_replace("/\[youtube\]https?:\/\/www.youtube.com\/watch\?v\=(.*?)\[\/youtube\]/ism",'[youtube]$1[/youtube]',$Text); 
519         $Text = preg_replace("/\[youtube\]https?:\/\/www.youtube.com\/embed\/(.*?)\[\/youtube\]/ism",'[youtube]$1[/youtube]',$Text); 
520         $Text = preg_replace("/\[youtube\]https?:\/\/youtu.be\/(.*?)\[\/youtube\]/ism",'[youtube]$1[/youtube]',$Text);
521
522         if ($tryoembed)
523                 $Text = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism", '<iframe width="' . $a->videowidth . '" height="' . $a->videoheight . '" src="http://www.youtube.com/embed/$1" frameborder="0" ></iframe>', $Text);
524         else
525                 $Text = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism", "http://www.youtube.com/watch?v=$1", $Text);
526
527
528         if ($tryoembed) {
529                 $Text = preg_replace_callback("/\[vimeo\](https?:\/\/player.vimeo.com\/video\/[0-9]+).*?\[\/vimeo\]/ism",'tryoembed',$Text); 
530                 $Text = preg_replace_callback("/\[vimeo\](https?:\/\/vimeo.com\/[0-9]+).*?\[\/vimeo\]/ism",'tryoembed',$Text); 
531         }
532
533         $Text = preg_replace("/\[vimeo\]https?:\/\/player.vimeo.com\/video\/([0-9]+)(.*?)\[\/vimeo\]/ism",'[vimeo]$1[/vimeo]',$Text); 
534         $Text = preg_replace("/\[vimeo\]https?:\/\/vimeo.com\/([0-9]+)(.*?)\[\/vimeo\]/ism",'[vimeo]$1[/vimeo]',$Text);
535
536         if ($tryoembed)
537                 $Text = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism", '<iframe width="' . $a->videowidth . '" height="' . $a->videoheight . '" src="http://player.vimeo.com/video/$1" frameborder="0" ></iframe>', $Text);
538         else
539                 $Text = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism", "http://vimeo.com/$1", $Text);
540
541 //      $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);
542
543
544         // oembed tag
545         $Text = oembed_bbcode2html($Text);
546
547         // Avoid triple linefeeds through oembed
548         $Text = str_replace("<br style='clear:left'></span><br /><br />", "<br style='clear:left'></span><br />", $Text);
549
550         // If we found an event earlier, strip out all the event code and replace with a reformatted version.
551         // Replace the event-start section with the entire formatted event. The other bbcode is stripped.
552         // Summary (e.g. title) is required, earlier revisions only required description (in addition to 
553         // start which is always required). Allow desc with a missing summary for compatibility.
554
555         if((x($ev,'desc') || x($ev,'summary')) && x($ev,'start')) {
556                 $sub = format_event_html($ev);
557
558                 $Text = preg_replace("/\[event\-summary\](.*?)\[\/event\-summary\]/ism",'',$Text);
559                 $Text = preg_replace("/\[event\-description\](.*?)\[\/event\-description\]/ism",'',$Text);
560                 $Text = preg_replace("/\[event\-start\](.*?)\[\/event\-start\]/ism",$sub,$Text); 
561                 $Text = preg_replace("/\[event\-finish\](.*?)\[\/event\-finish\]/ism",'',$Text);
562                 $Text = preg_replace("/\[event\-location\](.*?)\[\/event\-location\]/ism",'',$Text);
563                 $Text = preg_replace("/\[event\-adjust\](.*?)\[\/event\-adjust\]/ism",'',$Text);
564         }
565
566         // Unhide all [noparse] contained bbtags unspacefying them 
567         // and triming the [noparse] tag.
568
569         $Text = preg_replace_callback("/\[noparse\](.*?)\[\/noparse\]/ism", 'bb_unspacefy_and_trim',$Text);
570         $Text = preg_replace_callback("/\[nobb\](.*?)\[\/nobb\]/ism", 'bb_unspacefy_and_trim',$Text);
571         $Text = preg_replace_callback("/\[pre\](.*?)\[\/pre\]/ism", 'bb_unspacefy_and_trim',$Text);
572
573
574         $Text = preg_replace('/\[\&amp\;([#a-z0-9]+)\;\]/','&$1;',$Text);
575         $Text = preg_replace('/\&\#039\;/','\'',$Text);
576         $Text = preg_replace('/\&quot\;/','"',$Text);
577
578         // fix any escaped ampersands that may have been converted into links
579         $Text = preg_replace("/\<(.*?)(src|href)=(.*?)\&amp\;(.*?)\>/ism",'<$1$2=$3&$4>',$Text);
580         $Text = preg_replace("/\<(.*?)(src|href)=\"[^hfm](.*?)\>/ism",'<$1$2="">',$Text);
581
582         if($saved_image)
583                 $Text = bb_replace_images($Text, $saved_image);
584
585         // Clean up the HTML by loading and saving the HTML with the DOM
586         // Only do it when it has to be done - for performance reasons
587         if (!$tryoembed) {
588                 $doc = new DOMDocument();
589                 $doc->preserveWhiteSpace = false;
590
591                 $Text = mb_convert_encoding($Text, 'HTML-ENTITIES', "UTF-8");
592
593                 $doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">';
594                 @$doc->loadHTML($doctype."<html><body>".$Text."</body></html>");
595
596                 $Text = $doc->saveHTML();
597                 $Text = str_replace(array("<html><body>", "</body></html>", $doctype), array("", "", ""), $Text);
598
599                 $Text = str_replace('<br></li>','</li>', $Text);
600
601                 $Text = mb_convert_encoding($Text, "UTF-8", 'HTML-ENTITIES');
602         }
603
604         call_hooks('bbcode',$Text);
605
606         return $Text;
607 }
608