]> git.mxchange.org Git - friendica-addons.git/blob - mailstream/mailstream.php
Merge pull request #166 from annando/master
[friendica-addons.git] / mailstream / mailstream.php
1 <?php
2 /**
3  * Name: Mail Stream
4  * Description: Mail all items coming into your network feed to an email address
5  * Version: 0.2
6  * Author: Matthew Exon <http://mat.exon.name>
7  */
8
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');
14
15     $schema = file_get_contents(dirname(__file__).'/database.sql');
16     $arr = explode(';', $schema);
17     foreach ($arr as $a) {
18         $r = q($a);
19     }
20
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');
26     }
27     if (get_config('mailstream', 'dbversion') == '0.2') {
28         q('DELETE FROM `pconfig` WHERE `cat` = "mailstream" AND `k` = "delay"');
29     }
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');
33     }
34     if (get_config('mailstream', 'dbversion') == '0.4') {
35         q('ALTER TABLE `mailstream_item` CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin');
36     }
37     set_config('mailstream', 'dbversion', '0.5');
38 }
39
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');
47 }
48
49 function mailstream_module() {}
50
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',
55                     t('From Address'),
56                     $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')));
61 }
62
63 function mailstream_plugin_admin_post ($a) {
64     if (x($_POST, 'frommail')) {
65         set_config('mailstream', 'frommail', $_POST['frommail']);
66     }
67 }
68
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 . ">";
74 }
75
76 function mailstream_post_remote_hook(&$a, &$item) {
77     if (!get_pconfig($item['uid'], 'mailstream', 'enabled')) {
78         return;
79     }
80     if (!$item['uid']) {
81         return;
82     }
83     if (!$item['contact-id']) {
84         return;
85     }
86     if (!$item['uri']) {
87         return;
88     }
89
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']));
94     if (count($r) != 1) {
95         logger('mailstream_post_remote_hook: Unexpected number of items returned from mailstream_item', LOGGER_NORMAL);
96         return;
97     }
98     $ms_item = $r[0];
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']);
103     if (!$user) {
104         logger('mailstream_post_remote_hook: no user ' . $item['uid'], LOGGER_NORMAL);
105         return;
106     }
107     mailstream_send($a, $ms_item, $item, $user);
108 }
109
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);
114         return;
115     }
116     return $r[0];
117 }
118
119 function mailstream_do_images($a, &$item, &$attachments) {
120     $baseurl = $a->get_baseurl();
121     $id = 1;
122     $matches = array();
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();
127         }
128     }
129     preg_match_all("/\[img\](.*?)\[\/img\]/ism", $item["body"], $matches);
130     if (count($matches)) {
131         foreach ($matches[1] as $url) {
132             $attachments[$url] = array();
133         }
134     }
135     foreach ($attachments as $url=>$cid) {
136         if (strncmp($url, $baseurl, strlen($baseurl))) {
137             unset($attachments[$url]); // Not a local image, don't replace
138         }
139         else {
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']);
146         }
147     }
148 }
149
150 function mailstream_subject($item) {
151     if ($item['title']) {
152         return $item['title'];
153     }
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));
158         if (!count($r)) {
159             break;
160         }
161         if ($r[0]['thr-parent'] === $parent) {
162             break;
163         }
164         if ($r[0]['title']) {
165             return t('Re:') . ' ' . $r[0]['title'];
166         }
167         $parent = $r[0]['thr-parent'];
168     }
169     $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
170            intval($item['contact-id']), intval($item['uid']));
171     $contact = $r[0];
172     if ($contact['network'] === 'dfrn') {
173         return t("Friendica post");
174     }
175     if ($contact['network'] === 'dspr') {
176         return t("Diaspora post");
177     }
178     if ($contact['network'] === 'face') {
179         $subject = (strlen($item['body']) > 150) ? (substr($item['body'], 0, 140) . '...') : $item['body'];
180         return preg_replace('/\\s+/', ' ', $subject);
181     }
182     if ($contact['network'] === 'feed') {
183         return t("Feed item");
184     }
185     if ($contact['network'] === 'mail') {
186         return t("Email");
187     }
188     return t("Friendica Item");
189 }
190
191 function mailstream_send($a, $ms_item, $item, $user) {
192     if (!$item['visible']) {
193         return;
194     }
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';
202     }
203     $address = get_pconfig($item['uid'], 'mailstream', 'address');
204     if (!$address) {
205         $address = $user['email'];
206     }
207     $mail = new PHPmailer;
208     try {
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']));
216         }
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']);
222         }
223         $mail->IsHTML(true);
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'),
231                                          '$item' => $item));
232         if (!$mail->Send()) {
233             throw new Exception($mail->ErrorInfo);
234         }
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);
240     }
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
243     // every time.
244     q("UPDATE `mailstream_item` SET `completed` = now() WHERE `id` = %d", intval($ms_item['id']));
245 }
246
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']));
253         $item = $items[0];
254         $users = q("SELECT * FROM `user` WHERE `uid` = %d", intval($ms_item['uid']));
255         $user = $users[0];
256         if ($user && $item) {
257             mailstream_send($a, $ms_item, $item, $user);
258         }
259         else {
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']));
262         }
263     }
264     mailstream_tidy();
265 }
266
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(
272                              '$address' => array(
273                                  'mailstream_address',
274                                  t('Email Address'),
275                                  $address,
276                                  t("Leave blank to use your account email address")),
277                              '$enabled' => array(
278                                  'mailstream_enabled',
279                                  t('Enabled'),
280                                  $enabled),
281                              '$title' => t('Mail Stream Settings'),
282                              '$submit' => t('Save Settings')));
283 }
284
285 function mailstream_plugin_settings_post($a,$post) {
286     if ($_POST['mailstream_address'] != "") {
287         set_pconfig(local_user(), 'mailstream', 'address', $_POST['mailstream_address']);
288     }
289     else {
290         del_pconfig(local_user(), 'mailstream', 'address');
291     }
292     if ($_POST['mailstream_enabled']) {
293         set_pconfig(local_user(), 'mailstream', 'enabled', $_POST['mailstream_enabled']);
294     }
295     else {
296         del_pconfig(local_user(), 'mailstream', 'enabled');
297     }
298 }
299
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']));
304     }
305     logger('mailstream_tidy: deleted ' . count($r) . ' old items', LOGGER_DEBUG);
306 }