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('cron', 'addon/mailstream/mailstream.php', 'mailstream_cron');
36 Hook::register('mailstream_send_hook', 'addon/mailstream/mailstream.php', 'mailstream_send_hook');
38 Logger::info("mailstream: installed");
42 * Enforces that mailstream_install has set up the current version
44 function mailstream_check_version()
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");
52 'mailstream_convert_table_entries',
53 'addon/mailstream/mailstream.php',
54 'mailstream_convert_table_entries'
56 Hook::fork(Worker::PRIORITY_LOW, 'mailstream_convert_table_entries');
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
65 function mailstream_module() {}
68 * Adds an item in "addon features" in the admin menu of the site
70 * @param App $a App object (unused)
71 * @param string $o HTML form data
73 function mailstream_addon_admin(App $a, string &$o)
75 $frommail = DI::config()->get('mailstream', 'frommail');
76 $template = Renderer::getMarkupTemplate('admin.tpl', 'addon/mailstream/');
77 $config = ['frommail',
78 DI::l10n()->t('From Address'),
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')
88 * Process input from the "addon features" part of the admin menu
90 function mailstream_addon_admin_post()
92 if (!empty($_POST['frommail'])) {
93 DI::config()->set('mailstream', 'frommail', $_POST['frommail']);
98 * Creates a message ID for a post URI in accordance with RFC 1036
99 * See also http://www.jwz.org/doc/mid.html
101 * @param string $uri the URI to be converted to a message ID
103 * @return string the created message ID
105 function mailstream_generate_id(string $uri): string
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);
114 function mailstream_send_hook(App $a, array $data)
116 $criteria = array('uid' => $data['uid'], 'contact-id' => $data['contact-id'], 'uri' => $data['uri']);
117 $item = Post::selectFirst([], $criteria);
119 Logger::error('mailstream_send_hook could not find item');
123 $user = User::getById($item['uid']);
125 Logger::error('mailstream_send_hook could not fund user', ['uid' => $item['uid']]);
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);
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.
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)
146 function mailstream_post_hook(App $a, array &$item)
148 mailstream_check_version();
150 if (!DI::pConfig()->get($item['uid'], 'mailstream', 'enabled')) {
151 Logger::debug('mailstream: not enabled for item ' . $item['id']);
155 Logger::debug('mailstream: no uid for item ' . $item['id']);
158 if (!$item['contact-id']) {
159 Logger::debug('mailstream: no contact-id for item ' . $item['id']);
163 Logger::debug('mailstream: no uri for item ' . $item['id']);
166 if (!$item['plink']) {
167 Logger::debug('mailstream: no plink for item ' . $item['id']);
170 if (DI::pConfig()->get($item['uid'], 'mailstream', 'nolikes')) {
171 if ($item['verb'] == Activity::LIKE) {
172 Logger::debug('mailstream: like item ' . $item['id']);
177 $message_id = mailstream_generate_id($item['uri']);
180 'uid' => $item['uid'],
181 'contact-id' => $item['contact-id'],
182 'uri' => $item['uri'],
183 'message_id' => $message_id,
186 Hook::fork(Worker::PRIORITY_LOW, 'mailstream_send_hook', $send_hook_data);
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
195 * @param array $item content of the item
196 * @param array $attachments contains an array element for each attachment to add to the email
198 * @return array new value of the attachments table (results are also stored in the reference parameter)
200 function mailstream_do_images(array &$item, array &$attachments)
202 if (!DI::pConfig()->get($item['uid'], 'mailstream', 'attachimg')) {
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);
212 foreach (array_merge($matches1[3], $matches2[1], $matches3[1]) as $url) {
213 $components = parse_url($url);
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()
228 if (strlen($attachments[$url]['data'])) {
229 $item['body'] = str_replace($url, 'cid:' . $attachments[$url]['guid'], $item['body']);
238 * Creates a sender to use in the email, either from the contact or the author of the item, or both
240 * @param array $item content of the item
242 * @return string sender suitable for use in the email
244 function mailstream_sender(array $item): string
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'];
252 return $item['author-name'];
256 * Converts a bbcode-encoded subject line into a plaintext version suitable for the subject line of an email
258 * @param string $subject bbcode-encoded subject line
260 * @return string plaintext subject line
262 function mailstream_decode_subject(string $subject): string
264 $html = BBCode::convert($subject);
268 $notags = strip_tags($html);
272 $noentity = html_entity_decode($notags);
276 $nocodes = preg_replace_callback("/(&#[0-9]+;)/", function ($m) {
277 return mb_convert_encoding($m[1], 'UTF-8', 'HTML-ENTITIES');
282 $trimmed = trim($nocodes);
290 * Creates a subject line to use in the email
292 * @param array $item content of the item
294 * @return string subject line suitable for use in the email
296 function mailstream_subject(array $item): string
298 if ($item['title']) {
299 return mailstream_decode_subject($item['title']);
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)) {
308 if ($parent_item['thr-parent'] === $parent) {
311 if ($parent_item['title']) {
312 return DI::l10n()->t('Re:') . ' ' . mailstream_decode_subject($parent_item['title']);
314 $parent = $parent_item['thr-parent'];
316 $contact = Contact::selectFirst([], ['id' => $item['contact-id'], 'uid' => $item['uid']]);
317 if (!DBA::isResult($contact)) {
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']]
325 return DI::l10n()->t("Friendica post");
327 if ($contact['network'] === 'dfrn') {
328 return DI::l10n()->t("Friendica post");
330 if ($contact['network'] === 'dspr') {
331 return DI::l10n()->t("Diaspora post");
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);
340 if ($contact['network'] === 'feed') {
341 return DI::l10n()->t("Feed item");
343 if ($contact['network'] === 'mail') {
344 return DI::l10n()->t("Email");
346 return DI::l10n()->t("Friendica Item");
350 * Sends a message using PHPMailer
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
356 * @return bool True if this message has been completed. False if it should be retried.
358 function mailstream_send(string $message_id, array $item, array $user): bool
360 if (!is_array($item)) {
361 Logger::error('mailstream_send item is empty', ['message_id' => $message_id]);
365 if (!$item['visible']) {
366 Logger::debug('mailstream_send item not yet visible', ['item uri' => $item['uri']]);
370 Logger::error('mailstream_send no message ID supplied', ['item uri' => $item['uri'],
371 'user email' => $user['email']]);
375 require_once (dirname(__file__) . '/phpmailer/class.phpmailer.php');
378 mailstream_do_images($item, $attachments);
379 $frommail = DI::config()->get('mailstream', 'frommail');
380 if ($frommail == '') {
381 $frommail = 'friendica@localhost.local';
383 $address = DI::pConfig()->get($item['uid'], 'mailstream', 'address');
385 $address = $user['email'];
387 $mail = new PHPmailer();
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']));
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(
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'),
419 mailstream_html_wrap($mail->Body);
420 if (!$mail->Send()) {
421 throw new Exception($mail->ErrorInfo);
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());
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.
440 * @param string $text text to word wrap - modified in-place
442 function mailstream_html_wrap(string &$text)
444 $lines = str_split($text, 200);
445 for ($i = 0; $i < count($lines); $i++) {
446 $lines[$i] = preg_replace('/ /', "\n", $lines[$i], 1);
448 $text = implode($lines);
452 * Convert v1 mailstream table entries to v2 workerqueue items
454 function mailstream_convert_table_entries()
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'],
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');
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);
472 DBA::e('DROP TABLE `mailstream_item`');
476 * Form for configuring mailstream features for a user
478 * @param App $a App object
479 * @param array $data Hook data array
480 * @throws \Friendica\Network\HTTPException\ServiceUnavailableException
482 function mailstream_addon_settings(App &$a, array &$data)
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');
489 $template = Renderer::getMarkupTemplate('settings.tpl', 'addon/mailstream/');
490 $html = Renderer::replaceMacros($template, [
492 'mailstream_enabled',
493 DI::l10n()->t('Enabled'),
497 'mailstream_address',
498 DI::l10n()->t('Email Address'),
500 DI::l10n()->t('Leave blank to use your account email address')
503 'mailstream_nolikes',
504 DI::l10n()->t('Exclude Likes'),
506 DI::l10n()->t('Check this to omit mailing "Like" notifications')
509 'mailstream_attachimg',
510 DI::l10n()->t('Attach Images'),
512 DI::l10n()->t('Download images in posts and attach them to the email. ' .
513 'Useful for reading email while offline.')
518 'addon' => 'mailstream',
519 'title' => DI::l10n()->t('Mail Stream Settings'),
525 * Process data submitted to user's mailstream features form
527 * @param array $post POST data
530 function mailstream_addon_settings_post(App $a, array $post)
532 if (!DI::userSession()->getLocalUserId() || empty($post['mailstream-submit'])) {
536 if ($post['mailstream_address'] != "") {
537 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'mailstream', 'address', $post['mailstream_address']);
539 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'mailstream', 'address');
541 if ($post['mailstream_nolikes']) {
542 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'mailstream', 'nolikes', $post['mailstream_enabled']);
544 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'mailstream', 'nolikes');
546 if ($post['mailstream_enabled']) {
547 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'mailstream', 'enabled', $post['mailstream_enabled']);
549 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'mailstream', 'enabled');
551 if ($post['mailstream_attachimg']) {
552 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'mailstream', 'attachimg', $post['mailstream_attachimg']);
554 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'mailstream', 'attachimg');