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(PRIORITY_LOW, 'mailstream_convert_table_entries');
61 * This function indicates a module that can be wrapped in the LegacyModule class
63 function mailstream_module()
68 * Adds an item in "addon features" in the admin menu of the site
70 * @param Friendica\App $a App object (unused)
71 * @param string $o HTML form data
73 function mailstream_addon_admin(&$a, &$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')]);
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($uri)
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(&$a, $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 Friendica\App $a App object (unused)
142 * @param array $item content of the item (may or may not already be stored in the item table)
144 function mailstream_post_hook(&$a, &$item)
146 mailstream_check_version();
148 if (!DI::pConfig()->get($item['uid'], 'mailstream', 'enabled')) {
149 Logger::debug('mailstream: not enabled for item ' . $item['id']);
153 Logger::debug('mailstream: no uid for item ' . $item['id']);
156 if (!$item['contact-id']) {
157 Logger::debug('mailstream: no contact-id for item ' . $item['id']);
161 Logger::debug('mailstream: no uri for item ' . $item['id']);
164 if (!$item['plink']) {
165 Logger::debug('mailstream: no plink for item ' . $item['id']);
168 if (DI::pConfig()->get($item['uid'], 'mailstream', 'nolikes')) {
169 if ($item['verb'] == Activity::LIKE) {
170 Logger::debug('mailstream: like item ' . $item['id']);
175 $message_id = mailstream_generate_id($item['uri']);
177 $send_hook_data = array('uid' => $item['uid'],
178 'contact-id' => $item['contact-id'],
179 'uri' => $item['uri'],
180 'message_id' => $message_id,
182 Hook::fork(PRIORITY_LOW, 'mailstream_send_hook', $send_hook_data);
186 * If the user has configured attaching images to emails as
187 * attachments, this function searches the post for such images,
188 * retrieves the image, and inserts the data and metadata into the
191 * @param array $item content of the item
192 * @param array $attachments contains an array element for each attachment to add to the email
194 * @return array new value of the attachments table (results are also stored in the reference parameter)
196 function mailstream_do_images(&$item, &$attachments)
198 if (!DI::pConfig()->get($item['uid'], 'mailstream', 'attachimg')) {
202 preg_match_all("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", $item["body"], $matches1);
203 preg_match_all("/\[img\](.*?)\[\/img\]/ism", $item["body"], $matches2);
204 preg_match_all("/\[img\=([^\]]*)\]([^[]*)\[\/img\]/ism", $item["body"], $matches3);
205 foreach (array_merge($matches1[3], $matches2[1], $matches3[1]) as $url) {
206 $components = parse_url($url);
210 $cookiejar = tempnam(System::getTempPath(), 'cookiejar-mailstream-');
211 $curlResult = DI::httpClient()->fetchFull($url, HttpClientAccept::DEFAULT, 0, $cookiejar);
212 $attachments[$url] = [
213 'data' => $curlResult->getBody(),
214 'guid' => hash("crc32", $url),
215 'filename' => basename($components['path']),
216 'type' => $curlResult->getContentType()
219 if (strlen($attachments[$url]['data'])) {
220 $item['body'] = str_replace($url, 'cid:' . $attachments[$url]['guid'], $item['body']);
228 * Creates a sender to use in the email, either from the contact or the author of the item, or both
230 * @param array $item content of the item
232 * @return string sender suitable for use in the email
234 function mailstream_sender($item)
236 $contact = Contact::getById($item['contact-id']);
237 if (DBA::isResult($contact)) {
238 if ($contact['name'] != $item['author-name']) {
239 return $contact['name'] . ' - ' . $item['author-name'];
242 return $item['author-name'];
246 * Converts a bbcode-encoded subject line into a plaintext version suitable for the subject line of an email
248 * @param string $subject bbcode-encoded subject line
250 * @return string plaintext subject line
252 function mailstream_decode_subject($subject)
254 $html = BBCode::convert($subject);
258 $notags = strip_tags($html);
262 $noentity = html_entity_decode($notags);
266 $nocodes = preg_replace_callback("/(&#[0-9]+;)/", function ($m) {
267 return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES");
272 $trimmed = trim($nocodes);
280 * Creates a subject line to use in the email
282 * @param array $item content of the item
284 * @return string subject line suitable for use in the email
286 function mailstream_subject($item)
288 if ($item['title']) {
289 return mailstream_decode_subject($item['title']);
291 $parent = $item['thr-parent'];
292 // Don't look more than 100 levels deep for a subject, in case of loops
293 for ($i = 0; ($i < 100) && $parent; $i++) {
294 $parent_item = Post::selectFirst(['thr-parent', 'title'], ['uri' => $parent]);
295 if (!DBA::isResult($parent_item)) {
298 if ($parent_item['thr-parent'] === $parent) {
301 if ($parent_item['title']) {
302 return DI::l10n()->t('Re:') . ' ' . mailstream_decode_subject($parent_item['title']);
304 $parent = $parent_item['thr-parent'];
306 $contact = Contact::selectFirst([], ['id' => $item['contact-id'], 'uid' => $item['uid']]);
307 if (!DBA::isResult($contact)) {
309 'mailstream_subject no contact for item',
310 ['id' => $item['id'],
311 'plink' => $item['plink'],
312 'contact id' => $item['contact-id'],
313 'uid' => $item['uid']]
315 return DI::l10n()->t("Friendica post");
317 if ($contact['network'] === 'dfrn') {
318 return DI::l10n()->t("Friendica post");
320 if ($contact['network'] === 'dspr') {
321 return DI::l10n()->t("Diaspora post");
323 if ($contact['network'] === 'face') {
324 $text = mailstream_decode_subject($item['body']);
325 // For some reason these do show up in Facebook
326 $text = preg_replace('/\xA0$/', '', $text);
327 $subject = (strlen($text) > 150) ? (substr($text, 0, 140) . '...') : $text;
328 return preg_replace('/\\s+/', ' ', $subject);
330 if ($contact['network'] === 'feed') {
331 return DI::l10n()->t("Feed item");
333 if ($contact['network'] === 'mail') {
334 return DI::l10n()->t("Email");
336 return DI::l10n()->t("Friendica Item");
340 * Sends a message using PHPMailer
342 * @param string $message_id ID of the message (RFC 1036)
343 * @param array $item content of the item
344 * @param array $user results from the user table
346 * @return bool True if this message has been completed. False if it should be retried.
348 function mailstream_send($message_id, $item, $user)
350 if (!is_array($item)) {
351 Logger::error('mailstream_send item is empty', ['message_id' => $message_id]);
355 if (!$item['visible']) {
356 Logger::debug('mailstream_send item not yet visible', ['item uri' => $item['uri']]);
360 Logger::error('mailstream_send no message ID supplied', ['item uri' => $item['uri'],
361 'user email' => $user['email']]);
364 require_once(dirname(__file__).'/phpmailer/class.phpmailer.php');
367 mailstream_do_images($item, $attachments);
368 $frommail = DI::config()->get('mailstream', 'frommail');
369 if ($frommail == "") {
370 $frommail = 'friendica@localhost.local';
372 $address = DI::pConfig()->get($item['uid'], 'mailstream', 'address');
374 $address = $user['email'];
376 $mail = new PHPmailer;
378 $mail->XMailer = 'Friendica Mailstream Addon';
379 $mail->SetFrom($frommail, mailstream_sender($item));
380 $mail->AddAddress($address, $user['username']);
381 $mail->MessageID = $message_id;
382 $mail->Subject = mailstream_subject($item);
383 if ($item['thr-parent'] != $item['uri']) {
384 $mail->addCustomHeader('In-Reply-To: ' . mailstream_generate_id($item['thr-parent']));
386 $mail->addCustomHeader('X-Friendica-Mailstream-URI: ' . $item['uri']);
387 $mail->addCustomHeader('X-Friendica-Mailstream-Plink: ' . $item['plink']);
388 $encoding = 'base64';
389 foreach ($attachments as $url => $image) {
390 $mail->AddStringEmbeddedImage(
399 $mail->CharSet = 'utf-8';
400 $template = Renderer::getMarkupTemplate('mail.tpl', 'addon/mailstream/');
401 $mail->AltBody = BBCode::toPlaintext($item['body']);
402 $item['body'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::CONNECTORS);
403 $item['url'] = DI::baseUrl()->get() . '/display/' . $item['guid'];
404 $mail->Body = Renderer::replaceMacros($template, [
405 '$upstream' => DI::l10n()->t('Upstream'),
406 '$local' => DI::l10n()->t('Local'),
408 mailstream_html_wrap($mail->Body);
409 if (!$mail->Send()) {
410 throw new Exception($mail->ErrorInfo);
412 Logger::debug('mailstream_send sent message', ['message ID' => $mail->MessageID,
413 'subject' => $mail->Subject,
414 'address' => $address]);
415 } catch (phpmailerException $e) {
416 Logger::debug('mailstream_send PHPMailer exception sending message ' . $message_id . ': ' . $e->errorMessage());
417 } catch (Exception $e) {
418 Logger::debug('mailstream_send exception sending message ' . $message_id . ': ' . $e->getMessage());
425 * Email tends to break if you send excessively long lines. To make
426 * bbcode's output suitable for transmission, we try to break things
427 * up so that lines are about 200 characters.
429 * @param string $text text to word wrap - modified in-place
431 function mailstream_html_wrap(&$text)
433 $lines = str_split($text, 200);
434 for ($i = 0; $i < count($lines); $i++) {
435 $lines[$i] = preg_replace('/ /', "\n", $lines[$i], 1);
437 $text = implode($lines);
441 * Convert v1 mailstream table entries to v2 workerqueue items
443 function mailstream_convert_table_entries()
445 $ms_item_ids = DBA::selectToArray('mailstream_item', [], ['message-id', 'uri', 'uid', 'contact-id'], ["`mailstream_item`.`completed` IS NULL"]);
446 Logger::debug('mailstream_convert_table_entries processing ' . count($ms_item_ids) . ' items');
447 foreach ($ms_item_ids as $ms_item_id) {
448 $send_hook_data = array('uid' => $ms_item_id['uid'],
449 'contact-id' => $ms_item_id['contact-id'],
450 'uri' => $ms_item_id['uri'],
451 'message_id' => $ms_item_id['message-id'],
453 if (!$ms_item_id['message-id'] || !strlen($ms_item_id['message-id'])) {
454 Logger::info('mailstream_cron: Item ' .
455 $ms_item_id['id'] . ' URI ' . $ms_item_id['uri'] . ' has no message-id');
458 Logger::info('mailstream_convert_table_entries: convert item to workerqueue', $send_hook_data);
459 Hook::fork(PRIORITY_LOW, 'mailstream_send_hook', $send_hook_data);
461 DBA::e('DROP TABLE `mailstream_item`');
465 * Form for configuring mailstream features for a user
467 * @param App $a App object
468 * @param array $data Hook data array
469 * @throws \Friendica\Network\HTTPException\ServiceUnavailableException
471 function mailstream_addon_settings(App &$a, array &$data)
473 $enabled = DI::pConfig()->get(local_user(), 'mailstream', 'enabled');
474 $address = DI::pConfig()->get(local_user(), 'mailstream', 'address');
475 $nolikes = DI::pConfig()->get(local_user(), 'mailstream', 'nolikes');
476 $attachimg = DI::pConfig()->get(local_user(), 'mailstream', 'attachimg');
478 $template = Renderer::getMarkupTemplate('settings.tpl', 'addon/mailstream/');
479 $html = Renderer::replaceMacros($template, [
481 'mailstream_enabled',
482 DI::l10n()->t('Enabled'),
486 'mailstream_address',
487 DI::l10n()->t('Email Address'),
489 DI::l10n()->t('Leave blank to use your account email address')
492 'mailstream_nolikes',
493 DI::l10n()->t('Exclude Likes'),
495 DI::l10n()->t('Check this to omit mailing "Like" notifications')
498 'mailstream_attachimg',
499 DI::l10n()->t('Attach Images'),
501 DI::l10n()->t('Download images in posts and attach them to the email. ' .
502 'Useful for reading email while offline.')
507 'addon' => 'mailstream',
508 'title' => DI::l10n()->t('Mail Stream Settings'),
514 * Process data submitted to user's mailstream features form
516 * @param array $post POST data
518 function mailstream_addon_settings_post(App $a, array $post)
520 if (!local_user() || empty($post['mailstream-submit'])) {
524 if ($post['mailstream_address'] != "") {
525 DI::pConfig()->set(local_user(), 'mailstream', 'address', $post['mailstream_address']);
527 DI::pConfig()->delete(local_user(), 'mailstream', 'address');
529 if ($post['mailstream_nolikes']) {
530 DI::pConfig()->set(local_user(), 'mailstream', 'nolikes', $post['mailstream_enabled']);
532 DI::pConfig()->delete(local_user(), 'mailstream', 'nolikes');
534 if ($post['mailstream_enabled']) {
535 DI::pConfig()->set(local_user(), 'mailstream', 'enabled', $post['mailstream_enabled']);
537 DI::pConfig()->delete(local_user(), 'mailstream', 'enabled');
539 if ($post['mailstream_attachimg']) {
540 DI::pConfig()->set(local_user(), 'mailstream', 'attachimg', $post['mailstream_attachimg']);
542 DI::pConfig()->delete(local_user(), 'mailstream', 'attachimg');