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\Content\Text\BBCode;
10 use Friendica\Core\Addon;
11 use Friendica\Core\Config;
12 use Friendica\Core\L10n;
13 use Friendica\Core\PConfig;
14 use Friendica\Database\DBM;
15 use Friendica\Util\Network;
17 function mailstream_install() {
18 Addon::registerHook('addon_settings', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings');
19 Addon::registerHook('addon_settings_post', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings_post');
20 Addon::registerHook('post_local_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
21 Addon::registerHook('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
22 Addon::registerHook('cron', 'addon/mailstream/mailstream.php', 'mailstream_cron');
24 if (Config::get('mailstream', 'dbversion') == '0.1') {
25 q('ALTER TABLE `mailstream_item` DROP INDEX `uid`');
26 q('ALTER TABLE `mailstream_item` DROP INDEX `contact-id`');
27 q('ALTER TABLE `mailstream_item` DROP INDEX `plink`');
28 q('ALTER TABLE `mailstream_item` CHANGE `plink` `uri` char(255) NOT NULL');
29 Config::set('mailstream', 'dbversion', '0.2');
31 if (Config::get('mailstream', 'dbversion') == '0.2') {
32 q('DELETE FROM `pconfig` WHERE `cat` = "mailstream" AND `k` = "delay"');
33 Config::set('mailstream', 'dbversion', '0.3');
35 if (Config::get('mailstream', 'dbversion') == '0.3') {
36 q('ALTER TABLE `mailstream_item` CHANGE `created` `created` timestamp NOT NULL DEFAULT now()');
37 q('ALTER TABLE `mailstream_item` CHANGE `completed` `completed` timestamp NULL DEFAULT NULL');
38 Config::set('mailstream', 'dbversion', '0.4');
40 if (Config::get('mailstream', 'dbversion') == '0.4') {
41 q('ALTER TABLE `mailstream_item` CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin');
42 Config::set('mailstream', 'dbversion', '0.5');
44 if (Config::get('mailstream', 'dbversion') == '0.5') {
45 Config::set('mailstream', 'dbversion', '1.0');
48 if (Config::get('retriever', 'dbversion') != '1.0') {
49 $schema = file_get_contents(dirname(__file__).'/database.sql');
50 $arr = explode(';', $schema);
51 foreach ($arr as $a) {
54 Config::set('mailstream', 'dbversion', '1.0');
58 function mailstream_uninstall() {
59 Addon::unregisterHook('addon_settings', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings');
60 Addon::unregisterHook('addon_settings_post', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings_post');
61 Addon::unregisterHook('post_local', 'addon/mailstream/mailstream.php', 'mailstream_post_local_hook');
62 Addon::unregisterHook('post_remote', 'addon/mailstream/mailstream.php', 'mailstream_post_remote_hook');
63 Addon::unregisterHook('post_local_end', 'addon/mailstream/mailstream.php', 'mailstream_post_local_hook');
64 Addon::unregisterHook('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_remote_hook');
65 Addon::unregisterHook('post_local_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
66 Addon::unregisterHook('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
67 Addon::unregisterHook('cron', 'addon/mailstream/mailstream.php', 'mailstream_cron');
68 Addon::unregisterHook('incoming_mail', 'addon/mailstream/mailstream.php', 'mailstream_incoming_mail');
71 function mailstream_module() {}
73 function mailstream_addon_admin(&$a,&$o) {
74 $frommail = Config::get('mailstream', 'frommail');
75 $template = get_markup_template('admin.tpl', 'addon/mailstream/');
76 $config = ['frommail',
77 L10n::t('From Address'),
79 L10n::t('Email address that stream items will appear to be from.')];
80 $o .= replace_macros($template, [
81 '$frommail' => $config,
82 '$submit' => L10n::t('Save Settings')]);
85 function mailstream_addon_admin_post ($a) {
86 if (x($_POST, 'frommail')) {
87 Config::set('mailstream', 'frommail', $_POST['frommail']);
91 function mailstream_generate_id($a, $uri) {
92 // http://www.jwz.org/doc/mid.html
93 $host = $a->get_hostname();
94 $resource = hash('md5', $uri);
95 $message_id = "<" . $resource . "@" . $host . ">";
96 logger('mailstream: Generated message ID ' . $message_id . ' for URI ' . $uri, LOGGER_DEBUG);
100 function mailstream_post_hook(&$a, &$item) {
101 if (!PConfig::get($item['uid'], 'mailstream', 'enabled')) {
107 if (!$item['contact-id']) {
113 if (PConfig::get($item['uid'], 'mailstream', 'nolikes')) {
114 if ($item['verb'] == ACTIVITY_LIKE) {
119 $message_id = mailstream_generate_id($a, $item['uri']);
120 q("INSERT INTO `mailstream_item` (`uid`, `contact-id`, `uri`, `message-id`) " .
121 "VALUES (%d, '%s', '%s', '%s')", intval($item['uid']),
122 intval($item['contact-id']), dbesc($item['uri']), dbesc($message_id));
123 $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']));
124 if (count($r) != 1) {
125 logger('mailstream_post_remote_hook: Unexpected number of items returned from mailstream_item', LOGGER_NORMAL);
129 logger('mailstream_post_remote_hook: created mailstream_item '
130 . $ms_item['id'] . ' for item ' . $item['uri'] . ' '
131 . $item['uid'] . ' ' . $item['contact-id'], LOGGER_DATA);
132 $user = mailstream_get_user($item['uid']);
134 logger('mailstream_post_remote_hook: no user ' . $item['uid'], LOGGER_NORMAL);
137 mailstream_send($a, $ms_item['message-id'], $item, $user);
140 function mailstream_get_user($uid) {
141 $r = q('SELECT * FROM `user` WHERE `uid` = %d', intval($uid));
142 if (count($r) != 1) {
143 logger('mailstream_post_remote_hook: Unexpected number of users returned', LOGGER_NORMAL);
149 function mailstream_do_images($a, &$item, &$attachments) {
150 if (!PConfig::get($item['uid'], 'mailstream', 'attachimg')) {
154 $baseurl = $a->get_baseurl();
155 preg_match_all("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", $item["body"], $matches1);
156 preg_match_all("/\[img\](.*?)\[\/img\]/ism", $item["body"], $matches2);
157 foreach (array_merge($matches1[3], $matches2[1]) as $url) {
159 $cookiejar = tempnam(get_temppath(), 'cookiejar-mailstream-');
160 $attachments[$url] = [
161 'data' => Network::fetchUrl($url, true, $redirects, 0, null, $cookiejar),
162 'guid' => hash("crc32", $url),
163 'filename' => basename($url),
164 'type' => $a->get_curl_content_type()];
165 if (strlen($attachments[$url]['data'])) {
166 $item['body'] = str_replace($url, 'cid:' . $attachments[$url]['guid'], $item['body']);
173 function mailstream_sender($item) {
174 $r = q('SELECT * FROM `contact` WHERE `id` = %d', $item['contact-id']);
175 if (DBM::is_result($r)) {
177 if ($contact['name'] != $item['author-name']) {
178 return $contact['name'] . ' - ' . $item['author-name'];
181 return $item['author-name'];
184 function mailstream_decode_subject($subject) {
185 $html = BBCode::convert($subject);
189 $notags = strip_tags($html);
193 $noentity = html_entity_decode($notags);
197 $nocodes = preg_replace_callback("/(&#[0-9]+;)/", function($m) { return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES"); }, $noentity);
201 $trimmed = trim($nocodes);
208 function mailstream_subject($item) {
209 if ($item['title']) {
210 return mailstream_decode_subject($item['title']);
212 $parent = $item['thr-parent'];
213 // Don't look more than 100 levels deep for a subject, in case of loops
214 for ($i = 0; ($i < 100) && $parent; $i++) {
215 $r = q("SELECT `thr-parent`, `title` FROM `item` WHERE `uri` = '%s'", dbesc($parent));
216 if (!DBM::is_result($r)) {
219 if ($r[0]['thr-parent'] === $parent) {
222 if ($r[0]['title']) {
223 return L10n::t('Re:') . ' ' . mailstream_decode_subject($r[0]['title']);
225 $parent = $r[0]['thr-parent'];
227 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
228 intval($item['contact-id']), intval($item['uid']));
230 if ($contact['network'] === 'dfrn') {
231 return L10n::t("Friendica post");
233 if ($contact['network'] === 'dspr') {
234 return L10n::t("Diaspora post");
236 if ($contact['network'] === 'face') {
237 $text = mailstream_decode_subject($item['body']);
238 // For some reason these do show up in Facebook
239 $text = preg_replace('/\xA0$/', '', $text);
240 $subject = (strlen($text) > 150) ? (substr($text, 0, 140) . '...') : $text;
241 return preg_replace('/\\s+/', ' ', $subject);
243 if ($contact['network'] === 'feed') {
244 return L10n::t("Feed item");
246 if ($contact['network'] === 'mail') {
247 return L10n::t("Email");
249 return L10n::t("Friendica Item");
252 function mailstream_send($a, $message_id, $item, $user) {
253 if (!$item['visible']) {
259 require_once(dirname(__file__).'/phpmailer/class.phpmailer.php');
262 mailstream_do_images($a, $item, $attachments);
263 $frommail = Config::get('mailstream', 'frommail');
264 if ($frommail == "") {
265 $frommail = 'friendica@localhost.local';
267 $address = PConfig::get($item['uid'], 'mailstream', 'address');
269 $address = $user['email'];
271 $mail = new PHPmailer;
273 $mail->XMailer = 'Friendica Mailstream Addon';
274 $mail->SetFrom($frommail, mailstream_sender($item));
275 $mail->AddAddress($address, $user['username']);
276 $mail->MessageID = $message_id;
277 $mail->Subject = mailstream_subject($item);
278 if ($item['thr-parent'] != $item['uri']) {
279 $mail->addCustomHeader('In-Reply-To: ' . mailstream_generate_id($a, $item['thr-parent']));
281 $mail->addCustomHeader('X-Friendica-Mailstream-URI: ' . $item['uri']);
282 $mail->addCustomHeader('X-Friendica-Mailstream-Plink: ' . $item['plink']);
283 $encoding = 'base64';
284 foreach ($attachments as $url => $image) {
285 $mail->AddStringEmbeddedImage($image['data'], $image['guid'], $image['filename'], $encoding, $image['type']);
288 $mail->CharSet = 'utf-8';
289 $template = get_markup_template('mail.tpl', 'addon/mailstream/');
290 $item['body'] = BBCode::convert($item['body']);
291 $item['url'] = $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $item['id'];
292 $mail->Body = replace_macros($template, [
293 '$upstream' => L10n::t('Upstream'),
294 '$local' => L10n::t('Local'),
296 mailstream_html_wrap($mail->Body);
297 if (!$mail->Send()) {
298 throw new Exception($mail->ErrorInfo);
300 logger('mailstream_send sent message ' . $mail->MessageID . ' ' . $mail->Subject, LOGGER_DEBUG);
301 } catch (phpmailerException $e) {
302 logger('mailstream_send PHPMailer exception sending message ' . $message_id . ': ' . $e->errorMessage(), LOGGER_NORMAL);
303 } catch (Exception $e) {
304 logger('mailstream_send exception sending message ' . $message_id . ': ' . $e->getMessage(), LOGGER_NORMAL);
306 // In case of failure, still set the item to completed. Otherwise
307 // we'll just try to send it over and over again and it'll fail
309 q('UPDATE `mailstream_item` SET `completed` = now() WHERE `message-id` = "%s"', dbesc($message_id));
313 * Email tends to break if you send excessively long lines. To make
314 * bbcode's output suitable for transmission, we try to break things
315 * up so that lines are about 200 characters.
317 function mailstream_html_wrap(&$text)
319 $lines = str_split($text, 200);
320 for ($i = 0; $i < count($lines); $i++) {
321 $lines[$i] = preg_replace('/ /', "\n", $lines[$i], 1);
323 $text = implode($lines);
326 function mailstream_cron($a, $b) {
327 // Only process items older than an hour in cron. This is because
328 // we want to give mailstream_post_remote_hook a fair chance to
329 // send the email itself before cron jumps in. Only if
330 // mailstream_post_remote_hook fails for some reason will this get
331 // used, and in that case it's worth holding off a bit anyway.
332 $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");
333 logger('mailstream_cron processing ' . count($ms_item_ids) . ' items', LOGGER_DEBUG);
334 foreach ($ms_item_ids as $ms_item_id) {
335 if (!$ms_item_id['message-id'] || !strlen($ms_item_id['message-id'])) {
336 logger('mailstream_cron: Item ' . $ms_item_id['id'] . ' URI ' . $ms_item_id['uri'] . ' has no message-id', LOGGER_NORMAL);
338 $items = q('SELECT * FROM `item` WHERE `id` = %d', $ms_item_id['id']);
340 $users = q("SELECT * FROM `user` WHERE `uid` = %d", intval($item['uid']));
342 if ($user && $item) {
343 mailstream_send($a, $ms_item_id['message-id'], $item, $user);
346 logger('mailstream_cron: Unable to find item ' . $ms_item_id['id'], LOGGER_NORMAL);
347 q("UPDATE `mailstream_item` SET `completed` = now() WHERE `message-id` = %d", intval($ms_item['message-id']));
353 function mailstream_addon_settings(&$a,&$s) {
354 $enabled = PConfig::get(local_user(), 'mailstream', 'enabled');
355 $address = PConfig::get(local_user(), 'mailstream', 'address');
356 $nolikes = PConfig::get(local_user(), 'mailstream', 'nolikes');
357 $attachimg= PConfig::get(local_user(), 'mailstream', 'attachimg');
358 $template = get_markup_template('settings.tpl', 'addon/mailstream/');
359 $s .= replace_macros($template, [
361 'mailstream_enabled',
365 'mailstream_address',
366 L10n::t('Email Address'),
368 L10n::t("Leave blank to use your account email address")],
370 'mailstream_nolikes',
371 L10n::t('Exclude Likes'),
373 L10n::t("Check this to omit mailing \"Like\" notifications")],
375 'mailstream_attachimg',
376 L10n::t('Attach Images'),
378 L10n::t("Download images in posts and attach them to the email. Useful for reading email while offline.")],
379 '$title' => L10n::t('Mail Stream Settings'),
380 '$submit' => L10n::t('Save Settings')]);
383 function mailstream_addon_settings_post($a,$post) {
384 if ($_POST['mailstream_address'] != "") {
385 PConfig::set(local_user(), 'mailstream', 'address', $_POST['mailstream_address']);
388 PConfig::delete(local_user(), 'mailstream', 'address');
390 if ($_POST['mailstream_nolikes']) {
391 PConfig::set(local_user(), 'mailstream', 'nolikes', $_POST['mailstream_enabled']);
394 PConfig::delete(local_user(), 'mailstream', 'nolikes');
396 if ($_POST['mailstream_enabled']) {
397 PConfig::set(local_user(), 'mailstream', 'enabled', $_POST['mailstream_enabled']);
400 PConfig::delete(local_user(), 'mailstream', 'enabled');
402 if ($_POST['mailstream_attachimg']) {
403 PConfig::set(local_user(), 'mailstream', 'attachimg', $_POST['mailstream_attachimg']);
406 PConfig::delete(local_user(), 'mailstream', 'attachimg');
410 function mailstream_tidy() {
411 $r = q("SELECT id FROM mailstream_item WHERE completed IS NOT NULL AND completed < DATE_SUB(NOW(), INTERVAL 1 YEAR)");
412 foreach ($r as $rr) {
413 q('DELETE FROM mailstream_item WHERE id = %d', intval($rr['id']));
415 logger('mailstream_tidy: deleted ' . count($r) . ' old items', LOGGER_DEBUG);