]> git.mxchange.org Git - friendica-addons.git/blob - mailstream/mailstream.php
Merge pull request #1128 from nupplaphil/bug/twitter_timeout
[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\Hook;
11 use Friendica\Core\Logger;
12 use Friendica\Core\Renderer;
13 use Friendica\Database\DBA;
14 use Friendica\DI;
15 use Friendica\Model\Item;
16 use Friendica\Model\Post;
17 use Friendica\Protocol\Activity;
18
19 /**
20  * Sets up the addon hooks and the database table
21  */
22 function mailstream_install()
23 {
24         Hook::register('addon_settings', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings');
25         Hook::register('addon_settings_post', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings_post');
26         Hook::register('post_local_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
27         Hook::register('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
28         Hook::register('cron', 'addon/mailstream/mailstream.php', 'mailstream_cron');
29
30         if (DI::config()->get('mailstream', 'dbversion') == '0.1') {
31                 q('ALTER TABLE `mailstream_item` DROP INDEX `uid`');
32                 q('ALTER TABLE `mailstream_item` DROP INDEX `contact-id`');
33                 q('ALTER TABLE `mailstream_item` DROP INDEX `plink`');
34                 q('ALTER TABLE `mailstream_item` CHANGE `plink` `uri` char(255) NOT NULL');
35                 DI::config()->set('mailstream', 'dbversion', '0.2');
36         }
37         if (DI::config()->get('mailstream', 'dbversion') == '0.2') {
38                 q('DELETE FROM `pconfig` WHERE `cat` = "mailstream" AND `k` = "delay"');
39                 DI::config()->set('mailstream', 'dbversion', '0.3');
40         }
41         if (DI::config()->get('mailstream', 'dbversion') == '0.3') {
42                 q('ALTER TABLE `mailstream_item` CHANGE `created` `created` timestamp NOT NULL DEFAULT now()');
43                 q('ALTER TABLE `mailstream_item` CHANGE `completed` `completed` timestamp NULL DEFAULT NULL');
44                 DI::config()->set('mailstream', 'dbversion', '0.4');
45         }
46         if (DI::config()->get('mailstream', 'dbversion') == '0.4') {
47                 q('ALTER TABLE `mailstream_item` CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin');
48                 DI::config()->set('mailstream', 'dbversion', '0.5');
49         }
50         if (DI::config()->get('mailstream', 'dbversion') == '0.5') {
51                 DI::config()->set('mailstream', 'dbversion', '1.0');
52         }
53
54         if (DI::config()->get('retriever', 'dbversion') != '1.0') {
55                 $schema = file_get_contents(dirname(__file__).'/database.sql');
56                 $arr = explode(';', $schema);
57                 foreach ($arr as $a) {
58                         $r = q($a);
59                 }
60                 DI::config()->set('mailstream', 'dbversion', '1.0');
61         }
62 }
63
64 /**
65  * This funciton indicates a module that can be wrapped in the LegacyModule class
66  */
67 function mailstream_module()
68 {
69 }
70
71 /**
72  * Adds an item in "addon features" in the admin menu of the site
73  *
74  * @param Friendica\App $a App object (unused)
75  * @param string        $o HTML form data
76  */
77 function mailstream_addon_admin(&$a, &$o)
78 {
79         $frommail = DI::config()->get('mailstream', 'frommail');
80         $template = Renderer::getMarkupTemplate('admin.tpl', 'addon/mailstream/');
81         $config = ['frommail',
82                         DI::l10n()->t('From Address'),
83                         $frommail,
84                         DI::l10n()->t('Email address that stream items will appear to be from.')];
85         $o .= Renderer::replaceMacros($template, [
86                                  '$frommail' => $config,
87                                  '$submit' => DI::l10n()->t('Save Settings')]);
88 }
89
90 /**
91  * Process input from the "addon features" part of the admin menu
92  */
93 function mailstream_addon_admin_post()
94 {
95         if (!empty($_POST['frommail'])) {
96                 DI::config()->set('mailstream', 'frommail', $_POST['frommail']);
97         }
98 }
99
100 /**
101  * Creates a message ID for a post URI in accordance with RFC 1036
102  * See also http://www.jwz.org/doc/mid.html
103  *
104  * @param string $uri the URI to be converted to a message ID
105  *
106  * @return string the created message ID
107  */
108 function mailstream_generate_id($uri)
109 {
110         $host = DI::baseUrl()->getHostname();
111         $resource = hash('md5', $uri);
112         $message_id = "<" . $resource . "@" . $host . ">";
113         Logger::debug('mailstream: Generated message ID ' . $message_id . ' for URI ' . $uri);
114         return $message_id;
115 }
116
117 /**
118  * Called when either a local or remote post is created.  Creates a
119  * record in the mailstream_item table to track this email, and then
120  * immediately attempts to send it
121  *
122  * @param Friendica\App $a    App object (unused)
123  * @param array         $item content of the item (may or may not already be stored in the item table)
124  */
125 function mailstream_post_hook(&$a, &$item)
126 {
127         if (!DI::pConfig()->get($item['uid'], 'mailstream', 'enabled')) {
128                 Logger::debug('mailstream: not enabled for item ' . $item['id']);
129                 return;
130         }
131         if (!$item['uid']) {
132                 Logger::debug('mailstream: no uid for item ' . $item['id']);
133                 return;
134         }
135         if (!$item['contact-id']) {
136                 Logger::debug('mailstream: no contact-id for item ' . $item['id']);
137                 return;
138         }
139         if (!$item['uri']) {
140                 Logger::debug('mailstream: no uri for item ' . $item['id']);
141                 return;
142         }
143         if (!$item['plink']) {
144                 Logger::debug('mailstream: no plink for item ' . $item['id']);
145                 return;
146         }
147         if (DI::pConfig()->get($item['uid'], 'mailstream', 'nolikes')) {
148                 if ($item['verb'] == Activity::LIKE) {
149                         Logger::debug('mailstream: like item ' . $item['id']);
150                         return;
151                 }
152         }
153
154         $message_id = mailstream_generate_id($item['uri']);
155         q(
156                 "INSERT INTO `mailstream_item` (`uid`, `contact-id`, `uri`, `message-id`) " .
157                 "VALUES (%d, '%s', '%s', '%s')",
158                 intval($item['uid']),
159                 intval($item['contact-id']),
160                 DBA::escape($item['uri']),
161                 DBA::escape($message_id)
162         );
163         $r = q(
164                 'SELECT * FROM `mailstream_item` WHERE `uid` = %d AND `contact-id` = %d AND `uri` = "%s"',
165                 intval($item['uid']),
166                 intval($item['contact-id']),
167                 DBA::escape($item['uri'])
168         );
169         if (count($r) != 1) {
170                 Logger::info('mailstream_post_remote_hook: Unexpected number of items returned from mailstream_item');
171                 return;
172         }
173         $ms_item = $r[0];
174         Logger::debug('mailstream_post_remote_hook: created mailstream_item ' . $ms_item['id'] .
175                                           ' for item ' . $item['uri'] . ' ' . $item['uid'] . ' ' . $item['contact-id']);
176         $user = mailstream_get_user($item['uid']);
177         if (!$user) {
178                 Logger::info('mailstream_post_remote_hook: no user ' . $item['uid']);
179                 return;
180         }
181         mailstream_send($ms_item['message-id'], $item, $user);
182 }
183
184 /**
185  * Converts a user ID into a full user record from the corresponding database table
186  *
187  * @param int $uid ID of the user to query
188  *
189  * @return array results from the user table
190  */
191 function mailstream_get_user($uid)
192 {
193         $r = q('SELECT * FROM `user` WHERE `uid` = %d', intval($uid));
194         if (count($r) != 1) {
195                 Logger::info('mailstream_post_remote_hook: Unexpected number of users returned');
196                 return;
197         }
198         return $r[0];
199 }
200
201 /**
202  * If the user has configured attaching images to emails as
203  * attachments, this function searches the post for such images,
204  * retrieves the image, and inserts the data and metadata into the
205  * supplied array
206  *
207  * @param array         $item        content of the item
208  * @param array         $attachments contains an array element for each attachment to add to the email
209  *
210  * @return array new value of the attachments table (results are also stored in the reference parameter)
211  */
212 function mailstream_do_images(&$item, &$attachments)
213 {
214         if (!DI::pConfig()->get($item['uid'], 'mailstream', 'attachimg')) {
215                 return;
216         }
217         $attachments = [];
218         preg_match_all("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", $item["body"], $matches1);
219         preg_match_all("/\[img\](.*?)\[\/img\]/ism", $item["body"], $matches2);
220         preg_match_all("/\[img\=([^\]]*)\]([^[]*)\[\/img\]/ism", $item["body"], $matches3);
221         foreach (array_merge($matches1[3], $matches2[1], $matches3[1]) as $url) {
222                 $components = parse_url($url);
223                 if (!$components) {
224                         continue;
225                 }
226                 $cookiejar = tempnam(get_temppath(), 'cookiejar-mailstream-');
227                 $curlResult = DI::httpRequest()->fetchFull($url, 0, '', $cookiejar);
228                 $attachments[$url] = [
229                         'data' => $curlResult->getBody(),
230                         'guid' => hash("crc32", $url),
231                         'filename' => basename($components['path']),
232                         'type' => $curlResult->getContentType()
233                 ];
234
235                 if (strlen($attachments[$url]['data'])) {
236                         $item['body'] = str_replace($url, 'cid:' . $attachments[$url]['guid'], $item['body']);
237                         continue;
238                 }
239         }
240         return $attachments;
241 }
242
243 /**
244  * Creates a sender to use in the email, either from the contact or the author of the item, or both
245  *
246  * @param array $item content of the item
247  *
248  * @return string sender suitable for use in the email
249  */
250 function mailstream_sender($item)
251 {
252         $r = q('SELECT * FROM `contact` WHERE `id` = %d', $item['contact-id']);
253         if (DBA::isResult($r)) {
254                 $contact = $r[0];
255                 if ($contact['name'] != $item['author-name']) {
256                         return $contact['name'] . ' - ' . $item['author-name'];
257                 }
258         }
259         return $item['author-name'];
260 }
261
262 /**
263  * Converts a bbcode-encoded subject line into a plaintext version suitable for the subject line of an email
264  *
265  * @param string $subject bbcode-encoded subject line
266  *
267  * @return string plaintext subject line
268  */
269 function mailstream_decode_subject($subject)
270 {
271         $html = BBCode::convert($subject);
272         if (!$html) {
273                 return $subject;
274         }
275         $notags = strip_tags($html);
276         if (!$notags) {
277                 return $subject;
278         }
279         $noentity = html_entity_decode($notags);
280         if (!$noentity) {
281                 return $notags;
282         }
283         $nocodes = preg_replace_callback("/(&#[0-9]+;)/", function ($m) {
284                 return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES");
285         }, $noentity);
286         if (!$nocodes) {
287                 return $noentity;
288         }
289         $trimmed = trim($nocodes);
290         if (!$trimmed) {
291                 return $nocodes;
292         }
293         return $trimmed;
294 }
295
296 /**
297  * Creates a subject line to use in the email
298  *
299  * @param array $item content of the item
300  *
301  * @return string subject line suitable for use in the email
302  */
303 function mailstream_subject($item)
304 {
305         if ($item['title']) {
306                 return mailstream_decode_subject($item['title']);
307         }
308         $parent = $item['thr-parent'];
309         // Don't look more than 100 levels deep for a subject, in case of loops
310         for ($i = 0; ($i < 100) && $parent; $i++) {
311                 $parent_item = Post::selectFirst(['thr-parent', 'title'], ['uri' => $parent]);
312                 if (!DBA::isResult($parent_item)) {
313                         break;
314                 }
315                 if ($parent_item['thr-parent'] === $parent) {
316                         break;
317                 }
318                 if ($parent_item['title']) {
319                         return DI::l10n()->t('Re:') . ' ' . mailstream_decode_subject($parent_item['title']);
320                 }
321                 $parent = $parent_item['thr-parent'];
322         }
323         $r = q(
324                 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
325                 intval($item['contact-id']),
326                 intval($item['uid'])
327         );
328         if (!DBA::isResult($r)) {
329                 Logger::error(
330                         'mailstream_subject no contact for item',
331                         ['item id' => $item['id'], 'plink' => $item['plink'], 'contact id' => $item['contact-id'], 'uid' => $item['uid']]
332                 );
333                 return DI::l10n()->t("Friendica post");
334         }
335         $contact = $r[0];
336         if ($contact['network'] === 'dfrn') {
337                 return DI::l10n()->t("Friendica post");
338         }
339         if ($contact['network'] === 'dspr') {
340                 return DI::l10n()->t("Diaspora post");
341         }
342         if ($contact['network'] === 'face') {
343                 $text = mailstream_decode_subject($item['body']);
344                 // For some reason these do show up in Facebook
345                 $text = preg_replace('/\xA0$/', '', $text);
346                 $subject = (strlen($text) > 150) ? (substr($text, 0, 140) . '...') : $text;
347                 return preg_replace('/\\s+/', ' ', $subject);
348         }
349         if ($contact['network'] === 'feed') {
350                 return DI::l10n()->t("Feed item");
351         }
352         if ($contact['network'] === 'mail') {
353                 return DI::l10n()->t("Email");
354         }
355         return DI::l10n()->t("Friendica Item");
356 }
357
358 /**
359  * Sends a message using PHPMailer
360  *
361  * @param string $message_id ID of the message (RFC 1036)
362  * @param array  $item       content of the item
363  * @param array  $user       results from the user table
364  */
365 function mailstream_send($message_id, $item, $user)
366 {
367         if (!$item['visible']) {
368                 return;
369         }
370         if (!$message_id) {
371                 return;
372         }
373         require_once(dirname(__file__).'/phpmailer/class.phpmailer.php');
374
375         $attachments = [];
376         mailstream_do_images($item, $attachments);
377         $frommail = DI::config()->get('mailstream', 'frommail');
378         if ($frommail == "") {
379                 $frommail = 'friendica@localhost.local';
380         }
381         $address = DI::pConfig()->get($item['uid'], 'mailstream', 'address');
382         if (!$address) {
383                 $address = $user['email'];
384         }
385         $mail = new PHPmailer;
386         try {
387                 $mail->XMailer = 'Friendica Mailstream Addon';
388                 $mail->SetFrom($frommail, mailstream_sender($item));
389                 $mail->AddAddress($address, $user['username']);
390                 $mail->MessageID = $message_id;
391                 $mail->Subject = mailstream_subject($item);
392                 if ($item['thr-parent'] != $item['uri']) {
393                         $mail->addCustomHeader('In-Reply-To: ' . mailstream_generate_id($item['thr-parent']));
394                 }
395                 $mail->addCustomHeader('X-Friendica-Mailstream-URI: ' . $item['uri']);
396                 $mail->addCustomHeader('X-Friendica-Mailstream-Plink: ' . $item['plink']);
397                 $encoding = 'base64';
398                 foreach ($attachments as $url => $image) {
399                         $mail->AddStringEmbeddedImage(
400                                 $image['data'],
401                                 $image['guid'],
402                                 $image['filename'],
403                                 $encoding,
404                                 $image['type']
405                         );
406                 }
407                 $mail->IsHTML(true);
408                 $mail->CharSet = 'utf-8';
409                 $template = Renderer::getMarkupTemplate('mail.tpl', 'addon/mailstream/');
410                 $mail->AltBody = BBCode::toPlaintext($item['body']);
411                 $item['body'] = BBCode::convert($item['body'], false, BBCode::CONNECTORS);
412                 $item['url'] = DI::baseUrl()->get() . '/display/' . $item['guid'];
413                 $mail->Body = Renderer::replaceMacros($template, [
414                                                  '$upstream' => DI::l10n()->t('Upstream'),
415                                                  '$local' => DI::l10n()->t('Local'),
416                                                  '$item' => $item]);
417                 mailstream_html_wrap($mail->Body);
418                 if (!$mail->Send()) {
419                         throw new Exception($mail->ErrorInfo);
420                 }
421                 Logger::debug('mailstream_send sent message ' . $mail->MessageID . ' ' . $mail->Subject);
422         } catch (phpmailerException $e) {
423                 Logger::debug('mailstream_send PHPMailer exception sending message ' . $message_id . ': ' . $e->errorMessage());
424         } catch (Exception $e) {
425                 Logger::debug('mailstream_send exception sending message ' . $message_id . ': ' . $e->getMessage());
426         }
427         // In case of failure, still set the item to completed.  Otherwise
428         // we'll just try to send it over and over again and it'll fail
429         // every time.
430         q('UPDATE `mailstream_item` SET `completed` = now() WHERE `message-id` = "%s"', DBA::escape($message_id));
431 }
432
433 /**
434  * Email tends to break if you send excessively long lines.  To make
435  * bbcode's output suitable for transmission, we try to break things
436  * up so that lines are about 200 characters.
437  *
438  * @param string $text text to word wrap - modified in-place
439  */
440 function mailstream_html_wrap(&$text)
441 {
442         $lines = str_split($text, 200);
443         for ($i = 0; $i < count($lines); $i++) {
444                 $lines[$i] = preg_replace('/ /', "\n", $lines[$i], 1);
445         }
446         $text = implode($lines);
447 }
448
449 /**
450  * Cron job for the mailstream plugin.  Sends delayed messages and cleans up old successful entries from the table.
451  */
452 function mailstream_cron()
453 {
454         // Only process items older than an hour in cron.  This is because
455         // we want to give mailstream_post_remote_hook a fair chance to
456         // send the email itself before cron jumps in.  Only if
457         // mailstream_post_remote_hook fails for some reason will this get
458         // used, and in that case it's worth holding off a bit anyway.
459         $query = <<< EOT
460 SELECT
461   `mailstream_item`.`message-id`,
462   `mailstream_item`.`uri`,
463   `post-user-view`.`id`
464 FROM
465    `mailstream_item`
466   JOIN
467    `post-user-view`
468   ON (
469     `mailstream_item`.`uid` = `post-user-view`.`uid` AND
470     `mailstream_item`.`uri` = `post-user-view`.`uri` AND
471     `mailstream_item`.`contact-id` = `post-user-view`.`contact-id`
472   )
473 WHERE
474   `mailstream_item`.`completed` IS NULL AND
475   `mailstream_item`.`created` < DATE_SUB(NOW(), INTERVAL 1 HOUR) AND
476   `post-user-view`.`visible` = 1
477 ORDER BY `mailstream_item`.`created`
478 LIMIT 100
479
480 EOT;
481         $ms_item_ids = q($query);
482         if (DBA::isResult($ms_item_ids)) {
483                 Logger::debug('mailstream_cron processing ' . count($ms_item_ids) . ' items');
484                 foreach ($ms_item_ids as $ms_item_id) {
485                         if (!$ms_item_id['message-id'] || !strlen($ms_item_id['message-id'])) {
486                                 Logger::info('mailstream_cron: Item ' . $ms_item_id['id'] .
487                                                                                          ' URI ' . $ms_item_id['uri'] . ' has no message-id');
488                         }
489                         $item = Post::selectFirst([], ['id' => $ms_item_id['id']]);
490                         $users = q("SELECT * FROM `user` WHERE `uid` = %d", intval($item['uid']));
491                         $user = $users[0];
492                         if ($user && $item) {
493                                 mailstream_send($ms_item_id['message-id'], $item, $user);
494                         } else {
495                                 Logger::info('mailstream_cron: Unable to find item ' . $ms_item_id['id']);
496                                 q(
497                                         "UPDATE `mailstream_item` SET `completed` = now() WHERE `message-id` = %d",
498                                         intval($ms_item_id['message-id'])
499                                 );
500                         }
501                 }
502         }
503         mailstream_tidy();
504 }
505
506 /**
507  * Form for configuring mailstream features for a user
508  *
509  * @param Friendica\App $a App object
510  * @param string        $o HTML form data
511  */
512 function mailstream_addon_settings(&$a, &$s)
513 {
514         $enabled = DI::pConfig()->get(local_user(), 'mailstream', 'enabled');
515         $address = DI::pConfig()->get(local_user(), 'mailstream', 'address');
516         $nolikes = DI::pConfig()->get(local_user(), 'mailstream', 'nolikes');
517         $attachimg= DI::pConfig()->get(local_user(), 'mailstream', 'attachimg');
518         $template = Renderer::getMarkupTemplate('settings.tpl', 'addon/mailstream/');
519         $s .= Renderer::replaceMacros($template, [
520                                  '$enabled' => [
521                                         'mailstream_enabled',
522                                         DI::l10n()->t('Enabled'),
523                                         $enabled],
524                                  '$address' => [
525                                         'mailstream_address',
526                                         DI::l10n()->t('Email Address'),
527                                         $address,
528                                         DI::l10n()->t("Leave blank to use your account email address")],
529                                  '$nolikes' => [
530                                         'mailstream_nolikes',
531                                         DI::l10n()->t('Exclude Likes'),
532                                         $nolikes,
533                                         DI::l10n()->t("Check this to omit mailing \"Like\" notifications")],
534                                  '$attachimg' => [
535                                         'mailstream_attachimg',
536                                         DI::l10n()->t('Attach Images'),
537                                         $attachimg,
538                                         DI::l10n()->t("Download images in posts and attach them to the email.  " .
539                                                                                                           "Useful for reading email while offline.")],
540                                  '$title' => DI::l10n()->t('Mail Stream Settings'),
541                                  '$submit' => DI::l10n()->t('Save Settings')]);
542 }
543
544 /**
545  * Process data submitted to user's mailstream features form
546  */
547 function mailstream_addon_settings_post()
548 {
549         if ($_POST['mailstream_address'] != "") {
550                 DI::pConfig()->set(local_user(), 'mailstream', 'address', $_POST['mailstream_address']);
551         } else {
552                 DI::pConfig()->delete(local_user(), 'mailstream', 'address');
553         }
554         if ($_POST['mailstream_nolikes']) {
555                 DI::pConfig()->set(local_user(), 'mailstream', 'nolikes', $_POST['mailstream_enabled']);
556         } else {
557                 DI::pConfig()->delete(local_user(), 'mailstream', 'nolikes');
558         }
559         if ($_POST['mailstream_enabled']) {
560                 DI::pConfig()->set(local_user(), 'mailstream', 'enabled', $_POST['mailstream_enabled']);
561         } else {
562                 DI::pConfig()->delete(local_user(), 'mailstream', 'enabled');
563         }
564         if ($_POST['mailstream_attachimg']) {
565                 DI::pConfig()->set(local_user(), 'mailstream', 'attachimg', $_POST['mailstream_attachimg']);
566         } else {
567                 DI::pConfig()->delete(local_user(), 'mailstream', 'attachimg');
568         }
569 }
570
571 /**
572  * Deletes records from the mailstream_item table older than one year
573  */
574 function mailstream_tidy()
575 {
576         $query = <<< EOT
577 SELECT
578   id
579 FROM
580   mailstream_item
581 WHERE
582   completed IS NOT NULL AND
583   completed < DATE_SUB(NOW(), INTERVAL 1 YEAR)
584
585 EOT;
586         $r = q($query);
587         foreach ($r as $rr) {
588                 q('DELETE FROM mailstream_item WHERE id = %d', intval($rr['id']));
589         }
590         Logger::debug('mailstream_tidy: deleted ' . count($r) . ' old items');
591 }