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