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('Submit')));
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') === 'on') {
78 if ($item['uid'] && $item['contact-id'] && $item['uri']) {
79 q("INSERT INTO `mailstream_item` (`uid`, `contact-id`, `uri`, `message-id`) " .
80 "VALUES (%d, '%s', '%s', '%s')", intval($item['uid']),
81 intval($item['contact-id']), dbesc($item['uri']), dbesc(mailstream_generate_id($a, $item['uri'])));
82 $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']));
84 logger('mailstream_post_remote_hook: Unexpected number of items returned from mailstream_item', LOGGER_NORMAL);
88 logger('mailstream_post_remote_hook: created mailstream_item '
89 . $ms_item['id'] . ' for item ' . $item['uri'] . ' '
90 . $item['uid'] . ' ' . $item['contact-id'], LOGGER_DATA);
91 $r = q('SELECT * FROM `user` WHERE `uid` = %d', intval($item['uid']));
93 logger('mailstream_post_remote_hook: Unexpected number of users returned', LOGGER_NORMAL);
97 mailstream_send($a, $ms_item, $item, $user);
102 function mailstream_do_images($a, &$item, &$attachments) {
103 $baseurl = $a->get_baseurl();
106 preg_match_all("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", $item["body"], $matches);
107 if (count($matches)) {
108 foreach ($matches[3] as $url) {
109 $attachments[$url] = array();
112 preg_match_all("/\[img\](.*?)\[\/img\]/ism", $item["body"], $matches);
113 if (count($matches)) {
114 foreach ($matches[1] as $url) {
115 $attachments[$url] = array();
118 foreach ($attachments as $url=>$cid) {
119 if (strncmp($url, $baseurl, strlen($baseurl))) {
120 unset($attachments[$url]); // Not a local image, don't replace
123 $attachments[$url]['guid'] = substr($url, strlen($baseurl) + strlen('/photo/'));
124 $r = q("SELECT `data`, `filename`, `type` FROM `photo` WHERE `resource-id` = '%s'", dbesc($attachments[$url]['guid']));
125 $attachments[$url]['data'] = $r[0]['data'];
126 $attachments[$url]['filename'] = $r[0]['filename'];
127 $attachments[$url]['type'] = $r[0]['type'];
128 $item['body'] = str_replace($url, 'cid:' . $attachments[$url]['guid'], $item['body']);
133 function mailstream_subject($item) {
134 if ($item['title']) {
135 return $item['title'];
137 $parent = $item['thr-parent'];
138 // Don't look more than 100 levels deep for a subject, in case of loops
139 for ($i = 0; ($i < 100) && $parent; $i++) {
140 $r = q("SELECT `thr-parent`, `title` FROM `item` WHERE `uri` = '%s'", dbesc($parent));
144 if ($r[0]['thr-parent'] === $parent) {
147 if ($r[0]['title']) {
148 return t('Re:') . ' ' . $r[0]['title'];
150 $parent = $r[0]['thr-parent'];
152 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
153 intval($item['contact-id']), intval($item['uid']));
155 if ($contact['network'] === 'dfrn') {
156 return t("Friendica post");
158 if ($contact['network'] === 'dspr') {
159 return t("Diaspora post");
161 if ($contact['network'] === 'face') {
162 $subject = (strlen($item['body']) > 150) ? (substr($item['body'], 0, 140) . '...') : $item['body'];
163 return preg_replace('/\\s+/', ' ', $subject);
165 if ($contact['network'] === 'feed') {
166 return t("Feed item");
168 if ($contact['network'] === 'mail') {
171 return t("Friendica Item");
174 function mailstream_send($a, $ms_item, $item, $user) {
175 if (!$item['visible']) {
178 require_once(dirname(__file__).'/class.phpmailer.php');
179 require_once('include/bbcode.php');
180 $attachments = array();
181 mailstream_do_images($a, $item, $attachments);
182 $frommail = get_config('mailstream', 'frommail');
183 if ($frommail == "") {
184 $frommail = 'friendica@localhost.local';
186 $email = get_pconfig($item['uid'], 'mailstream', 'address');
187 $mail = new PHPmailer;
189 $mail->XMailer = 'Friendica Mailstream Plugin';
190 $mail->SetFrom($frommail, $item['author-name']);
191 $mail->AddAddress($email, $user['username']);
192 $mail->MessageID = $ms_item['message-id'];
193 $mail->Subject = mailstream_subject($item);
194 if ($item['thr-parent'] != $item['uri']) {
195 $mail->addCustomHeader('In-Reply-To: ' . mailstream_generate_id($a, $item['thr-parent']));
197 $mail->addCustomHeader('X-Friendica-Mailstream-URI: ' . $item['uri']);
198 $mail->addCustomHeader('X-Friendica-Mailstream-Plink: ' . $item['plink']);
199 $encoding = 'base64';
200 foreach ($attachments as $url=>$image) {
201 $mail->AddStringEmbeddedImage($image['data'], $image['guid'], $image['filename'], $encoding, $image['type']);
204 $mail->CharSet = 'utf-8';
205 $template = get_markup_template('mail.tpl', 'addon/mailstream/');
206 $item['body'] = bbcode($item['body']);
207 $item['url'] = $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $item['id'];
208 $mail->Body = replace_macros($template, array(
209 '$upstream' => t('Upstream'),
210 '$local' => t('Local'),
212 if (!$mail->Send()) {
213 throw new Exception($mail->ErrorInfo);
215 logger('mailstream_send sent message ' . $mail->MessageID . ' ' . $mail->Subject, LOGGER_DEBUG);
216 } catch (phpmailerException $e) {
217 logger('mailstream_send PHPMailer exception sending message ' . $ms_item['message-id'] . ': ' . $e->errorMessage(), LOGGER_NORMAL);
218 } catch (Exception $e) {
219 logger('mailstream_send exception sending message ' . $ms_item['message-id'] . ': ' . $e->getMessage(), LOGGER_NORMAL);
221 // In case of failure, still set the item to completed. Otherwise
222 // we'll just try to send it over and over again and it'll fail
224 q("UPDATE `mailstream_item` SET `completed` = now() WHERE `id` = %d", intval($ms_item['id']));
227 function mailstream_cron($a, $b) {
228 $ms_items = q("SELECT * FROM `mailstream_item` WHERE `completed` IS NULL LIMIT 100");
229 logger('mailstream_cron processing ' . count($ms_items) . ' items', LOGGER_DEBUG);
230 foreach ($ms_items as $ms_item) {
231 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `contact-id` = %d",
232 intval($ms_item['uid']), dbesc($ms_item['uri']), intval($ms_item['contact-id']));
234 $users = q("SELECT * FROM `user` WHERE `uid` = %d", intval($ms_item['uid']));
236 if ($user && $item) {
237 mailstream_send($a, $ms_item, $item, $user);
240 logger('mailstream_cron: Unable to find item ' . $ms_item['uri'], LOGGER_NORMAL);
241 q("UPDATE `mailstream_item` SET `completed` = now() WHERE `id` = %d", intval($ms_item['id']));
247 function mailstream_plugin_settings(&$a,&$s) {
248 $enabled = get_pconfig(local_user(), 'mailstream', 'enabled');
249 $enabled_mu = ($enabled === 'on') ? ' checked="true"' : '';
250 $address = get_pconfig(local_user(), 'mailstream', 'address');
251 $address_mu = $address ? (' value="' . $address . '"') : '';
252 $template = get_markup_template('settings.tpl', 'addon/mailstream/');
253 $s .= replace_macros($template, array(
254 '$submit' => t('Submit'),
255 '$address' => $address_mu,
256 '$address_caption' => t('Address:'),
257 '$enabled' => $enabled_mu,
258 '$enabled_caption' => t('Enabled:')));
261 function mailstream_plugin_settings_post($a,$post) {
262 if ($_POST['address'] != "") {
263 set_pconfig(local_user(), 'mailstream', 'address', $_POST['address']);
265 if ($_POST['enabled']) {
266 set_pconfig(local_user(), 'mailstream', 'enabled', $_POST['enabled']);
269 del_pconfig(local_user(), 'mailstream', 'enabled');
273 function mailstream_tidy() {
274 $r = q("SELECT id FROM mailstream_item WHERE completed IS NOT NULL AND completed < DATE_SUB(NOW(), INTERVAL 1 YEAR)");
275 foreach ($r as $rr) {
276 q('DELETE FROM mailstream_item WHERE id = %d', intval($rr['id']));
278 logger('mailstream_tidy: deleted ' . count($r) . ' old items', LOGGER_DEBUG);