]> git.mxchange.org Git - friendica.git/blob - include/bb2diaspora.php
Merge branch 'develop' into rewrites/coding-convention-split2
[friendica.git] / include / bb2diaspora.php
1 <?php
2
3 require_once("include/oembed.php");
4 require_once("include/event.php");
5 require_once("library/markdown.php");
6 require_once("include/html2bbcode.php");
7 require_once("include/bbcode.php");
8 require_once("library/html-to-markdown/HTML_To_Markdown.php");
9
10 /**
11  * @brief Callback function to replace a Diaspora style mention in a mention for Friendica
12  *
13  * @param array $match Matching values for the callback
14  * @return string Replaced mention
15  */
16 function diaspora_mention2bb($match) {
17         if ($match[2] == '') {
18                 return;
19         }
20
21         $data = get_contact_details_by_addr($match[2]);
22
23         $name = $match[1];
24
25         if ($name == '') {
26                 $name = $data['name'];
27         }
28
29         return '@[url='.$data['url'].']'.$name.'[/url]';
30 }
31
32 // we don't want to support a bbcode specific markdown interpreter
33 // and the markdown library we have is pretty good, but provides HTML output.
34 // So we'll use that to convert to HTML, then convert the HTML back to bbcode,
35 // and then clean up a few Diaspora specific constructs.
36
37 function diaspora2bb($s) {
38
39         $s = html_entity_decode($s, ENT_COMPAT, 'UTF-8');
40
41         // Handles single newlines
42         $s = str_replace("\r\n", "\n", $s);
43         $s = str_replace("\n", " \n", $s);
44         $s = str_replace("\r", " \n", $s);
45
46         // Replace lonely stars in lines not starting with it with literal stars
47         $s = preg_replace('/^([^\*]+)\*([^\*]*)$/im', '$1\*$2', $s);
48
49         // The parser cannot handle paragraphs correctly
50         $s = str_replace(array('</p>', '<p>', '<p dir="ltr">'), array('<br>', '<br>', '<br>'), $s);
51
52         // Escaping the hash tags
53         $s = preg_replace('/\#([^\s\#])/', '&#35;$1', $s);
54
55         $s = Markdown($s);
56
57         $regexp = "/@\{(?:([^\}]+?); )?([^\} ]+)\}/";
58         $s = preg_replace_callback($regexp, 'diaspora_mention2bb', $s);
59
60         $s = str_replace('&#35;', '#', $s);
61
62         $s = html2bbcode($s);
63
64         // protect the recycle symbol from turning into a tag, but without unescaping angles and naked ampersands
65         $s = str_replace('&#x2672;', html_entity_decode('&#x2672;', ENT_QUOTES, 'UTF-8'), $s);
66
67         // Convert everything that looks like a link to a link
68         $s = preg_replace('/([^\]=]|^)(https?\:\/\/)([a-zA-Z0-9:\/\-?&;.=_~#%$!+,@]+(?<!,))/ism', '$1[url=$2$3]$2$3[/url]', $s);
69
70         //$s = preg_replace("/([^\]\=]|^)(https?\:\/\/)(vimeo|youtu|www\.youtube|soundcloud)([a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2$3$4]$2$3$4[/url]',$s);
71         $s = bb_tag_preg_replace('/\[url\=?(.*?)\]https?:\/\/www.youtube.com\/watch\?v\=(.*?)\[\/url\]/ism', '[youtube]$2[/youtube]', 'url', $s);
72         $s = bb_tag_preg_replace('/\[url\=https?:\/\/www.youtube.com\/watch\?v\=(.*?)\].*?\[\/url\]/ism'   , '[youtube]$1[/youtube]', 'url', $s);
73         $s = bb_tag_preg_replace('/\[url\=?(.*?)\]https?:\/\/vimeo.com\/([0-9]+)(.*?)\[\/url\]/ism'        , '[vimeo]$2[/vimeo]'    , 'url', $s);
74         $s = bb_tag_preg_replace('/\[url\=https?:\/\/vimeo.com\/([0-9]+)\](.*?)\[\/url\]/ism'              , '[vimeo]$1[/vimeo]'    , 'url', $s);
75
76         // remove duplicate adjacent code tags
77         $s = preg_replace('/(\[code\])+(.*?)(\[\/code\])+/ism', '[code]$2[/code]', $s);
78
79         // Don't show link to full picture (until it is fixed)
80         $s = scale_external_images($s, false);
81
82         return $s;
83 }
84
85 /**
86  * @brief Callback function to replace a Friendica style mention in a mention for Diaspora
87  *
88  * @param array $match Matching values for the callback
89  * @return string Replaced mention
90  */
91 function diaspora_mentions($match) {
92
93         $contact = get_contact_details_by_url($match[3]);
94
95         if (!isset($contact['addr'])) {
96                 $contact = Probe::uri($match[3]);
97         }
98
99         if (!isset($contact['addr'])) {
100                 return $match[0];
101         }
102
103         $mention = '@{'.$match[2].'; '.$contact['addr'].'}';
104         return $mention;
105 }
106
107 function bb2diaspora($Text,$preserve_nl = false, $fordiaspora = true) {
108
109         $a = get_app();
110
111         $OriginalText = $Text;
112
113         // Since Diaspora is creating a summary for links, this function removes them before posting
114         if ($fordiaspora)
115                 $Text = bb_remove_share_information($Text);
116
117         /**
118          * Transform #tags, strip off the [url] and replace spaces with underscore
119          */
120         $URLSearchString = "^\[\]";
121         $Text = preg_replace_callback("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/i", create_function('$match',
122                 'return \'#\'. str_replace(\' \', \'_\', $match[2]);'
123         ), $Text);
124
125         // Converting images with size parameters to simple images. Markdown doesn't know it.
126         $Text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $Text);
127
128         // Convert it to HTML - don't try oembed
129         if ($fordiaspora) {
130                 $Text = bbcode($Text, $preserve_nl, false, 3);
131
132                 // Add all tags that maybe were removed
133                 if (preg_match_all("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",$OriginalText, $tags)) {
134                         $tagline = "";
135                         foreach($tags[2] as $tag) {
136                                 $tag = html_entity_decode($tag, ENT_QUOTES, 'UTF-8');
137                                 if (!strpos(html_entity_decode($Text, ENT_QUOTES, 'UTF-8'), "#".$tag))
138                                         $tagline .= "#".$tag." ";
139                         }
140                         $Text = $Text." ".$tagline;
141                 }
142
143         } else
144                 $Text = bbcode($Text, $preserve_nl, false, 4);
145
146         // mask some special HTML chars from conversation to markdown
147         $Text = str_replace(array('&lt;','&gt;','&amp;'),array('&_lt_;','&_gt_;','&_amp_;'),$Text);
148
149         // If a link is followed by a quote then there should be a newline before it
150         // Maybe we should make this newline at every time before a quote.
151         $Text = str_replace(array("</a><blockquote>"), array("</a><br><blockquote>"), $Text);
152
153         $stamp1 = microtime(true);
154
155         // Now convert HTML to Markdown
156         $Text = new HTML_To_Markdown($Text);
157
158         // unmask the special chars back to HTML
159         $Text = str_replace(array('&_lt_;','&_gt_;','&_amp_;'),array('&lt;','&gt;','&amp;'),$Text);
160
161         $a->save_timestamp($stamp1, "parser");
162
163         // Libertree has a problem with escaped hashtags.
164         $Text = str_replace(array('\#'), array('#'), $Text);
165
166         // Remove any leading or trailing whitespace, as this will mess up
167         // the Diaspora signature verification and cause the item to disappear
168         $Text = trim($Text);
169
170         if ($fordiaspora) {
171                 $URLSearchString = "^\[\]";
172                 $Text = preg_replace_callback("/([@]\[(.*?)\])\(([$URLSearchString]*?)\)/ism", 'diaspora_mentions', $Text);
173         }
174
175         call_hooks('bb2diaspora',$Text);
176
177         return $Text;
178 }
179
180 function unescape_underscores_in_links($m) {
181         $y = str_replace('\\_','_', $m[2]);
182         return('[' . $m[1] . '](' . $y . ')');
183 }
184
185 function format_event_diaspora($ev) {
186
187         if(! ((is_array($ev)) && count($ev)))
188                 return '';
189
190         $bd_format = t('l F d, Y \@ g:i A') ; // Friday January 18, 2011 @ 8 AM
191
192         $o = 'Friendica event notification:' . "\n";
193
194         $o .= '**' . (($ev['summary']) ? bb2diaspora($ev['summary']) : bb2diaspora($ev['desc'])) .  '**' . "\n";
195
196         $o .= t('Starts:') . ' ' . '['
197                 . (($ev['adjust']) ? day_translate(datetime_convert('UTC', 'UTC',
198                         $ev['start'] , $bd_format ))
199                         :  day_translate(datetime_convert('UTC', 'UTC',
200                         $ev['start'] , $bd_format)))
201                 .  '](' . App::get_baseurl() . '/localtime/?f=&time=' . urlencode(datetime_convert('UTC','UTC',$ev['start'])) . ")\n";
202
203         if(! $ev['nofinish'])
204                 $o .= t('Finishes:') . ' ' . '['
205                         . (($ev['adjust']) ? day_translate(datetime_convert('UTC', 'UTC',
206                                 $ev['finish'] , $bd_format ))
207                                 :  day_translate(datetime_convert('UTC', 'UTC',
208                                 $ev['finish'] , $bd_format )))
209                         . '](' . App::get_baseurl() . '/localtime/?f=&time=' . urlencode(datetime_convert('UTC','UTC',$ev['finish'])) . ")\n";
210
211         if(strlen($ev['location']))
212                 $o .= t('Location:') . bb2diaspora($ev['location'])
213                         . "\n";
214
215         $o .= "\n";
216         return $o;
217 }