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;
14 function mailstream_install() {
15 Addon::registerHook('addon_settings', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings');
16 Addon::registerHook('addon_settings_post', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings_post');
17 Addon::registerHook('post_local_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
18 Addon::registerHook('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
19 Addon::registerHook('cron', 'addon/mailstream/mailstream.php', 'mailstream_cron');
21 if (Config::get('mailstream', 'dbversion') == '0.1') {
22 q('ALTER TABLE `mailstream_item` DROP INDEX `uid`');
23 q('ALTER TABLE `mailstream_item` DROP INDEX `contact-id`');
24 q('ALTER TABLE `mailstream_item` DROP INDEX `plink`');
25 q('ALTER TABLE `mailstream_item` CHANGE `plink` `uri` char(255) NOT NULL');
26 Config::set('mailstream', 'dbversion', '0.2');
28 if (Config::get('mailstream', 'dbversion') == '0.2') {
29 q('DELETE FROM `pconfig` WHERE `cat` = "mailstream" AND `k` = "delay"');
30 Config::set('mailstream', 'dbversion', '0.3');
32 if (Config::get('mailstream', 'dbversion') == '0.3') {
33 q('ALTER TABLE `mailstream_item` CHANGE `created` `created` timestamp NOT NULL DEFAULT now()');
34 q('ALTER TABLE `mailstream_item` CHANGE `completed` `completed` timestamp NULL DEFAULT NULL');
35 Config::set('mailstream', 'dbversion', '0.4');
37 if (Config::get('mailstream', 'dbversion') == '0.4') {
38 q('ALTER TABLE `mailstream_item` CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin');
39 Config::set('mailstream', 'dbversion', '0.5');
41 if (Config::get('mailstream', 'dbversion') == '0.5') {
42 Config::set('mailstream', 'dbversion', '1.0');
45 if (Config::get('retriever', 'dbversion') != '1.0') {
46 $schema = file_get_contents(dirname(__file__).'/database.sql');
47 $arr = explode(';', $schema);
48 foreach ($arr as $a) {
51 Config::set('mailstream', 'dbversion', '1.0');
55 function mailstream_uninstall() {
56 Addon::unregisterHook('addon_settings', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings');
57 Addon::unregisterHook('addon_settings_post', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings_post');
58 Addon::unregisterHook('post_local', 'addon/mailstream/mailstream.php', 'mailstream_post_local_hook');
59 Addon::unregisterHook('post_remote', 'addon/mailstream/mailstream.php', 'mailstream_post_remote_hook');
60 Addon::unregisterHook('post_local_end', 'addon/mailstream/mailstream.php', 'mailstream_post_local_hook');
61 Addon::unregisterHook('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_remote_hook');
62 Addon::unregisterHook('post_local_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
63 Addon::unregisterHook('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
64 Addon::unregisterHook('cron', 'addon/mailstream/mailstream.php', 'mailstream_cron');
65 Addon::unregisterHook('incoming_mail', 'addon/mailstream/mailstream.php', 'mailstream_incoming_mail');
68 function mailstream_module() {}
70 function mailstream_addon_admin(&$a,&$o) {
71 $frommail = Config::get('mailstream', 'frommail');
72 $template = get_markup_template('admin.tpl', 'addon/mailstream/');
73 $config = ['frommail',
74 L10n::t('From Address'),
76 L10n::t('Email address that stream items will appear to be from.')];
77 $o .= replace_macros($template, [
78 '$frommail' => $config,
79 '$submit' => L10n::t('Save Settings')]);
82 function mailstream_addon_admin_post ($a) {
83 if (x($_POST, 'frommail')) {
84 Config::set('mailstream', 'frommail', $_POST['frommail']);
88 function mailstream_generate_id($a, $uri) {
89 // http://www.jwz.org/doc/mid.html
90 $host = $a->get_hostname();
91 $resource = hash('md5', $uri);
92 $message_id = "<" . $resource . "@" . $host . ">";
93 logger('mailstream: Generated message ID ' . $message_id . ' for URI ' . $uri, LOGGER_DEBUG);
97 function mailstream_post_hook(&$a, &$item) {
98 if (!PConfig::get($item['uid'], 'mailstream', 'enabled')) {
104 if (!$item['contact-id']) {
110 if (PConfig::get($item['uid'], 'mailstream', 'nolikes')) {
111 if ($item['verb'] == ACTIVITY_LIKE) {
116 $message_id = mailstream_generate_id($a, $item['uri']);
117 q("INSERT INTO `mailstream_item` (`uid`, `contact-id`, `uri`, `message-id`) " .
118 "VALUES (%d, '%s', '%s', '%s')", intval($item['uid']),
119 intval($item['contact-id']), dbesc($item['uri']), dbesc($message_id));
120 $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']));
121 if (count($r) != 1) {
122 logger('mailstream_post_remote_hook: Unexpected number of items returned from mailstream_item', LOGGER_NORMAL);
126 logger('mailstream_post_remote_hook: created mailstream_item '
127 . $ms_item['id'] . ' for item ' . $item['uri'] . ' '
128 . $item['uid'] . ' ' . $item['contact-id'], LOGGER_DATA);
129 $user = mailstream_get_user($item['uid']);
131 logger('mailstream_post_remote_hook: no user ' . $item['uid'], LOGGER_NORMAL);
134 mailstream_send($a, $ms_item['message-id'], $item, $user);
137 function mailstream_get_user($uid) {
138 $r = q('SELECT * FROM `user` WHERE `uid` = %d', intval($uid));
139 if (count($r) != 1) {
140 logger('mailstream_post_remote_hook: Unexpected number of users returned', LOGGER_NORMAL);
146 function mailstream_do_images($a, &$item, &$attachments) {
147 if (!PConfig::get($item['uid'], 'mailstream', 'attachimg')) {
151 $baseurl = $a->get_baseurl();
152 preg_match_all("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", $item["body"], $matches1);
153 preg_match_all("/\[img\](.*?)\[\/img\]/ism", $item["body"], $matches2);
154 foreach (array_merge($matches1[3], $matches2[1]) as $url) {
156 $cookiejar = tempnam(get_temppath(), 'cookiejar-mailstream-');
157 $attachments[$url] = [
158 'data' => fetch_url($url, true, $redirects, 0, Null, $cookiejar),
159 'guid' => hash("crc32", $url),
160 'filename' => basename($url),
161 'type' => $a->get_curl_content_type()];
162 if (strlen($attachments[$url]['data'])) {
163 $item['body'] = str_replace($url, 'cid:' . $attachments[$url]['guid'], $item['body']);
170 function mailstream_sender($item) {
171 $r = q('SELECT * FROM `contact` WHERE `id` = %d', $item['contact-id']);
172 if (DBM::is_result($r)) {
174 if ($contact['name'] != $item['author-name']) {
175 return $contact['name'] . ' - ' . $item['author-name'];
178 return $item['author-name'];
181 function mailstream_decode_subject($subject) {
182 $html = bbcode($subject);
186 $notags = strip_tags($html);
190 $noentity = html_entity_decode($notags);
194 $nocodes = preg_replace_callback("/(&#[0-9]+;)/", function($m) { return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES"); }, $noentity);
198 $trimmed = trim($nocodes);
205 function mailstream_subject($item) {
206 if ($item['title']) {
207 return mailstream_decode_subject($item['title']);
209 $parent = $item['thr-parent'];
210 // Don't look more than 100 levels deep for a subject, in case of loops
211 for ($i = 0; ($i < 100) && $parent; $i++) {
212 $r = q("SELECT `thr-parent`, `title` FROM `item` WHERE `uri` = '%s'", dbesc($parent));
213 if (!DBM::is_result($r)) {
216 if ($r[0]['thr-parent'] === $parent) {
219 if ($r[0]['title']) {
220 return L10n::t('Re:') . ' ' . mailstream_decode_subject($r[0]['title']);
222 $parent = $r[0]['thr-parent'];
224 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
225 intval($item['contact-id']), intval($item['uid']));
227 if ($contact['network'] === 'dfrn') {
228 return L10n::t("Friendica post");
230 if ($contact['network'] === 'dspr') {
231 return L10n::t("Diaspora post");
233 if ($contact['network'] === 'face') {
234 $text = mailstream_decode_subject($item['body']);
235 // For some reason these do show up in Facebook
236 $text = preg_replace('/\xA0$/', '', $text);
237 $subject = (strlen($text) > 150) ? (substr($text, 0, 140) . '...') : $text;
238 return preg_replace('/\\s+/', ' ', $subject);
240 if ($contact['network'] === 'feed') {
241 return L10n::t("Feed item");
243 if ($contact['network'] === 'mail') {
244 return L10n::t("Email");
246 return L10n::t("Friendica Item");
249 function mailstream_send($a, $message_id, $item, $user) {
250 if (!$item['visible']) {
256 require_once(dirname(__file__).'/phpmailer/class.phpmailer.php');
257 require_once('include/bbcode.php');
259 mailstream_do_images($a, $item, $attachments);
260 $frommail = Config::get('mailstream', 'frommail');
261 if ($frommail == "") {
262 $frommail = 'friendica@localhost.local';
264 $address = PConfig::get($item['uid'], 'mailstream', 'address');
266 $address = $user['email'];
268 $mail = new PHPmailer;
270 $mail->XMailer = 'Friendica Mailstream Addon';
271 $mail->SetFrom($frommail, mailstream_sender($item));
272 $mail->AddAddress($address, $user['username']);
273 $mail->MessageID = $message_id;
274 $mail->Subject = mailstream_subject($item);
275 if ($item['thr-parent'] != $item['uri']) {
276 $mail->addCustomHeader('In-Reply-To: ' . mailstream_generate_id($a, $item['thr-parent']));
278 $mail->addCustomHeader('X-Friendica-Mailstream-URI: ' . $item['uri']);
279 $mail->addCustomHeader('X-Friendica-Mailstream-Plink: ' . $item['plink']);
280 $encoding = 'base64';
281 foreach ($attachments as $url => $image) {
282 $mail->AddStringEmbeddedImage($image['data'], $image['guid'], $image['filename'], $encoding, $image['type']);
285 $mail->CharSet = 'utf-8';
286 $template = get_markup_template('mail.tpl', 'addon/mailstream/');
287 $item['body'] = bbcode($item['body']);
288 $item['url'] = $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $item['id'];
289 $mail->Body = replace_macros($template, [
290 '$upstream' => L10n::t('Upstream'),
291 '$local' => L10n::t('Local'),
293 mailstream_html_wrap($mail->Body);
294 if (!$mail->Send()) {
295 throw new Exception($mail->ErrorInfo);
297 logger('mailstream_send sent message ' . $mail->MessageID . ' ' . $mail->Subject, LOGGER_DEBUG);
298 } catch (phpmailerException $e) {
299 logger('mailstream_send PHPMailer exception sending message ' . $message_id . ': ' . $e->errorMessage(), LOGGER_NORMAL);
300 } catch (Exception $e) {
301 logger('mailstream_send exception sending message ' . $message_id . ': ' . $e->getMessage(), LOGGER_NORMAL);
303 // In case of failure, still set the item to completed. Otherwise
304 // we'll just try to send it over and over again and it'll fail
306 q('UPDATE `mailstream_item` SET `completed` = now() WHERE `message-id` = "%s"', dbesc($message_id));
310 * Email tends to break if you send excessively long lines. To make
311 * bbcode's output suitable for transmission, we try to break things
312 * up so that lines are about 200 characters.
314 function mailstream_html_wrap(&$text)
316 $lines = str_split($text, 200);
317 for ($i = 0; $i < count($lines); $i++) {
318 $lines[$i] = preg_replace('/ /', "\n", $lines[$i], 1);
320 $text = implode($lines);
323 function mailstream_cron($a, $b) {
324 // Only process items older than an hour in cron. This is because
325 // we want to give mailstream_post_remote_hook a fair chance to
326 // send the email itself before cron jumps in. Only if
327 // mailstream_post_remote_hook fails for some reason will this get
328 // used, and in that case it's worth holding off a bit anyway.
329 $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");
330 logger('mailstream_cron processing ' . count($ms_item_ids) . ' items', LOGGER_DEBUG);
331 foreach ($ms_item_ids as $ms_item_id) {
332 if (!$ms_item_id['message-id'] || !strlen($ms_item_id['message-id'])) {
333 logger('mailstream_cron: Item ' . $ms_item_id['id'] . ' URI ' . $ms_item_id['uri'] . ' has no message-id', LOGGER_NORMAL);
335 $items = q('SELECT * FROM `item` WHERE `id` = %d', $ms_item_id['id']);
337 $users = q("SELECT * FROM `user` WHERE `uid` = %d", intval($item['uid']));
339 if ($user && $item) {
340 mailstream_send($a, $ms_item_id['message-id'], $item, $user);
343 logger('mailstream_cron: Unable to find item ' . $ms_item_id['id'], LOGGER_NORMAL);
344 q("UPDATE `mailstream_item` SET `completed` = now() WHERE `message-id` = %d", intval($ms_item['message-id']));
350 function mailstream_addon_settings(&$a,&$s) {
351 $enabled = PConfig::get(local_user(), 'mailstream', 'enabled');
352 $address = PConfig::get(local_user(), 'mailstream', 'address');
353 $nolikes = PConfig::get(local_user(), 'mailstream', 'nolikes');
354 $attachimg= PConfig::get(local_user(), 'mailstream', 'attachimg');
355 $template = get_markup_template('settings.tpl', 'addon/mailstream/');
356 $s .= replace_macros($template, [
358 'mailstream_enabled',
362 'mailstream_address',
363 L10n::t('Email Address'),
365 L10n::t("Leave blank to use your account email address")],
367 'mailstream_nolikes',
368 L10n::t('Exclude Likes'),
370 L10n::t("Check this to omit mailing \"Like\" notifications")],
372 'mailstream_attachimg',
373 L10n::t('Attach Images'),
375 L10n::t("Download images in posts and attach them to the email. Useful for reading email while offline.")],
376 '$title' => L10n::t('Mail Stream Settings'),
377 '$submit' => L10n::t('Save Settings')]);
380 function mailstream_addon_settings_post($a,$post) {
381 if ($_POST['mailstream_address'] != "") {
382 PConfig::set(local_user(), 'mailstream', 'address', $_POST['mailstream_address']);
385 PConfig::delete(local_user(), 'mailstream', 'address');
387 if ($_POST['mailstream_nolikes']) {
388 PConfig::set(local_user(), 'mailstream', 'nolikes', $_POST['mailstream_enabled']);
391 PConfig::delete(local_user(), 'mailstream', 'nolikes');
393 if ($_POST['mailstream_enabled']) {
394 PConfig::set(local_user(), 'mailstream', 'enabled', $_POST['mailstream_enabled']);
397 PConfig::delete(local_user(), 'mailstream', 'enabled');
399 if ($_POST['mailstream_attachimg']) {
400 PConfig::set(local_user(), 'mailstream', 'attachimg', $_POST['mailstream_attachimg']);
403 PConfig::delete(local_user(), 'mailstream', 'attachimg');
407 function mailstream_tidy() {
408 $r = q("SELECT id FROM mailstream_item WHERE completed IS NOT NULL AND completed < DATE_SUB(NOW(), INTERVAL 1 YEAR)");
409 foreach ($r as $rr) {
410 q('DELETE FROM mailstream_item WHERE id = %d', intval($rr['id']));
412 logger('mailstream_tidy: deleted ' . count($r) . ' old items', LOGGER_DEBUG);