4 * Description: Mail all items coming into your network feed to an email address
6 * Author: Matthew Exon <http://mat.exon.name>
9 use Friendica\Content\Text\BBCode;
10 use Friendica\Core\Hook;
11 use Friendica\Core\Logger;
12 use Friendica\Core\Renderer;
13 use Friendica\Core\Worker;
14 use Friendica\Database\DBA;
16 use Friendica\Model\Contact;
17 use Friendica\Model\Item;
18 use Friendica\Model\Post;
19 use Friendica\Model\User;
20 use Friendica\Protocol\Activity;
21 use Friendica\Util\DateTimeFormat;
24 * Sets up the addon hooks and the database table
26 function mailstream_install()
28 Hook::register('addon_settings', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings');
29 Hook::register('addon_settings_post', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings_post');
30 Hook::register('post_local_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
31 Hook::register('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
32 Hook::register('cron', 'addon/mailstream/mailstream.php', 'mailstream_cron');
33 Hook::register('mailstream_send_hook', 'addon/mailstream/mailstream.php', 'mailstream_send_hook');
35 Logger::info("mailstream: installed");
39 * Enforces that mailstream_install has set up the current version
41 function mailstream_check_version()
43 if (!is_null(DI::config()->get('mailstream', 'dbversion'))) {
44 DI::config()->delete('mailstream', 'dbversion');
45 Logger::info("mailstream_check_version: old version detected, reinstalling");
49 'mailstream_convert_table_entries',
50 'addon/mailstream/mailstream.php',
51 'mailstream_convert_table_entries'
53 Hook::fork(PRIORITY_LOW, 'mailstream_convert_table_entries');
58 * This function indicates a module that can be wrapped in the LegacyModule class
60 function mailstream_module()
65 * Adds an item in "addon features" in the admin menu of the site
67 * @param Friendica\App $a App object (unused)
68 * @param string $o HTML form data
70 function mailstream_addon_admin(&$a, &$o)
72 $frommail = DI::config()->get('mailstream', 'frommail');
73 $template = Renderer::getMarkupTemplate('admin.tpl', 'addon/mailstream/');
74 $config = ['frommail',
75 DI::l10n()->t('From Address'),
77 DI::l10n()->t('Email address that stream items will appear to be from.')];
78 $o .= Renderer::replaceMacros($template, [
79 '$frommail' => $config,
80 '$submit' => DI::l10n()->t('Save Settings')]);
84 * Process input from the "addon features" part of the admin menu
86 function mailstream_addon_admin_post()
88 if (!empty($_POST['frommail'])) {
89 DI::config()->set('mailstream', 'frommail', $_POST['frommail']);
94 * Creates a message ID for a post URI in accordance with RFC 1036
95 * See also http://www.jwz.org/doc/mid.html
97 * @param string $uri the URI to be converted to a message ID
99 * @return string the created message ID
101 function mailstream_generate_id($uri)
103 $host = DI::baseUrl()->getHostname();
104 $resource = hash('md5', $uri);
105 $message_id = "<" . $resource . "@" . $host . ">";
106 Logger::debug('mailstream: Generated message ID ' . $message_id . ' for URI ' . $uri);
110 function mailstream_send_hook(&$a, $data)
112 $criteria = array('uid' => $data['uid'], 'contact-id' => $data['contact-id'], 'uri' => $data['uri']);
113 $item = Post::selectFirst([], $criteria);
115 Logger::error('mailstream_send_hook could not find item');
119 $user = User::getById($item['uid']);
121 Logger::error('mailstream_send_hook could not fund user', ['uid' => $item['uid']]);
125 if (!mailstream_send($data['message_id'], $item, $user)) {
126 Logger::debug('mailstream_send_hook send failed, will retry', $data);
127 if (!Worker::defer()) {
128 Logger::error('mailstream_send_hook failed and could not defer', $data);
134 * Called when either a local or remote post is created. If
135 * mailstream is enabled and the necessary data is available, forks a
136 * workerqueue item to send the email.
138 * @param Friendica\App $a App object (unused)
139 * @param array $item content of the item (may or may not already be stored in the item table)
141 function mailstream_post_hook(&$a, &$item)
143 mailstream_check_version();
145 if (!DI::pConfig()->get($item['uid'], 'mailstream', 'enabled')) {
146 Logger::debug('mailstream: not enabled for item ' . $item['id']);
150 Logger::debug('mailstream: no uid for item ' . $item['id']);
153 if (!$item['contact-id']) {
154 Logger::debug('mailstream: no contact-id for item ' . $item['id']);
158 Logger::debug('mailstream: no uri for item ' . $item['id']);
161 if (!$item['plink']) {
162 Logger::debug('mailstream: no plink for item ' . $item['id']);
165 if (DI::pConfig()->get($item['uid'], 'mailstream', 'nolikes')) {
166 if ($item['verb'] == Activity::LIKE) {
167 Logger::debug('mailstream: like item ' . $item['id']);
172 $message_id = mailstream_generate_id($item['uri']);
174 $send_hook_data = array('uid' => $item['uid'],
175 'contact-id' => $item['contact-id'],
176 'uri' => $item['uri'],
177 'message_id' => $message_id,
179 Hook::fork(PRIORITY_LOW, 'mailstream_send_hook', $send_hook_data);
183 * If the user has configured attaching images to emails as
184 * attachments, this function searches the post for such images,
185 * retrieves the image, and inserts the data and metadata into the
188 * @param array $item content of the item
189 * @param array $attachments contains an array element for each attachment to add to the email
191 * @return array new value of the attachments table (results are also stored in the reference parameter)
193 function mailstream_do_images(&$item, &$attachments)
195 if (!DI::pConfig()->get($item['uid'], 'mailstream', 'attachimg')) {
199 preg_match_all("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", $item["body"], $matches1);
200 preg_match_all("/\[img\](.*?)\[\/img\]/ism", $item["body"], $matches2);
201 preg_match_all("/\[img\=([^\]]*)\]([^[]*)\[\/img\]/ism", $item["body"], $matches3);
202 foreach (array_merge($matches1[3], $matches2[1], $matches3[1]) as $url) {
203 $components = parse_url($url);
207 $cookiejar = tempnam(get_temppath(), 'cookiejar-mailstream-');
208 $curlResult = DI::httpClient()->fetchFull($url, 0, '', $cookiejar);
209 $attachments[$url] = [
210 'data' => $curlResult->getBody(),
211 'guid' => hash("crc32", $url),
212 'filename' => basename($components['path']),
213 'type' => $curlResult->getContentType()
216 if (strlen($attachments[$url]['data'])) {
217 $item['body'] = str_replace($url, 'cid:' . $attachments[$url]['guid'], $item['body']);
225 * Creates a sender to use in the email, either from the contact or the author of the item, or both
227 * @param array $item content of the item
229 * @return string sender suitable for use in the email
231 function mailstream_sender($item)
233 $contact = Contact::getById($item['contact-id']);
234 if (DBA::isResult($contact)) {
235 if ($contact['name'] != $item['author-name']) {
236 return $contact['name'] . ' - ' . $item['author-name'];
239 return $item['author-name'];
243 * Converts a bbcode-encoded subject line into a plaintext version suitable for the subject line of an email
245 * @param string $subject bbcode-encoded subject line
247 * @return string plaintext subject line
249 function mailstream_decode_subject($subject)
251 $html = BBCode::convert($subject);
255 $notags = strip_tags($html);
259 $noentity = html_entity_decode($notags);
263 $nocodes = preg_replace_callback("/(&#[0-9]+;)/", function ($m) {
264 return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES");
269 $trimmed = trim($nocodes);
277 * Creates a subject line to use in the email
279 * @param array $item content of the item
281 * @return string subject line suitable for use in the email
283 function mailstream_subject($item)
285 if ($item['title']) {
286 return mailstream_decode_subject($item['title']);
288 $parent = $item['thr-parent'];
289 // Don't look more than 100 levels deep for a subject, in case of loops
290 for ($i = 0; ($i < 100) && $parent; $i++) {
291 $parent_item = Post::selectFirst(['thr-parent', 'title'], ['uri' => $parent]);
292 if (!DBA::isResult($parent_item)) {
295 if ($parent_item['thr-parent'] === $parent) {
298 if ($parent_item['title']) {
299 return DI::l10n()->t('Re:') . ' ' . mailstream_decode_subject($parent_item['title']);
301 $parent = $parent_item['thr-parent'];
303 $contact = Contact::selectFirst([], ['id' => $item['contact-id'], 'uid' => $item['uid']]);
304 if (!DBA::isResult($contact)) {
306 'mailstream_subject no contact for item',
307 ['id' => $item['id'],
308 'plink' => $item['plink'],
309 'contact id' => $item['contact-id'],
310 'uid' => $item['uid']]
312 return DI::l10n()->t("Friendica post");
314 if ($contact['network'] === 'dfrn') {
315 return DI::l10n()->t("Friendica post");
317 if ($contact['network'] === 'dspr') {
318 return DI::l10n()->t("Diaspora post");
320 if ($contact['network'] === 'face') {
321 $text = mailstream_decode_subject($item['body']);
322 // For some reason these do show up in Facebook
323 $text = preg_replace('/\xA0$/', '', $text);
324 $subject = (strlen($text) > 150) ? (substr($text, 0, 140) . '...') : $text;
325 return preg_replace('/\\s+/', ' ', $subject);
327 if ($contact['network'] === 'feed') {
328 return DI::l10n()->t("Feed item");
330 if ($contact['network'] === 'mail') {
331 return DI::l10n()->t("Email");
333 return DI::l10n()->t("Friendica Item");
337 * Sends a message using PHPMailer
339 * @param string $message_id ID of the message (RFC 1036)
340 * @param array $item content of the item
341 * @param array $user results from the user table
343 * @return bool True if this message has been completed. False if it should be retried.
345 function mailstream_send($message_id, $item, $user)
347 if (!is_array($item)) {
348 Logger::error('mailstream_send item is empty', ['message_id' => $message_id]);
352 if (!$item['visible']) {
353 Logger::debug('mailstream_send item not yet visible', ['item uri' => $item['uri']]);
357 Logger::error('mailstream_send no message ID supplied', ['item uri' => $item['uri'],
358 'user email' => $user['email']]);
361 require_once(dirname(__file__).'/phpmailer/class.phpmailer.php');
364 mailstream_do_images($item, $attachments);
365 $frommail = DI::config()->get('mailstream', 'frommail');
366 if ($frommail == "") {
367 $frommail = 'friendica@localhost.local';
369 $address = DI::pConfig()->get($item['uid'], 'mailstream', 'address');
371 $address = $user['email'];
373 $mail = new PHPmailer;
375 $mail->XMailer = 'Friendica Mailstream Addon';
376 $mail->SetFrom($frommail, mailstream_sender($item));
377 $mail->AddAddress($address, $user['username']);
378 $mail->MessageID = $message_id;
379 $mail->Subject = mailstream_subject($item);
380 if ($item['thr-parent'] != $item['uri']) {
381 $mail->addCustomHeader('In-Reply-To: ' . mailstream_generate_id($item['thr-parent']));
383 $mail->addCustomHeader('X-Friendica-Mailstream-URI: ' . $item['uri']);
384 $mail->addCustomHeader('X-Friendica-Mailstream-Plink: ' . $item['plink']);
385 $encoding = 'base64';
386 foreach ($attachments as $url => $image) {
387 $mail->AddStringEmbeddedImage(
396 $mail->CharSet = 'utf-8';
397 $template = Renderer::getMarkupTemplate('mail.tpl', 'addon/mailstream/');
398 $mail->AltBody = BBCode::toPlaintext($item['body']);
399 $item['body'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::CONNECTORS);
400 $item['url'] = DI::baseUrl()->get() . '/display/' . $item['guid'];
401 $mail->Body = Renderer::replaceMacros($template, [
402 '$upstream' => DI::l10n()->t('Upstream'),
403 '$local' => DI::l10n()->t('Local'),
405 mailstream_html_wrap($mail->Body);
406 if (!$mail->Send()) {
407 throw new Exception($mail->ErrorInfo);
409 Logger::debug('mailstream_send sent message', ['message ID' => $mail->MessageID,
410 'subject' => $mail->Subject,
411 'address' => $address]);
412 } catch (phpmailerException $e) {
413 Logger::debug('mailstream_send PHPMailer exception sending message ' . $message_id . ': ' . $e->errorMessage());
414 } catch (Exception $e) {
415 Logger::debug('mailstream_send exception sending message ' . $message_id . ': ' . $e->getMessage());
422 * Email tends to break if you send excessively long lines. To make
423 * bbcode's output suitable for transmission, we try to break things
424 * up so that lines are about 200 characters.
426 * @param string $text text to word wrap - modified in-place
428 function mailstream_html_wrap(&$text)
430 $lines = str_split($text, 200);
431 for ($i = 0; $i < count($lines); $i++) {
432 $lines[$i] = preg_replace('/ /', "\n", $lines[$i], 1);
434 $text = implode($lines);
438 * Convert v1 mailstream table entries to v2 workerqueue items
440 function mailstream_convert_table_entries()
442 $ms_item_ids = DBA::selectToArray('mailstream_item', [], ['message-id', 'uri', 'uid', 'contact-id'], ["`mailstream_item`.`completed` IS NULL"]);
443 Logger::debug('mailstream_convert_table_entries processing ' . count($ms_item_ids) . ' items');
444 foreach ($ms_item_ids as $ms_item_id) {
445 $send_hook_data = array('uid' => $ms_item_id['uid'],
446 'contact-id' => $ms_item_id['contact-id'],
447 'uri' => $ms_item_id['uri'],
448 'message_id' => $ms_item_id['message-id'],
450 if (!$ms_item_id['message-id'] || !strlen($ms_item_id['message-id'])) {
451 Logger::info('mailstream_cron: Item ' .
452 $ms_item_id['id'] . ' URI ' . $ms_item_id['uri'] . ' has no message-id');
455 Logger::info('mailstream_convert_table_entries: convert item to workerqueue', $send_hook_data);
456 Hook::fork(PRIORITY_LOW, 'mailstream_send_hook', $send_hook_data);
458 DBA::e('DROP TABLE `mailstream_item`');
462 * Form for configuring mailstream features for a user
464 * @param Friendica\App $a App object
465 * @param string $o HTML form data
467 function mailstream_addon_settings(&$a, &$s)
469 $enabled = DI::pConfig()->get(local_user(), 'mailstream', 'enabled');
470 $address = DI::pConfig()->get(local_user(), 'mailstream', 'address');
471 $nolikes = DI::pConfig()->get(local_user(), 'mailstream', 'nolikes');
472 $attachimg= DI::pConfig()->get(local_user(), 'mailstream', 'attachimg');
473 $template = Renderer::getMarkupTemplate('settings.tpl', 'addon/mailstream/');
474 $s .= Renderer::replaceMacros($template, [
476 'mailstream_enabled',
477 DI::l10n()->t('Enabled'),
481 'mailstream_address',
482 DI::l10n()->t('Email Address'),
484 DI::l10n()->t("Leave blank to use your account email address")
487 'mailstream_nolikes',
488 DI::l10n()->t('Exclude Likes'),
490 DI::l10n()->t("Check this to omit mailing \"Like\" notifications")
493 'mailstream_attachimg',
494 DI::l10n()->t('Attach Images'),
496 DI::l10n()->t("Download images in posts and attach them to the email. " .
497 "Useful for reading email while offline.")
499 '$title' => DI::l10n()->t('Mail Stream Settings'),
500 '$submit' => DI::l10n()->t('Save Settings')]);
504 * Process data submitted to user's mailstream features form
505 * @param \Friendica\App $a
506 * @param array $post POST data
508 function mailstream_addon_settings_post(\Friendica\App $a, array $post)
510 if (!local_user() || empty($post['mailstream-submit'])) {
514 if ($post['mailstream_address'] != "") {
515 DI::pConfig()->set(local_user(), 'mailstream', 'address', $post['mailstream_address']);
517 DI::pConfig()->delete(local_user(), 'mailstream', 'address');
519 if ($post['mailstream_nolikes']) {
520 DI::pConfig()->set(local_user(), 'mailstream', 'nolikes', $post['mailstream_enabled']);
522 DI::pConfig()->delete(local_user(), 'mailstream', 'nolikes');
524 if ($post['mailstream_enabled']) {
525 DI::pConfig()->set(local_user(), 'mailstream', 'enabled', $post['mailstream_enabled']);
527 DI::pConfig()->delete(local_user(), 'mailstream', 'enabled');
529 if ($post['mailstream_attachimg']) {
530 DI::pConfig()->set(local_user(), 'mailstream', 'attachimg', $post['mailstream_attachimg']);
532 DI::pConfig()->delete(local_user(), 'mailstream', 'attachimg');