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