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