]> git.mxchange.org Git - friendica-addons.git/blob - mailstream/mailstream.php
Add mailstream plugin
[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.1
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     set_config('mailstream', 'dbversion', '0.4');
35 }
36
37 function mailstream_uninstall() {
38     unregister_hook('plugin_settings', 'addon/mailstream/mailstream.php', 'mailstream_plugin_settings');
39     unregister_hook('plugin_settings_post', 'addon/mailstream/mailstream.php', 'mailstream_plugin_settings_post');
40     unregister_hook('post_remote', 'addon/mailstream/mailstream.php', 'mailstream_post_remote_hook');
41     unregister_hook('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_remote_hook');
42     unregister_hook('cron', 'addon/mailstream/mailstream.php', 'mailstream_cron');
43     unregister_hook('incoming_mail', 'addon/mailstream/mailstream.php', 'mailstream_incoming_mail');
44 }
45
46 function mailstream_module() {}
47
48 function mailstream_plugin_admin(&$a,&$o) {
49     $frommail = get_config('mailstream', 'frommail');
50     $template = file_get_contents(dirname(__file__).'/admin.tpl');
51     $config = array('frommail',
52                     t('From Address'),
53                     $frommail,
54                     t('Email address that stream items will appear to be from.'));
55     $o .= replace_macros($template, array('$frommail' => $config));
56 }
57
58 function mailstream_plugin_admin_post ($a) {
59     if (x($_POST, 'frommail')) {
60         set_config('mailstream', 'frommail', $_POST['frommail']);
61     }
62 }
63
64 function mailstream_generate_id($a, $uri) {
65     // http://www.jwz.org/doc/mid.html
66     $host = $a->get_hostname();
67     $resource = hash('md5', $uri);
68     return "<" . $resource . "@" . $host . ">";
69 }
70
71 function mailstream_post_remote_hook(&$a, &$item) {
72     if (get_pconfig($item['uid'], 'mailstream', 'enabled') === 'on') {
73         if ($item['uid'] && $item['contact-id'] && $item['uri']) {
74             q("INSERT INTO `mailstream_item` (`uid`, `contact-id`, `uri`, `message-id`) " .
75               "VALUES (%d, '%s', '%s', '%s')", intval($item['uid']),
76               intval($item['contact-id']), dbesc($item['uri']), dbesc(mailstream_generate_id($a, $item['uri'])));
77             $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']));
78             if (count($r) != 1) {
79                 logger('mailstream_post_remote_hook: Unexpected number of items returned from mailstream_item', LOGGER_ERROR);
80                 return;
81             }
82             $ms_item = $r[0];
83             logger('mailstream_post_remote_hook: created mailstream_item '
84                    . $ms_item['id'] . ' for item ' . $item['uri'] . ' '
85                    . $item['uid'] . ' ' . $item['contact-id'], LOGGER_DATA);
86             $r = q('SELECT * FROM `user` WHERE `uid` = %d', intval($item['uid']));
87             if (count($r) != 1) {
88                 logger('mailstream_post_remote_hook: Unexpected number of users returned', LOGGER_ERROR);
89                 return;
90             }
91             $user = $r[0];
92             mailstream_send($a, $ms_item, $item, $user);
93         }
94     }
95 }
96
97 function mailstream_do_images($a, &$item, &$attachments) {
98     $baseurl = $a->get_baseurl();
99     $id = 1;
100     $matches = array();
101     preg_match_all("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", $item["body"], $matches);
102     if (count($matches)) {
103         foreach ($matches[3] as $url) {
104             $attachments[$url] = array();
105         }
106     }
107     preg_match_all("/\[img\](.*?)\[\/img\]/ism", $item["body"], $matches);
108     if (count($matches)) {
109         foreach ($matches[1] as $url) {
110             $attachments[$url] = array();
111         }
112     }
113     foreach ($attachments as $url=>$cid) {
114         if (strncmp($url, $baseurl, strlen($baseurl))) {
115             unset($attachments[$url]); // Not a local image, don't replace
116         }
117         else {
118             $attachments[$url]['guid'] = substr($url, strlen($baseurl) + strlen('/photo/'));
119             $r = q("SELECT `data`, `filename`, `type` FROM `photo` WHERE `resource-id` = '%s'", dbesc($attachments[$url]['guid']));
120             $attachments[$url]['data'] = $r[0]['data'];
121             $attachments[$url]['filename'] = $r[0]['filename'];
122             $attachments[$url]['type'] = $r[0]['type'];
123             $item['body'] = str_replace($url, 'cid:' . $attachments[$url]['guid'], $item['body']);
124         }
125     }
126 }
127
128 function mailstream_subject($item) {
129     if ($item['title']) {
130         return $item['title'];
131     }
132     $parent = $item['thr-parent'];
133     // Don't look more than 100 levels deep for a subject, in case of loops
134     for ($i = 0; ($i < 100) && $parent; $i++) {
135         $r = q("SELECT `thr-parent`, `title` FROM `item` WHERE `uri` = '%s'", dbesc($parent));
136         if (!count($r)) {
137             break;
138         }
139         if ($r[0]['thr-parent'] === $parent) {
140             break;
141         }
142         if ($r[0]['title']) {
143             return t('Re:') . ' ' . $r[0]['title'];
144         }
145         $parent = $r[0]['thr-parent'];
146     }
147     $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
148            intval($item['contact-id']), intval($item['uid']));
149     $contact = $r[0];
150     if ($contact['network'] === 'dfrn') {
151         return t("Friendica post");
152     }
153     if ($contact['network'] === 'dspr') {
154         return t("Diaspora post");
155     }
156     if ($contact['network'] === 'face') {
157         $subject = (strlen($item['body']) > 150) ? (substr($item['body'], 0, 140) . '...') : $item['body'];
158         return preg_replace('/\\s+/', ' ', $subject);
159     }
160     if ($contact['network'] === 'feed') {
161         return t("Feed item");
162     }
163     if ($contact['network'] === 'mail') {
164         return t("Email");
165     }
166     return t("Friendica Item");
167 }
168
169 function mailstream_send($a, $ms_item, $item, $user) {
170     if (!$item['visible']) {
171         return;
172     }
173     require_once(dirname(__file__).'/class.phpmailer.php');
174     require_once('include/bbcode.php');
175     $attachments = array();
176     mailstream_do_images($a, $item, $attachments);
177     $frommail = get_config('mailstream', 'frommail');
178     if ($frommail == "") {
179         $frommail = 'friendica@localhost.local';
180     }
181     $email = get_pconfig($item['uid'], 'mailstream', 'address');
182     $mail = new PHPmailer;
183     try {
184         $mail->XMailer = 'Friendica Mailstream Plugin';
185         $mail->SetFrom($frommail, $item['author-name']);
186         $mail->AddAddress($email, $user['username']);
187         $mail->MessageID = $ms_item['message-id'];
188         $mail->Subject = mailstream_subject($item);
189         if ($item['thr-parent'] != $item['uri']) {
190             $mail->addCustomHeader('In-Reply-To: ' . mailstream_generate_id($a, $item['thr-parent']));
191         }
192         $mail->addCustomHeader('X-Friendica-Mailstream-URI: ' . $item['uri']);
193         $mail->addCustomHeader('X-Friendica-Mailstream-Plink: ' . $item['plink']);
194         $encoding = 'base64';
195         foreach ($attachments as $url=>$image) {
196             $mail->AddStringEmbeddedImage($image['data'], $image['guid'], $image['filename'], $encoding, $image['type']);
197         }
198         $mail->IsHTML(true);
199         $mail->CharSet = 'utf-8';
200         $template = file_get_contents(dirname(__file__).'/mail.tpl');
201         $item['body'] = bbcode($item['body']);
202         $mail->Body = replace_macros($template, array('$item' => $item));
203         if (!$mail->Send()) {
204             throw new Exception($mail->ErrorInfo);
205         }
206         logger('mailstream_send sent message ' . $mail->MessageID . ' ' . $mail->Subject, LOGGER_DEBUG);
207     } catch (phpmailerException $e) {
208         logger('mailstream_send PHPMailer exception sending message ' . $ms_item['message-id'] . ': ' . $e->errorMessage(), LOGGER_ERROR);
209     } catch (Exception $e) {
210         logger('mailstream_send exception sending message ' . $ms_item['message-id'] . ': ' . $e->getMessage(), LOGGER_ERROR);
211     }
212     // In case of failure, still set the item to completed.  Otherwise
213     // we'll just try to send it over and over again and it'll fail
214     // every time.
215     q("UPDATE `mailstream_item` SET `completed` = now() WHERE `id` = %d", intval($ms_item['id']));
216 }
217
218 function mailstream_cron($a, $b) {
219     $ms_items = q("SELECT * FROM `mailstream_item` WHERE `completed` IS NULL LIMIT 100");
220     logger('mailstream_cron processing ' . count($ms_items) . ' items', LOGGER_DEBUG);
221     foreach ($ms_items as $ms_item) {
222         $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `contact-id` = %d",
223                    intval($ms_item['uid']), dbesc($ms_item['uri']), intval($ms_item['contact-id']));
224         $item = $items[0];
225         $users = q("SELECT * FROM `user` WHERE `uid` = %d", intval($ms_item['uid']));
226         $user = $users[0];
227         if ($user && $item) {
228             mailstream_send($a, $ms_item, $item, $user);
229         }
230         else {
231             logger('mailstream_cron: Unable to find item ' . $ms_item['uri'], LOGGER_ERROR);
232             q("UPDATE `mailstream_item` SET `completed` = now() WHERE `id` = %d", intval($ms_item['id']));
233         }
234     }
235     mailstream_tidy();
236 }
237
238 function mailstream_plugin_settings(&$a,&$s) {
239     $enabled = get_pconfig(local_user(), 'mailstream', 'enabled');
240     $enabled_mu = ($enabled === 'on') ? ' checked="true"' : '';
241     $address = get_pconfig(local_user(), 'mailstream', 'address');
242     $address_mu = $address ? (' value="' . $address . '"') : '';
243     $template = file_get_contents(dirname(__file__).'/settings.tpl');
244     $s .= replace_macros($template, array('$address' => $address_mu,
245                                           '$address_caption' => t('Address:'),
246                                           '$enabled' => $enabled_mu,
247                                           '$enabled_caption' => t('Enabled:')));
248 }
249
250 function mailstream_plugin_settings_post($a,$post) {
251     if ($_POST['address'] != "") {
252         set_pconfig(local_user(), 'mailstream', 'address', $_POST['address']);
253     }
254     if ($_POST['enabled']) {
255         set_pconfig(local_user(), 'mailstream', 'enabled', $_POST['enabled']);
256     }
257     else {
258         del_pconfig(local_user(), 'mailstream', 'enabled');
259     }
260 }
261
262 function mailstream_tidy() {
263     $r = q("SELECT id FROM mailstream_item WHERE completed IS NOT NULL AND completed < DATE_SUB(NOW(), INTERVAL 1 YEAR)");
264     foreach ($r as $rr) {
265         q('DELETE FROM mailstream_item WHERE id = %d', intval($rr['id']));
266     }
267     logger('mailstream_tidy: deleted ' . count($r) . ' old items', LOGGER_DEBUG);
268 }