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