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