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