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