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