Move Activity/Namespaces defines to constants
[friendica-addons.git/.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: 1.1
6  * Author: Matthew Exon <http://mat.exon.name>
7  */
8
9 use Friendica\Content\Text\BBCode;
10 use Friendica\Core\Config;
11 use Friendica\Core\Hook;
12 use Friendica\Core\L10n;
13 use Friendica\Core\Logger;
14 use Friendica\Core\PConfig;
15 use Friendica\Core\Renderer;
16 use Friendica\Database\DBA;
17 use Friendica\Protocol\Activity;
18 use Friendica\Util\Network;
19 use Friendica\Model\Item;
20
21 function mailstream_install() {
22         Hook::register('addon_settings', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings');
23         Hook::register('addon_settings_post', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings_post');
24         Hook::register('post_local_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
25         Hook::register('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
26         Hook::register('cron', 'addon/mailstream/mailstream.php', 'mailstream_cron');
27
28         if (Config::get('mailstream', 'dbversion') == '0.1') {
29                 q('ALTER TABLE `mailstream_item` DROP INDEX `uid`');
30                 q('ALTER TABLE `mailstream_item` DROP INDEX `contact-id`');
31                 q('ALTER TABLE `mailstream_item` DROP INDEX `plink`');
32                 q('ALTER TABLE `mailstream_item` CHANGE `plink` `uri` char(255) NOT NULL');
33                 Config::set('mailstream', 'dbversion', '0.2');
34         }
35         if (Config::get('mailstream', 'dbversion') == '0.2') {
36                 q('DELETE FROM `pconfig` WHERE `cat` = "mailstream" AND `k` = "delay"');
37                 Config::set('mailstream', 'dbversion', '0.3');
38         }
39         if (Config::get('mailstream', 'dbversion') == '0.3') {
40                 q('ALTER TABLE `mailstream_item` CHANGE `created` `created` timestamp NOT NULL DEFAULT now()');
41                 q('ALTER TABLE `mailstream_item` CHANGE `completed` `completed` timestamp NULL DEFAULT NULL');
42                 Config::set('mailstream', 'dbversion', '0.4');
43         }
44         if (Config::get('mailstream', 'dbversion') == '0.4') {
45                 q('ALTER TABLE `mailstream_item` CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin');
46                 Config::set('mailstream', 'dbversion', '0.5');
47         }
48         if (Config::get('mailstream', 'dbversion') == '0.5') {
49                 Config::set('mailstream', 'dbversion', '1.0');
50         }
51
52         if (Config::get('retriever', 'dbversion') != '1.0') {
53                 $schema = file_get_contents(dirname(__file__).'/database.sql');
54                 $arr = explode(';', $schema);
55                 foreach ($arr as $a) {
56                         $r = q($a);
57                 }
58                 Config::set('mailstream', 'dbversion', '1.0');
59         }
60 }
61
62 function mailstream_uninstall() {
63         Hook::unregister('addon_settings', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings');
64         Hook::unregister('addon_settings_post', 'addon/mailstream/mailstream.php', 'mailstream_addon_settings_post');
65         Hook::unregister('post_local', 'addon/mailstream/mailstream.php', 'mailstream_post_local_hook');
66         Hook::unregister('post_remote', 'addon/mailstream/mailstream.php', 'mailstream_post_remote_hook');
67         Hook::unregister('post_local_end', 'addon/mailstream/mailstream.php', 'mailstream_post_local_hook');
68         Hook::unregister('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_remote_hook');
69         Hook::unregister('post_local_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
70         Hook::unregister('post_remote_end', 'addon/mailstream/mailstream.php', 'mailstream_post_hook');
71         Hook::unregister('cron', 'addon/mailstream/mailstream.php', 'mailstream_cron');
72         Hook::unregister('incoming_mail', 'addon/mailstream/mailstream.php', 'mailstream_incoming_mail');
73 }
74
75 function mailstream_module() {}
76
77 function mailstream_addon_admin(&$a,&$o) {
78         $frommail = Config::get('mailstream', 'frommail');
79         $template = Renderer::getMarkupTemplate('admin.tpl', 'addon/mailstream/');
80         $config = ['frommail',
81                         L10n::t('From Address'),
82                         $frommail,
83                         L10n::t('Email address that stream items will appear to be from.')];
84         $o .= Renderer::replaceMacros($template, [
85                                  '$frommail' => $config,
86                                  '$submit' => L10n::t('Save Settings')]);
87 }
88
89 function mailstream_addon_admin_post ($a) {
90         if (!empty($_POST['frommail'])) {
91                 Config::set('mailstream', 'frommail', $_POST['frommail']);
92         }
93 }
94
95 function mailstream_generate_id($a, $uri) {
96         // http://www.jwz.org/doc/mid.html
97         $host = $a->getHostName();
98         $resource = hash('md5', $uri);
99         $message_id = "<" . $resource . "@" . $host . ">";
100         Logger::debug('mailstream: Generated message ID ' . $message_id . ' for URI ' . $uri);
101         return $message_id;
102 }
103
104 function mailstream_post_hook(&$a, &$item) {
105         if (!PConfig::get($item['uid'], 'mailstream', 'enabled')) {
106                 Logger::debug('mailstream: not enabled for item ' . $item['id']);
107                 return;
108         }
109         if (!$item['uid']) {
110                 Logger::debug('mailstream: no uid for item ' . $item['id']);
111                 return;
112         }
113         if (!$item['contact-id']) {
114                 Logger::debug('mailstream: no contact-id for item ' . $item['id']);
115                 return;
116         }
117         if (!$item['uri']) {
118                 Logger::debug('mailstream: no uri for item ' . $item['id']);
119                 return;
120         }
121         if (!$item['plink']) {
122                 Logger::debug('mailstream: no plink for item ' . $item['id']);
123                 return;
124         }
125         if (PConfig::get($item['uid'], 'mailstream', 'nolikes')) {
126                 if ($item['verb'] == Activity::LIKE) {
127                         Logger::debug('mailstream: like item ' . $item['id']);
128                         return;
129                 }
130         }
131
132         $message_id = mailstream_generate_id($a, $item['uri']);
133         q("INSERT INTO `mailstream_item` (`uid`, `contact-id`, `uri`, `message-id`) " .
134                 "VALUES (%d, '%s', '%s', '%s')", intval($item['uid']),
135                 intval($item['contact-id']), DBA::escape($item['uri']), DBA::escape($message_id));
136         $r = q('SELECT * FROM `mailstream_item` WHERE `uid` = %d AND `contact-id` = %d AND `uri` = "%s"', intval($item['uid']), intval($item['contact-id']), DBA::escape($item['uri']));
137         if (count($r) != 1) {
138                 Logger::info('mailstream_post_remote_hook: Unexpected number of items returned from mailstream_item');
139                 return;
140         }
141         $ms_item = $r[0];
142         Logger::debug('mailstream_post_remote_hook: created mailstream_item ' . $ms_item['id'] . ' for item ' . $item['uri'] . ' ' . $item['uid'] . ' ' . $item['contact-id']);
143         $user = mailstream_get_user($item['uid']);
144         if (!$user) {
145                 Logger::info('mailstream_post_remote_hook: no user ' . $item['uid']);
146                 return;
147         }
148         mailstream_send($a, $ms_item['message-id'], $item, $user);
149 }
150
151 function mailstream_get_user($uid) {
152         $r = q('SELECT * FROM `user` WHERE `uid` = %d', intval($uid));
153         if (count($r) != 1) {
154                 Logger::info('mailstream_post_remote_hook: Unexpected number of users returned');
155                 return;
156         }
157         return $r[0];
158 }
159
160 function mailstream_do_images($a, &$item, &$attachments) {
161         if (!PConfig::get($item['uid'], 'mailstream', 'attachimg')) {
162                 return;
163         }
164         $attachments = [];
165         preg_match_all("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", $item["body"], $matches1);
166         preg_match_all("/\[img\](.*?)\[\/img\]/ism", $item["body"], $matches2);
167         preg_match_all("/\[img\=([^\]]*)\]([^[]*)\[\/img\]/ism", $item["body"], $matches3);
168         foreach (array_merge($matches1[3], $matches2[1], $matches3[1]) as $url) {
169                 $components = parse_url($url);
170                 if (!$components) {
171                         continue;
172                 }
173                 $cookiejar = tempnam(get_temppath(), 'cookiejar-mailstream-');
174                 $curlResult = Network::fetchUrlFull($url, true, 0, '', $cookiejar);
175                 $attachments[$url] = [
176                         'data' => $curlResult->getBody(),
177                         'guid' => hash("crc32", $url),
178                         'filename' => basename($components['path']),
179                         'type' => $curlResult->getContentType()
180                 ];
181
182                 if (strlen($attachments[$url]['data'])) {
183                         $item['body'] = str_replace($url, 'cid:' . $attachments[$url]['guid'], $item['body']);
184                         continue;
185                 }
186         }
187         return $attachments;
188 }
189
190 function mailstream_sender($item) {
191         $r = q('SELECT * FROM `contact` WHERE `id` = %d', $item['contact-id']);
192         if (DBA::isResult($r)) {
193                 $contact = $r[0];
194                 if ($contact['name'] != $item['author-name']) {
195                         return $contact['name'] . ' - ' . $item['author-name'];
196                 }
197         }
198         return $item['author-name'];
199 }
200
201 function mailstream_decode_subject($subject) {
202         $html = BBCode::convert($subject);
203         if (!$html) {
204                 return $subject;
205         }
206         $notags = strip_tags($html);
207         if (!$notags) {
208                 return $subject;
209         }
210         $noentity = html_entity_decode($notags);
211         if (!$noentity) {
212                 return $notags;
213         }
214         $nocodes = preg_replace_callback("/(&#[0-9]+;)/", function($m) { return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES"); }, $noentity);
215         if (!$nocodes) {
216                 return $noentity;
217         }
218         $trimmed = trim($nocodes);
219         if (!$trimmed) {
220                 return $nocodes;
221         }
222         return $trimmed;
223 }
224
225 function mailstream_subject($item) {
226         if ($item['title']) {
227                 return mailstream_decode_subject($item['title']);
228         }
229         $parent = $item['thr-parent'];
230         // Don't look more than 100 levels deep for a subject, in case of loops
231         for ($i = 0; ($i < 100) && $parent; $i++) {
232                 $parent_item = Item::selectFirst(['thr-parent', 'title'], ['uri' => $parent]);
233                 if (!DBA::isResult($parent_item)) {
234                         break;
235                 }
236                 if ($parent_item['thr-parent'] === $parent) {
237                         break;
238                 }
239                 if ($parent_item['title']) {
240                         return L10n::t('Re:') . ' ' . mailstream_decode_subject($parent_item['title']);
241                 }
242                 $parent = $parent_item['thr-parent'];
243         }
244         $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
245                 intval($item['contact-id']), intval($item['uid']));
246         $contact = $r[0];
247         if ($contact['network'] === 'dfrn') {
248                 return L10n::t("Friendica post");
249         }
250         if ($contact['network'] === 'dspr') {
251                 return L10n::t("Diaspora post");
252         }
253         if ($contact['network'] === 'face') {
254                 $text = mailstream_decode_subject($item['body']);
255                 // For some reason these do show up in Facebook
256                 $text = preg_replace('/\xA0$/', '', $text);
257                 $subject = (strlen($text) > 150) ? (substr($text, 0, 140) . '...') : $text;
258                 return preg_replace('/\\s+/', ' ', $subject);
259         }
260         if ($contact['network'] === 'feed') {
261                 return L10n::t("Feed item");
262         }
263         if ($contact['network'] === 'mail') {
264                 return L10n::t("Email");
265         }
266         return L10n::t("Friendica Item");
267 }
268
269 function mailstream_send(\Friendica\App $a, $message_id, $item, $user) {
270         if (!$item['visible']) {
271                 return;
272         }
273         if (!$message_id) {
274                 return;
275         }
276         require_once(dirname(__file__).'/phpmailer/class.phpmailer.php');
277
278         $attachments = [];
279         mailstream_do_images($a, $item, $attachments);
280         $frommail = Config::get('mailstream', 'frommail');
281         if ($frommail == "") {
282                 $frommail = 'friendica@localhost.local';
283         }
284         $address = PConfig::get($item['uid'], 'mailstream', 'address');
285         if (!$address) {
286                 $address = $user['email'];
287         }
288         $mail = new PHPmailer;
289         try {
290                 $mail->XMailer = 'Friendica Mailstream Addon';
291                 $mail->SetFrom($frommail, mailstream_sender($item));
292                 $mail->AddAddress($address, $user['username']);
293                 $mail->MessageID = $message_id;
294                 $mail->Subject = mailstream_subject($item);
295                 if ($item['thr-parent'] != $item['uri']) {
296                         $mail->addCustomHeader('In-Reply-To: ' . mailstream_generate_id($a, $item['thr-parent']));
297                 }
298                 $mail->addCustomHeader('X-Friendica-Mailstream-URI: ' . $item['uri']);
299                 $mail->addCustomHeader('X-Friendica-Mailstream-Plink: ' . $item['plink']);
300                 $encoding = 'base64';
301                 foreach ($attachments as $url => $image) {
302                         $mail->AddStringEmbeddedImage($image['data'], $image['guid'], $image['filename'], $encoding, $image['type']);
303                 }
304                 $mail->IsHTML(true);
305                 $mail->CharSet = 'utf-8';
306                 $template = Renderer::getMarkupTemplate('mail.tpl', 'addon/mailstream/');
307                 $mail->AltBody = BBCode::toPlaintext($item['body']);
308                 $item['body'] = BBCode::convert($item['body']);
309                 $item['url'] = $a->getBaseURL() . '/display/' . $item['guid'];
310                 $mail->Body = Renderer::replaceMacros($template, [
311                                                  '$upstream' => L10n::t('Upstream'),
312                                                  '$local' => L10n::t('Local'),
313                                                  '$item' => $item]);
314                 mailstream_html_wrap($mail->Body);
315                 if (!$mail->Send()) {
316                         throw new Exception($mail->ErrorInfo);
317                 }
318                 Logger::debug('mailstream_send sent message ' . $mail->MessageID . ' ' . $mail->Subject);
319         } catch (phpmailerException $e) {
320                 Logger::debug('mailstream_send PHPMailer exception sending message ' . $message_id . ': ' . $e->errorMessage());
321         } catch (Exception $e) {
322                 Logger::debug('mailstream_send exception sending message ' . $message_id . ': ' . $e->getMessage());
323         }
324         // In case of failure, still set the item to completed.  Otherwise
325         // we'll just try to send it over and over again and it'll fail
326         // every time.
327         q('UPDATE `mailstream_item` SET `completed` = now() WHERE `message-id` = "%s"', DBA::escape($message_id));
328 }
329
330 /**
331  * Email tends to break if you send excessively long lines.  To make
332  * bbcode's output suitable for transmission, we try to break things
333  * up so that lines are about 200 characters.
334  */
335 function mailstream_html_wrap(&$text)
336 {
337         $lines = str_split($text, 200);
338         for ($i = 0; $i < count($lines); $i++) {
339                 $lines[$i] = preg_replace('/ /', "\n", $lines[$i], 1);
340         }
341         $text = implode($lines);
342 }
343
344 function mailstream_cron($a, $b) {
345         // Only process items older than an hour in cron.  This is because
346         // we want to give mailstream_post_remote_hook a fair chance to
347         // send the email itself before cron jumps in.  Only if
348         // mailstream_post_remote_hook fails for some reason will this get
349         // used, and in that case it's worth holding off a bit anyway.
350         $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");
351         Logger::debug('mailstream_cron processing ' . count($ms_item_ids) . ' items');
352         foreach ($ms_item_ids as $ms_item_id) {
353                 if (!$ms_item_id['message-id'] || !strlen($ms_item_id['message-id'])) {
354                         Logger::info('mailstream_cron: Item ' . $ms_item_id['id'] . ' URI ' . $ms_item_id['uri'] . ' has no message-id');
355                 }
356                 $item = Item::selectFirst([], ['id' => $ms_item_id['id']]);
357                 $users = q("SELECT * FROM `user` WHERE `uid` = %d", intval($item['uid']));
358                 $user = $users[0];
359                 if ($user && $item) {
360                         mailstream_send($a, $ms_item_id['message-id'], $item, $user);
361                 }
362                 else {
363                         Logger::info('mailstream_cron: Unable to find item ' . $ms_item_id['id']);
364                         q("UPDATE `mailstream_item` SET `completed` = now() WHERE `message-id` = %d", intval($ms_item['message-id']));
365                 }
366         }
367         mailstream_tidy();
368 }
369
370 function mailstream_addon_settings(&$a,&$s) {
371         $enabled = PConfig::get(local_user(), 'mailstream', 'enabled');
372         $address = PConfig::get(local_user(), 'mailstream', 'address');
373         $nolikes = PConfig::get(local_user(), 'mailstream', 'nolikes');
374         $attachimg= PConfig::get(local_user(), 'mailstream', 'attachimg');
375         $template = Renderer::getMarkupTemplate('settings.tpl', 'addon/mailstream/');
376         $s .= Renderer::replaceMacros($template, [
377                                  '$enabled' => [
378                                         'mailstream_enabled',
379                                         L10n::t('Enabled'),
380                                         $enabled],
381                                  '$address' => [
382                                         'mailstream_address',
383                                         L10n::t('Email Address'),
384                                         $address,
385                                         L10n::t("Leave blank to use your account email address")],
386                                  '$nolikes' => [
387                                         'mailstream_nolikes',
388                                         L10n::t('Exclude Likes'),
389                                         $nolikes,
390                                         L10n::t("Check this to omit mailing \"Like\" notifications")],
391                                  '$attachimg' => [
392                                         'mailstream_attachimg',
393                                         L10n::t('Attach Images'),
394                                         $attachimg,
395                                         L10n::t("Download images in posts and attach them to the email.  Useful for reading email while offline.")],
396                                  '$title' => L10n::t('Mail Stream Settings'),
397                                  '$submit' => L10n::t('Save Settings')]);
398 }
399
400 function mailstream_addon_settings_post($a,$post) {
401         if ($_POST['mailstream_address'] != "") {
402                 PConfig::set(local_user(), 'mailstream', 'address', $_POST['mailstream_address']);
403         }
404         else {
405                 PConfig::delete(local_user(), 'mailstream', 'address');
406         }
407         if ($_POST['mailstream_nolikes']) {
408                 PConfig::set(local_user(), 'mailstream', 'nolikes', $_POST['mailstream_enabled']);
409         }
410         else {
411                 PConfig::delete(local_user(), 'mailstream', 'nolikes');
412         }
413         if ($_POST['mailstream_enabled']) {
414                 PConfig::set(local_user(), 'mailstream', 'enabled', $_POST['mailstream_enabled']);
415         }
416         else {
417                 PConfig::delete(local_user(), 'mailstream', 'enabled');
418         }
419         if ($_POST['mailstream_attachimg']) {
420                 PConfig::set(local_user(), 'mailstream', 'attachimg', $_POST['mailstream_attachimg']);
421         }
422         else {
423                 PConfig::delete(local_user(), 'mailstream', 'attachimg');
424         }
425 }
426
427 function mailstream_tidy() {
428         $r = q("SELECT id FROM mailstream_item WHERE completed IS NOT NULL AND completed < DATE_SUB(NOW(), INTERVAL 1 YEAR)");
429         foreach ($r as $rr) {
430                 q('DELETE FROM mailstream_item WHERE id = %d', intval($rr['id']));
431         }
432         Logger::debug('mailstream_tidy: deleted ' . count($r) . ' old items');
433 }