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