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