4 * Description: Mail all items coming into your network feed to an email address
6 * Author: Matthew Exon <http://mat.exon.name>
9 function mailstream_install() {
10 register_hook('plugin_settings', 'addon/mailstream/mailstream.php', 'mailstream_plugin_settings');
11 register_hook('plugin_settings_post', 'addon/mailstream/mailstream.php', 'mailstream_plugin_settings_post');
12 register_hook('post_local_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
13 register_hook('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
14 register_hook('cron', 'addon/mailstream/mailstream.php', 'mailstream_cron');
16 if (get_config('mailstream', 'dbversion') == '0.1') {
17 q('ALTER TABLE `mailstream_item` DROP INDEX `uid`');
18 q('ALTER TABLE `mailstream_item` DROP INDEX `contact-id`');
19 q('ALTER TABLE `mailstream_item` DROP INDEX `plink`');
20 q('ALTER TABLE `mailstream_item` CHANGE `plink` `uri` char(255) NOT NULL');
21 set_config('mailstream', 'dbversion', '0.2');
23 if (get_config('mailstream', 'dbversion') == '0.2') {
24 q('DELETE FROM `pconfig` WHERE `cat` = "mailstream" AND `k` = "delay"');
25 set_config('mailstream', 'dbversion', '0.3');
27 if (get_config('mailstream', 'dbversion') == '0.3') {
28 q('ALTER TABLE `mailstream_item` CHANGE `created` `created` timestamp NOT NULL DEFAULT now()');
29 q('ALTER TABLE `mailstream_item` CHANGE `completed` `completed` timestamp NULL DEFAULT NULL');
30 set_config('mailstream', 'dbversion', '0.4');
32 if (get_config('mailstream', 'dbversion') == '0.4') {
33 q('ALTER TABLE `mailstream_item` CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin');
34 set_config('mailstream', 'dbversion', '0.5');
36 if (get_config('mailstream', 'dbversion') == '0.5') {
37 set_config('mailstream', 'dbversion', '1.0');
40 if (get_config('retriever', 'dbversion') != '1.0') {
41 $schema = file_get_contents(dirname(__file__).'/database.sql');
42 $arr = explode(';', $schema);
43 foreach ($arr as $a) {
46 set_config('mailstream', 'dbversion', '1.0');
50 function mailstream_uninstall() {
51 unregister_hook('plugin_settings', 'addon/mailstream/mailstream.php', 'mailstream_plugin_settings');
52 unregister_hook('plugin_settings_post', 'addon/mailstream/mailstream.php', 'mailstream_plugin_settings_post');
53 unregister_hook('post_local', 'addon/mailstream/mailstream.php', 'mailstream_post_local_hook');
54 unregister_hook('post_remote', 'addon/mailstream/mailstream.php', 'mailstream_post_remote_hook');
55 unregister_hook('post_local_end', 'addon/mailstream/mailstream.php', 'mailstream_post_local_hook');
56 unregister_hook('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_remote_hook');
57 unregister_hook('post_local_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
58 unregister_hook('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
59 unregister_hook('cron', 'addon/mailstream/mailstream.php', 'mailstream_cron');
60 unregister_hook('incoming_mail', 'addon/mailstream/mailstream.php', 'mailstream_incoming_mail');
63 function mailstream_module() {}
65 function mailstream_plugin_admin(&$a,&$o) {
66 $frommail = get_config('mailstream', 'frommail');
67 $template = get_markup_template('admin.tpl', 'addon/mailstream/');
68 $config = array('frommail',
71 t('Email address that stream items will appear to be from.'));
72 $o .= replace_macros($template, array(
73 '$frommail' => $config,
74 '$submit' => t('Save Settings')));
77 function mailstream_plugin_admin_post ($a) {
78 if (x($_POST, 'frommail')) {
79 set_config('mailstream', 'frommail', $_POST['frommail']);
83 function mailstream_generate_id($a, $uri) {
84 // http://www.jwz.org/doc/mid.html
85 $host = $a->get_hostname();
86 $resource = hash('md5', $uri);
87 $message_id = "<" . $resource . "@" . $host . ">";
88 logger('mailstream: Generated message ID ' . $message_id . ' for URI ' . $uri, LOGGER_DEBUG);
92 function mailstream_post_hook(&$a, &$item) {
93 if (!get_pconfig($item['uid'], 'mailstream', 'enabled')) {
99 if (!$item['contact-id']) {
105 if (get_pconfig($item['uid'], 'mailstream', 'nolikes')) {
106 if ($item['verb'] == ACTIVITY_LIKE) {
111 $message_id = mailstream_generate_id($a, $item['uri']);
112 q("INSERT INTO `mailstream_item` (`uid`, `contact-id`, `uri`, `message-id`) " .
113 "VALUES (%d, '%s', '%s', '%s')", intval($item['uid']),
114 intval($item['contact-id']), dbesc($item['uri']), dbesc($message_id));
115 $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']));
116 if (count($r) != 1) {
117 logger('mailstream_post_remote_hook: Unexpected number of items returned from mailstream_item', LOGGER_NORMAL);
121 logger('mailstream_post_remote_hook: created mailstream_item '
122 . $ms_item['id'] . ' for item ' . $item['uri'] . ' '
123 . $item['uid'] . ' ' . $item['contact-id'], LOGGER_DATA);
124 $user = mailstream_get_user($item['uid']);
126 logger('mailstream_post_remote_hook: no user ' . $item['uid'], LOGGER_NORMAL);
129 mailstream_send($a, $ms_item['message-id'], $item, $user);
132 function mailstream_get_user($uid) {
133 $r = q('SELECT * FROM `user` WHERE `uid` = %d', intval($uid));
134 if (count($r) != 1) {
135 logger('mailstream_post_remote_hook: Unexpected number of users returned', LOGGER_NORMAL);
141 function mailstream_do_images($a, &$item, &$attachments) {
142 if (!get_pconfig($item['uid'], 'mailstream', 'attachimg')) {
145 $attachments = array();
146 $baseurl = $a->get_baseurl();
147 preg_match_all("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", $item["body"], $matches1);
148 preg_match_all("/\[img\](.*?)\[\/img\]/ism", $item["body"], $matches2);
149 foreach (array_merge($matches1[3], $matches2[1]) as $url) {
151 $cookiejar = tempnam(get_temppath(), 'cookiejar-mailstream-');
152 $attachments[$url] = array(
153 'data' => fetch_url($url, true, $redirects, 0, Null, $cookiejar),
154 'guid' => hash("crc32", $url),
155 'filename' => basename($url),
156 'type' => $a->get_curl_content_type());
157 if (strlen($attachments[$url]['data'])) {
158 $item['body'] = str_replace($url, 'cid:' . $attachments[$url]['guid'], $item['body']);
165 function mailstream_sender($item) {
166 $r = q('SELECT * FROM `contact` WHERE `id` = %d', $item['contact-id']);
167 if (dbm::is_result($r)) {
169 if ($contact['name'] != $item['author-name']) {
170 return $contact['name'] . ' - ' . $item['author-name'];
173 return $item['author-name'];
176 function mailstream_decode_subject($subject) {
177 $html = bbcode($subject);
181 $notags = strip_tags($html);
185 $noentity = html_entity_decode($notags);
189 $nocodes = preg_replace_callback("/(&#[0-9]+;)/", function($m) { return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES"); }, $noentity);
193 $trimmed = trim($nocodes);
200 function mailstream_subject($item) {
201 if ($item['title']) {
202 return mailstream_decode_subject($item['title']);
204 $parent = $item['thr-parent'];
205 // Don't look more than 100 levels deep for a subject, in case of loops
206 for ($i = 0; ($i < 100) && $parent; $i++) {
207 $r = q("SELECT `thr-parent`, `title` FROM `item` WHERE `uri` = '%s'", dbesc($parent));
208 if (!dbm::is_result($r)) {
211 if ($r[0]['thr-parent'] === $parent) {
214 if ($r[0]['title']) {
215 return t('Re:') . ' ' . mailstream_decode_subject($r[0]['title']);
217 $parent = $r[0]['thr-parent'];
219 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
220 intval($item['contact-id']), intval($item['uid']));
222 if ($contact['network'] === 'dfrn') {
223 return t("Friendica post");
225 if ($contact['network'] === 'dspr') {
226 return t("Diaspora post");
228 if ($contact['network'] === 'face') {
229 $text = mailstream_decode_subject($item['body']);
230 // For some reason these do show up in Facebook
231 $text = preg_replace('/\xA0$/', '', $text);
232 $subject = (strlen($text) > 150) ? (substr($text, 0, 140) . '...') : $text;
233 return preg_replace('/\\s+/', ' ', $subject);
235 if ($contact['network'] === 'feed') {
236 return t("Feed item");
238 if ($contact['network'] === 'mail') {
241 return t("Friendica Item");
244 function mailstream_send($a, $message_id, $item, $user) {
245 if (!$item['visible']) {
251 require_once(dirname(__file__).'/phpmailer/class.phpmailer.php');
252 require_once('include/bbcode.php');
253 $attachments = array();
254 mailstream_do_images($a, $item, $attachments);
255 $frommail = get_config('mailstream', 'frommail');
256 if ($frommail == "") {
257 $frommail = 'friendica@localhost.local';
259 $address = get_pconfig($item['uid'], 'mailstream', 'address');
261 $address = $user['email'];
263 $mail = new PHPmailer;
265 $mail->XMailer = 'Friendica Mailstream Plugin';
266 $mail->SetFrom($frommail, mailstream_sender($item));
267 $mail->AddAddress($address, $user['username']);
268 $mail->MessageID = $message_id;
269 $mail->Subject = mailstream_subject($item);
270 if ($item['thr-parent'] != $item['uri']) {
271 $mail->addCustomHeader('In-Reply-To: ' . mailstream_generate_id($a, $item['thr-parent']));
273 $mail->addCustomHeader('X-Friendica-Mailstream-URI: ' . $item['uri']);
274 $mail->addCustomHeader('X-Friendica-Mailstream-Plink: ' . $item['plink']);
275 $encoding = 'base64';
276 foreach ($attachments as $url => $image) {
277 $mail->AddStringEmbeddedImage($image['data'], $image['guid'], $image['filename'], $encoding, $image['type']);
280 $mail->CharSet = 'utf-8';
281 $template = get_markup_template('mail.tpl', 'addon/mailstream/');
282 $item['body'] = bbcode($item['body']);
283 $item['url'] = $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $item['id'];
284 $mail->Body = replace_macros($template, array(
285 '$upstream' => t('Upstream'),
286 '$local' => t('Local'),
288 mailstream_html_wrap($mail->Body);
289 if (!$mail->Send()) {
290 throw new Exception($mail->ErrorInfo);
292 logger('mailstream_send sent message ' . $mail->MessageID . ' ' . $mail->Subject, LOGGER_DEBUG);
293 } catch (phpmailerException $e) {
294 logger('mailstream_send PHPMailer exception sending message ' . $message_id . ': ' . $e->errorMessage(), LOGGER_NORMAL);
295 } catch (Exception $e) {
296 logger('mailstream_send exception sending message ' . $message_id . ': ' . $e->getMessage(), LOGGER_NORMAL);
298 // In case of failure, still set the item to completed. Otherwise
299 // we'll just try to send it over and over again and it'll fail
301 q('UPDATE `mailstream_item` SET `completed` = now() WHERE `message-id` = "%s"', dbesc($message_id));
305 * Email tends to break if you send excessively long lines. To make
306 * bbcode's output suitable for transmission, we try to break things
307 * up so that lines are about 200 characters.
309 function mailstream_html_wrap(&$text)
311 $lines = str_split($text, 200);
312 for ($i = 0; $i < count($lines); $i++) {
313 $lines[$i] = preg_replace('/ /', "\n", $lines[$i], 1);
315 $text = implode($lines);
318 function mailstream_cron($a, $b) {
319 // Only process items older than an hour in cron. This is because
320 // we want to give mailstream_post_remote_hook a fair chance to
321 // send the email itself before cron jumps in. Only if
322 // mailstream_post_remote_hook fails for some reason will this get
323 // used, and in that case it's worth holding off a bit anyway.
324 $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");
325 logger('mailstream_cron processing ' . count($ms_item_ids) . ' items', LOGGER_DEBUG);
326 foreach ($ms_item_ids as $ms_item_id) {
327 if (!$ms_item_id['message-id'] || !strlen($ms_item_id['message-id'])) {
328 logger('mailstream_cron: Item ' . $ms_item_id['id'] . ' URI ' . $ms_item_id['uri'] . ' has no message-id', LOGGER_NORMAL);
330 $items = q('SELECT * FROM `item` WHERE `id` = %d', $ms_item_id['id']);
332 $users = q("SELECT * FROM `user` WHERE `uid` = %d", intval($item['uid']));
334 if ($user && $item) {
335 mailstream_send($a, $ms_item_id['message-id'], $item, $user);
338 logger('mailstream_cron: Unable to find item ' . $ms_item_id['id'], LOGGER_NORMAL);
339 q("UPDATE `mailstream_item` SET `completed` = now() WHERE `message-id` = %d", intval($ms_item['message-id']));
345 function mailstream_plugin_settings(&$a,&$s) {
346 $enabled = get_pconfig(local_user(), 'mailstream', 'enabled');
347 $address = get_pconfig(local_user(), 'mailstream', 'address');
348 $nolikes = get_pconfig(local_user(), 'mailstream', 'nolikes');
349 $attachimg= get_pconfig(local_user(), 'mailstream', 'attachimg');
350 $template = get_markup_template('settings.tpl', 'addon/mailstream/');
351 $s .= replace_macros($template, array(
353 'mailstream_enabled',
357 'mailstream_address',
360 t("Leave blank to use your account email address")),
362 'mailstream_nolikes',
365 t("Check this to omit mailing \"Like\" notifications")),
366 '$attachimg' => array(
367 'mailstream_attachimg',
370 t("Download images in posts and attach them to the email. Useful for reading email while offline.")),
371 '$title' => t('Mail Stream Settings'),
372 '$submit' => t('Save Settings')));
375 function mailstream_plugin_settings_post($a,$post) {
376 if ($_POST['mailstream_address'] != "") {
377 set_pconfig(local_user(), 'mailstream', 'address', $_POST['mailstream_address']);
380 del_pconfig(local_user(), 'mailstream', 'address');
382 if ($_POST['mailstream_nolikes']) {
383 set_pconfig(local_user(), 'mailstream', 'nolikes', $_POST['mailstream_enabled']);
386 del_pconfig(local_user(), 'mailstream', 'nolikes');
388 if ($_POST['mailstream_enabled']) {
389 set_pconfig(local_user(), 'mailstream', 'enabled', $_POST['mailstream_enabled']);
392 del_pconfig(local_user(), 'mailstream', 'enabled');
394 if ($_POST['mailstream_attachimg']) {
395 set_pconfig(local_user(), 'mailstream', 'attachimg', $_POST['mailstream_attachimg']);
398 del_pconfig(local_user(), 'mailstream', 'attachimg');
402 function mailstream_tidy() {
403 $r = q("SELECT id FROM mailstream_item WHERE completed IS NOT NULL AND completed < DATE_SUB(NOW(), INTERVAL 1 YEAR)");
404 foreach ($r as $rr) {
405 q('DELETE FROM mailstream_item WHERE id = %d', intval($rr['id']));
407 logger('mailstream_tidy: deleted ' . count($r) . ' old items', LOGGER_DEBUG);