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