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_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_remote_hook');
13 register_hook('cron', 'addon/mailstream/mailstream.php', 'mailstream_cron');
15 $schema = file_get_contents(dirname(__file__).'/database.sql');
16 $arr = explode(';', $schema);
17 foreach ($arr as $a) {
21 if (get_config('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');
27 if (get_config('mailstream', 'dbversion') == '0.2') {
28 q('DELETE FROM `pconfig` WHERE `cat` = "mailstream" AND `k` = "delay"');
30 if (get_config('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');
34 if (get_config('mailstream', 'dbversion') == '0.4') {
35 q('ALTER TABLE `mailstream_item` CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin');
37 set_config('mailstream', 'dbversion', '0.5');
40 function mailstream_uninstall() {
41 unregister_hook('plugin_settings', 'addon/mailstream/mailstream.php', 'mailstream_plugin_settings');
42 unregister_hook('plugin_settings_post', 'addon/mailstream/mailstream.php', 'mailstream_plugin_settings_post');
43 unregister_hook('post_remote', 'addon/mailstream/mailstream.php', 'mailstream_post_remote_hook');
44 unregister_hook('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_remote_hook');
45 unregister_hook('cron', 'addon/mailstream/mailstream.php', 'mailstream_cron');
46 unregister_hook('incoming_mail', 'addon/mailstream/mailstream.php', 'mailstream_incoming_mail');
49 function mailstream_module() {}
51 function mailstream_plugin_admin(&$a,&$o) {
52 $frommail = get_config('mailstream', 'frommail');
53 $template = get_markup_template('admin.tpl', 'addon/mailstream/');
54 $config = array('frommail',
57 t('Email address that stream items will appear to be from.'));
58 $o .= replace_macros($template, array(
59 '$frommail' => $config,
60 '$submit' => t('Save Settings')));
63 function mailstream_plugin_admin_post ($a) {
64 if (x($_POST, 'frommail')) {
65 set_config('mailstream', 'frommail', $_POST['frommail']);
69 function mailstream_generate_id($a, $uri) {
70 // http://www.jwz.org/doc/mid.html
71 $host = $a->get_hostname();
72 $resource = hash('md5', $uri);
73 return "<" . $resource . "@" . $host . ">";
76 function mailstream_post_remote_hook(&$a, &$item) {
77 if (!get_pconfig($item['uid'], 'mailstream', 'enabled')) {
83 if (!$item['contact-id']) {
90 q("INSERT INTO `mailstream_item` (`uid`, `contact-id`, `uri`, `message-id`) " .
91 "VALUES (%d, '%s', '%s', '%s')", intval($item['uid']),
92 intval($item['contact-id']), dbesc($item['uri']), dbesc(mailstream_generate_id($a, $item['uri'])));
93 $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']));
95 logger('mailstream_post_remote_hook: Unexpected number of items returned from mailstream_item', LOGGER_NORMAL);
99 logger('mailstream_post_remote_hook: created mailstream_item '
100 . $ms_item['id'] . ' for item ' . $item['uri'] . ' '
101 . $item['uid'] . ' ' . $item['contact-id'], LOGGER_DATA);
102 $user = mailstream_get_user($item['uid']);
104 logger('mailstream_post_remote_hook: no user ' . $item['uid'], LOGGER_NORMAL);
107 mailstream_send($a, $ms_item, $item, $user);
110 function mailstream_get_user($uid) {
111 $r = q('SELECT * FROM `user` WHERE `uid` = %d', intval($uid));
112 if (count($r) != 1) {
113 logger('mailstream_post_remote_hook: Unexpected number of users returned', LOGGER_NORMAL);
119 function mailstream_do_images($a, &$item, &$attachments) {
120 $baseurl = $a->get_baseurl();
123 preg_match_all("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", $item["body"], $matches);
124 if (count($matches)) {
125 foreach ($matches[3] as $url) {
126 $attachments[$url] = array();
129 preg_match_all("/\[img\](.*?)\[\/img\]/ism", $item["body"], $matches);
130 if (count($matches)) {
131 foreach ($matches[1] as $url) {
132 $attachments[$url] = array();
135 foreach ($attachments as $url=>$cid) {
136 if (strncmp($url, $baseurl, strlen($baseurl))) {
137 unset($attachments[$url]); // Not a local image, don't replace
140 $attachments[$url]['guid'] = substr($url, strlen($baseurl) + strlen('/photo/'));
141 $r = q("SELECT `data`, `filename`, `type` FROM `photo` WHERE `resource-id` = '%s'", dbesc($attachments[$url]['guid']));
142 $attachments[$url]['data'] = $r[0]['data'];
143 $attachments[$url]['filename'] = $r[0]['filename'];
144 $attachments[$url]['type'] = $r[0]['type'];
145 $item['body'] = str_replace($url, 'cid:' . $attachments[$url]['guid'], $item['body']);
150 function mailstream_subject($item) {
151 if ($item['title']) {
152 return $item['title'];
154 $parent = $item['thr-parent'];
155 // Don't look more than 100 levels deep for a subject, in case of loops
156 for ($i = 0; ($i < 100) && $parent; $i++) {
157 $r = q("SELECT `thr-parent`, `title` FROM `item` WHERE `uri` = '%s'", dbesc($parent));
161 if ($r[0]['thr-parent'] === $parent) {
164 if ($r[0]['title']) {
165 return t('Re:') . ' ' . $r[0]['title'];
167 $parent = $r[0]['thr-parent'];
169 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
170 intval($item['contact-id']), intval($item['uid']));
172 if ($contact['network'] === 'dfrn') {
173 return t("Friendica post");
175 if ($contact['network'] === 'dspr') {
176 return t("Diaspora post");
178 if ($contact['network'] === 'face') {
179 $subject = (strlen($item['body']) > 150) ? (substr($item['body'], 0, 140) . '...') : $item['body'];
180 return preg_replace('/\\s+/', ' ', $subject);
182 if ($contact['network'] === 'feed') {
183 return t("Feed item");
185 if ($contact['network'] === 'mail') {
188 return t("Friendica Item");
191 function mailstream_send($a, $ms_item, $item, $user) {
192 if (!$item['visible']) {
195 require_once(dirname(__file__).'/class.phpmailer.php');
196 require_once('include/bbcode.php');
197 $attachments = array();
198 mailstream_do_images($a, $item, $attachments);
199 $frommail = get_config('mailstream', 'frommail');
200 if ($frommail == "") {
201 $frommail = 'friendica@localhost.local';
203 $address = get_pconfig($item['uid'], 'mailstream', 'address');
205 $address = $user['email'];
207 $mail = new PHPmailer;
209 $mail->XMailer = 'Friendica Mailstream Plugin';
210 $mail->SetFrom($frommail, $item['author-name']);
211 $mail->AddAddress($address, $user['username']);
212 $mail->MessageID = $ms_item['message-id'];
213 $mail->Subject = mailstream_subject($item);
214 if ($item['thr-parent'] != $item['uri']) {
215 $mail->addCustomHeader('In-Reply-To: ' . mailstream_generate_id($a, $item['thr-parent']));
217 $mail->addCustomHeader('X-Friendica-Mailstream-URI: ' . $item['uri']);
218 $mail->addCustomHeader('X-Friendica-Mailstream-Plink: ' . $item['plink']);
219 $encoding = 'base64';
220 foreach ($attachments as $url=>$image) {
221 $mail->AddStringEmbeddedImage($image['data'], $image['guid'], $image['filename'], $encoding, $image['type']);
224 $mail->CharSet = 'utf-8';
225 $template = get_markup_template('mail.tpl', 'addon/mailstream/');
226 $item['body'] = bbcode($item['body']);
227 $item['url'] = $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $item['id'];
228 $mail->Body = replace_macros($template, array(
229 '$upstream' => t('Upstream'),
230 '$local' => t('Local'),
232 if (!$mail->Send()) {
233 throw new Exception($mail->ErrorInfo);
235 logger('mailstream_send sent message ' . $mail->MessageID . ' ' . $mail->Subject, LOGGER_DEBUG);
236 } catch (phpmailerException $e) {
237 logger('mailstream_send PHPMailer exception sending message ' . $ms_item['message-id'] . ': ' . $e->errorMessage(), LOGGER_NORMAL);
238 } catch (Exception $e) {
239 logger('mailstream_send exception sending message ' . $ms_item['message-id'] . ': ' . $e->getMessage(), LOGGER_NORMAL);
241 // In case of failure, still set the item to completed. Otherwise
242 // we'll just try to send it over and over again and it'll fail
244 q("UPDATE `mailstream_item` SET `completed` = now() WHERE `id` = %d", intval($ms_item['id']));
247 function mailstream_cron($a, $b) {
248 $ms_items = q("SELECT * FROM `mailstream_item` WHERE `completed` IS NULL LIMIT 100");
249 logger('mailstream_cron processing ' . count($ms_items) . ' items', LOGGER_DEBUG);
250 foreach ($ms_items as $ms_item) {
251 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `contact-id` = %d",
252 intval($ms_item['uid']), dbesc($ms_item['uri']), intval($ms_item['contact-id']));
254 $users = q("SELECT * FROM `user` WHERE `uid` = %d", intval($ms_item['uid']));
256 if ($user && $item) {
257 mailstream_send($a, $ms_item, $item, $user);
260 logger('mailstream_cron: Unable to find item ' . $ms_item['uri'], LOGGER_NORMAL);
261 q("UPDATE `mailstream_item` SET `completed` = now() WHERE `id` = %d", intval($ms_item['id']));
267 function mailstream_plugin_settings(&$a,&$s) {
268 $enabled = get_pconfig(local_user(), 'mailstream', 'enabled');
269 $address = get_pconfig(local_user(), 'mailstream', 'address');
270 $template = get_markup_template('settings.tpl', 'addon/mailstream/');
271 $s .= replace_macros($template, array(
273 'mailstream_address',
276 t("Leave blank to use your account email address")),
278 'mailstream_enabled',
281 '$title' => t('Mail Stream Settings'),
282 '$submit' => t('Save Settings')));
285 function mailstream_plugin_settings_post($a,$post) {
286 if ($_POST['mailstream_address'] != "") {
287 set_pconfig(local_user(), 'mailstream', 'address', $_POST['mailstream_address']);
290 del_pconfig(local_user(), 'mailstream', 'address');
292 if ($_POST['mailstream_enabled']) {
293 set_pconfig(local_user(), 'mailstream', 'enabled', $_POST['mailstream_enabled']);
296 del_pconfig(local_user(), 'mailstream', 'enabled');
300 function mailstream_tidy() {
301 $r = q("SELECT id FROM mailstream_item WHERE completed IS NOT NULL AND completed < DATE_SUB(NOW(), INTERVAL 1 YEAR)");
302 foreach ($r as $rr) {
303 q('DELETE FROM mailstream_item WHERE id = %d', intval($rr['id']));
305 logger('mailstream_tidy: deleted ' . count($r) . ' old items', LOGGER_DEBUG);