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