4 * Description: Mail all items coming into your network feed to an email address
6 * Author: Matthew Exon <http://mat.exon.name>
8 use Friendica\Core\Addon;
9 use Friendica\Core\Config;
10 use Friendica\Core\L10n;
11 use Friendica\Core\PConfig;
12 use Friendica\Database\DBM;
13 use Friendica\Util\Network;
15 function mailstream_install() {
16 Addon::registerHook('addon_settings', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings');
17 Addon::registerHook('addon_settings_post', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings_post');
18 Addon::registerHook('post_local_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
19 Addon::registerHook('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
20 Addon::registerHook('cron', 'addon/mailstream/mailstream.php', 'mailstream_cron');
22 if (Config::get('mailstream', 'dbversion') == '0.1') {
23 q('ALTER TABLE `mailstream_item` DROP INDEX `uid`');
24 q('ALTER TABLE `mailstream_item` DROP INDEX `contact-id`');
25 q('ALTER TABLE `mailstream_item` DROP INDEX `plink`');
26 q('ALTER TABLE `mailstream_item` CHANGE `plink` `uri` char(255) NOT NULL');
27 Config::set('mailstream', 'dbversion', '0.2');
29 if (Config::get('mailstream', 'dbversion') == '0.2') {
30 q('DELETE FROM `pconfig` WHERE `cat` = "mailstream" AND `k` = "delay"');
31 Config::set('mailstream', 'dbversion', '0.3');
33 if (Config::get('mailstream', 'dbversion') == '0.3') {
34 q('ALTER TABLE `mailstream_item` CHANGE `created` `created` timestamp NOT NULL DEFAULT now()');
35 q('ALTER TABLE `mailstream_item` CHANGE `completed` `completed` timestamp NULL DEFAULT NULL');
36 Config::set('mailstream', 'dbversion', '0.4');
38 if (Config::get('mailstream', 'dbversion') == '0.4') {
39 q('ALTER TABLE `mailstream_item` CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin');
40 Config::set('mailstream', 'dbversion', '0.5');
42 if (Config::get('mailstream', 'dbversion') == '0.5') {
43 Config::set('mailstream', 'dbversion', '1.0');
46 if (Config::get('retriever', 'dbversion') != '1.0') {
47 $schema = file_get_contents(dirname(__file__).'/database.sql');
48 $arr = explode(';', $schema);
49 foreach ($arr as $a) {
52 Config::set('mailstream', 'dbversion', '1.0');
56 function mailstream_uninstall() {
57 Addon::unregisterHook('addon_settings', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings');
58 Addon::unregisterHook('addon_settings_post', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings_post');
59 Addon::unregisterHook('post_local', 'addon/mailstream/mailstream.php', 'mailstream_post_local_hook');
60 Addon::unregisterHook('post_remote', 'addon/mailstream/mailstream.php', 'mailstream_post_remote_hook');
61 Addon::unregisterHook('post_local_end', 'addon/mailstream/mailstream.php', 'mailstream_post_local_hook');
62 Addon::unregisterHook('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_remote_hook');
63 Addon::unregisterHook('post_local_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
64 Addon::unregisterHook('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
65 Addon::unregisterHook('cron', 'addon/mailstream/mailstream.php', 'mailstream_cron');
66 Addon::unregisterHook('incoming_mail', 'addon/mailstream/mailstream.php', 'mailstream_incoming_mail');
69 function mailstream_module() {}
71 function mailstream_addon_admin(&$a,&$o) {
72 $frommail = Config::get('mailstream', 'frommail');
73 $template = get_markup_template('admin.tpl', 'addon/mailstream/');
74 $config = ['frommail',
75 L10n::t('From Address'),
77 L10n::t('Email address that stream items will appear to be from.')];
78 $o .= replace_macros($template, [
79 '$frommail' => $config,
80 '$submit' => L10n::t('Save Settings')]);
83 function mailstream_addon_admin_post ($a) {
84 if (x($_POST, 'frommail')) {
85 Config::set('mailstream', 'frommail', $_POST['frommail']);
89 function mailstream_generate_id($a, $uri) {
90 // http://www.jwz.org/doc/mid.html
91 $host = $a->get_hostname();
92 $resource = hash('md5', $uri);
93 $message_id = "<" . $resource . "@" . $host . ">";
94 logger('mailstream: Generated message ID ' . $message_id . ' for URI ' . $uri, LOGGER_DEBUG);
98 function mailstream_post_hook(&$a, &$item) {
99 if (!PConfig::get($item['uid'], 'mailstream', 'enabled')) {
105 if (!$item['contact-id']) {
111 if (PConfig::get($item['uid'], 'mailstream', 'nolikes')) {
112 if ($item['verb'] == ACTIVITY_LIKE) {
117 $message_id = mailstream_generate_id($a, $item['uri']);
118 q("INSERT INTO `mailstream_item` (`uid`, `contact-id`, `uri`, `message-id`) " .
119 "VALUES (%d, '%s', '%s', '%s')", intval($item['uid']),
120 intval($item['contact-id']), dbesc($item['uri']), dbesc($message_id));
121 $r = q('SELECT * FROM `mailstream_item` WHERE `uid` = %d AND `contact-id` = %d AND `uri` = "%s"', intval($item['uid']), intval($item['contact-id']), dbesc($item['uri']));
122 if (count($r) != 1) {
123 logger('mailstream_post_remote_hook: Unexpected number of items returned from mailstream_item', LOGGER_NORMAL);
127 logger('mailstream_post_remote_hook: created mailstream_item '
128 . $ms_item['id'] . ' for item ' . $item['uri'] . ' '
129 . $item['uid'] . ' ' . $item['contact-id'], LOGGER_DATA);
130 $user = mailstream_get_user($item['uid']);
132 logger('mailstream_post_remote_hook: no user ' . $item['uid'], LOGGER_NORMAL);
135 mailstream_send($a, $ms_item['message-id'], $item, $user);
138 function mailstream_get_user($uid) {
139 $r = q('SELECT * FROM `user` WHERE `uid` = %d', intval($uid));
140 if (count($r) != 1) {
141 logger('mailstream_post_remote_hook: Unexpected number of users returned', LOGGER_NORMAL);
147 function mailstream_do_images($a, &$item, &$attachments) {
148 if (!PConfig::get($item['uid'], 'mailstream', 'attachimg')) {
152 $baseurl = $a->get_baseurl();
153 preg_match_all("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", $item["body"], $matches1);
154 preg_match_all("/\[img\](.*?)\[\/img\]/ism", $item["body"], $matches2);
155 foreach (array_merge($matches1[3], $matches2[1]) as $url) {
157 $cookiejar = tempnam(get_temppath(), 'cookiejar-mailstream-');
158 $attachments[$url] = [
159 'data' => Network::fetchUrl($url, true, $redirects, 0, null, $cookiejar),
160 'guid' => hash("crc32", $url),
161 'filename' => basename($url),
162 'type' => $a->get_curl_content_type()];
163 if (strlen($attachments[$url]['data'])) {
164 $item['body'] = str_replace($url, 'cid:' . $attachments[$url]['guid'], $item['body']);
171 function mailstream_sender($item) {
172 $r = q('SELECT * FROM `contact` WHERE `id` = %d', $item['contact-id']);
173 if (DBM::is_result($r)) {
175 if ($contact['name'] != $item['author-name']) {
176 return $contact['name'] . ' - ' . $item['author-name'];
179 return $item['author-name'];
182 function mailstream_decode_subject($subject) {
183 $html = bbcode($subject);
187 $notags = strip_tags($html);
191 $noentity = html_entity_decode($notags);
195 $nocodes = preg_replace_callback("/(&#[0-9]+;)/", function($m) { return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES"); }, $noentity);
199 $trimmed = trim($nocodes);
206 function mailstream_subject($item) {
207 if ($item['title']) {
208 return mailstream_decode_subject($item['title']);
210 $parent = $item['thr-parent'];
211 // Don't look more than 100 levels deep for a subject, in case of loops
212 for ($i = 0; ($i < 100) && $parent; $i++) {
213 $r = q("SELECT `thr-parent`, `title` FROM `item` WHERE `uri` = '%s'", dbesc($parent));
214 if (!DBM::is_result($r)) {
217 if ($r[0]['thr-parent'] === $parent) {
220 if ($r[0]['title']) {
221 return L10n::t('Re:') . ' ' . mailstream_decode_subject($r[0]['title']);
223 $parent = $r[0]['thr-parent'];
225 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
226 intval($item['contact-id']), intval($item['uid']));
228 if ($contact['network'] === 'dfrn') {
229 return L10n::t("Friendica post");
231 if ($contact['network'] === 'dspr') {
232 return L10n::t("Diaspora post");
234 if ($contact['network'] === 'face') {
235 $text = mailstream_decode_subject($item['body']);
236 // For some reason these do show up in Facebook
237 $text = preg_replace('/\xA0$/', '', $text);
238 $subject = (strlen($text) > 150) ? (substr($text, 0, 140) . '...') : $text;
239 return preg_replace('/\\s+/', ' ', $subject);
241 if ($contact['network'] === 'feed') {
242 return L10n::t("Feed item");
244 if ($contact['network'] === 'mail') {
245 return L10n::t("Email");
247 return L10n::t("Friendica Item");
250 function mailstream_send($a, $message_id, $item, $user) {
251 if (!$item['visible']) {
257 require_once(dirname(__file__).'/phpmailer/class.phpmailer.php');
258 require_once('include/bbcode.php');
260 mailstream_do_images($a, $item, $attachments);
261 $frommail = Config::get('mailstream', 'frommail');
262 if ($frommail == "") {
263 $frommail = 'friendica@localhost.local';
265 $address = PConfig::get($item['uid'], 'mailstream', 'address');
267 $address = $user['email'];
269 $mail = new PHPmailer;
271 $mail->XMailer = 'Friendica Mailstream Addon';
272 $mail->SetFrom($frommail, mailstream_sender($item));
273 $mail->AddAddress($address, $user['username']);
274 $mail->MessageID = $message_id;
275 $mail->Subject = mailstream_subject($item);
276 if ($item['thr-parent'] != $item['uri']) {
277 $mail->addCustomHeader('In-Reply-To: ' . mailstream_generate_id($a, $item['thr-parent']));
279 $mail->addCustomHeader('X-Friendica-Mailstream-URI: ' . $item['uri']);
280 $mail->addCustomHeader('X-Friendica-Mailstream-Plink: ' . $item['plink']);
281 $encoding = 'base64';
282 foreach ($attachments as $url => $image) {
283 $mail->AddStringEmbeddedImage($image['data'], $image['guid'], $image['filename'], $encoding, $image['type']);
286 $mail->CharSet = 'utf-8';
287 $template = get_markup_template('mail.tpl', 'addon/mailstream/');
288 $item['body'] = bbcode($item['body']);
289 $item['url'] = $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $item['id'];
290 $mail->Body = replace_macros($template, [
291 '$upstream' => L10n::t('Upstream'),
292 '$local' => L10n::t('Local'),
294 mailstream_html_wrap($mail->Body);
295 if (!$mail->Send()) {
296 throw new Exception($mail->ErrorInfo);
298 logger('mailstream_send sent message ' . $mail->MessageID . ' ' . $mail->Subject, LOGGER_DEBUG);
299 } catch (phpmailerException $e) {
300 logger('mailstream_send PHPMailer exception sending message ' . $message_id . ': ' . $e->errorMessage(), LOGGER_NORMAL);
301 } catch (Exception $e) {
302 logger('mailstream_send exception sending message ' . $message_id . ': ' . $e->getMessage(), LOGGER_NORMAL);
304 // In case of failure, still set the item to completed. Otherwise
305 // we'll just try to send it over and over again and it'll fail
307 q('UPDATE `mailstream_item` SET `completed` = now() WHERE `message-id` = "%s"', dbesc($message_id));
311 * Email tends to break if you send excessively long lines. To make
312 * bbcode's output suitable for transmission, we try to break things
313 * up so that lines are about 200 characters.
315 function mailstream_html_wrap(&$text)
317 $lines = str_split($text, 200);
318 for ($i = 0; $i < count($lines); $i++) {
319 $lines[$i] = preg_replace('/ /', "\n", $lines[$i], 1);
321 $text = implode($lines);
324 function mailstream_cron($a, $b) {
325 // Only process items older than an hour in cron. This is because
326 // we want to give mailstream_post_remote_hook a fair chance to
327 // send the email itself before cron jumps in. Only if
328 // mailstream_post_remote_hook fails for some reason will this get
329 // used, and in that case it's worth holding off a bit anyway.
330 $ms_item_ids = q("SELECT `mailstream_item`.`message-id`, `mailstream_item`.`uri`, `item`.`id` FROM `mailstream_item` JOIN `item` ON (`mailstream_item`.`uid` = `item`.`uid` AND `mailstream_item`.`uri` = `item`.`uri` AND `mailstream_item`.`contact-id` = `item`.`contact-id`) WHERE `mailstream_item`.`completed` IS NULL AND `mailstream_item`.`created` < DATE_SUB(NOW(), INTERVAL 1 HOUR) AND `item`.`visible` = 1 ORDER BY `mailstream_item`.`created` LIMIT 100");
331 logger('mailstream_cron processing ' . count($ms_item_ids) . ' items', LOGGER_DEBUG);
332 foreach ($ms_item_ids as $ms_item_id) {
333 if (!$ms_item_id['message-id'] || !strlen($ms_item_id['message-id'])) {
334 logger('mailstream_cron: Item ' . $ms_item_id['id'] . ' URI ' . $ms_item_id['uri'] . ' has no message-id', LOGGER_NORMAL);
336 $items = q('SELECT * FROM `item` WHERE `id` = %d', $ms_item_id['id']);
338 $users = q("SELECT * FROM `user` WHERE `uid` = %d", intval($item['uid']));
340 if ($user && $item) {
341 mailstream_send($a, $ms_item_id['message-id'], $item, $user);
344 logger('mailstream_cron: Unable to find item ' . $ms_item_id['id'], LOGGER_NORMAL);
345 q("UPDATE `mailstream_item` SET `completed` = now() WHERE `message-id` = %d", intval($ms_item['message-id']));
351 function mailstream_addon_settings(&$a,&$s) {
352 $enabled = PConfig::get(local_user(), 'mailstream', 'enabled');
353 $address = PConfig::get(local_user(), 'mailstream', 'address');
354 $nolikes = PConfig::get(local_user(), 'mailstream', 'nolikes');
355 $attachimg= PConfig::get(local_user(), 'mailstream', 'attachimg');
356 $template = get_markup_template('settings.tpl', 'addon/mailstream/');
357 $s .= replace_macros($template, [
359 'mailstream_enabled',
363 'mailstream_address',
364 L10n::t('Email Address'),
366 L10n::t("Leave blank to use your account email address")],
368 'mailstream_nolikes',
369 L10n::t('Exclude Likes'),
371 L10n::t("Check this to omit mailing \"Like\" notifications")],
373 'mailstream_attachimg',
374 L10n::t('Attach Images'),
376 L10n::t("Download images in posts and attach them to the email. Useful for reading email while offline.")],
377 '$title' => L10n::t('Mail Stream Settings'),
378 '$submit' => L10n::t('Save Settings')]);
381 function mailstream_addon_settings_post($a,$post) {
382 if ($_POST['mailstream_address'] != "") {
383 PConfig::set(local_user(), 'mailstream', 'address', $_POST['mailstream_address']);
386 PConfig::delete(local_user(), 'mailstream', 'address');
388 if ($_POST['mailstream_nolikes']) {
389 PConfig::set(local_user(), 'mailstream', 'nolikes', $_POST['mailstream_enabled']);
392 PConfig::delete(local_user(), 'mailstream', 'nolikes');
394 if ($_POST['mailstream_enabled']) {
395 PConfig::set(local_user(), 'mailstream', 'enabled', $_POST['mailstream_enabled']);
398 PConfig::delete(local_user(), 'mailstream', 'enabled');
400 if ($_POST['mailstream_attachimg']) {
401 PConfig::set(local_user(), 'mailstream', 'attachimg', $_POST['mailstream_attachimg']);
404 PConfig::delete(local_user(), 'mailstream', 'attachimg');
408 function mailstream_tidy() {
409 $r = q("SELECT id FROM mailstream_item WHERE completed IS NOT NULL AND completed < DATE_SUB(NOW(), INTERVAL 1 YEAR)");
410 foreach ($r as $rr) {
411 q('DELETE FROM mailstream_item WHERE id = %d', intval($rr['id']));
413 logger('mailstream_tidy: deleted ' . count($r) . ' old items', LOGGER_DEBUG);