]> git.mxchange.org Git - friendica-addons.git/blob - discourse/discourse.php
"escapeTags" is removed from the addons
[friendica-addons.git] / discourse / discourse.php
1 <?php
2
3 /**
4  * Name: Discourse Mail Connector
5  * Description: Improves mails from Discourse in mailing list mode
6  * Version: 0.1
7  * Author: Michael Vogel <http://pirati.ca/profile/heluecht>
8  *
9  */
10
11 use Friendica\App;
12 use Friendica\Content\Text\Markdown;
13 use Friendica\Core\Hook;
14 use Friendica\Core\Logger;
15 use Friendica\Core\Protocol;
16 use Friendica\Core\Renderer;
17 use Friendica\Database\DBA;
18 use Friendica\DI;
19 use Friendica\Model\Contact;
20 use Friendica\Util\DateTimeFormat;
21 use Friendica\Util\Strings;
22
23 /* Todo:
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)
30 */
31
32 function discourse_install()
33 {
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');
37 }
38
39 function discourse_settings(App $a, &$s)
40 {
41         if (!local_user()) {
42                 return;
43         }
44
45         $enabled = intval(DI::pConfig()->get(local_user(), 'discourse', 'enabled'));
46
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'),
52         ]);
53 }
54
55 function discourse_settings_post(App $a)
56 {
57         if (!local_user() || empty($_POST['discourse-submit'])) {
58                 return;
59         }
60
61         DI::pConfig()->set(local_user(), 'discourse', 'enabled', intval($_POST['enabled']));
62 }
63
64 function discourse_email_getmessage(App $a, &$message)
65 {
66         if (empty($message['item']['uid'])) {
67                 return;
68         }
69
70         if (!DI::pConfig()->get($message['item']['uid'], 'discourse', 'enabled')) {
71                 return;
72         }
73
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]]);
78                 return;
79         }
80
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]]);
84                 return;
85         }
86
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);
90         }
91
92         if (empty($message['item']['plink']) || !preg_match('=(http.*)/t/.*/(.*\d)/(.*\d)=', $message['item']['plink'], $matches)) {
93                 Logger::info('This is no Discourse post');
94                 return;
95         }
96
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]]);
99                 return;
100         }
101
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);
106         }
107
108         // Remove the title on comments, they don't serve any purpose there
109         if ($message['item']['thr-parent'] != $message['item']['uri']) {
110                 unset($message['item']['title']);
111         }
112 }
113
114 function discourse_fetch_post($host, $topic, $pid)
115 {
116         $url = $host . '/t/' . $topic . '/' . $pid . '.json';
117         $curlResult = DI::httpClient()->get($url);
118         if (!$curlResult->isSuccess()) {
119                 Logger::info('No success', ['url' => $url]);
120                 return false;
121         }
122
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
129                         continue;
130                 }
131                 Logger::info('Got post data from topic', $post);
132                 return $post;
133         }
134
135         Logger::info('Post not found', ['host' => $host, 'topic' => $topic, 'pid' => $pid]);
136         return false;
137 }
138
139 function discourse_fetch_topic_from_api(&$message, $host, $topic, $pid)
140 {
141         $post = discourse_fetch_post($host, $topic, $pid);
142         if (empty($post)) {
143                 return false;
144         }
145
146         $message = discourse_process_post($message, $post, $host);
147         return true;
148 }
149
150 function discourse_fetch_post_from_api(&$message, $post, $host)
151 {
152         $hostaddr = 'https://' . $host;
153         $url = $hostaddr . '/posts/' . $post . '.json';
154         $curlResult = DI::httpClient()->get($url);
155         if (!$curlResult->isSuccess()) {
156                 return false;
157         }
158
159         $raw = $curlResult->getBody();
160         $data = json_decode($raw, true);
161         if (empty($data)) {
162                 return false;
163         }
164
165         $message = discourse_process_post($message, $data, $hostaddr);
166
167         Logger::info('Got API data', $message);
168         return true;
169 }
170
171 function discourse_get_user($post, $hostaddr)
172 {
173         $host = parse_url($hostaddr, PHP_URL_HOST);
174
175         // Currently unused contact fields:
176         // - display_username
177         // - user_id
178
179         $contact = [];
180         $contact['uid'] = 0;
181         $contact['network'] = Protocol::DISCOURSE;
182         $contact['name'] = $contact['nick'] = $post['username'];
183         if (!empty($post['name'])) {
184                 $contact['name'] = $post['name'];
185         }
186
187         $contact['about'] = $post['user_title'];
188
189         if (parse_url($post['avatar_template'], PHP_URL_SCHEME)) {
190                 $contact['photo'] = str_replace('{size}', '300', $post['avatar_template']);
191         } else {
192                 $contact['photo'] = $hostaddr . str_replace('{size}', '300', $post['avatar_template']);
193         }
194
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, false, $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($contact['id'], $avatar);
207                 $contact['photo'] = $avatar;
208         }
209
210         return $contact;
211 }
212
213 function discourse_process_post($message, $post, $hostaddr)
214 {
215         $host = parse_url($hostaddr, PHP_URL_HOST);
216
217         $message['html'] = $post['cooked'];
218
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'];
226
227         if ($post['post_number'] == 1) {
228                 $message['item']['parent-uri'] = $message['item']['uri'] = 'topic/' . $post['topic_id'] . '@' . $host;
229
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']);
234                 }
235                 /// @ToDo Fetch thread information
236         } else {
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;
241                 } else {
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;
244                 }
245         }
246
247         return $message;
248 }
249
250 function discourse_get_html($message)
251 {
252         $doc = new DOMDocument();
253         $doc2 = new DOMDocument();
254         $doc->preserveWhiteSpace = false;
255
256         $html = mb_convert_encoding($message['html'], 'HTML-ENTITIES', "UTF-8");
257         @$doc->loadHTML($html, LIBXML_HTML_NODEFDTD);
258
259         $xpath = new DomXPath($doc);
260
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']]);
267
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, false, $profile);
272                 $message['item']['author-link'] = $profile['url'];
273                 $message['item']['author-name'] = $profile['name'];
274                 $message['item']['author-avatar'] = $profile['photo'];
275         }
276
277         return $message;
278 }
279
280 function discourse_get_text($message)
281 {
282         $text = $message['text'];
283         $text = str_replace("\r", '', $text);
284         $pos = strpos($text, "\n---\n");
285         if ($pos == 0) {
286                 Logger::info('No separator found', ['text' => $text]);
287                 return $message;
288         }
289
290         $message['text'] = trim(substr($text, 0, $pos));
291
292         Logger::info('Found text body', ['text' => $message['text']]);
293
294         $message['text'] = Markdown::toBBCode($message['text']);
295
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']]);
301         }
302         return $message;
303 }
304
305 function discourse_get_profile($xpath)
306 {
307         $profile = [];
308         $list = $xpath->query("//td//following::img");
309         foreach ($list as $node) {
310                 $attr = [];
311                 foreach ($node->attributes as $attribute) {
312                         $attr[$attribute->name] = $attribute->value;
313                 }
314
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']];
319                         break;
320                 }
321         }
322
323         $list = $xpath->query("//td//following::a");
324         foreach ($list as $node) {
325                 if (!empty(trim($node->textContent)) && $node->attributes->length) {
326                         $attr = [];
327                         foreach ($node->attributes as $attribute) {
328                                 $attr[$attribute->name] = $attribute->value;
329                         }
330                         if (!empty($attr['href']) && (strpos($attr['href'], '/' . $profile['name']))) {
331                                 $profile['url'] = $attr['href'];
332                                 break;
333                         }
334                 }
335         }
336         return $profile;
337 }