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