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