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