]> git.mxchange.org Git - friendica-addons.git/blob - mailstream/mailstream.php
Merge pull request 'Bluesky: Fix some issues when fetching posts' (#1424) from heluec...
[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()->getHost();
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                 try {
218                         $curlResult = DI::httpClient()->fetchFull($url, HttpClientAccept::DEFAULT, 0, $cookiejar);
219                 } catch (InvalidArgumentException $e) {
220                         Logger::error('mailstream_do_images exception fetching url', ['url' => $url, 'item_id' => $item['id']]);
221                         continue;
222                 }
223                 $attachments[$url] = [
224                         'data' => $curlResult->getBody(),
225                         'guid' => hash('crc32', $url),
226                         'filename' => basename($components['path']),
227                         'type' => $curlResult->getContentType()
228                 ];
229
230                 if (strlen($attachments[$url]['data'])) {
231                         $item['body'] = str_replace($url, 'cid:' . $attachments[$url]['guid'], $item['body']);
232                         continue;
233                 }
234         }
235
236         return $attachments;
237 }
238
239 /**
240  * Creates a sender to use in the email, either from the contact or the author of the item, or both
241  *
242  * @param array $item content of the item
243  *
244  * @return string sender suitable for use in the email
245  */
246 function mailstream_sender(array $item): string
247 {
248         $contact = Contact::getById($item['contact-id']);
249         if (DBA::isResult($contact)) {
250                 if ($contact['name'] != $item['author-name']) {
251                         return $contact['name'] . ' - ' . $item['author-name'];
252                 }
253         }
254         return $item['author-name'];
255 }
256
257 /**
258  * Converts a bbcode-encoded subject line into a plaintext version suitable for the subject line of an email
259  *
260  * @param string $subject bbcode-encoded subject line
261  * @param int    $uri_id
262  *
263  * @return string plaintext subject line
264  */
265 function mailstream_decode_subject(string $subject, int $uri_id): string
266 {
267         $html = BBCode::convertForUriId($uri_id, $subject);
268         if (!$html) {
269                 return $subject;
270         }
271         $notags = strip_tags($html);
272         if (!$notags) {
273                 return $subject;
274         }
275         $noentity = html_entity_decode($notags);
276         if (!$noentity) {
277                 return $notags;
278         }
279         $nocodes = preg_replace_callback("/(&#[0-9]+;)/", function ($m) {
280                 return mb_convert_encoding($m[1], 'UTF-8', 'HTML-ENTITIES');
281         }, $noentity);
282         if (!$nocodes) {
283                 return $noentity;
284         }
285         $trimmed = trim($nocodes);
286         if (!$trimmed) {
287                 return $nocodes;
288         }
289         return $trimmed;
290 }
291
292 /**
293  * Creates a subject line to use in the email
294  *
295  * @param array $item content of the item
296  *
297  * @return string subject line suitable for use in the email
298  */
299 function mailstream_subject(array $item): string
300 {
301         if ($item['title']) {
302                 return mailstream_decode_subject($item['title'], $item['uri-id']);
303         }
304         $parent = $item['thr-parent'];
305         // Don't look more than 100 levels deep for a subject, in case of loops
306         for ($i = 0; ($i < 100) && $parent; $i++) {
307                 $parent_item = Post::selectFirst(['thr-parent', 'title'], ['uri' => $parent]);
308                 if (!DBA::isResult($parent_item)) {
309                         break;
310                 }
311                 if ($parent_item['thr-parent'] === $parent) {
312                         break;
313                 }
314                 if ($parent_item['title']) {
315                         return DI::l10n()->t('Re:') . ' ' . mailstream_decode_subject($parent_item['title'], $item['uri-id']);
316                 }
317                 $parent = $parent_item['thr-parent'];
318         }
319         $contact = Contact::selectFirst([], ['id' => $item['contact-id'], 'uid' => $item['uid']]);
320         if (!DBA::isResult($contact)) {
321                 Logger::error(
322                         'mailstream_subject no contact for item',
323                         ['id' => $item['id'],
324                                 'plink' => $item['plink'],
325                                 'contact id' => $item['contact-id'],
326                         'uid' => $item['uid']]
327                 );
328                 return DI::l10n()->t("Friendica post");
329         }
330         if ($contact['network'] === 'dfrn') {
331                 return DI::l10n()->t("Friendica post");
332         }
333         if ($contact['network'] === 'dspr') {
334                 return DI::l10n()->t("Diaspora post");
335         }
336         if ($contact['network'] === 'face') {
337                 $text = mailstream_decode_subject($item['body'], $item['uri-id']);
338                 // For some reason these do show up in Facebook
339                 $text = preg_replace('/\xA0$/', '', $text);
340                 $subject = (strlen($text) > 150) ? (substr($text, 0, 140) . '...') : $text;
341                 return preg_replace('/\\s+/', ' ', $subject);
342         }
343         if ($contact['network'] === 'feed') {
344                 return DI::l10n()->t("Feed item");
345         }
346         if ($contact['network'] === 'mail') {
347                 return DI::l10n()->t("Email");
348         }
349         return DI::l10n()->t("Friendica Item");
350 }
351
352 /**
353  * Sends a message using PHPMailer
354  *
355  * @param string $message_id ID of the message (RFC 1036)
356  * @param array  $item       content of the item
357  * @param array  $user       results from the user table
358  *
359  * @return bool True if this message has been completed.  False if it should be retried.
360  */
361 function mailstream_send(string $message_id, array $item, array $user): bool
362 {
363         if (!is_array($item)) {
364                 Logger::error('mailstream_send item is empty', ['message_id' => $message_id]);
365                 return false;
366         }
367
368         if (!$item['visible']) {
369                 Logger::debug('mailstream_send item not yet visible', ['item uri' => $item['uri']]);
370                 return false;
371         }
372         if (!$message_id) {
373                 Logger::error('mailstream_send no message ID supplied', ['item uri' => $item['uri'],
374                                 'user email' => $user['email']]);
375                 return true;
376         }
377
378         require_once (dirname(__file__) . '/phpmailer/class.phpmailer.php');
379
380         $item['body'] = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
381
382         $attachments = [];
383         mailstream_do_images($item, $attachments);
384         $frommail = DI::config()->get('mailstream', 'frommail');
385         if ($frommail == '') {
386                 $frommail = 'friendica@localhost.local';
387         }
388         $address = DI::pConfig()->get($item['uid'], 'mailstream', 'address');
389         if (!$address) {
390                 $address = $user['email'];
391         }
392         $mail = new PHPmailer();
393         try {
394                 $mail->XMailer = 'Friendica Mailstream Addon';
395                 $mail->SetFrom($frommail, mailstream_sender($item));
396                 $mail->AddAddress($address, $user['username']);
397                 $mail->MessageID = $message_id;
398                 $mail->Subject = mailstream_subject($item);
399                 if ($item['thr-parent'] != $item['uri']) {
400                         $mail->addCustomHeader('In-Reply-To: ' . mailstream_generate_id($item['thr-parent']));
401                 }
402                 $mail->addCustomHeader('X-Friendica-Mailstream-URI: ' . $item['uri']);
403                 if ($item['plink']) {
404                         $mail->addCustomHeader('X-Friendica-Mailstream-Plink: ' . $item['plink']);
405                 }
406                 $encoding = 'base64';
407                 foreach ($attachments as $url => $image) {
408                         $mail->AddStringEmbeddedImage(
409                                 $image['data'],
410                                 $image['guid'],
411                                 $image['filename'],
412                                 $encoding,
413                                 $image['type']
414                         );
415                 }
416                 $mail->IsHTML(true);
417                 $mail->CharSet = 'utf-8';
418                 $template = Renderer::getMarkupTemplate('mail.tpl', 'addon/mailstream/');
419                 $mail->AltBody = BBCode::toPlaintext($item['body']);
420                 $item['body'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::CONNECTORS);
421                 $item['url'] = DI::baseUrl() . '/display/' . $item['guid'];
422                 $mail->Body = Renderer::replaceMacros($template, [
423                                                  '$upstream' => DI::l10n()->t('Upstream'),
424                                                  '$uri' => DI::l10n()->t('URI'),
425                                                  '$local' => DI::l10n()->t('Local'),
426                                                  '$item' => $item]);
427                 $mail->Body = mailstream_html_wrap($mail->Body);
428                 if (!$mail->Send()) {
429                         throw new Exception($mail->ErrorInfo);
430                 }
431                 Logger::debug('mailstream_send sent message', ['message ID' => $mail->MessageID,
432                                 'subject' => $mail->Subject,
433                                 'address' => $address]);
434         } catch (phpmailerException $e) {
435                 Logger::debug('mailstream_send PHPMailer exception sending message ' . $message_id . ': ' . $e->errorMessage());
436         } catch (Exception $e) {
437                 Logger::debug('mailstream_send exception sending message ' . $message_id . ': ' . $e->getMessage());
438         }
439
440         return true;
441 }
442
443 /**
444  * Email tends to break if you send excessively long lines.  To make
445  * bbcode's output suitable for transmission, we try to break things
446  * up so that lines are about 200 characters.
447  *
448  * @param string $text text to word wrap
449  * @return string wrapped text
450  */
451 function mailstream_html_wrap(string &$text)
452 {
453         $lines = str_split($text, 200);
454         for ($i = 0; $i < count($lines); $i++) {
455                 $lines[$i] = preg_replace('/ /', "\n", $lines[$i], 1);
456         }
457         $text = implode($lines);
458         return $text;
459 }
460
461 /**
462  * Convert v1 mailstream table entries to v2 workerqueue items
463  */
464 function mailstream_convert_table_entries()
465 {
466         $ms_item_ids = DBA::selectToArray('mailstream_item', [], ['message-id', 'uri', 'uid', 'contact-id'], ["`mailstream_item`.`completed` IS NULL"]);
467         Logger::debug('mailstream_convert_table_entries processing ' . count($ms_item_ids) . ' items');
468         foreach ($ms_item_ids as $ms_item_id) {
469                 $send_hook_data = array('uid' => $ms_item_id['uid'],
470                                         'contact-id' => $ms_item_id['contact-id'],
471                                         'uri' => $ms_item_id['uri'],
472                                         'message_id' => $ms_item_id['message-id'],
473                                         'tries' => 0);
474                 if (!$ms_item_id['message-id'] || !strlen($ms_item_id['message-id'])) {
475                         Logger::info('mailstream_convert_table_entries: item has no message-id.', ['item' => $ms_item_id['id'], 'uri' => $ms_item_id['uri']]);
476                                                         continue;
477                 }
478                 Logger::info('mailstream_convert_table_entries: convert item to workerqueue', $send_hook_data);
479                 Hook::fork(Worker::PRIORITY_LOW, 'mailstream_send_hook', $send_hook_data);
480         }
481         DBA::e('DROP TABLE `mailstream_item`');
482 }
483
484 /**
485  * Form for configuring mailstream features for a user
486  *
487  * @param array $data Hook data array
488  * @throws \Friendica\Network\HTTPException\ServiceUnavailableException
489  */
490 function mailstream_addon_settings(array &$data)
491 {
492         $enabled   = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'mailstream', 'enabled');
493         $address   = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'mailstream', 'address');
494         $nolikes   = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'mailstream', 'nolikes');
495         $attachimg = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'mailstream', 'attachimg');
496
497         $template  = Renderer::getMarkupTemplate('settings.tpl', 'addon/mailstream/');
498         $html      = Renderer::replaceMacros($template, [
499                 '$enabled'   => [
500                         'mailstream_enabled',
501                         DI::l10n()->t('Enabled'),
502                         $enabled
503                 ],
504                 '$address'   => [
505                         'mailstream_address',
506                         DI::l10n()->t('Email Address'),
507                         $address,
508                         DI::l10n()->t('Leave blank to use your account email address')
509                 ],
510                 '$nolikes'   => [
511                         'mailstream_nolikes',
512                         DI::l10n()->t('Exclude Likes'),
513                         $nolikes,
514                         DI::l10n()->t('Check this to omit mailing "Like" notifications')
515                 ],
516                 '$attachimg' => [
517                         'mailstream_attachimg',
518                         DI::l10n()->t('Attach Images'),
519                         $attachimg,
520                         DI::l10n()->t('Download images in posts and attach them to the email.  ' .
521                                 'Useful for reading email while offline.')
522                 ],
523         ]);
524
525         $data = [
526                 'addon' => 'mailstream',
527                 'title' => DI::l10n()->t('Mail Stream Settings'),
528                 'html'  => $html,
529         ];
530 }
531
532 /**
533  * Process data submitted to user's mailstream features form
534  * @param array          $post POST data
535  * @return void
536  */
537 function mailstream_addon_settings_post(array $post)
538 {
539         if (!DI::userSession()->getLocalUserId() || empty($post['mailstream-submit'])) {
540                 return;
541         }
542
543         if ($post['mailstream_address'] != "") {
544                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'mailstream', 'address', $post['mailstream_address']);
545         } else {
546                 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'mailstream', 'address');
547         }
548         if ($post['mailstream_nolikes']) {
549                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'mailstream', 'nolikes', $post['mailstream_enabled']);
550         } else {
551                 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'mailstream', 'nolikes');
552         }
553         if ($post['mailstream_enabled']) {
554                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'mailstream', 'enabled', $post['mailstream_enabled']);
555         } else {
556                 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'mailstream', 'enabled');
557         }
558         if ($post['mailstream_attachimg']) {
559                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'mailstream', 'attachimg', $post['mailstream_attachimg']);
560         } else {
561                 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'mailstream', 'attachimg');
562         }
563 }