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