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\Core\Config;
10 use Friendica\Core\PConfig;
11 use Friendica\Database\DBM;
13 function mailstream_install() {
14 register_hook('plugin_settings', 'addon/mailstream/mailstream.php', 'mailstream_plugin_settings');
15 register_hook('plugin_settings_post', 'addon/mailstream/mailstream.php', 'mailstream_plugin_settings_post');
16 register_hook('post_local_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
17 register_hook('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
18 register_hook('cron', 'addon/mailstream/mailstream.php', 'mailstream_cron');
20 if (Config::get('mailstream', 'dbversion') == '0.1') {
21 q('ALTER TABLE `mailstream_item` DROP INDEX `uid`');
22 q('ALTER TABLE `mailstream_item` DROP INDEX `contact-id`');
23 q('ALTER TABLE `mailstream_item` DROP INDEX `plink`');
24 q('ALTER TABLE `mailstream_item` CHANGE `plink` `uri` char(255) NOT NULL');
25 Config::set('mailstream', 'dbversion', '0.2');
27 if (Config::get('mailstream', 'dbversion') == '0.2') {
28 q('DELETE FROM `pconfig` WHERE `cat` = "mailstream" AND `k` = "delay"');
29 Config::set('mailstream', 'dbversion', '0.3');
31 if (Config::get('mailstream', 'dbversion') == '0.3') {
32 q('ALTER TABLE `mailstream_item` CHANGE `created` `created` timestamp NOT NULL DEFAULT now()');
33 q('ALTER TABLE `mailstream_item` CHANGE `completed` `completed` timestamp NULL DEFAULT NULL');
34 Config::set('mailstream', 'dbversion', '0.4');
36 if (Config::get('mailstream', 'dbversion') == '0.4') {
37 q('ALTER TABLE `mailstream_item` CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin');
38 Config::set('mailstream', 'dbversion', '0.5');
40 if (Config::get('mailstream', 'dbversion') == '0.5') {
41 Config::set('mailstream', 'dbversion', '1.0');
44 if (Config::get('retriever', 'dbversion') != '1.0') {
45 $schema = file_get_contents(dirname(__file__).'/database.sql');
46 $arr = explode(';', $schema);
47 foreach ($arr as $a) {
50 Config::set('mailstream', 'dbversion', '1.0');
54 function mailstream_uninstall() {
55 unregister_hook('plugin_settings', 'addon/mailstream/mailstream.php', 'mailstream_plugin_settings');
56 unregister_hook('plugin_settings_post', 'addon/mailstream/mailstream.php', 'mailstream_plugin_settings_post');
57 unregister_hook('post_local', 'addon/mailstream/mailstream.php', 'mailstream_post_local_hook');
58 unregister_hook('post_remote', 'addon/mailstream/mailstream.php', 'mailstream_post_remote_hook');
59 unregister_hook('post_local_end', 'addon/mailstream/mailstream.php', 'mailstream_post_local_hook');
60 unregister_hook('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_remote_hook');
61 unregister_hook('post_local_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
62 unregister_hook('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
63 unregister_hook('cron', 'addon/mailstream/mailstream.php', 'mailstream_cron');
64 unregister_hook('incoming_mail', 'addon/mailstream/mailstream.php', 'mailstream_incoming_mail');
67 function mailstream_module() {}
69 function mailstream_plugin_admin(&$a,&$o) {
70 $frommail = Config::get('mailstream', 'frommail');
71 $template = get_markup_template('admin.tpl', 'addon/mailstream/');
72 $config = array('frommail',
75 t('Email address that stream items will appear to be from.'));
76 $o .= replace_macros($template, array(
77 '$frommail' => $config,
78 '$submit' => t('Save Settings')));
81 function mailstream_plugin_admin_post ($a) {
82 if (x($_POST, 'frommail')) {
83 Config::set('mailstream', 'frommail', $_POST['frommail']);
87 function mailstream_generate_id($a, $uri) {
88 // http://www.jwz.org/doc/mid.html
89 $host = $a->get_hostname();
90 $resource = hash('md5', $uri);
91 $message_id = "<" . $resource . "@" . $host . ">";
92 logger('mailstream: Generated message ID ' . $message_id . ' for URI ' . $uri, LOGGER_DEBUG);
96 function mailstream_post_hook(&$a, &$item) {
97 if (!PConfig::get($item['uid'], 'mailstream', 'enabled')) {
103 if (!$item['contact-id']) {
109 if (PConfig::get($item['uid'], 'mailstream', 'nolikes')) {
110 if ($item['verb'] == ACTIVITY_LIKE) {
115 $message_id = mailstream_generate_id($a, $item['uri']);
116 q("INSERT INTO `mailstream_item` (`uid`, `contact-id`, `uri`, `message-id`) " .
117 "VALUES (%d, '%s', '%s', '%s')", intval($item['uid']),
118 intval($item['contact-id']), dbesc($item['uri']), dbesc($message_id));
119 $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']));
120 if (count($r) != 1) {
121 logger('mailstream_post_remote_hook: Unexpected number of items returned from mailstream_item', LOGGER_NORMAL);
125 logger('mailstream_post_remote_hook: created mailstream_item '
126 . $ms_item['id'] . ' for item ' . $item['uri'] . ' '
127 . $item['uid'] . ' ' . $item['contact-id'], LOGGER_DATA);
128 $user = mailstream_get_user($item['uid']);
130 logger('mailstream_post_remote_hook: no user ' . $item['uid'], LOGGER_NORMAL);
133 mailstream_send($a, $ms_item['message-id'], $item, $user);
136 function mailstream_get_user($uid) {
137 $r = q('SELECT * FROM `user` WHERE `uid` = %d', intval($uid));
138 if (count($r) != 1) {
139 logger('mailstream_post_remote_hook: Unexpected number of users returned', LOGGER_NORMAL);
145 function mailstream_do_images($a, &$item, &$attachments) {
146 if (!PConfig::get($item['uid'], 'mailstream', 'attachimg')) {
149 $attachments = array();
150 $baseurl = $a->get_baseurl();
151 preg_match_all("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", $item["body"], $matches1);
152 preg_match_all("/\[img\](.*?)\[\/img\]/ism", $item["body"], $matches2);
153 foreach (array_merge($matches1[3], $matches2[1]) as $url) {
155 $cookiejar = tempnam(get_temppath(), 'cookiejar-mailstream-');
156 $attachments[$url] = array(
157 'data' => fetch_url($url, true, $redirects, 0, Null, $cookiejar),
158 'guid' => hash("crc32", $url),
159 'filename' => basename($url),
160 'type' => $a->get_curl_content_type());
161 if (strlen($attachments[$url]['data'])) {
162 $item['body'] = str_replace($url, 'cid:' . $attachments[$url]['guid'], $item['body']);
169 function mailstream_sender($item) {
170 $r = q('SELECT * FROM `contact` WHERE `id` = %d', $item['contact-id']);
171 if (DBM::is_result($r)) {
173 if ($contact['name'] != $item['author-name']) {
174 return $contact['name'] . ' - ' . $item['author-name'];
177 return $item['author-name'];
180 function mailstream_decode_subject($subject) {
181 $html = bbcode($subject);
185 $notags = strip_tags($html);
189 $noentity = html_entity_decode($notags);
193 $nocodes = preg_replace_callback("/(&#[0-9]+;)/", function($m) { return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES"); }, $noentity);
197 $trimmed = trim($nocodes);
204 function mailstream_subject($item) {
205 if ($item['title']) {
206 return mailstream_decode_subject($item['title']);
208 $parent = $item['thr-parent'];
209 // Don't look more than 100 levels deep for a subject, in case of loops
210 for ($i = 0; ($i < 100) && $parent; $i++) {
211 $r = q("SELECT `thr-parent`, `title` FROM `item` WHERE `uri` = '%s'", dbesc($parent));
212 if (!DBM::is_result($r)) {
215 if ($r[0]['thr-parent'] === $parent) {
218 if ($r[0]['title']) {
219 return t('Re:') . ' ' . mailstream_decode_subject($r[0]['title']);
221 $parent = $r[0]['thr-parent'];
223 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
224 intval($item['contact-id']), intval($item['uid']));
226 if ($contact['network'] === 'dfrn') {
227 return t("Friendica post");
229 if ($contact['network'] === 'dspr') {
230 return t("Diaspora post");
232 if ($contact['network'] === 'face') {
233 $text = mailstream_decode_subject($item['body']);
234 // For some reason these do show up in Facebook
235 $text = preg_replace('/\xA0$/', '', $text);
236 $subject = (strlen($text) > 150) ? (substr($text, 0, 140) . '...') : $text;
237 return preg_replace('/\\s+/', ' ', $subject);
239 if ($contact['network'] === 'feed') {
240 return t("Feed item");
242 if ($contact['network'] === 'mail') {
245 return t("Friendica Item");
248 function mailstream_send($a, $message_id, $item, $user) {
249 if (!$item['visible']) {
255 require_once(dirname(__file__).'/phpmailer/class.phpmailer.php');
256 require_once('include/bbcode.php');
257 $attachments = array();
258 mailstream_do_images($a, $item, $attachments);
259 $frommail = Config::get('mailstream', 'frommail');
260 if ($frommail == "") {
261 $frommail = 'friendica@localhost.local';
263 $address = PConfig::get($item['uid'], 'mailstream', 'address');
265 $address = $user['email'];
267 $mail = new PHPmailer;
269 $mail->XMailer = 'Friendica Mailstream Plugin';
270 $mail->SetFrom($frommail, mailstream_sender($item));
271 $mail->AddAddress($address, $user['username']);
272 $mail->MessageID = $message_id;
273 $mail->Subject = mailstream_subject($item);
274 if ($item['thr-parent'] != $item['uri']) {
275 $mail->addCustomHeader('In-Reply-To: ' . mailstream_generate_id($a, $item['thr-parent']));
277 $mail->addCustomHeader('X-Friendica-Mailstream-URI: ' . $item['uri']);
278 $mail->addCustomHeader('X-Friendica-Mailstream-Plink: ' . $item['plink']);
279 $encoding = 'base64';
280 foreach ($attachments as $url => $image) {
281 $mail->AddStringEmbeddedImage($image['data'], $image['guid'], $image['filename'], $encoding, $image['type']);
284 $mail->CharSet = 'utf-8';
285 $template = get_markup_template('mail.tpl', 'addon/mailstream/');
286 $item['body'] = bbcode($item['body']);
287 $item['url'] = $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $item['id'];
288 $mail->Body = replace_macros($template, array(
289 '$upstream' => t('Upstream'),
290 '$local' => t('Local'),
292 mailstream_html_wrap($mail->Body);
293 if (!$mail->Send()) {
294 throw new Exception($mail->ErrorInfo);
296 logger('mailstream_send sent message ' . $mail->MessageID . ' ' . $mail->Subject, LOGGER_DEBUG);
297 } catch (phpmailerException $e) {
298 logger('mailstream_send PHPMailer exception sending message ' . $message_id . ': ' . $e->errorMessage(), LOGGER_NORMAL);
299 } catch (Exception $e) {
300 logger('mailstream_send exception sending message ' . $message_id . ': ' . $e->getMessage(), LOGGER_NORMAL);
302 // In case of failure, still set the item to completed. Otherwise
303 // we'll just try to send it over and over again and it'll fail
305 q('UPDATE `mailstream_item` SET `completed` = now() WHERE `message-id` = "%s"', dbesc($message_id));
309 * Email tends to break if you send excessively long lines. To make
310 * bbcode's output suitable for transmission, we try to break things
311 * up so that lines are about 200 characters.
313 function mailstream_html_wrap(&$text)
315 $lines = str_split($text, 200);
316 for ($i = 0; $i < count($lines); $i++) {
317 $lines[$i] = preg_replace('/ /', "\n", $lines[$i], 1);
319 $text = implode($lines);
322 function mailstream_cron($a, $b) {
323 // Only process items older than an hour in cron. This is because
324 // we want to give mailstream_post_remote_hook a fair chance to
325 // send the email itself before cron jumps in. Only if
326 // mailstream_post_remote_hook fails for some reason will this get
327 // used, and in that case it's worth holding off a bit anyway.
328 $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");
329 logger('mailstream_cron processing ' . count($ms_item_ids) . ' items', LOGGER_DEBUG);
330 foreach ($ms_item_ids as $ms_item_id) {
331 if (!$ms_item_id['message-id'] || !strlen($ms_item_id['message-id'])) {
332 logger('mailstream_cron: Item ' . $ms_item_id['id'] . ' URI ' . $ms_item_id['uri'] . ' has no message-id', LOGGER_NORMAL);
334 $items = q('SELECT * FROM `item` WHERE `id` = %d', $ms_item_id['id']);
336 $users = q("SELECT * FROM `user` WHERE `uid` = %d", intval($item['uid']));
338 if ($user && $item) {
339 mailstream_send($a, $ms_item_id['message-id'], $item, $user);
342 logger('mailstream_cron: Unable to find item ' . $ms_item_id['id'], LOGGER_NORMAL);
343 q("UPDATE `mailstream_item` SET `completed` = now() WHERE `message-id` = %d", intval($ms_item['message-id']));
349 function mailstream_plugin_settings(&$a,&$s) {
350 $enabled = PConfig::get(local_user(), 'mailstream', 'enabled');
351 $address = PConfig::get(local_user(), 'mailstream', 'address');
352 $nolikes = PConfig::get(local_user(), 'mailstream', 'nolikes');
353 $attachimg= PConfig::get(local_user(), 'mailstream', 'attachimg');
354 $template = get_markup_template('settings.tpl', 'addon/mailstream/');
355 $s .= replace_macros($template, array(
357 'mailstream_enabled',
361 'mailstream_address',
364 t("Leave blank to use your account email address")),
366 'mailstream_nolikes',
369 t("Check this to omit mailing \"Like\" notifications")),
370 '$attachimg' => array(
371 'mailstream_attachimg',
374 t("Download images in posts and attach them to the email. Useful for reading email while offline.")),
375 '$title' => t('Mail Stream Settings'),
376 '$submit' => t('Save Settings')));
379 function mailstream_plugin_settings_post($a,$post) {
380 if ($_POST['mailstream_address'] != "") {
381 PConfig::set(local_user(), 'mailstream', 'address', $_POST['mailstream_address']);
384 del_pconfig(local_user(), 'mailstream', 'address');
386 if ($_POST['mailstream_nolikes']) {
387 PConfig::set(local_user(), 'mailstream', 'nolikes', $_POST['mailstream_enabled']);
390 del_pconfig(local_user(), 'mailstream', 'nolikes');
392 if ($_POST['mailstream_enabled']) {
393 PConfig::set(local_user(), 'mailstream', 'enabled', $_POST['mailstream_enabled']);
396 del_pconfig(local_user(), 'mailstream', 'enabled');
398 if ($_POST['mailstream_attachimg']) {
399 PConfig::set(local_user(), 'mailstream', 'attachimg', $_POST['mailstream_attachimg']);
402 del_pconfig(local_user(), 'mailstream', 'attachimg');
406 function mailstream_tidy() {
407 $r = q("SELECT id FROM mailstream_item WHERE completed IS NOT NULL AND completed < DATE_SUB(NOW(), INTERVAL 1 YEAR)");
408 foreach ($r as $rr) {
409 q('DELETE FROM mailstream_item WHERE id = %d', intval($rr['id']));
411 logger('mailstream_tidy: deleted ' . count($r) . ' old items', LOGGER_DEBUG);