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