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()->getHostname();
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-');
217 $curlResult = DI::httpClient()->fetchFull($url, HttpClientAccept::DEFAULT, 0, $cookiejar);
218 $attachments[$url] = [
219 'data' => $curlResult->getBody(),
220 'guid' => hash('crc32', $url),
221 'filename' => basename($components['path']),
222 'type' => $curlResult->getContentType()
225 if (strlen($attachments[$url]['data'])) {
226 $item['body'] = str_replace($url, 'cid:' . $attachments[$url]['guid'], $item['body']);
235 * Creates a sender to use in the email, either from the contact or the author of the item, or both
237 * @param array $item content of the item
239 * @return string sender suitable for use in the email
241 function mailstream_sender(array $item): string
243 $contact = Contact::getById($item['contact-id']);
244 if (DBA::isResult($contact)) {
245 if ($contact['name'] != $item['author-name']) {
246 return $contact['name'] . ' - ' . $item['author-name'];
249 return $item['author-name'];
253 * Converts a bbcode-encoded subject line into a plaintext version suitable for the subject line of an email
255 * @param string $subject bbcode-encoded subject line
257 * @return string plaintext subject line
259 function mailstream_decode_subject(string $subject): string
261 $html = BBCode::convert($subject);
265 $notags = strip_tags($html);
269 $noentity = html_entity_decode($notags);
273 $nocodes = preg_replace_callback("/(&#[0-9]+;)/", function ($m) {
274 return mb_convert_encoding($m[1], 'UTF-8', 'HTML-ENTITIES');
279 $trimmed = trim($nocodes);
287 * Creates a subject line to use in the email
289 * @param array $item content of the item
291 * @return string subject line suitable for use in the email
293 function mailstream_subject(array $item): string
295 if ($item['title']) {
296 return mailstream_decode_subject($item['title']);
298 $parent = $item['thr-parent'];
299 // Don't look more than 100 levels deep for a subject, in case of loops
300 for ($i = 0; ($i < 100) && $parent; $i++) {
301 $parent_item = Post::selectFirst(['thr-parent', 'title'], ['uri' => $parent]);
302 if (!DBA::isResult($parent_item)) {
305 if ($parent_item['thr-parent'] === $parent) {
308 if ($parent_item['title']) {
309 return DI::l10n()->t('Re:') . ' ' . mailstream_decode_subject($parent_item['title']);
311 $parent = $parent_item['thr-parent'];
313 $contact = Contact::selectFirst([], ['id' => $item['contact-id'], 'uid' => $item['uid']]);
314 if (!DBA::isResult($contact)) {
316 'mailstream_subject no contact for item',
317 ['id' => $item['id'],
318 'plink' => $item['plink'],
319 'contact id' => $item['contact-id'],
320 'uid' => $item['uid']]
322 return DI::l10n()->t("Friendica post");
324 if ($contact['network'] === 'dfrn') {
325 return DI::l10n()->t("Friendica post");
327 if ($contact['network'] === 'dspr') {
328 return DI::l10n()->t("Diaspora post");
330 if ($contact['network'] === 'face') {
331 $text = mailstream_decode_subject($item['body']);
332 // For some reason these do show up in Facebook
333 $text = preg_replace('/\xA0$/', '', $text);
334 $subject = (strlen($text) > 150) ? (substr($text, 0, 140) . '...') : $text;
335 return preg_replace('/\\s+/', ' ', $subject);
337 if ($contact['network'] === 'feed') {
338 return DI::l10n()->t("Feed item");
340 if ($contact['network'] === 'mail') {
341 return DI::l10n()->t("Email");
343 return DI::l10n()->t("Friendica Item");
347 * Sends a message using PHPMailer
349 * @param string $message_id ID of the message (RFC 1036)
350 * @param array $item content of the item
351 * @param array $user results from the user table
353 * @return bool True if this message has been completed. False if it should be retried.
355 function mailstream_send(string $message_id, array $item, array $user): bool
357 if (!is_array($item)) {
358 Logger::error('mailstream_send item is empty', ['message_id' => $message_id]);
362 if (!$item['visible']) {
363 Logger::debug('mailstream_send item not yet visible', ['item uri' => $item['uri']]);
367 Logger::error('mailstream_send no message ID supplied', ['item uri' => $item['uri'],
368 'user email' => $user['email']]);
372 require_once (dirname(__file__) . '/phpmailer/class.phpmailer.php');
374 $item['body'] = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
377 mailstream_do_images($item, $attachments);
378 $frommail = DI::config()->get('mailstream', 'frommail');
379 if ($frommail == '') {
380 $frommail = 'friendica@localhost.local';
382 $address = DI::pConfig()->get($item['uid'], 'mailstream', 'address');
384 $address = $user['email'];
386 $mail = new PHPmailer();
388 $mail->XMailer = 'Friendica Mailstream Addon';
389 $mail->SetFrom($frommail, mailstream_sender($item));
390 $mail->AddAddress($address, $user['username']);
391 $mail->MessageID = $message_id;
392 $mail->Subject = mailstream_subject($item);
393 if ($item['thr-parent'] != $item['uri']) {
394 $mail->addCustomHeader('In-Reply-To: ' . mailstream_generate_id($item['thr-parent']));
396 $mail->addCustomHeader('X-Friendica-Mailstream-URI: ' . $item['uri']);
397 if ($item['plink']) {
398 $mail->addCustomHeader('X-Friendica-Mailstream-Plink: ' . $item['plink']);
400 $encoding = 'base64';
401 foreach ($attachments as $url => $image) {
402 $mail->AddStringEmbeddedImage(
411 $mail->CharSet = 'utf-8';
412 $template = Renderer::getMarkupTemplate('mail.tpl', 'addon/mailstream/');
413 $mail->AltBody = BBCode::toPlaintext($item['body']);
414 $item['body'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::CONNECTORS);
415 $item['url'] = DI::baseUrl()->get() . '/display/' . $item['guid'];
416 $mail->Body = Renderer::replaceMacros($template, [
417 '$upstream' => DI::l10n()->t('Upstream'),
418 '$uri' => DI::l10n()->t('URI'),
419 '$local' => DI::l10n()->t('Local'),
421 $mail->Body = mailstream_html_wrap($mail->Body);
422 if (!$mail->Send()) {
423 throw new Exception($mail->ErrorInfo);
425 Logger::debug('mailstream_send sent message', ['message ID' => $mail->MessageID,
426 'subject' => $mail->Subject,
427 'address' => $address]);
428 } catch (phpmailerException $e) {
429 Logger::debug('mailstream_send PHPMailer exception sending message ' . $message_id . ': ' . $e->errorMessage());
430 } catch (Exception $e) {
431 Logger::debug('mailstream_send exception sending message ' . $message_id . ': ' . $e->getMessage());
438 * Email tends to break if you send excessively long lines. To make
439 * bbcode's output suitable for transmission, we try to break things
440 * up so that lines are about 200 characters.
442 * @param string $text text to word wrap
443 * @return string wrapped text
445 function mailstream_html_wrap(string &$text)
447 $lines = str_split($text, 200);
448 for ($i = 0; $i < count($lines); $i++) {
449 $lines[$i] = preg_replace('/ /', "\n", $lines[$i], 1);
451 $text = implode($lines);
456 * Convert v1 mailstream table entries to v2 workerqueue items
458 function mailstream_convert_table_entries()
460 $ms_item_ids = DBA::selectToArray('mailstream_item', [], ['message-id', 'uri', 'uid', 'contact-id'], ["`mailstream_item`.`completed` IS NULL"]);
461 Logger::debug('mailstream_convert_table_entries processing ' . count($ms_item_ids) . ' items');
462 foreach ($ms_item_ids as $ms_item_id) {
463 $send_hook_data = array('uid' => $ms_item_id['uid'],
464 'contact-id' => $ms_item_id['contact-id'],
465 'uri' => $ms_item_id['uri'],
466 'message_id' => $ms_item_id['message-id'],
468 if (!$ms_item_id['message-id'] || !strlen($ms_item_id['message-id'])) {
469 Logger::info('mailstream_convert_table_entries: item has no message-id.', ['item' => $ms_item_id['id'], 'uri' => $ms_item_id['uri']]);
472 Logger::info('mailstream_convert_table_entries: convert item to workerqueue', $send_hook_data);
473 Hook::fork(Worker::PRIORITY_LOW, 'mailstream_send_hook', $send_hook_data);
475 DBA::e('DROP TABLE `mailstream_item`');
479 * Form for configuring mailstream features for a user
481 * @param array $data Hook data array
482 * @throws \Friendica\Network\HTTPException\ServiceUnavailableException
484 function mailstream_addon_settings(array &$data)
486 $enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'mailstream', 'enabled');
487 $address = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'mailstream', 'address');
488 $nolikes = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'mailstream', 'nolikes');
489 $attachimg = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'mailstream', 'attachimg');
491 $template = Renderer::getMarkupTemplate('settings.tpl', 'addon/mailstream/');
492 $html = Renderer::replaceMacros($template, [
494 'mailstream_enabled',
495 DI::l10n()->t('Enabled'),
499 'mailstream_address',
500 DI::l10n()->t('Email Address'),
502 DI::l10n()->t('Leave blank to use your account email address')
505 'mailstream_nolikes',
506 DI::l10n()->t('Exclude Likes'),
508 DI::l10n()->t('Check this to omit mailing "Like" notifications')
511 'mailstream_attachimg',
512 DI::l10n()->t('Attach Images'),
514 DI::l10n()->t('Download images in posts and attach them to the email. ' .
515 'Useful for reading email while offline.')
520 'addon' => 'mailstream',
521 'title' => DI::l10n()->t('Mail Stream Settings'),
527 * Process data submitted to user's mailstream features form
528 * @param array $post POST data
531 function mailstream_addon_settings_post(array $post)
533 if (!DI::userSession()->getLocalUserId() || empty($post['mailstream-submit'])) {
537 if ($post['mailstream_address'] != "") {
538 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'mailstream', 'address', $post['mailstream_address']);
540 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'mailstream', 'address');
542 if ($post['mailstream_nolikes']) {
543 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'mailstream', 'nolikes', $post['mailstream_enabled']);
545 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'mailstream', 'nolikes');
547 if ($post['mailstream_enabled']) {
548 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'mailstream', 'enabled', $post['mailstream_enabled']);
550 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'mailstream', 'enabled');
552 if ($post['mailstream_attachimg']) {
553 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'mailstream', 'attachimg', $post['mailstream_attachimg']);
555 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'mailstream', 'attachimg');