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