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