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