]> git.mxchange.org Git - friendica-addons.git/blob - mailstream/mailstream.php
1392d0d1d611286124ee951c66c0cd41beb41e4c
[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: 2.0
6  * Author: Matthew Exon <http://mat.exon.name>
7  */
8
9 use Friendica\App;
10 use Friendica\Content\Text\BBCode;
11 use Friendica\Core\Hook;
12 use Friendica\Core\Logger;
13 use Friendica\Core\Renderer;
14 use Friendica\Core\System;
15 use Friendica\Core\Worker;
16 use Friendica\Database\DBA;
17 use Friendica\DI;
18 use Friendica\Model\Contact;
19 use Friendica\Model\Item;
20 use Friendica\Model\Post;
21 use Friendica\Model\User;
22 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
23 use Friendica\Protocol\Activity;
24 use Friendica\Util\DateTimeFormat;
25
26 /**
27  * Sets up the addon hooks and the database table
28  */
29 function mailstream_install()
30 {
31         Hook::register('addon_settings', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings');
32         Hook::register('addon_settings_post', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings_post');
33         Hook::register('post_local_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
34         Hook::register('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
35         Hook::register('mailstream_send_hook', 'addon/mailstream/mailstream.php', 'mailstream_send_hook');
36
37         Logger::info("mailstream: installed");
38 }
39
40 /**
41  * Enforces that mailstream_install has set up the current version
42  */
43 function mailstream_check_version()
44 {
45         if (!is_null(DI::config()->get('mailstream', 'dbversion'))) {
46                 DI::config()->delete('mailstream', 'dbversion');
47                 Logger::info("mailstream_check_version: old version detected, reinstalling");
48                 mailstream_install();
49                 Hook::loadHooks();
50                 Hook::add(
51                         'mailstream_convert_table_entries',
52                         'addon/mailstream/mailstream.php',
53                         'mailstream_convert_table_entries'
54                 );
55                 Hook::fork(Worker::PRIORITY_LOW, 'mailstream_convert_table_entries');
56         }
57 }
58
59 /**
60  * This is a statement rather than an actual function definition. The simple
61  * existence of this method is checked to figure out if the addon offers a
62  * module.
63  */
64 function mailstream_module() {}
65
66 /**
67  * Adds an item in "addon features" in the admin menu of the site
68  *
69  * @param string        $o HTML form data
70  */
71 function mailstream_addon_admin(string &$o)
72 {
73         $frommail = DI::config()->get('mailstream', 'frommail');
74         $template = Renderer::getMarkupTemplate('admin.tpl', 'addon/mailstream/');
75         $config = ['frommail',
76                 DI::l10n()->t('From Address'),
77                 $frommail,
78                 DI::l10n()->t('Email address that stream items will appear to be from.')];
79         $o .= Renderer::replaceMacros($template, [
80                 '$frommail' => $config,
81                 '$submit' => DI::l10n()->t('Save Settings')
82         ]);
83 }
84
85 /**
86  * Process input from the "addon features" part of the admin menu
87  */
88 function mailstream_addon_admin_post()
89 {
90         if (!empty($_POST['frommail'])) {
91                 DI::config()->set('mailstream', 'frommail', $_POST['frommail']);
92         }
93 }
94
95 /**
96  * Creates a message ID for a post URI in accordance with RFC 1036
97  * See also http://www.jwz.org/doc/mid.html
98  *
99  * @param string $uri the URI to be converted to a message ID
100  *
101  * @return string the created message ID
102  */
103 function mailstream_generate_id(string $uri): string
104 {
105         $host = DI::baseUrl()->getHostname();
106         $resource = hash('md5', $uri);
107         $message_id = "<" . $resource . "@" . $host . ">";
108         Logger::debug('mailstream: Generated message ID ' . $message_id . ' for URI ' . $uri);
109         return $message_id;
110 }
111
112 function mailstream_send_hook(array $data)
113 {
114         $criteria = array('uid' => $data['uid'], 'contact-id' => $data['contact-id'], 'uri' => $data['uri']);
115         $item = Post::selectFirst([], $criteria);
116         if (empty($item)) {
117                 Logger::error('mailstream_send_hook could not find item');
118                 return;
119         }
120
121         $user = User::getById($item['uid']);
122         if (empty($user)) {
123                         Logger::error('mailstream_send_hook could not fund user', ['uid' => $item['uid']]);
124                 return;
125         }
126
127         if (!mailstream_send($data['message_id'], $item, $user)) {
128                 Logger::debug('mailstream_send_hook send failed, will retry', $data);
129                 if (!Worker::defer()) {
130                         Logger::error('mailstream_send_hook failed and could not defer', $data);
131                 }
132         }
133 }
134
135 /**
136  * Called when either a local or remote post is created.  If
137  * mailstream is enabled and the necessary data is available, forks a
138  * workerqueue item to send the email.
139  *
140  * @param array     $item content of the item (may or may not already be stored in the item table)
141  * @return void
142  */
143 function mailstream_post_hook(array &$item)
144 {
145         mailstream_check_version();
146
147         if (!DI::pConfig()->get($item['uid'], 'mailstream', 'enabled')) {
148                 Logger::debug('mailstream: not enabled.', ['item' => $item['id'], ' uid ' => $item['uid']]);
149                 return;
150         }
151         if (!$item['uid']) {
152                 Logger::debug('mailstream: no uid for item ' . $item['id']);
153                 return;
154         }
155         if (!$item['contact-id']) {
156                 Logger::debug('mailstream: no contact-id for item ' . $item['id']);
157                 return;
158         }
159         if (!$item['uri']) {
160                 Logger::debug('mailstream: no uri for item ' . $item['id']);
161                 return;
162         }
163         if ($item['verb'] == Activity::ANNOUNCE) {
164                 Logger::debug('mailstream: announce item ', ['item' => $item['id']]);
165                 return;
166         }
167         if (DI::pConfig()->get($item['uid'], 'mailstream', 'nolikes')) {
168                 if ($item['verb'] == Activity::LIKE) {
169                         Logger::debug('mailstream: like item ' . $item['id']);
170                         return;
171                 }
172         }
173
174         $message_id = mailstream_generate_id($item['uri']);
175
176         $send_hook_data = [
177                 'uid' => $item['uid'],
178                 'contact-id' => $item['contact-id'],
179                 'uri' => $item['uri'],
180                 'message_id' => $message_id,
181                 'tries' => 0,
182         ];
183         Hook::fork(Worker::PRIORITY_LOW, 'mailstream_send_hook', $send_hook_data);
184 }
185
186 /**
187  * If the user has configured attaching images to emails as
188  * attachments, this function searches the post for such images,
189  * retrieves the image, and inserts the data and metadata into the
190  * supplied array
191  *
192  * @param array         $item        content of the item
193  * @param array         $attachments contains an array element for each attachment to add to the email
194  *
195  * @return array new value of the attachments table (results are also stored in the reference parameter)
196  */
197 function mailstream_do_images(array &$item, array &$attachments)
198 {
199         if (!DI::pConfig()->get($item['uid'], 'mailstream', 'attachimg')) {
200                 return;
201         }
202
203         $attachments = [];
204
205         preg_match_all("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", $item["body"], $matches1);
206         preg_match_all("/\[img\](.*?)\[\/img\]/ism", $item["body"], $matches2);
207         preg_match_all("/\[img\=([^\]]*)\]([^[]*)\[\/img\]/ism", $item["body"], $matches3);
208
209         foreach (array_merge($matches1[3], $matches2[1], $matches3[1]) as $url) {
210                 $components = parse_url($url);
211
212                 if (!$components) {
213                         continue;
214                 }
215
216                 $cookiejar = tempnam(System::getTempPath(), 'cookiejar-mailstream-');
217                 $curlResult = DI::httpClient()->fetchFull($url, HttpClientAccept::DEFAULT, 0, $cookiejar);
218                 $attachments[$url] = [
219                         'data' => $curlResult->getBody(),
220                         'guid' => hash('crc32', $url),
221                         'filename' => basename($components['path']),
222                         'type' => $curlResult->getContentType()
223                 ];
224
225                 if (strlen($attachments[$url]['data'])) {
226                         $item['body'] = str_replace($url, 'cid:' . $attachments[$url]['guid'], $item['body']);
227                         continue;
228                 }
229         }
230
231         return $attachments;
232 }
233
234 /**
235  * Creates a sender to use in the email, either from the contact or the author of the item, or both
236  *
237  * @param array $item content of the item
238  *
239  * @return string sender suitable for use in the email
240  */
241 function mailstream_sender(array $item): string
242 {
243         $contact = Contact::getById($item['contact-id']);
244         if (DBA::isResult($contact)) {
245                 if ($contact['name'] != $item['author-name']) {
246                         return $contact['name'] . ' - ' . $item['author-name'];
247                 }
248         }
249         return $item['author-name'];
250 }
251
252 /**
253  * Converts a bbcode-encoded subject line into a plaintext version suitable for the subject line of an email
254  *
255  * @param string $subject bbcode-encoded subject line
256  *
257  * @return string plaintext subject line
258  */
259 function mailstream_decode_subject(string $subject): string
260 {
261         $html = BBCode::convert($subject);
262         if (!$html) {
263                 return $subject;
264         }
265         $notags = strip_tags($html);
266         if (!$notags) {
267                 return $subject;
268         }
269         $noentity = html_entity_decode($notags);
270         if (!$noentity) {
271                 return $notags;
272         }
273         $nocodes = preg_replace_callback("/(&#[0-9]+;)/", function ($m) {
274                 return mb_convert_encoding($m[1], 'UTF-8', 'HTML-ENTITIES');
275         }, $noentity);
276         if (!$nocodes) {
277                 return $noentity;
278         }
279         $trimmed = trim($nocodes);
280         if (!$trimmed) {
281                 return $nocodes;
282         }
283         return $trimmed;
284 }
285
286 /**
287  * Creates a subject line to use in the email
288  *
289  * @param array $item content of the item
290  *
291  * @return string subject line suitable for use in the email
292  */
293 function mailstream_subject(array $item): string
294 {
295         if ($item['title']) {
296                 return mailstream_decode_subject($item['title']);
297         }
298         $parent = $item['thr-parent'];
299         // Don't look more than 100 levels deep for a subject, in case of loops
300         for ($i = 0; ($i < 100) && $parent; $i++) {
301                 $parent_item = Post::selectFirst(['thr-parent', 'title'], ['uri' => $parent]);
302                 if (!DBA::isResult($parent_item)) {
303                         break;
304                 }
305                 if ($parent_item['thr-parent'] === $parent) {
306                         break;
307                 }
308                 if ($parent_item['title']) {
309                         return DI::l10n()->t('Re:') . ' ' . mailstream_decode_subject($parent_item['title']);
310                 }
311                 $parent = $parent_item['thr-parent'];
312         }
313         $contact = Contact::selectFirst([], ['id' => $item['contact-id'], 'uid' => $item['uid']]);
314         if (!DBA::isResult($contact)) {
315                 Logger::error(
316                         'mailstream_subject no contact for item',
317                         ['id' => $item['id'],
318                                 'plink' => $item['plink'],
319                                 'contact id' => $item['contact-id'],
320                         'uid' => $item['uid']]
321                 );
322                 return DI::l10n()->t("Friendica post");
323         }
324         if ($contact['network'] === 'dfrn') {
325                 return DI::l10n()->t("Friendica post");
326         }
327         if ($contact['network'] === 'dspr') {
328                 return DI::l10n()->t("Diaspora post");
329         }
330         if ($contact['network'] === 'face') {
331                 $text = mailstream_decode_subject($item['body']);
332                 // For some reason these do show up in Facebook
333                 $text = preg_replace('/\xA0$/', '', $text);
334                 $subject = (strlen($text) > 150) ? (substr($text, 0, 140) . '...') : $text;
335                 return preg_replace('/\\s+/', ' ', $subject);
336         }
337         if ($contact['network'] === 'feed') {
338                 return DI::l10n()->t("Feed item");
339         }
340         if ($contact['network'] === 'mail') {
341                 return DI::l10n()->t("Email");
342         }
343         return DI::l10n()->t("Friendica Item");
344 }
345
346 /**
347  * Sends a message using PHPMailer
348  *
349  * @param string $message_id ID of the message (RFC 1036)
350  * @param array  $item       content of the item
351  * @param array  $user       results from the user table
352  *
353  * @return bool True if this message has been completed.  False if it should be retried.
354  */
355 function mailstream_send(string $message_id, array $item, array $user): bool
356 {
357         if (!is_array($item)) {
358                 Logger::error('mailstream_send item is empty', ['message_id' => $message_id]);
359                 return false;
360         }
361
362         if (!$item['visible']) {
363                 Logger::debug('mailstream_send item not yet visible', ['item uri' => $item['uri']]);
364                 return false;
365         }
366         if (!$message_id) {
367                 Logger::error('mailstream_send no message ID supplied', ['item uri' => $item['uri'],
368                                 'user email' => $user['email']]);
369                 return true;
370         }
371
372         require_once (dirname(__file__) . '/phpmailer/class.phpmailer.php');
373
374         $item['body'] = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
375
376         $attachments = [];
377         mailstream_do_images($item, $attachments);
378         $frommail = DI::config()->get('mailstream', 'frommail');
379         if ($frommail == '') {
380                 $frommail = 'friendica@localhost.local';
381         }
382         $address = DI::pConfig()->get($item['uid'], 'mailstream', 'address');
383         if (!$address) {
384                 $address = $user['email'];
385         }
386         $mail = new PHPmailer();
387         try {
388                 $mail->XMailer = 'Friendica Mailstream Addon';
389                 $mail->SetFrom($frommail, mailstream_sender($item));
390                 $mail->AddAddress($address, $user['username']);
391                 $mail->MessageID = $message_id;
392                 $mail->Subject = mailstream_subject($item);
393                 if ($item['thr-parent'] != $item['uri']) {
394                         $mail->addCustomHeader('In-Reply-To: ' . mailstream_generate_id($item['thr-parent']));
395                 }
396                 $mail->addCustomHeader('X-Friendica-Mailstream-URI: ' . $item['uri']);
397                 if ($item['plink']) {
398                         $mail->addCustomHeader('X-Friendica-Mailstream-Plink: ' . $item['plink']);
399                 }
400                 $encoding = 'base64';
401                 foreach ($attachments as $url => $image) {
402                         $mail->AddStringEmbeddedImage(
403                                 $image['data'],
404                                 $image['guid'],
405                                 $image['filename'],
406                                 $encoding,
407                                 $image['type']
408                         );
409                 }
410                 $mail->IsHTML(true);
411                 $mail->CharSet = 'utf-8';
412                 $template = Renderer::getMarkupTemplate('mail.tpl', 'addon/mailstream/');
413                 $mail->AltBody = BBCode::toPlaintext($item['body']);
414                 $item['body'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::CONNECTORS);
415                 $item['url'] = DI::baseUrl()->get() . '/display/' . $item['guid'];
416                 $mail->Body = Renderer::replaceMacros($template, [
417                                                  '$upstream' => DI::l10n()->t('Upstream'),
418                                                  '$uri' => DI::l10n()->t('URI'),
419                                                  '$local' => DI::l10n()->t('Local'),
420                                                  '$item' => $item]);
421                 $mail->Body = mailstream_html_wrap($mail->Body);
422                 if (!$mail->Send()) {
423                         throw new Exception($mail->ErrorInfo);
424                 }
425                 Logger::debug('mailstream_send sent message', ['message ID' => $mail->MessageID,
426                                 'subject' => $mail->Subject,
427                                 'address' => $address]);
428         } catch (phpmailerException $e) {
429                 Logger::debug('mailstream_send PHPMailer exception sending message ' . $message_id . ': ' . $e->errorMessage());
430         } catch (Exception $e) {
431                 Logger::debug('mailstream_send exception sending message ' . $message_id . ': ' . $e->getMessage());
432         }
433
434         return true;
435 }
436
437 /**
438  * Email tends to break if you send excessively long lines.  To make
439  * bbcode's output suitable for transmission, we try to break things
440  * up so that lines are about 200 characters.
441  *
442  * @param string $text text to word wrap
443  * @return string wrapped text
444  */
445 function mailstream_html_wrap(string &$text)
446 {
447         $lines = str_split($text, 200);
448         for ($i = 0; $i < count($lines); $i++) {
449                 $lines[$i] = preg_replace('/ /', "\n", $lines[$i], 1);
450         }
451         $text = implode($lines);
452         return $text;
453 }
454
455 /**
456  * Convert v1 mailstream table entries to v2 workerqueue items
457  */
458 function mailstream_convert_table_entries()
459 {
460         $ms_item_ids = DBA::selectToArray('mailstream_item', [], ['message-id', 'uri', 'uid', 'contact-id'], ["`mailstream_item`.`completed` IS NULL"]);
461         Logger::debug('mailstream_convert_table_entries processing ' . count($ms_item_ids) . ' items');
462         foreach ($ms_item_ids as $ms_item_id) {
463                 $send_hook_data = array('uid' => $ms_item_id['uid'],
464                                         'contact-id' => $ms_item_id['contact-id'],
465                                         'uri' => $ms_item_id['uri'],
466                                         'message_id' => $ms_item_id['message-id'],
467                                         'tries' => 0);
468                 if (!$ms_item_id['message-id'] || !strlen($ms_item_id['message-id'])) {
469                         Logger::info('mailstream_convert_table_entries: item has no message-id.', ['item' => $ms_item_id['id'], 'uri' => $ms_item_id['uri']]);
470                                                         continue;
471                 }
472                 Logger::info('mailstream_convert_table_entries: convert item to workerqueue', $send_hook_data);
473                 Hook::fork(Worker::PRIORITY_LOW, 'mailstream_send_hook', $send_hook_data);
474         }
475         DBA::e('DROP TABLE `mailstream_item`');
476 }
477
478 /**
479  * Form for configuring mailstream features for a user
480  *
481  * @param array $data Hook data array
482  * @throws \Friendica\Network\HTTPException\ServiceUnavailableException
483  */
484 function mailstream_addon_settings(array &$data)
485 {
486         $enabled   = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'mailstream', 'enabled');
487         $address   = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'mailstream', 'address');
488         $nolikes   = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'mailstream', 'nolikes');
489         $attachimg = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'mailstream', 'attachimg');
490
491         $template  = Renderer::getMarkupTemplate('settings.tpl', 'addon/mailstream/');
492         $html      = Renderer::replaceMacros($template, [
493                 '$enabled'   => [
494                         'mailstream_enabled',
495                         DI::l10n()->t('Enabled'),
496                         $enabled
497                 ],
498                 '$address'   => [
499                         'mailstream_address',
500                         DI::l10n()->t('Email Address'),
501                         $address,
502                         DI::l10n()->t('Leave blank to use your account email address')
503                 ],
504                 '$nolikes'   => [
505                         'mailstream_nolikes',
506                         DI::l10n()->t('Exclude Likes'),
507                         $nolikes,
508                         DI::l10n()->t('Check this to omit mailing "Like" notifications')
509                 ],
510                 '$attachimg' => [
511                         'mailstream_attachimg',
512                         DI::l10n()->t('Attach Images'),
513                         $attachimg,
514                         DI::l10n()->t('Download images in posts and attach them to the email.  ' .
515                                 'Useful for reading email while offline.')
516                 ],
517         ]);
518
519         $data = [
520                 'addon' => 'mailstream',
521                 'title' => DI::l10n()->t('Mail Stream Settings'),
522                 'html'  => $html,
523         ];
524 }
525
526 /**
527  * Process data submitted to user's mailstream features form
528  * @param array          $post POST data
529  * @return void
530  */
531 function mailstream_addon_settings_post(array $post)
532 {
533         if (!DI::userSession()->getLocalUserId() || empty($post['mailstream-submit'])) {
534                 return;
535         }
536
537         if ($post['mailstream_address'] != "") {
538                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'mailstream', 'address', $post['mailstream_address']);
539         } else {
540                 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'mailstream', 'address');
541         }
542         if ($post['mailstream_nolikes']) {
543                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'mailstream', 'nolikes', $post['mailstream_enabled']);
544         } else {
545                 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'mailstream', 'nolikes');
546         }
547         if ($post['mailstream_enabled']) {
548                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'mailstream', 'enabled', $post['mailstream_enabled']);
549         } else {
550                 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'mailstream', 'enabled');
551         }
552         if ($post['mailstream_attachimg']) {
553                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'mailstream', 'attachimg', $post['mailstream_attachimg']);
554         } else {
555                 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'mailstream', 'attachimg');
556         }
557 }