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