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