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 string $o HTML form data
71 function mailstream_addon_admin(string &$o)
73 $frommail = DI::config()->get('mailstream', 'frommail');
74 $template = Renderer::getMarkupTemplate('admin.tpl', 'addon/mailstream/');
75 $config = ['frommail',
76 DI::l10n()->t('From Address'),
78 DI::l10n()->t('Email address that stream items will appear to be from.')];
79 $o .= Renderer::replaceMacros($template, [
80 '$frommail' => $config,
81 '$submit' => DI::l10n()->t('Save Settings')
86 * Process input from the "addon features" part of the admin menu
88 function mailstream_addon_admin_post()
90 if (!empty($_POST['frommail'])) {
91 DI::config()->set('mailstream', 'frommail', $_POST['frommail']);
96 * Creates a message ID for a post URI in accordance with RFC 1036
97 * See also http://www.jwz.org/doc/mid.html
99 * @param string $uri the URI to be converted to a message ID
101 * @return string the created message ID
103 function mailstream_generate_id(string $uri): string
105 $host = DI::baseUrl()->getHost();
106 $resource = hash('md5', $uri);
107 $message_id = "<" . $resource . "@" . $host . ">";
108 Logger::debug('mailstream: Generated message ID ' . $message_id . ' for URI ' . $uri);
112 function mailstream_send_hook(array $data)
114 $criteria = array('uid' => $data['uid'], 'contact-id' => $data['contact-id'], 'uri' => $data['uri']);
115 $item = Post::selectFirst([], $criteria);
117 Logger::error('mailstream_send_hook could not find item');
121 $user = User::getById($item['uid']);
123 Logger::error('mailstream_send_hook could not fund user', ['uid' => $item['uid']]);
127 if (!mailstream_send($data['message_id'], $item, $user)) {
128 Logger::debug('mailstream_send_hook send failed, will retry', $data);
129 if (!Worker::defer()) {
130 Logger::error('mailstream_send_hook failed and could not defer', $data);
136 * Called when either a local or remote post is created. If
137 * mailstream is enabled and the necessary data is available, forks a
138 * workerqueue item to send the email.
140 * @param array $item content of the item (may or may not already be stored in the item table)
143 function mailstream_post_hook(array &$item)
145 mailstream_check_version();
147 if (!DI::pConfig()->get($item['uid'], 'mailstream', 'enabled')) {
148 Logger::debug('mailstream: not enabled.', ['item' => $item['id'], ' uid ' => $item['uid']]);
152 Logger::debug('mailstream: no uid for item ' . $item['id']);
155 if (!$item['contact-id']) {
156 Logger::debug('mailstream: no contact-id for item ' . $item['id']);
160 Logger::debug('mailstream: no uri for item ' . $item['id']);
163 if ($item['verb'] == Activity::ANNOUNCE) {
164 Logger::debug('mailstream: announce item ', ['item' => $item['id']]);
167 if (DI::pConfig()->get($item['uid'], 'mailstream', 'nolikes')) {
168 if ($item['verb'] == Activity::LIKE) {
169 Logger::debug('mailstream: like item ' . $item['id']);
174 $message_id = mailstream_generate_id($item['uri']);
177 'uid' => $item['uid'],
178 'contact-id' => $item['contact-id'],
179 'uri' => $item['uri'],
180 'message_id' => $message_id,
183 Hook::fork(Worker::PRIORITY_LOW, 'mailstream_send_hook', $send_hook_data);
187 * If the user has configured attaching images to emails as
188 * attachments, this function searches the post for such images,
189 * retrieves the image, and inserts the data and metadata into the
192 * @param array $item content of the item
193 * @param array $attachments contains an array element for each attachment to add to the email
195 * @return array new value of the attachments table (results are also stored in the reference parameter)
197 function mailstream_do_images(array &$item, array &$attachments)
199 if (!DI::pConfig()->get($item['uid'], 'mailstream', 'attachimg')) {
205 preg_match_all("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", $item["body"], $matches1);
206 preg_match_all("/\[img\](.*?)\[\/img\]/ism", $item["body"], $matches2);
207 preg_match_all("/\[img\=([^\]]*)\]([^[]*)\[\/img\]/ism", $item["body"], $matches3);
209 foreach (array_merge($matches1[3], $matches2[1], $matches3[1]) as $url) {
210 $components = parse_url($url);
216 $cookiejar = tempnam(System::getTempPath(), 'cookiejar-mailstream-');
218 $curlResult = DI::httpClient()->fetchFull($url, HttpClientAccept::DEFAULT, 0, $cookiejar);
219 } catch (InvalidArgumentException $e) {
220 Logger::error('mailstream_do_images exception fetching url', ['url' => $url, 'item_id' => $item['id']]);
223 $attachments[$url] = [
224 'data' => $curlResult->getBody(),
225 'guid' => hash('crc32', $url),
226 'filename' => basename($components['path']),
227 'type' => $curlResult->getContentType()
230 if (strlen($attachments[$url]['data'])) {
231 $item['body'] = str_replace($url, 'cid:' . $attachments[$url]['guid'], $item['body']);
240 * Creates a sender to use in the email, either from the contact or the author of the item, or both
242 * @param array $item content of the item
244 * @return string sender suitable for use in the email
246 function mailstream_sender(array $item): string
248 $contact = Contact::getById($item['contact-id']);
249 if (DBA::isResult($contact)) {
250 if ($contact['name'] != $item['author-name']) {
251 return $contact['name'] . ' - ' . $item['author-name'];
254 return $item['author-name'];
258 * Converts a bbcode-encoded subject line into a plaintext version suitable for the subject line of an email
260 * @param string $subject bbcode-encoded subject line
263 * @return string plaintext subject line
265 function mailstream_decode_subject(string $subject, int $uri_id): string
267 $html = BBCode::convertForUriId($uri_id, $subject);
271 $notags = strip_tags($html);
275 $noentity = html_entity_decode($notags);
279 $nocodes = preg_replace_callback("/(&#[0-9]+;)/", function ($m) {
280 return mb_convert_encoding($m[1], 'UTF-8', 'HTML-ENTITIES');
285 $trimmed = trim($nocodes);
293 * Creates a subject line to use in the email
295 * @param array $item content of the item
297 * @return string subject line suitable for use in the email
299 function mailstream_subject(array $item): string
301 if ($item['title']) {
302 return mailstream_decode_subject($item['title'], $item['uri-id']);
304 $parent = $item['thr-parent'];
305 // Don't look more than 100 levels deep for a subject, in case of loops
306 for ($i = 0; ($i < 100) && $parent; $i++) {
307 $parent_item = Post::selectFirst(['thr-parent', 'title'], ['uri' => $parent]);
308 if (!DBA::isResult($parent_item)) {
311 if ($parent_item['thr-parent'] === $parent) {
314 if ($parent_item['title']) {
315 return DI::l10n()->t('Re:') . ' ' . mailstream_decode_subject($parent_item['title'], $item['uri-id']);
317 $parent = $parent_item['thr-parent'];
319 $contact = Contact::selectFirst([], ['id' => $item['contact-id'], 'uid' => $item['uid']]);
320 if (!DBA::isResult($contact)) {
322 'mailstream_subject no contact for item',
323 ['id' => $item['id'],
324 'plink' => $item['plink'],
325 'contact id' => $item['contact-id'],
326 'uid' => $item['uid']]
328 return DI::l10n()->t("Friendica post");
330 if ($contact['network'] === 'dfrn') {
331 return DI::l10n()->t("Friendica post");
333 if ($contact['network'] === 'dspr') {
334 return DI::l10n()->t("Diaspora post");
336 if ($contact['network'] === 'face') {
337 $text = mailstream_decode_subject($item['body'], $item['uri-id']);
338 // For some reason these do show up in Facebook
339 $text = preg_replace('/\xA0$/', '', $text);
340 $subject = (strlen($text) > 150) ? (substr($text, 0, 140) . '...') : $text;
341 return preg_replace('/\\s+/', ' ', $subject);
343 if ($contact['network'] === 'feed') {
344 return DI::l10n()->t("Feed item");
346 if ($contact['network'] === 'mail') {
347 return DI::l10n()->t("Email");
349 return DI::l10n()->t("Friendica Item");
353 * Sends a message using PHPMailer
355 * @param string $message_id ID of the message (RFC 1036)
356 * @param array $item content of the item
357 * @param array $user results from the user table
359 * @return bool True if this message has been completed. False if it should be retried.
361 function mailstream_send(string $message_id, array $item, array $user): bool
363 if (!is_array($item)) {
364 Logger::error('mailstream_send item is empty', ['message_id' => $message_id]);
368 if (!$item['visible']) {
369 Logger::debug('mailstream_send item not yet visible', ['item uri' => $item['uri']]);
373 Logger::error('mailstream_send no message ID supplied', ['item uri' => $item['uri'],
374 'user email' => $user['email']]);
378 require_once (dirname(__file__) . '/phpmailer/class.phpmailer.php');
380 $item['body'] = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
383 mailstream_do_images($item, $attachments);
384 $frommail = DI::config()->get('mailstream', 'frommail');
385 if ($frommail == '') {
386 $frommail = 'friendica@localhost.local';
388 $address = DI::pConfig()->get($item['uid'], 'mailstream', 'address');
390 $address = $user['email'];
392 $mail = new PHPmailer();
394 $mail->XMailer = 'Friendica Mailstream Addon';
395 $mail->SetFrom($frommail, mailstream_sender($item));
396 $mail->AddAddress($address, $user['username']);
397 $mail->MessageID = $message_id;
398 $mail->Subject = mailstream_subject($item);
399 if ($item['thr-parent'] != $item['uri']) {
400 $mail->addCustomHeader('In-Reply-To: ' . mailstream_generate_id($item['thr-parent']));
402 $mail->addCustomHeader('X-Friendica-Mailstream-URI: ' . $item['uri']);
403 if ($item['plink']) {
404 $mail->addCustomHeader('X-Friendica-Mailstream-Plink: ' . $item['plink']);
406 $encoding = 'base64';
407 foreach ($attachments as $url => $image) {
408 $mail->AddStringEmbeddedImage(
417 $mail->CharSet = 'utf-8';
418 $template = Renderer::getMarkupTemplate('mail.tpl', 'addon/mailstream/');
419 $mail->AltBody = BBCode::toPlaintext($item['body']);
420 $item['body'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::CONNECTORS);
421 $item['url'] = DI::baseUrl() . '/display/' . $item['guid'];
422 $mail->Body = Renderer::replaceMacros($template, [
423 '$upstream' => DI::l10n()->t('Upstream'),
424 '$uri' => DI::l10n()->t('URI'),
425 '$local' => DI::l10n()->t('Local'),
427 $mail->Body = mailstream_html_wrap($mail->Body);
428 if (!$mail->Send()) {
429 throw new Exception($mail->ErrorInfo);
431 Logger::debug('mailstream_send sent message', ['message ID' => $mail->MessageID,
432 'subject' => $mail->Subject,
433 'address' => $address]);
434 } catch (phpmailerException $e) {
435 Logger::debug('mailstream_send PHPMailer exception sending message ' . $message_id . ': ' . $e->errorMessage());
436 } catch (Exception $e) {
437 Logger::debug('mailstream_send exception sending message ' . $message_id . ': ' . $e->getMessage());
444 * Email tends to break if you send excessively long lines. To make
445 * bbcode's output suitable for transmission, we try to break things
446 * up so that lines are about 200 characters.
448 * @param string $text text to word wrap
449 * @return string wrapped text
451 function mailstream_html_wrap(string &$text)
453 $lines = str_split($text, 200);
454 for ($i = 0; $i < count($lines); $i++) {
455 $lines[$i] = preg_replace('/ /', "\n", $lines[$i], 1);
457 $text = implode($lines);
462 * Convert v1 mailstream table entries to v2 workerqueue items
464 function mailstream_convert_table_entries()
466 $ms_item_ids = DBA::selectToArray('mailstream_item', [], ['message-id', 'uri', 'uid', 'contact-id'], ["`mailstream_item`.`completed` IS NULL"]);
467 Logger::debug('mailstream_convert_table_entries processing ' . count($ms_item_ids) . ' items');
468 foreach ($ms_item_ids as $ms_item_id) {
469 $send_hook_data = array('uid' => $ms_item_id['uid'],
470 'contact-id' => $ms_item_id['contact-id'],
471 'uri' => $ms_item_id['uri'],
472 'message_id' => $ms_item_id['message-id'],
474 if (!$ms_item_id['message-id'] || !strlen($ms_item_id['message-id'])) {
475 Logger::info('mailstream_convert_table_entries: item has no message-id.', ['item' => $ms_item_id['id'], 'uri' => $ms_item_id['uri']]);
478 Logger::info('mailstream_convert_table_entries: convert item to workerqueue', $send_hook_data);
479 Hook::fork(Worker::PRIORITY_LOW, 'mailstream_send_hook', $send_hook_data);
481 DBA::e('DROP TABLE `mailstream_item`');
485 * Form for configuring mailstream features for a user
487 * @param array $data Hook data array
488 * @throws \Friendica\Network\HTTPException\ServiceUnavailableException
490 function mailstream_addon_settings(array &$data)
492 $enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'mailstream', 'enabled');
493 $address = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'mailstream', 'address');
494 $nolikes = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'mailstream', 'nolikes');
495 $attachimg = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'mailstream', 'attachimg');
497 $template = Renderer::getMarkupTemplate('settings.tpl', 'addon/mailstream/');
498 $html = Renderer::replaceMacros($template, [
500 'mailstream_enabled',
501 DI::l10n()->t('Enabled'),
505 'mailstream_address',
506 DI::l10n()->t('Email Address'),
508 DI::l10n()->t('Leave blank to use your account email address')
511 'mailstream_nolikes',
512 DI::l10n()->t('Exclude Likes'),
514 DI::l10n()->t('Check this to omit mailing "Like" notifications')
517 'mailstream_attachimg',
518 DI::l10n()->t('Attach Images'),
520 DI::l10n()->t('Download images in posts and attach them to the email. ' .
521 'Useful for reading email while offline.')
526 'addon' => 'mailstream',
527 'title' => DI::l10n()->t('Mail Stream Settings'),
533 * Process data submitted to user's mailstream features form
534 * @param array $post POST data
537 function mailstream_addon_settings_post(array $post)
539 if (!DI::userSession()->getLocalUserId() || empty($post['mailstream-submit'])) {
543 if ($post['mailstream_address'] != "") {
544 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'mailstream', 'address', $post['mailstream_address']);
546 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'mailstream', 'address');
548 if ($post['mailstream_nolikes']) {
549 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'mailstream', 'nolikes', $post['mailstream_enabled']);
551 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'mailstream', 'nolikes');
553 if ($post['mailstream_enabled']) {
554 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'mailstream', 'enabled', $post['mailstream_enabled']);
556 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'mailstream', 'enabled');
558 if ($post['mailstream_attachimg']) {
559 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'mailstream', 'attachimg', $post['mailstream_attachimg']);
561 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'mailstream', 'attachimg');