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