4 * Name: Discourse Mail Connector
5 * Description: Improves mails from Discourse in mailing list mode
7 * Author: Michael Vogel <http://pirati.ca/profile/heluecht>
11 use Friendica\Core\Hook;
12 use Friendica\Core\Logger;
13 use Friendica\Core\Renderer;
14 use Friendica\Core\Protocol;
15 use Friendica\Database\DBA;
17 use Friendica\Model\Contact;
18 use Friendica\Content\Text\Markdown;
19 use Friendica\Util\Network;
20 use Friendica\Util\Strings;
21 Use Friendica\Util\DateTimeFormat;
24 * - Obtaining API tokens to be able to read non public posts as well
25 * - Handling duplicates (possibly using some non visible marker)
26 * - Fetching missing posts
27 * - Fetch topic information
28 * - Support mail free mode when write tokens are available
29 * - Fix incomplete (relative) links (hosts are missing)
32 function discourse_install()
34 Hook::register('email_getmessage', __FILE__, 'discourse_email_getmessage');
35 Hook::register('connector_settings', __FILE__, 'discourse_settings');
36 Hook::register('connector_settings_post', __FILE__, 'discourse_settings_post');
39 function discourse_settings(App $a, &$s)
45 $enabled = intval(DI::pConfig()->get(local_user(), 'discourse', 'enabled'));
47 $t = Renderer::getMarkupTemplate('settings.tpl', 'addon/discourse/');
48 $s .= Renderer::replaceMacros($t, [
49 '$title' => DI::l10n()->t('Discourse'),
50 '$enabled' => ['enabled', DI::l10n()->t('Enable processing of Discourse mailing list mails'), $enabled, DI::l10n()->t('If enabled, incoming mails from Discourse will be improved so they look much better. To make it work, you have to configure the e-mail settings in Friendica. You also have to enable the mailing list mode in Discourse. Then you have to add the Discourse mail account as contact.')],
51 '$submit' => DI::l10n()->t('Save Settings'),
55 function discourse_settings_post(App $a)
57 if (!local_user() || empty($_POST['discourse-submit'])) {
61 DI::pConfig()->set(local_user(), 'discourse', 'enabled', intval($_POST['enabled']));
64 function discourse_email_getmessage(App $a, &$message)
66 if (empty($message['item']['uid'])) {
70 if (!DI::pConfig()->get($message['item']['uid'], 'discourse', 'enabled')) {
74 // We do assume that all Discourse servers are running with SSL
75 if (preg_match('=topic/(.*\d)/(.*\d)@(.*)=', $message['item']['uri'], $matches) &&
76 discourse_fetch_post_from_api($message, $matches[2], $matches[3])) {
77 Logger::info('Fetched comment via API (message-id mode)', ['host' => $matches[3], 'topic' => $matches[1], 'post' => $matches[2]]);
81 if (preg_match('=topic/(.*\d)@(.*)=', $message['item']['uri'], $matches) &&
82 discourse_fetch_topic_from_api($message, 'https://' . $matches[2], $matches[1], 1)) {
83 Logger::info('Fetched starting post via API (message-id mode)', ['host' => $matches[2], 'topic' => $matches[1]]);
87 // Search in the text part for the link to the discourse entry and the text body
88 if (!empty($message['text'])) {
89 $message = discourse_get_text($message);
92 if (empty($message['item']['plink']) || !preg_match('=(http.*)/t/.*/(.*\d)/(.*\d)=', $message['item']['plink'], $matches)) {
93 Logger::info('This is no Discourse post');
97 if (discourse_fetch_topic_from_api($message, $matches[1], $matches[2], $matches[3])) {
98 Logger::info('Fetched post via API (plink mode)', ['host' => $matches[1], 'topic' => $matches[2], 'id' => $matches[3]]);
102 Logger::info('Fallback mode', ['plink' => $message['item']['plink']]);
103 // Search in the HTML part for the discourse entry and the author profile
104 if (!empty($message['html'])) {
105 $message = discourse_get_html($message);
108 // Remove the title on comments, they don't serve any purpose there
109 if ($message['item']['parent-uri'] != $message['item']['uri']) {
110 unset($message['item']['title']);
114 function discourse_fetch_post($host, $topic, $pid)
116 $url = $host . '/t/' . $topic . '/' . $pid . '.json';
117 $curlResult = Network::curl($url);
118 if (!$curlResult->isSuccess()) {
119 Logger::info('No success', ['url' => $url]);
123 $raw = $curlResult->getBody();
124 $data = json_decode($raw, true);
125 $posts = $data['post_stream']['posts'];
126 foreach($posts as $post) {
127 if ($post['post_number'] != $pid) {
128 /// @todo Possibly fetch missing posts here
131 Logger::info('Got post data from topic', $post);
135 Logger::info('Post not found', ['host' => $host, 'topic' => $topic, 'pid' => $pid]);
139 function discourse_fetch_topic_from_api(&$message, $host, $topic, $pid)
141 $post = discourse_fetch_post($host, $topic, $pid);
146 $message = discourse_process_post($message, $post, $host);
150 function discourse_fetch_post_from_api(&$message, $post, $host)
152 $hostaddr = 'https://' . $host;
153 $url = $hostaddr . '/posts/' . $post . '.json';
154 $curlResult = Network::curl($url);
155 if (!$curlResult->isSuccess()) {
159 $raw = $curlResult->getBody();
160 $data = json_decode($raw, true);
165 $message = discourse_process_post($message, $data, $hostaddr);
167 Logger::info('Got API data', $message);
171 function discourse_get_user($post, $hostaddr)
173 $host = parse_url($hostaddr, PHP_URL_HOST);
175 // Currently unused contact fields:
176 // - display_username
181 $contact['network'] = Protocol::DISCOURSE;
182 $contact['name'] = $contact['nick'] = $post['username'];
183 if (!empty($post['name'])) {
184 $contact['name'] = $post['name'];
187 $contact['about'] = $post['user_title'];
189 if (parse_url($post['avatar_template'], PHP_URL_SCHEME)) {
190 $contact['photo'] = str_replace('{size}', '300', $post['avatar_template']);
192 $contact['photo'] = $hostaddr . str_replace('{size}', '300', $post['avatar_template']);
195 $contact['addr'] = $contact['nick'] . '@' . $host;
196 $contact['contact-type'] = Contact::TYPE_PERSON;
197 $contact['url'] = $hostaddr . '/u/' . $contact['nick'];
198 $contact['nurl'] = Strings::normaliseLink($contact['url']);
199 $contact['baseurl'] = $hostaddr;
200 Logger::info('Contact', $contact);
201 $contact['id'] = Contact::getIdForURL($contact['url'], 0, true, $contact);
202 if (!empty($contact['id'])) {
203 $avatar = $contact['photo'];
204 unset($contact['photo']);
205 DBA::update('contact', $contact, ['id' => $contact['id']]);
206 Contact::updateAvatar($avatar, 0, $contact['id']);
207 $contact['photo'] = $avatar;
213 function discourse_process_post($message, $post, $hostaddr)
215 $host = parse_url($hostaddr, PHP_URL_HOST);
217 $message['html'] = $post['cooked'];
219 $contact = discourse_get_user($post, $hostaddr);
220 $message['item']['author-id'] = $contact['id'];
221 $message['item']['author-link'] = $contact['url'];
222 $message['item']['author-name'] = $contact['name'];
223 $message['item']['author-avatar'] = $contact['photo'];
224 $message['item']['created'] = DateTimeFormat::utc($post['created_at']);
225 $message['item']['plink'] = $hostaddr . '/t/' . $post['topic_slug'] . '/' . $post['topic_id'] . '/' . $post['post_number'];
227 if ($post['post_number'] == 1) {
228 $message['item']['parent-uri'] = $message['item']['uri'] = 'topic/' . $post['topic_id'] . '@' . $host;
230 // Remove the Discourse forum name from the subject
231 $pattern = '=\[.*\].*\s(\[.*\].*)=';
232 if (preg_match($pattern, $message['item']['title'])) {
233 $message['item']['title'] = preg_replace($pattern, '$1', $message['item']['title']);
235 /// @ToDo Fetch thread information
237 $message['item']['uri'] = 'topic/' . $post['topic_id'] . '/' . $post['id'] . '@' . $host;
238 unset($message['item']['title']);
239 if (empty($post['reply_to_post_number']) || $post['reply_to_post_number'] == 1) {
240 $message['item']['parent-uri'] = 'topic/' . $post['topic_id'] . '@' . $host;
242 $reply = discourse_fetch_post($hostaddr, $post['topic_id'], $post['reply_to_post_number']);
243 $message['item']['parent-uri'] = 'topic/' . $post['topic_id'] . '/' . $reply['id'] . '@' . $host;
250 function discourse_get_html($message)
252 $doc = new DOMDocument();
253 $doc2 = new DOMDocument();
254 $doc->preserveWhiteSpace = false;
256 $html = mb_convert_encoding($message['html'], 'HTML-ENTITIES', "UTF-8");
257 @$doc->loadHTML($html, LIBXML_HTML_NODEFDTD);
259 $xpath = new DomXPath($doc);
261 // Fetch the first 'div' before the 'hr' - hopefully this fits for all systems
262 $result = $xpath->query("//hr//preceding::div[1]");
263 $div = $doc2->importNode($result->item(0), true);
264 $doc2->appendChild($div);
265 $message['html'] = $doc2->saveHTML();
266 Logger::info('Found html body', ['html' => $message['html']]);
268 $profile = discourse_get_profile($xpath);
269 if (!empty($profile['url'])) {
270 Logger::info('Found profile', $profile);
271 $message['item']['author-id'] = Contact::getIdForURL($profile['url'], 0, true, $profile);
272 $message['item']['author-link'] = $profile['url'];
273 $message['item']['author-name'] = $profile['name'];
274 $message['item']['author-avatar'] = $profile['photo'];
280 function discourse_get_text($message)
282 $text = $message['text'];
283 $text = str_replace("\r", '', $text);
284 $pos = strpos($text, "\n---\n");
286 Logger::info('No separator found', ['text' => $text]);
290 $message['text'] = trim(substr($text, 0, $pos));
292 Logger::info('Found text body', ['text' => $message['text']]);
294 $message['text'] = Markdown::toBBCode($message['text']);
296 $text = substr($text, $pos);
297 Logger::info('Found footer', ['text' => $text]);
298 if (preg_match('=\((http.*/t/.*/.*\d/.*\d)\)=', $text, $link)) {
299 $message['item']['plink'] = $link[1];
300 Logger::info('Found plink', ['plink' => $message['item']['plink']]);
305 function discourse_get_profile($xpath)
308 $list = $xpath->query("//td//following::img");
309 foreach ($list as $node) {
311 foreach ($node->attributes as $attribute) {
312 $attr[$attribute->name] = $attribute->value;
315 if (!empty($attr['src']) && !empty($attr['title'])
316 && !empty($attr['width']) && !empty($attr['height'])
317 && ($attr['width'] == $attr['height'])) {
318 $profile = ['photo' => $attr['src'], 'name' => $attr['title']];
323 $list = $xpath->query("//td//following::a");
324 foreach ($list as $node) {
325 if (!empty(trim($node->textContent)) && $node->attributes->length) {
327 foreach ($node->attributes as $attribute) {
328 $attr[$attribute->name] = $attribute->value;
330 if (!empty($attr['href']) && (strpos($attr['href'], '/' . $profile['name']))) {
331 $profile['url'] = $attr['href'];