]> git.mxchange.org Git - friendica-addons.git/blob - mailstream/mailstream.php
Twitter addon translation update THX kalon33
[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 App $a App object (unused)
71  * @param string        $o HTML form data
72  */
73 function mailstream_addon_admin(App $a, string &$o)
74 {
75         $frommail = DI::config()->get('mailstream', 'frommail');
76         $template = Renderer::getMarkupTemplate('admin.tpl', 'addon/mailstream/');
77         $config = ['frommail',
78                 DI::l10n()->t('From Address'),
79                 $frommail,
80                 DI::l10n()->t('Email address that stream items will appear to be from.')];
81         $o .= Renderer::replaceMacros($template, [
82                 '$frommail' => $config,
83                 '$submit' => DI::l10n()->t('Save Settings')
84         ]);
85 }
86
87 /**
88  * Process input from the "addon features" part of the admin menu
89  */
90 function mailstream_addon_admin_post()
91 {
92         if (!empty($_POST['frommail'])) {
93                 DI::config()->set('mailstream', 'frommail', $_POST['frommail']);
94         }
95 }
96
97 /**
98  * Creates a message ID for a post URI in accordance with RFC 1036
99  * See also http://www.jwz.org/doc/mid.html
100  *
101  * @param string $uri the URI to be converted to a message ID
102  *
103  * @return string the created message ID
104  */
105 function mailstream_generate_id(string $uri): string
106 {
107         $host = DI::baseUrl()->getHostname();
108         $resource = hash('md5', $uri);
109         $message_id = "<" . $resource . "@" . $host . ">";
110         Logger::debug('mailstream: Generated message ID ' . $message_id . ' for URI ' . $uri);
111         return $message_id;
112 }
113
114 function mailstream_send_hook(App $a, array $data)
115 {
116         $criteria = array('uid' => $data['uid'], 'contact-id' => $data['contact-id'], 'uri' => $data['uri']);
117         $item = Post::selectFirst([], $criteria);
118         if (empty($item)) {
119                 Logger::error('mailstream_send_hook could not find item');
120                 return;
121         }
122
123         $user = User::getById($item['uid']);
124         if (empty($user)) {
125                         Logger::error('mailstream_send_hook could not fund user', ['uid' => $item['uid']]);
126                 return;
127         }
128
129         if (!mailstream_send($data['message_id'], $item, $user)) {
130                 Logger::debug('mailstream_send_hook send failed, will retry', $data);
131                 if (!Worker::defer()) {
132                         Logger::error('mailstream_send_hook failed and could not defer', $data);
133                 }
134         }
135 }
136
137 /**
138  * Called when either a local or remote post is created.  If
139  * mailstream is enabled and the necessary data is available, forks a
140  * workerqueue item to send the email.
141  *
142  * @param App $a    App object (unused)
143  * @param array     $item content of the item (may or may not already be stored in the item table)
144  * @return void
145  */
146 function mailstream_post_hook(App $a, array &$item)
147 {
148         mailstream_check_version();
149
150         if (!DI::pConfig()->get($item['uid'], 'mailstream', 'enabled')) {
151                 Logger::debug('mailstream: not enabled for item ' . $item['id']);
152                 return;
153         }
154         if (!$item['uid']) {
155                 Logger::debug('mailstream: no uid for item ' . $item['id']);
156                 return;
157         }
158         if (!$item['contact-id']) {
159                 Logger::debug('mailstream: no contact-id for item ' . $item['id']);
160                 return;
161         }
162         if (!$item['uri']) {
163                 Logger::debug('mailstream: no uri for item ' . $item['id']);
164                 return;
165         }
166         if (!$item['plink']) {
167                 Logger::debug('mailstream: no plink for item ' . $item['id']);
168                 return;
169         }
170         if (DI::pConfig()->get($item['uid'], 'mailstream', 'nolikes')) {
171                 if ($item['verb'] == Activity::LIKE) {
172                         Logger::debug('mailstream: like item ' . $item['id']);
173                         return;
174                 }
175         }
176
177         $message_id = mailstream_generate_id($item['uri']);
178
179         $send_hook_data = [
180                 'uid' => $item['uid'],
181                 'contact-id' => $item['contact-id'],
182                 'uri' => $item['uri'],
183                 'message_id' => $message_id,
184                 'tries' => 0,
185         ];
186         Hook::fork(Worker::PRIORITY_LOW, 'mailstream_send_hook', $send_hook_data);
187 }
188
189 /**
190  * If the user has configured attaching images to emails as
191  * attachments, this function searches the post for such images,
192  * retrieves the image, and inserts the data and metadata into the
193  * supplied array
194  *
195  * @param array         $item        content of the item
196  * @param array         $attachments contains an array element for each attachment to add to the email
197  *
198  * @return array new value of the attachments table (results are also stored in the reference parameter)
199  */
200 function mailstream_do_images(array &$item, array &$attachments)
201 {
202         if (!DI::pConfig()->get($item['uid'], 'mailstream', 'attachimg')) {
203                 return;
204         }
205
206         $attachments = [];
207
208         preg_match_all("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", $item["body"], $matches1);
209         preg_match_all("/\[img\](.*?)\[\/img\]/ism", $item["body"], $matches2);
210         preg_match_all("/\[img\=([^\]]*)\]([^[]*)\[\/img\]/ism", $item["body"], $matches3);
211
212         foreach (array_merge($matches1[3], $matches2[1], $matches3[1]) as $url) {
213                 $components = parse_url($url);
214
215                 if (!$components) {
216                         continue;
217                 }
218
219                 $cookiejar = tempnam(System::getTempPath(), 'cookiejar-mailstream-');
220                 $curlResult = DI::httpClient()->fetchFull($url, HttpClientAccept::DEFAULT, 0, $cookiejar);
221                 $attachments[$url] = [
222                         'data' => $curlResult->getBody(),
223                         'guid' => hash('crc32', $url),
224                         'filename' => basename($components['path']),
225                         'type' => $curlResult->getContentType()
226                 ];
227
228                 if (strlen($attachments[$url]['data'])) {
229                         $item['body'] = str_replace($url, 'cid:' . $attachments[$url]['guid'], $item['body']);
230                         continue;
231                 }
232         }
233
234         return $attachments;
235 }
236
237 /**
238  * Creates a sender to use in the email, either from the contact or the author of the item, or both
239  *
240  * @param array $item content of the item
241  *
242  * @return string sender suitable for use in the email
243  */
244 function mailstream_sender(array $item): string
245 {
246         $contact = Contact::getById($item['contact-id']);
247         if (DBA::isResult($contact)) {
248                 if ($contact['name'] != $item['author-name']) {
249                         return $contact['name'] . ' - ' . $item['author-name'];
250                 }
251         }
252         return $item['author-name'];
253 }
254
255 /**
256  * Converts a bbcode-encoded subject line into a plaintext version suitable for the subject line of an email
257  *
258  * @param string $subject bbcode-encoded subject line
259  *
260  * @return string plaintext subject line
261  */
262 function mailstream_decode_subject(string $subject): string
263 {
264         $html = BBCode::convert($subject);
265         if (!$html) {
266                 return $subject;
267         }
268         $notags = strip_tags($html);
269         if (!$notags) {
270                 return $subject;
271         }
272         $noentity = html_entity_decode($notags);
273         if (!$noentity) {
274                 return $notags;
275         }
276         $nocodes = preg_replace_callback("/(&#[0-9]+;)/", function ($m) {
277                 return mb_convert_encoding($m[1], 'UTF-8', 'HTML-ENTITIES');
278         }, $noentity);
279         if (!$nocodes) {
280                 return $noentity;
281         }
282         $trimmed = trim($nocodes);
283         if (!$trimmed) {
284                 return $nocodes;
285         }
286         return $trimmed;
287 }
288
289 /**
290  * Creates a subject line to use in the email
291  *
292  * @param array $item content of the item
293  *
294  * @return string subject line suitable for use in the email
295  */
296 function mailstream_subject(array $item): string
297 {
298         if ($item['title']) {
299                 return mailstream_decode_subject($item['title']);
300         }
301         $parent = $item['thr-parent'];
302         // Don't look more than 100 levels deep for a subject, in case of loops
303         for ($i = 0; ($i < 100) && $parent; $i++) {
304                 $parent_item = Post::selectFirst(['thr-parent', 'title'], ['uri' => $parent]);
305                 if (!DBA::isResult($parent_item)) {
306                         break;
307                 }
308                 if ($parent_item['thr-parent'] === $parent) {
309                         break;
310                 }
311                 if ($parent_item['title']) {
312                         return DI::l10n()->t('Re:') . ' ' . mailstream_decode_subject($parent_item['title']);
313                 }
314                 $parent = $parent_item['thr-parent'];
315         }
316         $contact = Contact::selectFirst([], ['id' => $item['contact-id'], 'uid' => $item['uid']]);
317         if (!DBA::isResult($contact)) {
318                 Logger::error(
319                         'mailstream_subject no contact for item',
320                         ['id' => $item['id'],
321                                 'plink' => $item['plink'],
322                                 'contact id' => $item['contact-id'],
323                         'uid' => $item['uid']]
324                 );
325                 return DI::l10n()->t("Friendica post");
326         }
327         if ($contact['network'] === 'dfrn') {
328                 return DI::l10n()->t("Friendica post");
329         }
330         if ($contact['network'] === 'dspr') {
331                 return DI::l10n()->t("Diaspora post");
332         }
333         if ($contact['network'] === 'face') {
334                 $text = mailstream_decode_subject($item['body']);
335                 // For some reason these do show up in Facebook
336                 $text = preg_replace('/\xA0$/', '', $text);
337                 $subject = (strlen($text) > 150) ? (substr($text, 0, 140) . '...') : $text;
338                 return preg_replace('/\\s+/', ' ', $subject);
339         }
340         if ($contact['network'] === 'feed') {
341                 return DI::l10n()->t("Feed item");
342         }
343         if ($contact['network'] === 'mail') {
344                 return DI::l10n()->t("Email");
345         }
346         return DI::l10n()->t("Friendica Item");
347 }
348
349 /**
350  * Sends a message using PHPMailer
351  *
352  * @param string $message_id ID of the message (RFC 1036)
353  * @param array  $item       content of the item
354  * @param array  $user       results from the user table
355  *
356  * @return bool True if this message has been completed.  False if it should be retried.
357  */
358 function mailstream_send(string $message_id, array $item, array $user): bool
359 {
360         if (!is_array($item)) {
361                 Logger::error('mailstream_send item is empty', ['message_id' => $message_id]);
362                 return false;
363         }
364
365         if (!$item['visible']) {
366                 Logger::debug('mailstream_send item not yet visible', ['item uri' => $item['uri']]);
367                 return false;
368         }
369         if (!$message_id) {
370                 Logger::error('mailstream_send no message ID supplied', ['item uri' => $item['uri'],
371                                 'user email' => $user['email']]);
372                 return true;
373         }
374
375         require_once (dirname(__file__) . '/phpmailer/class.phpmailer.php');
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()->get() . '/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 App   $a    App object
479  * @param array $data Hook data array
480  * @throws \Friendica\Network\HTTPException\ServiceUnavailableException
481  */
482 function mailstream_addon_settings(App &$a, array &$data)
483 {
484         $enabled   = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'mailstream', 'enabled');
485         $address   = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'mailstream', 'address');
486         $nolikes   = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'mailstream', 'nolikes');
487         $attachimg = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'mailstream', 'attachimg');
488
489         $template  = Renderer::getMarkupTemplate('settings.tpl', 'addon/mailstream/');
490         $html      = Renderer::replaceMacros($template, [
491                 '$enabled'   => [
492                         'mailstream_enabled',
493                         DI::l10n()->t('Enabled'),
494                         $enabled
495                 ],
496                 '$address'   => [
497                         'mailstream_address',
498                         DI::l10n()->t('Email Address'),
499                         $address,
500                         DI::l10n()->t('Leave blank to use your account email address')
501                 ],
502                 '$nolikes'   => [
503                         'mailstream_nolikes',
504                         DI::l10n()->t('Exclude Likes'),
505                         $nolikes,
506                         DI::l10n()->t('Check this to omit mailing "Like" notifications')
507                 ],
508                 '$attachimg' => [
509                         'mailstream_attachimg',
510                         DI::l10n()->t('Attach Images'),
511                         $attachimg,
512                         DI::l10n()->t('Download images in posts and attach them to the email.  ' .
513                                 'Useful for reading email while offline.')
514                 ],
515         ]);
516
517         $data = [
518                 'addon' => 'mailstream',
519                 'title' => DI::l10n()->t('Mail Stream Settings'),
520                 'html'  => $html,
521         ];
522 }
523
524 /**
525  * Process data submitted to user's mailstream features form
526  * @param App $a
527  * @param array          $post POST data
528  * @return void
529  */
530 function mailstream_addon_settings_post(App $a, array $post)
531 {
532         if (!DI::userSession()->getLocalUserId() || empty($post['mailstream-submit'])) {
533                 return;
534         }
535
536         if ($post['mailstream_address'] != "") {
537                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'mailstream', 'address', $post['mailstream_address']);
538         } else {
539                 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'mailstream', 'address');
540         }
541         if ($post['mailstream_nolikes']) {
542                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'mailstream', 'nolikes', $post['mailstream_enabled']);
543         } else {
544                 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'mailstream', 'nolikes');
545         }
546         if ($post['mailstream_enabled']) {
547                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'mailstream', 'enabled', $post['mailstream_enabled']);
548         } else {
549                 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'mailstream', 'enabled');
550         }
551         if ($post['mailstream_attachimg']) {
552                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'mailstream', 'attachimg', $post['mailstream_attachimg']);
553         } else {
554                 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'mailstream', 'attachimg');
555         }
556 }