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\Protocol\Activity;
20 * Sets up the addon hooks and the database table
22 function mailstream_install()
24 Hook::register('addon_settings', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings');
25 Hook::register('addon_settings_post', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings_post');
26 Hook::register('post_local_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
27 Hook::register('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
28 Hook::register('cron', 'addon/mailstream/mailstream.php', 'mailstream_cron');
30 if (DI::config()->get('mailstream', 'dbversion') == '0.1') {
31 q('ALTER TABLE `mailstream_item` DROP INDEX `uid`');
32 q('ALTER TABLE `mailstream_item` DROP INDEX `contact-id`');
33 q('ALTER TABLE `mailstream_item` DROP INDEX `plink`');
34 q('ALTER TABLE `mailstream_item` CHANGE `plink` `uri` char(255) NOT NULL');
35 DI::config()->set('mailstream', 'dbversion', '0.2');
37 if (DI::config()->get('mailstream', 'dbversion') == '0.2') {
38 q('DELETE FROM `pconfig` WHERE `cat` = "mailstream" AND `k` = "delay"');
39 DI::config()->set('mailstream', 'dbversion', '0.3');
41 if (DI::config()->get('mailstream', 'dbversion') == '0.3') {
42 q('ALTER TABLE `mailstream_item` CHANGE `created` `created` timestamp NOT NULL DEFAULT now()');
43 q('ALTER TABLE `mailstream_item` CHANGE `completed` `completed` timestamp NULL DEFAULT NULL');
44 DI::config()->set('mailstream', 'dbversion', '0.4');
46 if (DI::config()->get('mailstream', 'dbversion') == '0.4') {
47 q('ALTER TABLE `mailstream_item` CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin');
48 DI::config()->set('mailstream', 'dbversion', '0.5');
50 if (DI::config()->get('mailstream', 'dbversion') == '0.5') {
51 DI::config()->set('mailstream', 'dbversion', '1.0');
54 if (DI::config()->get('retriever', 'dbversion') != '1.0') {
55 $schema = file_get_contents(dirname(__file__).'/database.sql');
56 $arr = explode(';', $schema);
57 foreach ($arr as $a) {
60 DI::config()->set('mailstream', 'dbversion', '1.0');
65 * This funciton indicates a module that can be wrapped in the LegacyModule class
67 function mailstream_module()
72 * Adds an item in "addon features" in the admin menu of the site
74 * @param Friendica\App $a App object (unused)
75 * @param string $o HTML form data
77 function mailstream_addon_admin(&$a, &$o)
79 $frommail = DI::config()->get('mailstream', 'frommail');
80 $template = Renderer::getMarkupTemplate('admin.tpl', 'addon/mailstream/');
81 $config = ['frommail',
82 DI::l10n()->t('From Address'),
84 DI::l10n()->t('Email address that stream items will appear to be from.')];
85 $o .= Renderer::replaceMacros($template, [
86 '$frommail' => $config,
87 '$submit' => DI::l10n()->t('Save Settings')]);
91 * Process input from the "addon features" part of the admin menu
93 function mailstream_addon_admin_post()
95 if (!empty($_POST['frommail'])) {
96 DI::config()->set('mailstream', 'frommail', $_POST['frommail']);
101 * Creates a message ID for a post URI in accordance with RFC 1036
102 * See also http://www.jwz.org/doc/mid.html
104 * @param string $uri the URI to be converted to a message ID
106 * @return string the created message ID
108 function mailstream_generate_id($uri)
110 $host = DI::baseUrl()->getHostname();
111 $resource = hash('md5', $uri);
112 $message_id = "<" . $resource . "@" . $host . ">";
113 Logger::debug('mailstream: Generated message ID ' . $message_id . ' for URI ' . $uri);
118 * Called when either a local or remote post is created. Creates a
119 * record in the mailstream_item table to track this email, and then
120 * immediately attempts to send it
122 * @param Friendica\App $a App object (unused)
123 * @param array $item content of the item (may or may not already be stored in the item table)
125 function mailstream_post_hook(&$a, &$item)
127 if (!DI::pConfig()->get($item['uid'], 'mailstream', 'enabled')) {
128 Logger::debug('mailstream: not enabled for item ' . $item['id']);
132 Logger::debug('mailstream: no uid for item ' . $item['id']);
135 if (!$item['contact-id']) {
136 Logger::debug('mailstream: no contact-id for item ' . $item['id']);
140 Logger::debug('mailstream: no uri for item ' . $item['id']);
143 if (!$item['plink']) {
144 Logger::debug('mailstream: no plink for item ' . $item['id']);
147 if (DI::pConfig()->get($item['uid'], 'mailstream', 'nolikes')) {
148 if ($item['verb'] == Activity::LIKE) {
149 Logger::debug('mailstream: like item ' . $item['id']);
154 $message_id = mailstream_generate_id($item['uri']);
156 "INSERT INTO `mailstream_item` (`uid`, `contact-id`, `uri`, `message-id`) " .
157 "VALUES (%d, '%s', '%s', '%s')",
158 intval($item['uid']),
159 intval($item['contact-id']),
160 DBA::escape($item['uri']),
161 DBA::escape($message_id)
164 'SELECT * FROM `mailstream_item` WHERE `uid` = %d AND `contact-id` = %d AND `uri` = "%s"',
165 intval($item['uid']),
166 intval($item['contact-id']),
167 DBA::escape($item['uri'])
169 if (count($r) != 1) {
170 Logger::info('mailstream_post_remote_hook: Unexpected number of items returned from mailstream_item');
174 Logger::debug('mailstream_post_remote_hook: created mailstream_item ' . $ms_item['id'] .
175 ' for item ' . $item['uri'] . ' ' . $item['uid'] . ' ' . $item['contact-id']);
176 $user = mailstream_get_user($item['uid']);
178 Logger::info('mailstream_post_remote_hook: no user ' . $item['uid']);
181 mailstream_send($ms_item['message-id'], $item, $user);
185 * Converts a user ID into a full user record from the corresponding database table
187 * @param int $uid ID of the user to query
189 * @return array results from the user table
191 function mailstream_get_user($uid)
193 $r = q('SELECT * FROM `user` WHERE `uid` = %d', intval($uid));
194 if (count($r) != 1) {
195 Logger::info('mailstream_post_remote_hook: Unexpected number of users returned');
202 * If the user has configured attaching images to emails as
203 * attachments, this function searches the post for such images,
204 * retrieves the image, and inserts the data and metadata into the
207 * @param array $item content of the item
208 * @param array $attachments contains an array element for each attachment to add to the email
210 * @return array new value of the attachments table (results are also stored in the reference parameter)
212 function mailstream_do_images(&$item, &$attachments)
214 if (!DI::pConfig()->get($item['uid'], 'mailstream', 'attachimg')) {
218 preg_match_all("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", $item["body"], $matches1);
219 preg_match_all("/\[img\](.*?)\[\/img\]/ism", $item["body"], $matches2);
220 preg_match_all("/\[img\=([^\]]*)\]([^[]*)\[\/img\]/ism", $item["body"], $matches3);
221 foreach (array_merge($matches1[3], $matches2[1], $matches3[1]) as $url) {
222 $components = parse_url($url);
226 $cookiejar = tempnam(get_temppath(), 'cookiejar-mailstream-');
227 $curlResult = DI::httpRequest()->fetchFull($url, 0, '', $cookiejar);
228 $attachments[$url] = [
229 'data' => $curlResult->getBody(),
230 'guid' => hash("crc32", $url),
231 'filename' => basename($components['path']),
232 'type' => $curlResult->getContentType()
235 if (strlen($attachments[$url]['data'])) {
236 $item['body'] = str_replace($url, 'cid:' . $attachments[$url]['guid'], $item['body']);
244 * Creates a sender to use in the email, either from the contact or the author of the item, or both
246 * @param array $item content of the item
248 * @return string sender suitable for use in the email
250 function mailstream_sender($item)
252 $r = q('SELECT * FROM `contact` WHERE `id` = %d', $item['contact-id']);
253 if (DBA::isResult($r)) {
255 if ($contact['name'] != $item['author-name']) {
256 return $contact['name'] . ' - ' . $item['author-name'];
259 return $item['author-name'];
263 * Converts a bbcode-encoded subject line into a plaintext version suitable for the subject line of an email
265 * @param string $subject bbcode-encoded subject line
267 * @return string plaintext subject line
269 function mailstream_decode_subject($subject)
271 $html = BBCode::convert($subject);
275 $notags = strip_tags($html);
279 $noentity = html_entity_decode($notags);
283 $nocodes = preg_replace_callback("/(&#[0-9]+;)/", function ($m) {
284 return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES");
289 $trimmed = trim($nocodes);
297 * Creates a subject line to use in the email
299 * @param array $item content of the item
301 * @return string subject line suitable for use in the email
303 function mailstream_subject($item)
305 if ($item['title']) {
306 return mailstream_decode_subject($item['title']);
308 $parent = $item['thr-parent'];
309 // Don't look more than 100 levels deep for a subject, in case of loops
310 for ($i = 0; ($i < 100) && $parent; $i++) {
311 $parent_item = Post::selectFirst(['thr-parent', 'title'], ['uri' => $parent]);
312 if (!DBA::isResult($parent_item)) {
315 if ($parent_item['thr-parent'] === $parent) {
318 if ($parent_item['title']) {
319 return DI::l10n()->t('Re:') . ' ' . mailstream_decode_subject($parent_item['title']);
321 $parent = $parent_item['thr-parent'];
324 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
325 intval($item['contact-id']),
328 if (!DBA::isResult($r)) {
330 'mailstream_subject no contact for item',
331 ['item id' => $item['id'], 'plink' => $item['plink'], 'contact id' => $item['contact-id'], 'uid' => $item['uid']]
333 return DI::l10n()->t("Friendica post");
336 if ($contact['network'] === 'dfrn') {
337 return DI::l10n()->t("Friendica post");
339 if ($contact['network'] === 'dspr') {
340 return DI::l10n()->t("Diaspora post");
342 if ($contact['network'] === 'face') {
343 $text = mailstream_decode_subject($item['body']);
344 // For some reason these do show up in Facebook
345 $text = preg_replace('/\xA0$/', '', $text);
346 $subject = (strlen($text) > 150) ? (substr($text, 0, 140) . '...') : $text;
347 return preg_replace('/\\s+/', ' ', $subject);
349 if ($contact['network'] === 'feed') {
350 return DI::l10n()->t("Feed item");
352 if ($contact['network'] === 'mail') {
353 return DI::l10n()->t("Email");
355 return DI::l10n()->t("Friendica Item");
359 * Sends a message using PHPMailer
361 * @param string $message_id ID of the message (RFC 1036)
362 * @param array $item content of the item
363 * @param array $user results from the user table
365 function mailstream_send($message_id, $item, $user)
367 if (!$item['visible']) {
373 require_once(dirname(__file__).'/phpmailer/class.phpmailer.php');
376 mailstream_do_images($item, $attachments);
377 $frommail = DI::config()->get('mailstream', 'frommail');
378 if ($frommail == "") {
379 $frommail = 'friendica@localhost.local';
381 $address = DI::pConfig()->get($item['uid'], 'mailstream', 'address');
383 $address = $user['email'];
385 $mail = new PHPmailer;
387 $mail->XMailer = 'Friendica Mailstream Addon';
388 $mail->SetFrom($frommail, mailstream_sender($item));
389 $mail->AddAddress($address, $user['username']);
390 $mail->MessageID = $message_id;
391 $mail->Subject = mailstream_subject($item);
392 if ($item['thr-parent'] != $item['uri']) {
393 $mail->addCustomHeader('In-Reply-To: ' . mailstream_generate_id($item['thr-parent']));
395 $mail->addCustomHeader('X-Friendica-Mailstream-URI: ' . $item['uri']);
396 $mail->addCustomHeader('X-Friendica-Mailstream-Plink: ' . $item['plink']);
397 $encoding = 'base64';
398 foreach ($attachments as $url => $image) {
399 $mail->AddStringEmbeddedImage(
408 $mail->CharSet = 'utf-8';
409 $template = Renderer::getMarkupTemplate('mail.tpl', 'addon/mailstream/');
410 $mail->AltBody = BBCode::toPlaintext($item['body']);
411 $item['body'] = BBCode::convert($item['body'], false, BBCode::CONNECTORS);
412 $item['url'] = DI::baseUrl()->get() . '/display/' . $item['guid'];
413 $mail->Body = Renderer::replaceMacros($template, [
414 '$upstream' => DI::l10n()->t('Upstream'),
415 '$local' => DI::l10n()->t('Local'),
417 mailstream_html_wrap($mail->Body);
418 if (!$mail->Send()) {
419 throw new Exception($mail->ErrorInfo);
421 Logger::debug('mailstream_send sent message ' . $mail->MessageID . ' ' . $mail->Subject);
422 } catch (phpmailerException $e) {
423 Logger::debug('mailstream_send PHPMailer exception sending message ' . $message_id . ': ' . $e->errorMessage());
424 } catch (Exception $e) {
425 Logger::debug('mailstream_send exception sending message ' . $message_id . ': ' . $e->getMessage());
427 // In case of failure, still set the item to completed. Otherwise
428 // we'll just try to send it over and over again and it'll fail
430 q('UPDATE `mailstream_item` SET `completed` = now() WHERE `message-id` = "%s"', DBA::escape($message_id));
434 * Email tends to break if you send excessively long lines. To make
435 * bbcode's output suitable for transmission, we try to break things
436 * up so that lines are about 200 characters.
438 * @param string $text text to word wrap - modified in-place
440 function mailstream_html_wrap(&$text)
442 $lines = str_split($text, 200);
443 for ($i = 0; $i < count($lines); $i++) {
444 $lines[$i] = preg_replace('/ /', "\n", $lines[$i], 1);
446 $text = implode($lines);
450 * Cron job for the mailstream plugin. Sends delayed messages and cleans up old successful entries from the table.
452 function mailstream_cron()
454 // Only process items older than an hour in cron. This is because
455 // we want to give mailstream_post_remote_hook a fair chance to
456 // send the email itself before cron jumps in. Only if
457 // mailstream_post_remote_hook fails for some reason will this get
458 // used, and in that case it's worth holding off a bit anyway.
461 `mailstream_item`.`message-id`,
462 `mailstream_item`.`uri`,
463 `post-user-view`.`id`
469 `mailstream_item`.`uid` = `post-user-view`.`uid` AND
470 `mailstream_item`.`uri` = `post-user-view`.`uri` AND
471 `mailstream_item`.`contact-id` = `post-user-view`.`contact-id`
474 `mailstream_item`.`completed` IS NULL AND
475 `mailstream_item`.`created` < DATE_SUB(NOW(), INTERVAL 1 HOUR) AND
476 `post-user-view`.`visible` = 1
477 ORDER BY `mailstream_item`.`created`
481 $ms_item_ids = q($query);
482 if (DBA::isResult($ms_item_ids)) {
483 Logger::debug('mailstream_cron processing ' . count($ms_item_ids) . ' items');
484 foreach ($ms_item_ids as $ms_item_id) {
485 if (!$ms_item_id['message-id'] || !strlen($ms_item_id['message-id'])) {
486 Logger::info('mailstream_cron: Item ' . $ms_item_id['id'] .
487 ' URI ' . $ms_item_id['uri'] . ' has no message-id');
489 $item = Post::selectFirst([], ['id' => $ms_item_id['id']]);
490 $users = q("SELECT * FROM `user` WHERE `uid` = %d", intval($item['uid']));
492 if ($user && $item) {
493 mailstream_send($ms_item_id['message-id'], $item, $user);
495 Logger::info('mailstream_cron: Unable to find item ' . $ms_item_id['id']);
497 "UPDATE `mailstream_item` SET `completed` = now() WHERE `message-id` = %d",
498 intval($ms_item_id['message-id'])
507 * Form for configuring mailstream features for a user
509 * @param Friendica\App $a App object
510 * @param string $o HTML form data
512 function mailstream_addon_settings(&$a, &$s)
514 $enabled = DI::pConfig()->get(local_user(), 'mailstream', 'enabled');
515 $address = DI::pConfig()->get(local_user(), 'mailstream', 'address');
516 $nolikes = DI::pConfig()->get(local_user(), 'mailstream', 'nolikes');
517 $attachimg= DI::pConfig()->get(local_user(), 'mailstream', 'attachimg');
518 $template = Renderer::getMarkupTemplate('settings.tpl', 'addon/mailstream/');
519 $s .= Renderer::replaceMacros($template, [
521 'mailstream_enabled',
522 DI::l10n()->t('Enabled'),
525 'mailstream_address',
526 DI::l10n()->t('Email Address'),
528 DI::l10n()->t("Leave blank to use your account email address")],
530 'mailstream_nolikes',
531 DI::l10n()->t('Exclude Likes'),
533 DI::l10n()->t("Check this to omit mailing \"Like\" notifications")],
535 'mailstream_attachimg',
536 DI::l10n()->t('Attach Images'),
538 DI::l10n()->t("Download images in posts and attach them to the email. " .
539 "Useful for reading email while offline.")],
540 '$title' => DI::l10n()->t('Mail Stream Settings'),
541 '$submit' => DI::l10n()->t('Save Settings')]);
545 * Process data submitted to user's mailstream features form
547 function mailstream_addon_settings_post()
549 if ($_POST['mailstream_address'] != "") {
550 DI::pConfig()->set(local_user(), 'mailstream', 'address', $_POST['mailstream_address']);
552 DI::pConfig()->delete(local_user(), 'mailstream', 'address');
554 if ($_POST['mailstream_nolikes']) {
555 DI::pConfig()->set(local_user(), 'mailstream', 'nolikes', $_POST['mailstream_enabled']);
557 DI::pConfig()->delete(local_user(), 'mailstream', 'nolikes');
559 if ($_POST['mailstream_enabled']) {
560 DI::pConfig()->set(local_user(), 'mailstream', 'enabled', $_POST['mailstream_enabled']);
562 DI::pConfig()->delete(local_user(), 'mailstream', 'enabled');
564 if ($_POST['mailstream_attachimg']) {
565 DI::pConfig()->set(local_user(), 'mailstream', 'attachimg', $_POST['mailstream_attachimg']);
567 DI::pConfig()->delete(local_user(), 'mailstream', 'attachimg');
572 * Deletes records from the mailstream_item table older than one year
574 function mailstream_tidy()
582 completed IS NOT NULL AND
583 completed < DATE_SUB(NOW(), INTERVAL 1 YEAR)
587 foreach ($r as $rr) {
588 q('DELETE FROM mailstream_item WHERE id = %d', intval($rr['id']));
590 Logger::debug('mailstream_tidy: deleted ' . count($r) . ' old items');