Merge pull request #723 from annando/fix-pumpio
[friendica-addons.git/.git] / mailstream / mailstream.php
1 <?php
2 /**
3  * Name: Mail Stream
4  * Description: Mail all items coming into your network feed to an email address
5  * Version: 1.1
6  * Author: Matthew Exon <http://mat.exon.name>
7  */
8
9 use Friendica\Content\Text\BBCode;
10 use Friendica\Core\Addon;
11 use Friendica\Core\Config;
12 use Friendica\Core\L10n;
13 use Friendica\Core\PConfig;
14 use Friendica\Database\DBA;
15 use Friendica\Util\Network;
16 use Friendica\Model\Item;
17
18 function mailstream_install() {
19         Addon::registerHook('addon_settings', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings');
20         Addon::registerHook('addon_settings_post', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings_post');
21         Addon::registerHook('post_local_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
22         Addon::registerHook('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
23         Addon::registerHook('cron', 'addon/mailstream/mailstream.php', 'mailstream_cron');
24
25         if (Config::get('mailstream', 'dbversion') == '0.1') {
26                 q('ALTER TABLE `mailstream_item` DROP INDEX `uid`');
27                 q('ALTER TABLE `mailstream_item` DROP INDEX `contact-id`');
28                 q('ALTER TABLE `mailstream_item` DROP INDEX `plink`');
29                 q('ALTER TABLE `mailstream_item` CHANGE `plink` `uri` char(255) NOT NULL');
30                 Config::set('mailstream', 'dbversion', '0.2');
31         }
32         if (Config::get('mailstream', 'dbversion') == '0.2') {
33                 q('DELETE FROM `pconfig` WHERE `cat` = "mailstream" AND `k` = "delay"');
34                 Config::set('mailstream', 'dbversion', '0.3');
35         }
36         if (Config::get('mailstream', 'dbversion') == '0.3') {
37                 q('ALTER TABLE `mailstream_item` CHANGE `created` `created` timestamp NOT NULL DEFAULT now()');
38                 q('ALTER TABLE `mailstream_item` CHANGE `completed` `completed` timestamp NULL DEFAULT NULL');
39                 Config::set('mailstream', 'dbversion', '0.4');
40         }
41         if (Config::get('mailstream', 'dbversion') == '0.4') {
42                 q('ALTER TABLE `mailstream_item` CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin');
43                 Config::set('mailstream', 'dbversion', '0.5');
44         }
45         if (Config::get('mailstream', 'dbversion') == '0.5') {
46                 Config::set('mailstream', 'dbversion', '1.0');
47         }
48
49         if (Config::get('retriever', 'dbversion') != '1.0') {
50                 $schema = file_get_contents(dirname(__file__).'/database.sql');
51                 $arr = explode(';', $schema);
52                 foreach ($arr as $a) {
53                         $r = q($a);
54                 }
55                 Config::set('mailstream', 'dbversion', '1.0');
56         }
57 }
58
59 function mailstream_uninstall() {
60         Addon::unregisterHook('addon_settings', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings');
61         Addon::unregisterHook('addon_settings_post', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings_post');
62         Addon::unregisterHook('post_local', 'addon/mailstream/mailstream.php', 'mailstream_post_local_hook');
63         Addon::unregisterHook('post_remote', 'addon/mailstream/mailstream.php', 'mailstream_post_remote_hook');
64         Addon::unregisterHook('post_local_end', 'addon/mailstream/mailstream.php', 'mailstream_post_local_hook');
65         Addon::unregisterHook('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_remote_hook');
66         Addon::unregisterHook('post_local_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
67         Addon::unregisterHook('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
68         Addon::unregisterHook('cron', 'addon/mailstream/mailstream.php', 'mailstream_cron');
69         Addon::unregisterHook('incoming_mail', 'addon/mailstream/mailstream.php', 'mailstream_incoming_mail');
70 }
71
72 function mailstream_module() {}
73
74 function mailstream_addon_admin(&$a,&$o) {
75         $frommail = Config::get('mailstream', 'frommail');
76         $template = get_markup_template('admin.tpl', 'addon/mailstream/');
77         $config = ['frommail',
78                         L10n::t('From Address'),
79                         $frommail,
80                         L10n::t('Email address that stream items will appear to be from.')];
81         $o .= replace_macros($template, [
82                                  '$frommail' => $config,
83                                  '$submit' => L10n::t('Save Settings')]);
84 }
85
86 function mailstream_addon_admin_post ($a) {
87         if (x($_POST, 'frommail')) {
88                 Config::set('mailstream', 'frommail', $_POST['frommail']);
89         }
90 }
91
92 function mailstream_generate_id($a, $uri) {
93         // http://www.jwz.org/doc/mid.html
94         $host = $a->get_hostname();
95         $resource = hash('md5', $uri);
96         $message_id = "<" . $resource . "@" . $host . ">";
97         logger('mailstream: Generated message ID ' . $message_id . ' for URI ' . $uri, LOGGER_DEBUG);
98         return $message_id;
99 }
100
101 function mailstream_post_hook(&$a, &$item) {
102         if (!PConfig::get($item['uid'], 'mailstream', 'enabled')) {
103                 return;
104         }
105         if (!$item['uid']) {
106                 return;
107         }
108         if (!$item['contact-id']) {
109                 return;
110         }
111         if (!$item['uri']) {
112                 return;
113         }
114         if (PConfig::get($item['uid'], 'mailstream', 'nolikes')) {
115                 if ($item['verb'] == ACTIVITY_LIKE) {
116                         return;
117                 }
118         }
119
120         $message_id = mailstream_generate_id($a, $item['uri']);
121         q("INSERT INTO `mailstream_item` (`uid`, `contact-id`, `uri`, `message-id`) " .
122                 "VALUES (%d, '%s', '%s', '%s')", intval($item['uid']),
123                 intval($item['contact-id']), DBA::escape($item['uri']), DBA::escape($message_id));
124         $r = q('SELECT * FROM `mailstream_item` WHERE `uid` = %d AND `contact-id` = %d AND `uri` = "%s"', intval($item['uid']), intval($item['contact-id']), DBA::escape($item['uri']));
125         if (count($r) != 1) {
126                 logger('mailstream_post_remote_hook: Unexpected number of items returned from mailstream_item', LOGGER_INFO);
127                 return;
128         }
129         $ms_item = $r[0];
130         logger('mailstream_post_remote_hook: created mailstream_item '
131                 . $ms_item['id'] . ' for item ' . $item['uri'] . ' '
132                 . $item['uid'] . ' ' . $item['contact-id'], LOGGER_DATA);
133         $user = mailstream_get_user($item['uid']);
134         if (!$user) {
135                 logger('mailstream_post_remote_hook: no user ' . $item['uid'], LOGGER_INFO);
136                 return;
137         }
138         mailstream_send($a, $ms_item['message-id'], $item, $user);
139 }
140
141 function mailstream_get_user($uid) {
142         $r = q('SELECT * FROM `user` WHERE `uid` = %d', intval($uid));
143         if (count($r) != 1) {
144                 logger('mailstream_post_remote_hook: Unexpected number of users returned', LOGGER_INFO);
145                 return;
146         }
147         return $r[0];
148 }
149
150 function mailstream_do_images($a, &$item, &$attachments) {
151         if (!PConfig::get($item['uid'], 'mailstream', 'attachimg')) {
152                 return;
153         }
154         $attachments = [];
155         $baseurl = $a->get_baseurl();
156         preg_match_all("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", $item["body"], $matches1);
157         preg_match_all("/\[img\](.*?)\[\/img\]/ism", $item["body"], $matches2);
158         foreach (array_merge($matches1[3], $matches2[1]) as $url) {
159                 $redirects;
160                 $cookiejar = tempnam(get_temppath(), 'cookiejar-mailstream-');
161                 $attachments[$url] = [
162                         'data' => Network::fetchUrl($url, true, $redirects, 0, null, $cookiejar),
163                         'guid' => hash("crc32", $url),
164                         'filename' => basename($url),
165                         'type' => $a->get_curl_content_type()];
166                 if (strlen($attachments[$url]['data'])) {
167                         $item['body'] = str_replace($url, 'cid:' . $attachments[$url]['guid'], $item['body']);
168                         continue;
169                 }
170         }
171         return $attachments;
172 }
173
174 function mailstream_sender($item) {
175         $r = q('SELECT * FROM `contact` WHERE `id` = %d', $item['contact-id']);
176         if (DBA::isResult($r)) {
177                 $contact = $r[0];
178                 if ($contact['name'] != $item['author-name']) {
179                         return $contact['name'] . ' - ' . $item['author-name'];
180                 }
181         }
182         return $item['author-name'];
183 }
184
185 function mailstream_decode_subject($subject) {
186         $html = BBCode::convert($subject);
187         if (!$html) {
188                 return $subject;
189         }
190         $notags = strip_tags($html);
191         if (!$notags) {
192                 return $subject;
193         }
194         $noentity = html_entity_decode($notags);
195         if (!$noentity) {
196                 return $notags;
197         }
198         $nocodes = preg_replace_callback("/(&#[0-9]+;)/", function($m) { return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES"); }, $noentity);
199         if (!$nocodes) {
200                 return $noentity;
201         }
202         $trimmed = trim($nocodes);
203         if (!$trimmed) {
204                 return $nocodes;
205         }
206         return $trimmed;
207 }
208
209 function mailstream_subject($item) {
210         if ($item['title']) {
211                 return mailstream_decode_subject($item['title']);
212         }
213         $parent = $item['thr-parent'];
214         // Don't look more than 100 levels deep for a subject, in case of loops
215         for ($i = 0; ($i < 100) && $parent; $i++) {
216                 $parent_item = Item::selectFirst(['thr-parent', 'title'], ['uri' => $parent]);
217                 if (!DBA::isResult($parent_item)) {
218                         break;
219                 }
220                 if ($parent_item['thr-parent'] === $parent) {
221                         break;
222                 }
223                 if ($parent_item['title']) {
224                         return L10n::t('Re:') . ' ' . mailstream_decode_subject($parent_item['title']);
225                 }
226                 $parent = $parent_item['thr-parent'];
227         }
228         $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
229                 intval($item['contact-id']), intval($item['uid']));
230         $contact = $r[0];
231         if ($contact['network'] === 'dfrn') {
232                 return L10n::t("Friendica post");
233         }
234         if ($contact['network'] === 'dspr') {
235                 return L10n::t("Diaspora post");
236         }
237         if ($contact['network'] === 'face') {
238                 $text = mailstream_decode_subject($item['body']);
239                 // For some reason these do show up in Facebook
240                 $text = preg_replace('/\xA0$/', '', $text);
241                 $subject = (strlen($text) > 150) ? (substr($text, 0, 140) . '...') : $text;
242                 return preg_replace('/\\s+/', ' ', $subject);
243         }
244         if ($contact['network'] === 'feed') {
245                 return L10n::t("Feed item");
246         }
247         if ($contact['network'] === 'mail') {
248                 return L10n::t("Email");
249         }
250         return L10n::t("Friendica Item");
251 }
252
253 function mailstream_send($a, $message_id, $item, $user) {
254         if (!$item['visible']) {
255                 return;
256         }
257         if (!$message_id) {
258                 return;
259         }
260         require_once(dirname(__file__).'/phpmailer/class.phpmailer.php');
261
262         $attachments = [];
263         mailstream_do_images($a, $item, $attachments);
264         $frommail = Config::get('mailstream', 'frommail');
265         if ($frommail == "") {
266                 $frommail = 'friendica@localhost.local';
267         }
268         $address = PConfig::get($item['uid'], 'mailstream', 'address');
269         if (!$address) {
270                 $address = $user['email'];
271         }
272         $mail = new PHPmailer;
273         try {
274                 $mail->XMailer = 'Friendica Mailstream Addon';
275                 $mail->SetFrom($frommail, mailstream_sender($item));
276                 $mail->AddAddress($address, $user['username']);
277                 $mail->MessageID = $message_id;
278                 $mail->Subject = mailstream_subject($item);
279                 if ($item['thr-parent'] != $item['uri']) {
280                         $mail->addCustomHeader('In-Reply-To: ' . mailstream_generate_id($a, $item['thr-parent']));
281                 }
282                 $mail->addCustomHeader('X-Friendica-Mailstream-URI: ' . $item['uri']);
283                 $mail->addCustomHeader('X-Friendica-Mailstream-Plink: ' . $item['plink']);
284                 $encoding = 'base64';
285                 foreach ($attachments as $url => $image) {
286                         $mail->AddStringEmbeddedImage($image['data'], $image['guid'], $image['filename'], $encoding, $image['type']);
287                 }
288                 $mail->IsHTML(true);
289                 $mail->CharSet = 'utf-8';
290                 $template = get_markup_template('mail.tpl', 'addon/mailstream/');
291                 $item['body'] = BBCode::convert($item['body']);
292                 $item['url'] = $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $item['id'];
293                 $mail->Body = replace_macros($template, [
294                                                  '$upstream' => L10n::t('Upstream'),
295                                                  '$local' => L10n::t('Local'),
296                                                  '$item' => $item]);
297                 mailstream_html_wrap($mail->Body);
298                 if (!$mail->Send()) {
299                         throw new Exception($mail->ErrorInfo);
300                 }
301                 logger('mailstream_send sent message ' . $mail->MessageID . ' ' . $mail->Subject, LOGGER_DEBUG);
302         } catch (phpmailerException $e) {
303                 logger('mailstream_send PHPMailer exception sending message ' . $message_id . ': ' . $e->errorMessage(), LOGGER_INFO);
304         } catch (Exception $e) {
305                 logger('mailstream_send exception sending message ' . $message_id . ': ' . $e->getMessage(), LOGGER_INFO);
306         }
307         // In case of failure, still set the item to completed.  Otherwise
308         // we'll just try to send it over and over again and it'll fail
309         // every time.
310         q('UPDATE `mailstream_item` SET `completed` = now() WHERE `message-id` = "%s"', DBA::escape($message_id));
311 }
312
313 /**
314  * Email tends to break if you send excessively long lines.  To make
315  * bbcode's output suitable for transmission, we try to break things
316  * up so that lines are about 200 characters.
317  */
318 function mailstream_html_wrap(&$text)
319 {
320         $lines = str_split($text, 200);
321         for ($i = 0; $i < count($lines); $i++) {
322                 $lines[$i] = preg_replace('/ /', "\n", $lines[$i], 1);
323         }
324         $text = implode($lines);
325 }
326
327 function mailstream_cron($a, $b) {
328         // Only process items older than an hour in cron.  This is because
329         // we want to give mailstream_post_remote_hook a fair chance to
330         // send the email itself before cron jumps in.  Only if
331         // mailstream_post_remote_hook fails for some reason will this get
332         // used, and in that case it's worth holding off a bit anyway.
333         $ms_item_ids = q("SELECT `mailstream_item`.`message-id`, `mailstream_item`.`uri`, `item`.`id` FROM `mailstream_item` JOIN `item` ON (`mailstream_item`.`uid` = `item`.`uid` AND `mailstream_item`.`uri` = `item`.`uri` AND `mailstream_item`.`contact-id` = `item`.`contact-id`) WHERE `mailstream_item`.`completed` IS NULL AND `mailstream_item`.`created` < DATE_SUB(NOW(), INTERVAL 1 HOUR) AND `item`.`visible` = 1 ORDER BY `mailstream_item`.`created` LIMIT 100");
334         logger('mailstream_cron processing ' . count($ms_item_ids) . ' items', LOGGER_DEBUG);
335         foreach ($ms_item_ids as $ms_item_id) {
336                 if (!$ms_item_id['message-id'] || !strlen($ms_item_id['message-id'])) {
337                         logger('mailstream_cron: Item ' . $ms_item_id['id'] . ' URI ' . $ms_item_id['uri'] . ' has no message-id', LOGGER_INFO);
338                 }
339                 $item = Item::selectFirst([], ['id' => $ms_item_id['id']]);
340                 $users = q("SELECT * FROM `user` WHERE `uid` = %d", intval($item['uid']));
341                 $user = $users[0];
342                 if ($user && $item) {
343                         mailstream_send($a, $ms_item_id['message-id'], $item, $user);
344                 }
345                 else {
346                         logger('mailstream_cron: Unable to find item ' . $ms_item_id['id'], LOGGER_INFO);
347                         q("UPDATE `mailstream_item` SET `completed` = now() WHERE `message-id` = %d", intval($ms_item['message-id']));
348                 }
349         }
350         mailstream_tidy();
351 }
352
353 function mailstream_addon_settings(&$a,&$s) {
354         $enabled = PConfig::get(local_user(), 'mailstream', 'enabled');
355         $address = PConfig::get(local_user(), 'mailstream', 'address');
356         $nolikes = PConfig::get(local_user(), 'mailstream', 'nolikes');
357         $attachimg= PConfig::get(local_user(), 'mailstream', 'attachimg');
358         $template = get_markup_template('settings.tpl', 'addon/mailstream/');
359         $s .= replace_macros($template, [
360                                  '$enabled' => [
361                                         'mailstream_enabled',
362                                         L10n::t('Enabled'),
363                                         $enabled],
364                                  '$address' => [
365                                         'mailstream_address',
366                                         L10n::t('Email Address'),
367                                         $address,
368                                         L10n::t("Leave blank to use your account email address")],
369                                  '$nolikes' => [
370                                         'mailstream_nolikes',
371                                         L10n::t('Exclude Likes'),
372                                         $nolikes,
373                                         L10n::t("Check this to omit mailing \"Like\" notifications")],
374                                  '$attachimg' => [
375                                         'mailstream_attachimg',
376                                         L10n::t('Attach Images'),
377                                         $attachimg,
378                                         L10n::t("Download images in posts and attach them to the email.  Useful for reading email while offline.")],
379                                  '$title' => L10n::t('Mail Stream Settings'),
380                                  '$submit' => L10n::t('Save Settings')]);
381 }
382
383 function mailstream_addon_settings_post($a,$post) {
384         if ($_POST['mailstream_address'] != "") {
385                 PConfig::set(local_user(), 'mailstream', 'address', $_POST['mailstream_address']);
386         }
387         else {
388                 PConfig::delete(local_user(), 'mailstream', 'address');
389         }
390         if ($_POST['mailstream_nolikes']) {
391                 PConfig::set(local_user(), 'mailstream', 'nolikes', $_POST['mailstream_enabled']);
392         }
393         else {
394                 PConfig::delete(local_user(), 'mailstream', 'nolikes');
395         }
396         if ($_POST['mailstream_enabled']) {
397                 PConfig::set(local_user(), 'mailstream', 'enabled', $_POST['mailstream_enabled']);
398         }
399         else {
400                 PConfig::delete(local_user(), 'mailstream', 'enabled');
401         }
402         if ($_POST['mailstream_attachimg']) {
403                 PConfig::set(local_user(), 'mailstream', 'attachimg', $_POST['mailstream_attachimg']);
404         }
405         else {
406                 PConfig::delete(local_user(), 'mailstream', 'attachimg');
407         }
408 }
409
410 function mailstream_tidy() {
411         $r = q("SELECT id FROM mailstream_item WHERE completed IS NOT NULL AND completed < DATE_SUB(NOW(), INTERVAL 1 YEAR)");
412         foreach ($r as $rr) {
413                 q('DELETE FROM mailstream_item WHERE id = %d', intval($rr['id']));
414         }
415         logger('mailstream_tidy: deleted ' . count($r) . ' old items', LOGGER_DEBUG);
416 }