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