4 * Description: Mail all items coming into your network feed to an email address
6 * Author: Matthew Exon <http://mat.exon.name>
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;
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;
27 * Sets up the addon hooks and the database table
29 function mailstream_install()
31 Hook::register('addon_settings', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings');
32 Hook::register('addon_settings_post', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings_post');
33 Hook::register('post_local_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
34 Hook::register('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
35 Hook::register('mailstream_send_hook', 'addon/mailstream/mailstream.php', 'mailstream_send_hook');
37 Logger::info("mailstream: installed");
41 * Enforces that mailstream_install has set up the current version
43 function mailstream_check_version()
45 if (!is_null(DI::config()->get('mailstream', 'dbversion'))) {
46 DI::config()->delete('mailstream', 'dbversion');
47 Logger::info("mailstream_check_version: old version detected, reinstalling");
51 'mailstream_convert_table_entries',
52 'addon/mailstream/mailstream.php',
53 'mailstream_convert_table_entries'
55 Hook::fork(Worker::PRIORITY_LOW, 'mailstream_convert_table_entries');
60 * This is a statement rather than an actual function definition. The simple
61 * existence of this method is checked to figure out if the addon offers a
64 function mailstream_module() {}
67 * Adds an item in "addon features" in the admin menu of the site
69 * @param App $a App object (unused)
70 * @param string $o HTML form data
72 function mailstream_addon_admin(App $a, string &$o)
74 $frommail = DI::config()->get('mailstream', 'frommail');
75 $template = Renderer::getMarkupTemplate('admin.tpl', 'addon/mailstream/');
76 $config = ['frommail',
77 DI::l10n()->t('From Address'),
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')
87 * Process input from the "addon features" part of the admin menu
89 function mailstream_addon_admin_post()
91 if (!empty($_POST['frommail'])) {
92 DI::config()->set('mailstream', 'frommail', $_POST['frommail']);
97 * Creates a message ID for a post URI in accordance with RFC 1036
98 * See also http://www.jwz.org/doc/mid.html
100 * @param string $uri the URI to be converted to a message ID
102 * @return string the created message ID
104 function mailstream_generate_id(string $uri): string
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);
113 function mailstream_send_hook(App $a, array $data)
115 $criteria = array('uid' => $data['uid'], 'contact-id' => $data['contact-id'], 'uri' => $data['uri']);
116 $item = Post::selectFirst([], $criteria);
118 Logger::error('mailstream_send_hook could not find item');
122 $user = User::getById($item['uid']);
124 Logger::error('mailstream_send_hook could not fund user', ['uid' => $item['uid']]);
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);
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.
141 * @param App $a App object (unused)
142 * @param array $item content of the item (may or may not already be stored in the item table)
145 function mailstream_post_hook(App $a, array &$item)
147 mailstream_check_version();
149 if (!DI::pConfig()->get($item['uid'], 'mailstream', 'enabled')) {
150 Logger::debug('mailstream: not enabled.', ['item' => $item['id'], ' uid ' => $item['uid']]);
154 Logger::debug('mailstream: no uid for item ' . $item['id']);
157 if (!$item['contact-id']) {
158 Logger::debug('mailstream: no contact-id for item ' . $item['id']);
162 Logger::debug('mailstream: no uri for item ' . $item['id']);
165 if ($item['verb'] == Activity::ANNOUNCE) {
166 Logger::debug('mailstream: announce item ', ['item' => $item['id']]);
169 if (DI::pConfig()->get($item['uid'], 'mailstream', 'nolikes')) {
170 if ($item['verb'] == Activity::LIKE) {
171 Logger::debug('mailstream: like item ' . $item['id']);
176 $message_id = mailstream_generate_id($item['uri']);
179 'uid' => $item['uid'],
180 'contact-id' => $item['contact-id'],
181 'uri' => $item['uri'],
182 'message_id' => $message_id,
185 Hook::fork(Worker::PRIORITY_LOW, 'mailstream_send_hook', $send_hook_data);
189 * If the user has configured attaching images to emails as
190 * attachments, this function searches the post for such images,
191 * retrieves the image, and inserts the data and metadata into the
194 * @param array $item content of the item
195 * @param array $attachments contains an array element for each attachment to add to the email
197 * @return array new value of the attachments table (results are also stored in the reference parameter)
199 function mailstream_do_images(array &$item, array &$attachments)
201 if (!DI::pConfig()->get($item['uid'], 'mailstream', 'attachimg')) {
207 preg_match_all("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", $item["body"], $matches1);
208 preg_match_all("/\[img\](.*?)\[\/img\]/ism", $item["body"], $matches2);
209 preg_match_all("/\[img\=([^\]]*)\]([^[]*)\[\/img\]/ism", $item["body"], $matches3);
211 foreach (array_merge($matches1[3], $matches2[1], $matches3[1]) as $url) {
212 $components = parse_url($url);
218 $cookiejar = tempnam(System::getTempPath(), 'cookiejar-mailstream-');
219 $curlResult = DI::httpClient()->fetchFull($url, HttpClientAccept::DEFAULT, 0, $cookiejar);
220 $attachments[$url] = [
221 'data' => $curlResult->getBody(),
222 'guid' => hash('crc32', $url),
223 'filename' => basename($components['path']),
224 'type' => $curlResult->getContentType()
227 if (strlen($attachments[$url]['data'])) {
228 $item['body'] = str_replace($url, 'cid:' . $attachments[$url]['guid'], $item['body']);
237 * Creates a sender to use in the email, either from the contact or the author of the item, or both
239 * @param array $item content of the item
241 * @return string sender suitable for use in the email
243 function mailstream_sender(array $item): string
245 $contact = Contact::getById($item['contact-id']);
246 if (DBA::isResult($contact)) {
247 if ($contact['name'] != $item['author-name']) {
248 return $contact['name'] . ' - ' . $item['author-name'];
251 return $item['author-name'];
255 * Converts a bbcode-encoded subject line into a plaintext version suitable for the subject line of an email
257 * @param string $subject bbcode-encoded subject line
259 * @return string plaintext subject line
261 function mailstream_decode_subject(string $subject): string
263 $html = BBCode::convert($subject);
267 $notags = strip_tags($html);
271 $noentity = html_entity_decode($notags);
275 $nocodes = preg_replace_callback("/(&#[0-9]+;)/", function ($m) {
276 return mb_convert_encoding($m[1], 'UTF-8', 'HTML-ENTITIES');
281 $trimmed = trim($nocodes);
289 * Creates a subject line to use in the email
291 * @param array $item content of the item
293 * @return string subject line suitable for use in the email
295 function mailstream_subject(array $item): string
297 if ($item['title']) {
298 return mailstream_decode_subject($item['title']);
300 $parent = $item['thr-parent'];
301 // Don't look more than 100 levels deep for a subject, in case of loops
302 for ($i = 0; ($i < 100) && $parent; $i++) {
303 $parent_item = Post::selectFirst(['thr-parent', 'title'], ['uri' => $parent]);
304 if (!DBA::isResult($parent_item)) {
307 if ($parent_item['thr-parent'] === $parent) {
310 if ($parent_item['title']) {
311 return DI::l10n()->t('Re:') . ' ' . mailstream_decode_subject($parent_item['title']);
313 $parent = $parent_item['thr-parent'];
315 $contact = Contact::selectFirst([], ['id' => $item['contact-id'], 'uid' => $item['uid']]);
316 if (!DBA::isResult($contact)) {
318 'mailstream_subject no contact for item',
319 ['id' => $item['id'],
320 'plink' => $item['plink'],
321 'contact id' => $item['contact-id'],
322 'uid' => $item['uid']]
324 return DI::l10n()->t("Friendica post");
326 if ($contact['network'] === 'dfrn') {
327 return DI::l10n()->t("Friendica post");
329 if ($contact['network'] === 'dspr') {
330 return DI::l10n()->t("Diaspora post");
332 if ($contact['network'] === 'face') {
333 $text = mailstream_decode_subject($item['body']);
334 // For some reason these do show up in Facebook
335 $text = preg_replace('/\xA0$/', '', $text);
336 $subject = (strlen($text) > 150) ? (substr($text, 0, 140) . '...') : $text;
337 return preg_replace('/\\s+/', ' ', $subject);
339 if ($contact['network'] === 'feed') {
340 return DI::l10n()->t("Feed item");
342 if ($contact['network'] === 'mail') {
343 return DI::l10n()->t("Email");
345 return DI::l10n()->t("Friendica Item");
349 * Sends a message using PHPMailer
351 * @param string $message_id ID of the message (RFC 1036)
352 * @param array $item content of the item
353 * @param array $user results from the user table
355 * @return bool True if this message has been completed. False if it should be retried.
357 function mailstream_send(string $message_id, array $item, array $user): bool
359 if (!is_array($item)) {
360 Logger::error('mailstream_send item is empty', ['message_id' => $message_id]);
364 if (!$item['visible']) {
365 Logger::debug('mailstream_send item not yet visible', ['item uri' => $item['uri']]);
369 Logger::error('mailstream_send no message ID supplied', ['item uri' => $item['uri'],
370 'user email' => $user['email']]);
374 require_once (dirname(__file__) . '/phpmailer/class.phpmailer.php');
376 $item['body'] = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
379 mailstream_do_images($item, $attachments);
380 $frommail = DI::config()->get('mailstream', 'frommail');
381 if ($frommail == '') {
382 $frommail = 'friendica@localhost.local';
384 $address = DI::pConfig()->get($item['uid'], 'mailstream', 'address');
386 $address = $user['email'];
388 $mail = new PHPmailer();
390 $mail->XMailer = 'Friendica Mailstream Addon';
391 $mail->SetFrom($frommail, mailstream_sender($item));
392 $mail->AddAddress($address, $user['username']);
393 $mail->MessageID = $message_id;
394 $mail->Subject = mailstream_subject($item);
395 if ($item['thr-parent'] != $item['uri']) {
396 $mail->addCustomHeader('In-Reply-To: ' . mailstream_generate_id($item['thr-parent']));
398 $mail->addCustomHeader('X-Friendica-Mailstream-URI: ' . $item['uri']);
399 if ($item['plink']) {
400 $mail->addCustomHeader('X-Friendica-Mailstream-Plink: ' . $item['plink']);
402 $encoding = 'base64';
403 foreach ($attachments as $url => $image) {
404 $mail->AddStringEmbeddedImage(
413 $mail->CharSet = 'utf-8';
414 $template = Renderer::getMarkupTemplate('mail.tpl', 'addon/mailstream/');
415 $mail->AltBody = BBCode::toPlaintext($item['body']);
416 $item['body'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::CONNECTORS);
417 $item['url'] = DI::baseUrl()->get() . '/display/' . $item['guid'];
418 $mail->Body = Renderer::replaceMacros($template, [
419 '$upstream' => DI::l10n()->t('Upstream'),
420 '$uri' => DI::l10n()->t('URI'),
421 '$local' => DI::l10n()->t('Local'),
423 $mail->Body = mailstream_html_wrap($mail->Body);
424 if (!$mail->Send()) {
425 throw new Exception($mail->ErrorInfo);
427 Logger::debug('mailstream_send sent message', ['message ID' => $mail->MessageID,
428 'subject' => $mail->Subject,
429 'address' => $address]);
430 } catch (phpmailerException $e) {
431 Logger::debug('mailstream_send PHPMailer exception sending message ' . $message_id . ': ' . $e->errorMessage());
432 } catch (Exception $e) {
433 Logger::debug('mailstream_send exception sending message ' . $message_id . ': ' . $e->getMessage());
440 * Email tends to break if you send excessively long lines. To make
441 * bbcode's output suitable for transmission, we try to break things
442 * up so that lines are about 200 characters.
444 * @param string $text text to word wrap
445 * @return string wrapped text
447 function mailstream_html_wrap(string &$text)
449 $lines = str_split($text, 200);
450 for ($i = 0; $i < count($lines); $i++) {
451 $lines[$i] = preg_replace('/ /', "\n", $lines[$i], 1);
453 $text = implode($lines);
458 * Convert v1 mailstream table entries to v2 workerqueue items
460 function mailstream_convert_table_entries()
462 $ms_item_ids = DBA::selectToArray('mailstream_item', [], ['message-id', 'uri', 'uid', 'contact-id'], ["`mailstream_item`.`completed` IS NULL"]);
463 Logger::debug('mailstream_convert_table_entries processing ' . count($ms_item_ids) . ' items');
464 foreach ($ms_item_ids as $ms_item_id) {
465 $send_hook_data = array('uid' => $ms_item_id['uid'],
466 'contact-id' => $ms_item_id['contact-id'],
467 'uri' => $ms_item_id['uri'],
468 'message_id' => $ms_item_id['message-id'],
470 if (!$ms_item_id['message-id'] || !strlen($ms_item_id['message-id'])) {
471 Logger::info('mailstream_convert_table_entries: item has no message-id.', ['item' => $ms_item_id['id'], 'uri' => $ms_item_id['uri']]);
474 Logger::info('mailstream_convert_table_entries: convert item to workerqueue', $send_hook_data);
475 Hook::fork(Worker::PRIORITY_LOW, 'mailstream_send_hook', $send_hook_data);
477 DBA::e('DROP TABLE `mailstream_item`');
481 * Form for configuring mailstream features for a user
483 * @param App $a App object
484 * @param array $data Hook data array
485 * @throws \Friendica\Network\HTTPException\ServiceUnavailableException
487 function mailstream_addon_settings(App &$a, array &$data)
489 $enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'mailstream', 'enabled');
490 $address = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'mailstream', 'address');
491 $nolikes = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'mailstream', 'nolikes');
492 $attachimg = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'mailstream', 'attachimg');
494 $template = Renderer::getMarkupTemplate('settings.tpl', 'addon/mailstream/');
495 $html = Renderer::replaceMacros($template, [
497 'mailstream_enabled',
498 DI::l10n()->t('Enabled'),
502 'mailstream_address',
503 DI::l10n()->t('Email Address'),
505 DI::l10n()->t('Leave blank to use your account email address')
508 'mailstream_nolikes',
509 DI::l10n()->t('Exclude Likes'),
511 DI::l10n()->t('Check this to omit mailing "Like" notifications')
514 'mailstream_attachimg',
515 DI::l10n()->t('Attach Images'),
517 DI::l10n()->t('Download images in posts and attach them to the email. ' .
518 'Useful for reading email while offline.')
523 'addon' => 'mailstream',
524 'title' => DI::l10n()->t('Mail Stream Settings'),
530 * Process data submitted to user's mailstream features form
532 * @param array $post POST data
535 function mailstream_addon_settings_post(App $a, array $post)
537 if (!DI::userSession()->getLocalUserId() || empty($post['mailstream-submit'])) {
541 if ($post['mailstream_address'] != "") {
542 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'mailstream', 'address', $post['mailstream_address']);
544 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'mailstream', 'address');
546 if ($post['mailstream_nolikes']) {
547 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'mailstream', 'nolikes', $post['mailstream_enabled']);
549 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'mailstream', 'nolikes');
551 if ($post['mailstream_enabled']) {
552 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'mailstream', 'enabled', $post['mailstream_enabled']);
554 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'mailstream', 'enabled');
556 if ($post['mailstream_attachimg']) {
557 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'mailstream', 'attachimg', $post['mailstream_attachimg']);
559 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'mailstream', 'attachimg');