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