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;
12 function mailstream_install() {
13 register_hook('plugin_settings', 'addon/mailstream/mailstream.php', 'mailstream_plugin_settings');
14 register_hook('plugin_settings_post', 'addon/mailstream/mailstream.php', 'mailstream_plugin_settings_post');
15 register_hook('post_local_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
16 register_hook('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
17 register_hook('cron', 'addon/mailstream/mailstream.php', 'mailstream_cron');
19 if (Config::get('mailstream', 'dbversion') == '0.1') {
20 q('ALTER TABLE `mailstream_item` DROP INDEX `uid`');
21 q('ALTER TABLE `mailstream_item` DROP INDEX `contact-id`');
22 q('ALTER TABLE `mailstream_item` DROP INDEX `plink`');
23 q('ALTER TABLE `mailstream_item` CHANGE `plink` `uri` char(255) NOT NULL');
24 Config::set('mailstream', 'dbversion', '0.2');
26 if (Config::get('mailstream', 'dbversion') == '0.2') {
27 q('DELETE FROM `pconfig` WHERE `cat` = "mailstream" AND `k` = "delay"');
28 Config::set('mailstream', 'dbversion', '0.3');
30 if (Config::get('mailstream', 'dbversion') == '0.3') {
31 q('ALTER TABLE `mailstream_item` CHANGE `created` `created` timestamp NOT NULL DEFAULT now()');
32 q('ALTER TABLE `mailstream_item` CHANGE `completed` `completed` timestamp NULL DEFAULT NULL');
33 Config::set('mailstream', 'dbversion', '0.4');
35 if (Config::get('mailstream', 'dbversion') == '0.4') {
36 q('ALTER TABLE `mailstream_item` CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin');
37 Config::set('mailstream', 'dbversion', '0.5');
39 if (Config::get('mailstream', 'dbversion') == '0.5') {
40 Config::set('mailstream', 'dbversion', '1.0');
43 if (Config::get('retriever', 'dbversion') != '1.0') {
44 $schema = file_get_contents(dirname(__file__).'/database.sql');
45 $arr = explode(';', $schema);
46 foreach ($arr as $a) {
49 Config::set('mailstream', 'dbversion', '1.0');
53 function mailstream_uninstall() {
54 unregister_hook('plugin_settings', 'addon/mailstream/mailstream.php', 'mailstream_plugin_settings');
55 unregister_hook('plugin_settings_post', 'addon/mailstream/mailstream.php', 'mailstream_plugin_settings_post');
56 unregister_hook('post_local', 'addon/mailstream/mailstream.php', 'mailstream_post_local_hook');
57 unregister_hook('post_remote', 'addon/mailstream/mailstream.php', 'mailstream_post_remote_hook');
58 unregister_hook('post_local_end', 'addon/mailstream/mailstream.php', 'mailstream_post_local_hook');
59 unregister_hook('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_remote_hook');
60 unregister_hook('post_local_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
61 unregister_hook('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
62 unregister_hook('cron', 'addon/mailstream/mailstream.php', 'mailstream_cron');
63 unregister_hook('incoming_mail', 'addon/mailstream/mailstream.php', 'mailstream_incoming_mail');
66 function mailstream_module() {}
68 function mailstream_plugin_admin(&$a,&$o) {
69 $frommail = Config::get('mailstream', 'frommail');
70 $template = get_markup_template('admin.tpl', 'addon/mailstream/');
71 $config = array('frommail',
74 t('Email address that stream items will appear to be from.'));
75 $o .= replace_macros($template, array(
76 '$frommail' => $config,
77 '$submit' => t('Save Settings')));
80 function mailstream_plugin_admin_post ($a) {
81 if (x($_POST, 'frommail')) {
82 Config::set('mailstream', 'frommail', $_POST['frommail']);
86 function mailstream_generate_id($a, $uri) {
87 // http://www.jwz.org/doc/mid.html
88 $host = $a->get_hostname();
89 $resource = hash('md5', $uri);
90 $message_id = "<" . $resource . "@" . $host . ">";
91 logger('mailstream: Generated message ID ' . $message_id . ' for URI ' . $uri, LOGGER_DEBUG);
95 function mailstream_post_hook(&$a, &$item) {
96 if (!PConfig::get($item['uid'], 'mailstream', 'enabled')) {
102 if (!$item['contact-id']) {
108 if (PConfig::get($item['uid'], 'mailstream', 'nolikes')) {
109 if ($item['verb'] == ACTIVITY_LIKE) {
114 $message_id = mailstream_generate_id($a, $item['uri']);
115 q("INSERT INTO `mailstream_item` (`uid`, `contact-id`, `uri`, `message-id`) " .
116 "VALUES (%d, '%s', '%s', '%s')", intval($item['uid']),
117 intval($item['contact-id']), dbesc($item['uri']), dbesc($message_id));
118 $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']));
119 if (count($r) != 1) {
120 logger('mailstream_post_remote_hook: Unexpected number of items returned from mailstream_item', LOGGER_NORMAL);
124 logger('mailstream_post_remote_hook: created mailstream_item '
125 . $ms_item['id'] . ' for item ' . $item['uri'] . ' '
126 . $item['uid'] . ' ' . $item['contact-id'], LOGGER_DATA);
127 $user = mailstream_get_user($item['uid']);
129 logger('mailstream_post_remote_hook: no user ' . $item['uid'], LOGGER_NORMAL);
132 mailstream_send($a, $ms_item['message-id'], $item, $user);
135 function mailstream_get_user($uid) {
136 $r = q('SELECT * FROM `user` WHERE `uid` = %d', intval($uid));
137 if (count($r) != 1) {
138 logger('mailstream_post_remote_hook: Unexpected number of users returned', LOGGER_NORMAL);
144 function mailstream_do_images($a, &$item, &$attachments) {
145 if (!PConfig::get($item['uid'], 'mailstream', 'attachimg')) {
148 $attachments = array();
149 $baseurl = $a->get_baseurl();
150 preg_match_all("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", $item["body"], $matches1);
151 preg_match_all("/\[img\](.*?)\[\/img\]/ism", $item["body"], $matches2);
152 foreach (array_merge($matches1[3], $matches2[1]) as $url) {
154 $cookiejar = tempnam(get_temppath(), 'cookiejar-mailstream-');
155 $attachments[$url] = array(
156 'data' => fetch_url($url, true, $redirects, 0, Null, $cookiejar),
157 'guid' => hash("crc32", $url),
158 'filename' => basename($url),
159 'type' => $a->get_curl_content_type());
160 if (strlen($attachments[$url]['data'])) {
161 $item['body'] = str_replace($url, 'cid:' . $attachments[$url]['guid'], $item['body']);
168 function mailstream_sender($item) {
169 $r = q('SELECT * FROM `contact` WHERE `id` = %d', $item['contact-id']);
170 if (dbm::is_result($r)) {
172 if ($contact['name'] != $item['author-name']) {
173 return $contact['name'] . ' - ' . $item['author-name'];
176 return $item['author-name'];
179 function mailstream_decode_subject($subject) {
180 $html = bbcode($subject);
184 $notags = strip_tags($html);
188 $noentity = html_entity_decode($notags);
192 $nocodes = preg_replace_callback("/(&#[0-9]+;)/", function($m) { return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES"); }, $noentity);
196 $trimmed = trim($nocodes);
203 function mailstream_subject($item) {
204 if ($item['title']) {
205 return mailstream_decode_subject($item['title']);
207 $parent = $item['thr-parent'];
208 // Don't look more than 100 levels deep for a subject, in case of loops
209 for ($i = 0; ($i < 100) && $parent; $i++) {
210 $r = q("SELECT `thr-parent`, `title` FROM `item` WHERE `uri` = '%s'", dbesc($parent));
211 if (!dbm::is_result($r)) {
214 if ($r[0]['thr-parent'] === $parent) {
217 if ($r[0]['title']) {
218 return t('Re:') . ' ' . mailstream_decode_subject($r[0]['title']);
220 $parent = $r[0]['thr-parent'];
222 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
223 intval($item['contact-id']), intval($item['uid']));
225 if ($contact['network'] === 'dfrn') {
226 return t("Friendica post");
228 if ($contact['network'] === 'dspr') {
229 return t("Diaspora post");
231 if ($contact['network'] === 'face') {
232 $text = mailstream_decode_subject($item['body']);
233 // For some reason these do show up in Facebook
234 $text = preg_replace('/\xA0$/', '', $text);
235 $subject = (strlen($text) > 150) ? (substr($text, 0, 140) . '...') : $text;
236 return preg_replace('/\\s+/', ' ', $subject);
238 if ($contact['network'] === 'feed') {
239 return t("Feed item");
241 if ($contact['network'] === 'mail') {
244 return t("Friendica Item");
247 function mailstream_send($a, $message_id, $item, $user) {
248 if (!$item['visible']) {
254 require_once(dirname(__file__).'/phpmailer/class.phpmailer.php');
255 require_once('include/bbcode.php');
256 $attachments = array();
257 mailstream_do_images($a, $item, $attachments);
258 $frommail = Config::get('mailstream', 'frommail');
259 if ($frommail == "") {
260 $frommail = 'friendica@localhost.local';
262 $address = PConfig::get($item['uid'], 'mailstream', 'address');
264 $address = $user['email'];
266 $mail = new PHPmailer;
268 $mail->XMailer = 'Friendica Mailstream Plugin';
269 $mail->SetFrom($frommail, mailstream_sender($item));
270 $mail->AddAddress($address, $user['username']);
271 $mail->MessageID = $message_id;
272 $mail->Subject = mailstream_subject($item);
273 if ($item['thr-parent'] != $item['uri']) {
274 $mail->addCustomHeader('In-Reply-To: ' . mailstream_generate_id($a, $item['thr-parent']));
276 $mail->addCustomHeader('X-Friendica-Mailstream-URI: ' . $item['uri']);
277 $mail->addCustomHeader('X-Friendica-Mailstream-Plink: ' . $item['plink']);
278 $encoding = 'base64';
279 foreach ($attachments as $url => $image) {
280 $mail->AddStringEmbeddedImage($image['data'], $image['guid'], $image['filename'], $encoding, $image['type']);
283 $mail->CharSet = 'utf-8';
284 $template = get_markup_template('mail.tpl', 'addon/mailstream/');
285 $item['body'] = bbcode($item['body']);
286 $item['url'] = $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $item['id'];
287 $mail->Body = replace_macros($template, array(
288 '$upstream' => t('Upstream'),
289 '$local' => t('Local'),
291 mailstream_html_wrap($mail->Body);
292 if (!$mail->Send()) {
293 throw new Exception($mail->ErrorInfo);
295 logger('mailstream_send sent message ' . $mail->MessageID . ' ' . $mail->Subject, LOGGER_DEBUG);
296 } catch (phpmailerException $e) {
297 logger('mailstream_send PHPMailer exception sending message ' . $message_id . ': ' . $e->errorMessage(), LOGGER_NORMAL);
298 } catch (Exception $e) {
299 logger('mailstream_send exception sending message ' . $message_id . ': ' . $e->getMessage(), LOGGER_NORMAL);
301 // In case of failure, still set the item to completed. Otherwise
302 // we'll just try to send it over and over again and it'll fail
304 q('UPDATE `mailstream_item` SET `completed` = now() WHERE `message-id` = "%s"', dbesc($message_id));
308 * Email tends to break if you send excessively long lines. To make
309 * bbcode's output suitable for transmission, we try to break things
310 * up so that lines are about 200 characters.
312 function mailstream_html_wrap(&$text)
314 $lines = str_split($text, 200);
315 for ($i = 0; $i < count($lines); $i++) {
316 $lines[$i] = preg_replace('/ /', "\n", $lines[$i], 1);
318 $text = implode($lines);
321 function mailstream_cron($a, $b) {
322 // Only process items older than an hour in cron. This is because
323 // we want to give mailstream_post_remote_hook a fair chance to
324 // send the email itself before cron jumps in. Only if
325 // mailstream_post_remote_hook fails for some reason will this get
326 // used, and in that case it's worth holding off a bit anyway.
327 $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");
328 logger('mailstream_cron processing ' . count($ms_item_ids) . ' items', LOGGER_DEBUG);
329 foreach ($ms_item_ids as $ms_item_id) {
330 if (!$ms_item_id['message-id'] || !strlen($ms_item_id['message-id'])) {
331 logger('mailstream_cron: Item ' . $ms_item_id['id'] . ' URI ' . $ms_item_id['uri'] . ' has no message-id', LOGGER_NORMAL);
333 $items = q('SELECT * FROM `item` WHERE `id` = %d', $ms_item_id['id']);
335 $users = q("SELECT * FROM `user` WHERE `uid` = %d", intval($item['uid']));
337 if ($user && $item) {
338 mailstream_send($a, $ms_item_id['message-id'], $item, $user);
341 logger('mailstream_cron: Unable to find item ' . $ms_item_id['id'], LOGGER_NORMAL);
342 q("UPDATE `mailstream_item` SET `completed` = now() WHERE `message-id` = %d", intval($ms_item['message-id']));
348 function mailstream_plugin_settings(&$a,&$s) {
349 $enabled = PConfig::get(local_user(), 'mailstream', 'enabled');
350 $address = PConfig::get(local_user(), 'mailstream', 'address');
351 $nolikes = PConfig::get(local_user(), 'mailstream', 'nolikes');
352 $attachimg= PConfig::get(local_user(), 'mailstream', 'attachimg');
353 $template = get_markup_template('settings.tpl', 'addon/mailstream/');
354 $s .= replace_macros($template, array(
356 'mailstream_enabled',
360 'mailstream_address',
363 t("Leave blank to use your account email address")),
365 'mailstream_nolikes',
368 t("Check this to omit mailing \"Like\" notifications")),
369 '$attachimg' => array(
370 'mailstream_attachimg',
373 t("Download images in posts and attach them to the email. Useful for reading email while offline.")),
374 '$title' => t('Mail Stream Settings'),
375 '$submit' => t('Save Settings')));
378 function mailstream_plugin_settings_post($a,$post) {
379 if ($_POST['mailstream_address'] != "") {
380 PConfig::set(local_user(), 'mailstream', 'address', $_POST['mailstream_address']);
383 del_pconfig(local_user(), 'mailstream', 'address');
385 if ($_POST['mailstream_nolikes']) {
386 PConfig::set(local_user(), 'mailstream', 'nolikes', $_POST['mailstream_enabled']);
389 del_pconfig(local_user(), 'mailstream', 'nolikes');
391 if ($_POST['mailstream_enabled']) {
392 PConfig::set(local_user(), 'mailstream', 'enabled', $_POST['mailstream_enabled']);
395 del_pconfig(local_user(), 'mailstream', 'enabled');
397 if ($_POST['mailstream_attachimg']) {
398 PConfig::set(local_user(), 'mailstream', 'attachimg', $_POST['mailstream_attachimg']);
401 del_pconfig(local_user(), 'mailstream', 'attachimg');
405 function mailstream_tidy() {
406 $r = q("SELECT id FROM mailstream_item WHERE completed IS NOT NULL AND completed < DATE_SUB(NOW(), INTERVAL 1 YEAR)");
407 foreach ($r as $rr) {
408 q('DELETE FROM mailstream_item WHERE id = %d', intval($rr['id']));
410 logger('mailstream_tidy: deleted ' . count($r) . ' old items', LOGGER_DEBUG);