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\Database\DBA;
15 use Friendica\Model\Item;
16 use Friendica\Model\Post;
17 use Friendica\Model\User;
18 use Friendica\Protocol\Activity;
19 use Friendica\Util\DateTimeFormat;
22 * Sets up the addon hooks and the database table
24 function mailstream_install()
26 Hook::register('addon_settings', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings');
27 Hook::register('addon_settings_post', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings_post');
28 Hook::register('post_local_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
29 Hook::register('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
30 Hook::register('cron', 'addon/mailstream/mailstream.php', 'mailstream_cron');
31 Hook::register('mailstream_send_hook', 'addon/mailstream/mailstream.php', 'mailstream_send_hook');
33 Logger::info("mailstream: installed");
37 * Enforces that mailstream_install has set up the current version
39 function mailstream_check_version()
41 if (!is_null(DI::config()->get('mailstream', 'dbversion'))) {
42 DI::config()->delete('mailstream', 'dbversion');
43 Logger::info("mailstream_check_version: old version detected, reinstalling");
47 'mailstream_convert_table_entries',
48 'addon/mailstream/mailstream.php',
49 'mailstream_convert_table_entries'
51 Hook::fork(PRIORITY_LOW, 'mailstream_convert_table_entries');
56 * This function indicates a module that can be wrapped in the LegacyModule class
58 function mailstream_module()
63 * Adds an item in "addon features" in the admin menu of the site
65 * @param Friendica\App $a App object (unused)
66 * @param string $o HTML form data
68 function mailstream_addon_admin(&$a, &$o)
70 $frommail = DI::config()->get('mailstream', 'frommail');
71 $template = Renderer::getMarkupTemplate('admin.tpl', 'addon/mailstream/');
72 $config = ['frommail',
73 DI::l10n()->t('From Address'),
75 DI::l10n()->t('Email address that stream items will appear to be from.')];
76 $o .= Renderer::replaceMacros($template, [
77 '$frommail' => $config,
78 '$submit' => DI::l10n()->t('Save Settings')]);
82 * Process input from the "addon features" part of the admin menu
84 function mailstream_addon_admin_post()
86 if (!empty($_POST['frommail'])) {
87 DI::config()->set('mailstream', 'frommail', $_POST['frommail']);
92 * Creates a message ID for a post URI in accordance with RFC 1036
93 * See also http://www.jwz.org/doc/mid.html
95 * @param string $uri the URI to be converted to a message ID
97 * @return string the created message ID
99 function mailstream_generate_id($uri)
101 $host = DI::baseUrl()->getHostname();
102 $resource = hash('md5', $uri);
103 $message_id = "<" . $resource . "@" . $host . ">";
104 Logger::debug('mailstream: Generated message ID ' . $message_id . ' for URI ' . $uri);
108 function mailstream_send_hook(&$a, $data)
110 $criteria = array('uid' => $data['uid'], 'contact-id' => $data['contact-id'], 'uri' => $data['uri']);
111 $item = Post::selectFirst([], $criteria);
113 Logger::error('mailstream_send_hook could not find item');
117 $user = User::getById($item['uid']);
119 Logger::error('mailstream_send_hook could not fund user', ['uid' => $item['uid']]);
123 if (!mailstream_send($data['message_id'], $item, $user)) {
124 $delayed = date(DateTimeFormat::utc('now + 1 hour'));
126 Hook::fork(['priority' => PRIORITY_LOW, 'delayed' => $delayed], 'mailstream_send_hook', $data);
131 * Called when either a local or remote post is created. If
132 * mailstream is enabled and the necessary data is available, forks a
133 * workerqueue item to send the email.
135 * @param Friendica\App $a App object (unused)
136 * @param array $item content of the item (may or may not already be stored in the item table)
138 function mailstream_post_hook(&$a, &$item)
140 mailstream_check_version();
142 if (!DI::pConfig()->get($item['uid'], 'mailstream', 'enabled')) {
143 Logger::debug('mailstream: not enabled for item ' . $item['id']);
147 Logger::debug('mailstream: no uid for item ' . $item['id']);
150 if (!$item['contact-id']) {
151 Logger::debug('mailstream: no contact-id for item ' . $item['id']);
155 Logger::debug('mailstream: no uri for item ' . $item['id']);
158 if (!$item['plink']) {
159 Logger::debug('mailstream: no plink for item ' . $item['id']);
162 if (DI::pConfig()->get($item['uid'], 'mailstream', 'nolikes')) {
163 if ($item['verb'] == Activity::LIKE) {
164 Logger::debug('mailstream: like item ' . $item['id']);
169 $message_id = mailstream_generate_id($item['uri']);
171 $send_hook_data = array('uid' => $item['uid'],
172 'contact-id' => $item['contact-id'],
173 'uri' => $item['uri'],
174 'message_id' => $message_id,
176 Hook::fork(PRIORITY_LOW, 'mailstream_send_hook', $send_hook_data);
180 * If the user has configured attaching images to emails as
181 * attachments, this function searches the post for such images,
182 * retrieves the image, and inserts the data and metadata into the
185 * @param array $item content of the item
186 * @param array $attachments contains an array element for each attachment to add to the email
188 * @return array new value of the attachments table (results are also stored in the reference parameter)
190 function mailstream_do_images(&$item, &$attachments)
192 if (!DI::pConfig()->get($item['uid'], 'mailstream', 'attachimg')) {
196 preg_match_all("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", $item["body"], $matches1);
197 preg_match_all("/\[img\](.*?)\[\/img\]/ism", $item["body"], $matches2);
198 preg_match_all("/\[img\=([^\]]*)\]([^[]*)\[\/img\]/ism", $item["body"], $matches3);
199 foreach (array_merge($matches1[3], $matches2[1], $matches3[1]) as $url) {
200 $components = parse_url($url);
204 $cookiejar = tempnam(get_temppath(), 'cookiejar-mailstream-');
205 $curlResult = DI::httpRequest()->fetchFull($url, 0, '', $cookiejar);
206 $attachments[$url] = [
207 'data' => $curlResult->getBody(),
208 'guid' => hash("crc32", $url),
209 'filename' => basename($components['path']),
210 'type' => $curlResult->getContentType()
213 if (strlen($attachments[$url]['data'])) {
214 $item['body'] = str_replace($url, 'cid:' . $attachments[$url]['guid'], $item['body']);
222 * Creates a sender to use in the email, either from the contact or the author of the item, or both
224 * @param array $item content of the item
226 * @return string sender suitable for use in the email
228 function mailstream_sender($item)
230 $r = q('SELECT * FROM `contact` WHERE `id` = %d', $item['contact-id']);
231 if (DBA::isResult($r)) {
233 if ($contact['name'] != $item['author-name']) {
234 return $contact['name'] . ' - ' . $item['author-name'];
237 return $item['author-name'];
241 * Converts a bbcode-encoded subject line into a plaintext version suitable for the subject line of an email
243 * @param string $subject bbcode-encoded subject line
245 * @return string plaintext subject line
247 function mailstream_decode_subject($subject)
249 $html = BBCode::convert($subject);
253 $notags = strip_tags($html);
257 $noentity = html_entity_decode($notags);
261 $nocodes = preg_replace_callback("/(&#[0-9]+;)/", function ($m) {
262 return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES");
267 $trimmed = trim($nocodes);
275 * Creates a subject line to use in the email
277 * @param array $item content of the item
279 * @return string subject line suitable for use in the email
281 function mailstream_subject($item)
283 if ($item['title']) {
284 return mailstream_decode_subject($item['title']);
286 $parent = $item['thr-parent'];
287 // Don't look more than 100 levels deep for a subject, in case of loops
288 for ($i = 0; ($i < 100) && $parent; $i++) {
289 $parent_item = Post::selectFirst(['thr-parent', 'title'], ['uri' => $parent]);
290 if (!DBA::isResult($parent_item)) {
293 if ($parent_item['thr-parent'] === $parent) {
296 if ($parent_item['title']) {
297 return DI::l10n()->t('Re:') . ' ' . mailstream_decode_subject($parent_item['title']);
299 $parent = $parent_item['thr-parent'];
302 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
303 intval($item['contact-id']),
306 if (!DBA::isResult($r)) {
308 'mailstream_subject no contact for item',
309 ['id' => $item['id'],
310 'plink' => $item['plink'],
311 'contact id' => $item['contact-id'],
312 'uid' => $item['uid']]
314 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::convert($item['body'], false, 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()
454 `mailstream_item`.`completed` IS NULL
457 $ms_item_ids = q($query);
458 if (DBA::isResult($ms_item_ids)) {
459 Logger::debug('mailstream_convert_table_entries processing ' . count($ms_item_ids) . ' items');
460 foreach ($ms_item_ids as $ms_item_id) {
461 $send_hook_data = array('uid' => $ms_item_id['uid'],
462 'contact-id' => $ms_item_id['contact-id'],
463 'uri' => $ms_item_id['uri'],
464 'message_id' => $ms_item_id['message-id'],
466 if (!$ms_item_id['message-id'] || !strlen($ms_item_id['message-id'])) {
467 Logger::info('mailstream_cron: Item ' .
468 $ms_item_id['id'] . ' URI ' . $ms_item_id['uri'] . ' has no message-id');
471 Logger::info('mailstream_convert_table_entries: convert item to workerqueue', $send_hook_data);
472 Hook::fork(PRIORITY_LOW, 'mailstream_send_hook', $send_hook_data);
475 q('DROP TABLE `mailstream_item`');
479 * Form for configuring mailstream features for a user
481 * @param Friendica\App $a App object
482 * @param string $o HTML form data
484 function mailstream_addon_settings(&$a, &$s)
486 $enabled = DI::pConfig()->get(local_user(), 'mailstream', 'enabled');
487 $address = DI::pConfig()->get(local_user(), 'mailstream', 'address');
488 $nolikes = DI::pConfig()->get(local_user(), 'mailstream', 'nolikes');
489 $attachimg= DI::pConfig()->get(local_user(), 'mailstream', 'attachimg');
490 $template = Renderer::getMarkupTemplate('settings.tpl', 'addon/mailstream/');
491 $s .= Renderer::replaceMacros($template, [
493 'mailstream_enabled',
494 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")],
502 'mailstream_nolikes',
503 DI::l10n()->t('Exclude Likes'),
505 DI::l10n()->t("Check this to omit mailing \"Like\" notifications")],
507 'mailstream_attachimg',
508 DI::l10n()->t('Attach Images'),
510 DI::l10n()->t("Download images in posts and attach them to the email. " .
511 "Useful for reading email while offline.")],
512 '$title' => DI::l10n()->t('Mail Stream Settings'),
513 '$submit' => DI::l10n()->t('Save Settings')]);
517 * Process data submitted to user's mailstream features form
519 function mailstream_addon_settings_post()
521 if ($_POST['mailstream_address'] != "") {
522 DI::pConfig()->set(local_user(), 'mailstream', 'address', $_POST['mailstream_address']);
524 DI::pConfig()->delete(local_user(), 'mailstream', 'address');
526 if ($_POST['mailstream_nolikes']) {
527 DI::pConfig()->set(local_user(), 'mailstream', 'nolikes', $_POST['mailstream_enabled']);
529 DI::pConfig()->delete(local_user(), 'mailstream', 'nolikes');
531 if ($_POST['mailstream_enabled']) {
532 DI::pConfig()->set(local_user(), 'mailstream', 'enabled', $_POST['mailstream_enabled']);
534 DI::pConfig()->delete(local_user(), 'mailstream', 'enabled');
536 if ($_POST['mailstream_attachimg']) {
537 DI::pConfig()->set(local_user(), 'mailstream', 'attachimg', $_POST['mailstream_attachimg']);
539 DI::pConfig()->delete(local_user(), 'mailstream', 'attachimg');