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\Temporal;
11 use League\HTMLToMarkdown\HtmlConverter;
13 require_once 'include/event.php';
14 require_once 'include/html2bbcode.php';
15 require_once 'include/bbcode.php';
18 * @brief Callback function to replace a Diaspora style mention in a mention for Friendica
20 * @param array $match Matching values for the callback
21 * @return string Replaced mention
23 function diaspora_mention2bb($match) {
24 if ($match[2] == '') {
28 $data = Contact::getDetailsByAddr($match[2]);
33 $name = $data['name'];
36 return '@[url=' . $data['url'] . ']' . $name . '[/url]';
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.
45 function diaspora2bb($s) {
47 $s = html_entity_decode($s, ENT_COMPAT, 'UTF-8');
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);
54 // Replace lonely stars in lines not starting with it with literal stars
55 $s = preg_replace('/^([^\*]+)\*([^\*]*)$/im', '$1\*$2', $s);
57 // The parser cannot handle paragraphs correctly
58 $s = str_replace(['</p>', '<p>', '<p dir="ltr">'], ['<br>', '<br>', '<br>'], $s);
60 // Escaping the hash tags
61 $s = preg_replace('/\#([^\s\#])/', '#$1', $s);
63 $s = Markdown::convert($s);
65 $regexp = "/@\{(?:([^\}]+?); )?([^\} ]+)\}/";
66 $s = preg_replace_callback($regexp, 'diaspora_mention2bb', $s);
68 $s = str_replace('#', '#', $s);
72 // protect the recycle symbol from turning into a tag, but without unescaping angles and naked ampersands
73 $s = str_replace('♲', html_entity_decode('♲', ENT_QUOTES, 'UTF-8'), $s);
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);
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 = bb_tag_preg_replace('/\[url\=?(.*?)\]https?:\/\/www.youtube.com\/watch\?v\=(.*?)\[\/url\]/ism', '[youtube]$2[/youtube]', 'url', $s);
80 $s = bb_tag_preg_replace('/\[url\=https?:\/\/www.youtube.com\/watch\?v\=(.*?)\].*?\[\/url\]/ism' , '[youtube]$1[/youtube]', 'url', $s);
81 $s = bb_tag_preg_replace('/\[url\=?(.*?)\]https?:\/\/vimeo.com\/([0-9]+)(.*?)\[\/url\]/ism' , '[vimeo]$2[/vimeo]' , 'url', $s);
82 $s = bb_tag_preg_replace('/\[url\=https?:\/\/vimeo.com\/([0-9]+)\](.*?)\[\/url\]/ism' , '[vimeo]$1[/vimeo]' , 'url', $s);
84 // remove duplicate adjacent code tags
85 $s = preg_replace('/(\[code\])+(.*?)(\[\/code\])+/ism', '[code]$2[/code]', $s);
87 // Don't show link to full picture (until it is fixed)
88 $s = BBCode::scaleExternalImages($s, false);
94 * @brief Callback function to replace a Friendica style mention in a mention for Diaspora
96 * @param array $match Matching values for the callback
97 * @return string Replaced mention
99 function diaspora_mentions($match) {
101 $contact = Contact::getDetailsByURL($match[3]);
103 if (!x($contact, 'addr')) {
104 $contact = Probe::uri($match[3]);
107 if (!x($contact, 'addr')) {
111 $mention = '@{' . $match[2] . '; ' . $contact['addr'] . '}';
116 * @brief Converts a BBCode text into Markdown
118 * This function converts a BBCode item body to be sent to Markdown-enabled
119 * systems like Diaspora and Libertree
121 * @param string $Text
122 * @param bool $preserve_nl Effects unclear, unused in Friendica
123 * @param bool $fordiaspora Diaspora requires more changes than Libertree
126 function bb2diaspora($Text, $preserve_nl = false, $fordiaspora = true) {
129 $OriginalText = $Text;
131 // Since Diaspora is creating a summary for links, this function removes them before posting
133 $Text = bb_remove_share_information($Text);
137 * Transform #tags, strip off the [url] and replace spaces with underscore
139 $URLSearchString = "^\[\]";
140 $Text = preg_replace_callback("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/i",
141 function ($matches) {
142 return '#' . str_replace(' ', '_', $matches[2]);
146 // Converting images with size parameters to simple images. Markdown doesn't know it.
147 $Text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $Text);
149 // Extracting multi-line code blocks before the whitespace processing/code highlighter in bbcode()
152 $Text = preg_replace_callback("#\[code(?:=([^\]]*))?\](.*?)\[\/code\]#is",
153 function ($matches) use (&$codeblocks) {
154 $return = $matches[0];
155 if (strpos($matches[2], "\n") !== false) {
156 $return = '#codeblock-' . count($codeblocks) . '#';
158 $prefix = '````' . $matches[1] . PHP_EOL;
159 $codeblocks[] = $prefix . trim($matches[2]) . PHP_EOL . '````';
165 // Convert it to HTML - don't try oembed
167 $Text = bbcode($Text, $preserve_nl, false, 3);
169 // Add all tags that maybe were removed
170 if (preg_match_all("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $OriginalText, $tags)) {
172 foreach ($tags[2] as $tag) {
173 $tag = html_entity_decode($tag, ENT_QUOTES, 'UTF-8');
174 if (!strpos(html_entity_decode($Text, ENT_QUOTES, 'UTF-8'), '#' . $tag)) {
175 $tagline .= '#' . $tag . ' ';
178 $Text = $Text." ".$tagline;
181 $Text = bbcode($Text, $preserve_nl, false, 4);
184 // mask some special HTML chars from conversation to markdown
185 $Text = str_replace(['<', '>', '&'], ['&_lt_;', '&_gt_;', '&_amp_;'], $Text);
187 // If a link is followed by a quote then there should be a newline before it
188 // Maybe we should make this newline at every time before a quote.
189 $Text = str_replace(["</a><blockquote>"], ["</a><br><blockquote>"], $Text);
191 $stamp1 = microtime(true);
193 // Now convert HTML to Markdown
194 $converter = new HtmlConverter();
195 $Text = $converter->convert($Text);
197 // unmask the special chars back to HTML
198 $Text = str_replace(['&\_lt\_;', '&\_gt\_;', '&\_amp\_;'], ['<', '>', '&'], $Text);
200 $a->save_timestamp($stamp1, "parser");
202 // Libertree has a problem with escaped hashtags.
203 $Text = str_replace(['\#'], ['#'], $Text);
205 // Remove any leading or trailing whitespace, as this will mess up
206 // the Diaspora signature verification and cause the item to disappear
210 $URLSearchString = "^\[\]";
211 $Text = preg_replace_callback("/([@]\[(.*?)\])\(([$URLSearchString]*?)\)/ism", 'diaspora_mentions', $Text);
214 // Restore code blocks
215 $Text = preg_replace_callback('/#codeblock-([0-9]+)#/iU',
216 function ($matches) use ($codeblocks) {
218 if (isset($codeblocks[intval($matches[1])])) {
219 $return = $codeblocks[$matches[1]];
225 Addon::callHooks('bb2diaspora',$Text);
230 function unescape_underscores_in_links($m) {
231 $y = str_replace('\\_', '_', $m[2]);
232 return('[' . $m[1] . '](' . $y . ')');
235 function format_event_diaspora($ev) {
236 if (! ((is_array($ev)) && count($ev))) {
240 $bd_format = L10n::t('l F d, Y \@ g:i A') ; // Friday January 18, 2011 @ 8 AM
242 $o = 'Friendica event notification:' . "\n";
244 $o .= '**' . (($ev['summary']) ? bb2diaspora($ev['summary']) : bb2diaspora($ev['desc'])) . '**' . "\n";
246 // @todo What. Is. Going. On. With. This. Useless. Ternary. Operator? - mrpetovan
247 $o .= L10n::t('Starts:') . ' ' . '[' . day_translate(
248 $ev['adjust'] ? Temporal::utc($ev['start'], $bd_format) : Temporal::utc($ev['start'], $bd_format)
250 . '](' . System::baseUrl() . '/localtime/?f=&time=' . urlencode(Temporal::utc($ev['start'])) . ")\n";
252 if (! $ev['nofinish']) {
253 $o .= L10n::t('Finishes:') . ' ' . '[' . day_translate(
254 $ev['adjust'] ? Temporal::utc($ev['finish'], $bd_format) : Temporal::utc($ev['finish'], $bd_format)
256 . '](' . System::baseUrl() . '/localtime/?f=&time=' . urlencode(Temporal::utc($ev['finish'])) . ")\n";
259 if (strlen($ev['location'])) {
260 $o .= L10n::t('Location:') . bb2diaspora($ev['location'])