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