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