]> git.mxchange.org Git - friendica.git/blob - include/enotify.php
Issue 5158: Ignore all threads, even public ones (#5588)
[friendica.git] / include / enotify.php
1 <?php
2 /**
3  * @file include/enotify.php
4  */
5
6 use Friendica\Content\Text\BBCode;
7 use Friendica\Core\Addon;
8 use Friendica\Core\Config;
9 use Friendica\Core\L10n;
10 use Friendica\Core\System;
11 use Friendica\Database\DBA;
12 use Friendica\Model\Contact;
13 use Friendica\Model\Item;
14 use Friendica\Util\DateTimeFormat;
15 use Friendica\Util\Emailer;
16
17 /**
18  * @brief Creates a notification entry and possibly sends a mail
19  *
20  * @param array $params Array with the elements:
21  *                      uid, item, parent, type, otype, verb, event,
22  *                      link, subject, body, to_name, to_email, source_name,
23  *                      source_link, activity, preamble, notify_flags,
24  *                      language, show_in_notification_page
25  */
26 function notification($params)
27 {
28         $a = get_app();
29
30         // Temporary logging for finding the origin
31         if (!isset($params['language']) || !isset($params['uid'])) {
32                 logger('Missing parameters.' . System::callstack());
33         }
34
35         // from here on everything is in the recipients language
36         L10n::pushLang($params['language']);
37
38         $banner = L10n::t('Friendica Notification');
39         $product = FRIENDICA_PLATFORM;
40         $siteurl = System::baseUrl(true);
41         $thanks = L10n::t('Thank You,');
42         $sitename = Config::get('config', 'sitename');
43         if (Config::get('config', 'admin_name')) {
44                 $site_admin = L10n::t('%1$s, %2$s Administrator', Config::get('config', 'admin_name'), $sitename);
45         } else {
46                 $site_admin = L10n::t('%s Administrator', $sitename);
47         }
48
49         $sender_name = $sitename;
50         $hostname = $a->get_hostname();
51         if (strpos($hostname, ':')) {
52                 $hostname = substr($hostname, 0, strpos($hostname, ':'));
53         }
54
55         $sender_email = $a->getSenderEmailAddress();
56
57         if ($params['type'] != SYSTEM_EMAIL) {
58                 $user = DBA::selectFirst('user', ['nickname', 'page-flags'],
59                         ['uid' => $params['uid']]);
60
61                 // There is no need to create notifications for forum accounts
62                 if (!DBA::isResult($user) || in_array($user["page-flags"], [Contact::PAGE_COMMUNITY, Contact::PAGE_PRVGROUP])) {
63                         return;
64                 }
65                 $nickname = $user["nickname"];
66         } else {
67                 $nickname = '';
68         }
69
70         // with $params['show_in_notification_page'] == false, the notification isn't inserted into
71         // the database, and an email is sent if applicable.
72         // default, if not specified: true
73         $show_in_notification_page = ((x($params, 'show_in_notification_page')) ? $params['show_in_notification_page']:true);
74
75         $additional_mail_header = "";
76         $additional_mail_header .= "Precedence: list\n";
77         $additional_mail_header .= "X-Friendica-Host: ".$hostname."\n";
78         $additional_mail_header .= "X-Friendica-Account: <".$nickname."@".$hostname.">\n";
79         $additional_mail_header .= "X-Friendica-Platform: ".FRIENDICA_PLATFORM."\n";
80         $additional_mail_header .= "X-Friendica-Version: ".FRIENDICA_VERSION."\n";
81         $additional_mail_header .= "List-ID: <notification.".$hostname.">\n";
82         $additional_mail_header .= "List-Archive: <".System::baseUrl()."/notifications/system>\n";
83
84         if (array_key_exists('item', $params)) {
85                 $title = $params['item']['title'];
86                 $body = $params['item']['body'];
87         } else {
88                 $title = $body = '';
89         }
90
91         if (isset($params['item']['id'])) {
92                 $item_id = $params['item']['id'];
93         } else {
94                 $item_id = 0;
95         }
96
97         if (isset($params['parent'])) {
98                 $parent_id = $params['parent'];
99         } else {
100                 $parent_id = 0;
101         }
102
103         $epreamble = '';
104
105         if ($params['type'] == NOTIFY_MAIL) {
106                 $itemlink = $siteurl.'/message/'.$params['item']['id'];
107                 $params["link"] = $itemlink;
108
109                 $subject = L10n::t('[Friendica:Notify] New mail received at %s', $sitename);
110
111                 $preamble = L10n::t('%1$s sent you a new private message at %2$s.', $params['source_name'], $sitename);
112                 $epreamble = L10n::t('%1$s sent you %2$s.', '[url='.$params['source_link'].']'.$params['source_name'].'[/url]', '[url=$itemlink]'.L10n::t('a private message').'[/url]');
113
114                 $sitelink = L10n::t('Please visit %s to view and/or reply to your private messages.');
115                 $tsitelink = sprintf($sitelink, $siteurl.'/message/'.$params['item']['id']);
116                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'/message/'.$params['item']['id'].'">'.$sitename.'</a>');
117         }
118
119         if ($params['type'] == NOTIFY_COMMENT) {
120                 $thread = Item::selectFirstThreadForUser($params['uid'] ,['ignored'], ['iid' => $parent_id]);
121                 if (DBA::isResult($thread) && $thread["ignored"]) {
122                         logger("Thread ".$parent_id." will be ignored", LOGGER_DEBUG);
123                         return;
124                 }
125
126                 // Check to see if there was already a tag notify or comment notify for this post.
127                 // If so don't create a second notification
128                 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d, %d) AND `link` = '%s' AND `uid` = %d LIMIT 1",
129                         intval(NOTIFY_TAGSELF),
130                         intval(NOTIFY_COMMENT),
131                         intval(NOTIFY_SHARE),
132                         DBA::escape($params['link']),
133                         intval($params['uid'])
134                 );
135                 if ($p && count($p)) {
136                         L10n::popLang();
137                         return;
138                 }
139
140                 // if it's a post figure out who's post it is.
141
142                 $item = null;
143
144                 if ($params['otype'] === 'item' && $parent_id) {
145                         $item = Item::selectFirstForUser($params['uid'], Item::ITEM_FIELDLIST, ['id' => $parent_id]);
146                 }
147
148                 $item_post_type = item_post_type($item);
149                 $itemlink = $item['plink'];
150
151                 // "a post"
152                 $dest_str = L10n::t('%1$s commented on [url=%2$s]a %3$s[/url]',
153                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
154                         $itemlink,
155                         $item_post_type
156                 );
157
158                 // "George Bull's post"
159                 if ($item) {
160                         $dest_str = L10n::t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]',
161                                 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
162                                 $itemlink,
163                                 $item['author-name'],
164                                 $item_post_type
165                         );
166                 }
167
168                 // "your post"
169                 if (DBA::isResult($item) && $item['owner-id'] == $item['author-id'] && $item['wall']) {
170                         $dest_str = L10n::t('%1$s commented on [url=%2$s]your %3$s[/url]',
171                                 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
172                                 $itemlink,
173                                 $item_post_type
174                         );
175                 }
176
177                 // Some mail softwares relies on subject field for threading.
178                 // So, we cannot have different subjects for notifications of the same thread.
179                 // Before this we have the name of the replier on the subject rendering
180                 // differents subjects for messages on the same thread.
181
182                 $subject = L10n::t('[Friendica:Notify] Comment to conversation #%1$d by %2$s', $parent_id, $params['source_name']);
183
184                 $preamble = L10n::t('%s commented on an item/conversation you have been following.', $params['source_name']);
185                 $epreamble = $dest_str;
186
187                 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
188                 $tsitelink = sprintf($sitelink, $siteurl);
189                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
190                 $itemlink =  $params['link'];
191         }
192
193         if ($params['type'] == NOTIFY_WALL) {
194                 $subject = L10n::t('[Friendica:Notify] %s posted to your profile wall', $params['source_name']);
195
196                 $preamble = L10n::t('%1$s posted to your profile wall at %2$s', $params['source_name'], $sitename);
197                 $epreamble = L10n::t('%1$s posted to [url=%2$s]your wall[/url]',
198                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
199                         $params['link']
200                 );
201
202                 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
203                 $tsitelink = sprintf($sitelink, $siteurl);
204                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
205                 $itemlink =  $params['link'];
206         }
207
208         if ($params['type'] == NOTIFY_TAGSELF) {
209                 $subject = L10n::t('[Friendica:Notify] %s tagged you', $params['source_name']);
210
211                 $preamble = L10n::t('%1$s tagged you at %2$s', $params['source_name'], $sitename);
212                 $epreamble = L10n::t('%1$s [url=%2$s]tagged you[/url].',
213                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
214                         $params['link']
215                 );
216
217                 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
218                 $tsitelink = sprintf($sitelink, $siteurl);
219                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
220                 $itemlink =  $params['link'];
221         }
222
223         if ($params['type'] == NOTIFY_SHARE) {
224                 $subject = L10n::t('[Friendica:Notify] %s shared a new post', $params['source_name']);
225
226                 $preamble = L10n::t('%1$s shared a new post at %2$s', $params['source_name'], $sitename);
227                 $epreamble = L10n::t('%1$s [url=%2$s]shared a post[/url].',
228                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
229                         $params['link']
230                 );
231
232                 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
233                 $tsitelink = sprintf($sitelink, $siteurl);
234                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
235                 $itemlink =  $params['link'];
236         }
237
238         if ($params['type'] == NOTIFY_POKE) {
239                 $subject = L10n::t('[Friendica:Notify] %1$s poked you', $params['source_name']);
240
241                 $preamble = L10n::t('%1$s poked you at %2$s', $params['source_name'], $sitename);
242                 $epreamble = L10n::t('%1$s [url=%2$s]poked you[/url].',
243                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
244                         $params['link']
245                 );
246
247                 $subject = str_replace('poked', L10n::t($params['activity']), $subject);
248                 $preamble = str_replace('poked', L10n::t($params['activity']), $preamble);
249                 $epreamble = str_replace('poked', L10n::t($params['activity']), $epreamble);
250
251                 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
252                 $tsitelink = sprintf($sitelink, $siteurl);
253                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
254                 $itemlink =  $params['link'];
255         }
256
257         if ($params['type'] == NOTIFY_TAGSHARE) {
258                 $itemlink =  $params['link'];
259                 $subject = L10n::t('[Friendica:Notify] %s tagged your post', $params['source_name']);
260
261                 $preamble = L10n::t('%1$s tagged your post at %2$s', $params['source_name'], $sitename);
262                 $epreamble = L10n::t('%1$s tagged [url=%2$s]your post[/url]',
263                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
264                         $itemlink
265                 );
266
267                 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
268                 $tsitelink = sprintf($sitelink, $siteurl);
269                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
270         }
271
272         if ($params['type'] == NOTIFY_INTRO) {
273                 $itemlink = $params['link'];
274                 $subject = L10n::t('[Friendica:Notify] Introduction received');
275
276                 $preamble = L10n::t('You\'ve received an introduction from \'%1$s\' at %2$s', $params['source_name'], $sitename);
277                 $epreamble = L10n::t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.',
278                         $itemlink,
279                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
280                 );
281
282                 $body = L10n::t('You may visit their profile at %s', $params['source_link']);
283
284                 $sitelink = L10n::t('Please visit %s to approve or reject the introduction.');
285                 $tsitelink = sprintf($sitelink, $siteurl);
286                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
287
288                 switch ($params['verb']) {
289                         case ACTIVITY_FRIEND:
290                                 // someone started to share with user (mostly OStatus)
291                                 $subject = L10n::t('[Friendica:Notify] A new person is sharing with you');
292
293                                 $preamble = L10n::t('%1$s is sharing with you at %2$s', $params['source_name'], $sitename);
294                                 $epreamble = L10n::t('%1$s is sharing with you at %2$s',
295                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
296                                         $sitename
297                                 );
298                                 break;
299                         case ACTIVITY_FOLLOW:
300                                 // someone started to follow the user (mostly OStatus)
301                                 $subject = L10n::t('[Friendica:Notify] You have a new follower');
302
303                                 $preamble = L10n::t('You have a new follower at %2$s : %1$s', $params['source_name'], $sitename);
304                                 $epreamble = L10n::t('You have a new follower at %2$s : %1$s',
305                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
306                                         $sitename
307                                 );
308                                 break;
309                         default:
310                                 // ACTIVITY_REQ_FRIEND is default activity for notifications
311                                 break;
312                 }
313         }
314
315         if ($params['type'] == NOTIFY_SUGGEST) {
316                 $itemlink =  $params['link'];
317                 $subject = L10n::t('[Friendica:Notify] Friend suggestion received');
318
319                 $preamble = L10n::t('You\'ve received a friend suggestion from \'%1$s\' at %2$s', $params['source_name'], $sitename);
320                 $epreamble = L10n::t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.',
321                         $itemlink,
322                         '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
323                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
324                 );
325
326                 $body = L10n::t('Name:').' '.$params['item']['name']."\n";
327                 $body .= L10n::t('Photo:').' '.$params['item']['photo']."\n";
328                 $body .= L10n::t('You may visit their profile at %s', $params['item']['url']);
329
330                 $sitelink = L10n::t('Please visit %s to approve or reject the suggestion.');
331                 $tsitelink = sprintf($sitelink, $siteurl);
332                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
333         }
334
335         if ($params['type'] == NOTIFY_CONFIRM) {
336                 if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
337                         $itemlink =  $params['link'];
338                         $subject = L10n::t('[Friendica:Notify] Connection accepted');
339
340                         $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
341                         $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
342                                 $itemlink,
343                                 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
344                         );
345
346                         $body =  L10n::t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
347
348                         $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
349                         $tsitelink = sprintf($sitelink, $siteurl);
350                         $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
351                 } else { // ACTIVITY_FOLLOW
352                         $itemlink =  $params['link'];
353                         $subject = L10n::t('[Friendica:Notify] Connection accepted');
354
355                         $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
356                         $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
357                                 $itemlink,
358                                 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
359                         );
360
361                         $body =  L10n::t('\'%1$s\' has chosen to accept you a fan, which restricts some forms of communication - such as private messaging and some profile interactions. If this is a celebrity or community page, these settings were applied automatically.', $params['source_name']);
362                         $body .= "\n\n";
363                         $body .= L10n::t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.', $params['source_name']);
364
365                         $sitelink = L10n::t('Please visit %s  if you wish to make any changes to this relationship.');
366                         $tsitelink = sprintf($sitelink, $siteurl);
367                         $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
368                 }
369         }
370
371         if ($params['type'] == NOTIFY_SYSTEM) {
372                 switch($params['event']) {
373                         case "SYSTEM_REGISTER_REQUEST":
374                                 $itemlink =  $params['link'];
375                                 $subject = L10n::t('[Friendica System Notify]') . ' ' . L10n::t('registration request');
376
377                                 $preamble = L10n::t('You\'ve received a registration request from \'%1$s\' at %2$s', $params['source_name'], $sitename);
378                                 $epreamble = L10n::t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.',
379                                         $itemlink,
380                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
381                                 );
382
383                                 $body = L10n::t("Full Name:     %s\nSite Location:      %s\nLogin Name: %s (%s)",
384                                         $params['source_name'],
385                                         $siteurl, $params['source_mail'],
386                                         $params['source_nick']
387                                 );
388
389                                 $sitelink = L10n::t('Please visit %s to approve or reject the request.');
390                                 $tsitelink = sprintf($sitelink, $params['link']);
391                                 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
392                                 break;
393                         case "SYSTEM_DB_UPDATE_FAIL":
394                                 break;
395                 }
396         }
397
398         if ($params['type'] == SYSTEM_EMAIL) {
399                 // not part of the notifications.
400                 // it just send a mail to the user.
401                 // It will be used by the system to send emails to users (like
402                 // password reset, invitations and so) using one look (but without
403                 // add a notification to the user, with could be inexistent)
404                 $subject = $params['subject'];
405
406                 $preamble = $params['preamble'];
407
408                 $body =  $params['body'];
409
410                 $sitelink = "";
411                 $tsitelink = "";
412                 $hsitelink = "";
413                 $itemlink =  "";
414                 $show_in_notification_page = false;
415         }
416
417         $subject .= " (".$nickname."@".$hostname.")";
418
419         $h = [
420                 'params'    => $params,
421                 'subject'   => $subject,
422                 'preamble'  => $preamble,
423                 'epreamble' => $epreamble,
424                 'body'      => $body,
425                 'sitelink'  => $sitelink,
426                 'tsitelink' => $tsitelink,
427                 'hsitelink' => $hsitelink,
428                 'itemlink'  => $itemlink
429         ];
430
431         Addon::callHooks('enotify', $h);
432
433         $subject   = $h['subject'];
434
435         $preamble  = $h['preamble'];
436         $epreamble = $h['epreamble'];
437
438         $body      = $h['body'];
439
440         $tsitelink = $h['tsitelink'];
441         $hsitelink = $h['hsitelink'];
442         $itemlink  = $h['itemlink'];
443
444         if ($show_in_notification_page) {
445                 logger("adding notification entry", LOGGER_DEBUG);
446                 do {
447                         $dups = false;
448                         $hash = random_string();
449                         $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' LIMIT 1",
450                                 DBA::escape($hash));
451                         if (DBA::isResult($r)) {
452                                 $dups = true;
453                         }
454                 } while ($dups == true);
455
456                 /// @TODO One statement is enough
457                 $datarray = [];
458                 $datarray['hash']  = $hash;
459                 $datarray['name']  = $params['source_name'];
460                 $datarray['name_cache'] = strip_tags(BBCode::convert($params['source_name']));
461                 $datarray['url']   = $params['source_link'];
462                 $datarray['photo'] = $params['source_photo'];
463                 $datarray['date']  = DateTimeFormat::utcNow();
464                 $datarray['uid']   = $params['uid'];
465                 $datarray['link']  = $itemlink;
466                 $datarray['iid']   = $item_id;
467                 $datarray['parent'] = $parent_id;
468                 $datarray['type']  = $params['type'];
469                 $datarray['verb']  = $params['verb'];
470                 $datarray['otype'] = $params['otype'];
471                 $datarray['abort'] = false;
472
473                 Addon::callHooks('enotify_store', $datarray);
474
475                 if ($datarray['abort']) {
476                         L10n::popLang();
477                         return False;
478                 }
479
480                 // create notification entry in DB
481                 q("INSERT INTO `notify` (`hash`, `name`, `url`, `photo`, `date`, `uid`, `link`, `iid`, `parent`, `type`, `verb`, `otype`, `name_cache`)
482                         values('%s', '%s', '%s', '%s', '%s', %d, '%s', %d, %d, %d, '%s', '%s', '%s')",
483                         DBA::escape($datarray['hash']),
484                         DBA::escape($datarray['name']),
485                         DBA::escape($datarray['url']),
486                         DBA::escape($datarray['photo']),
487                         DBA::escape($datarray['date']),
488                         intval($datarray['uid']),
489                         DBA::escape($datarray['link']),
490                         intval($datarray['iid']),
491                         intval($datarray['parent']),
492                         intval($datarray['type']),
493                         DBA::escape($datarray['verb']),
494                         DBA::escape($datarray['otype']),
495                         DBA::escape($datarray["name_cache"])
496                 );
497
498                 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' AND `uid` = %d LIMIT 1",
499                         DBA::escape($hash),
500                         intval($params['uid'])
501                 );
502                 if ($r) {
503                         $notify_id = $r[0]['id'];
504                 } else {
505                         L10n::popLang();
506                         return False;
507                 }
508
509                 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
510                 // After we've stored everything, look again to see if there are any duplicates and if so remove them
511                 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
512                         intval(NOTIFY_TAGSELF),
513                         intval(NOTIFY_COMMENT),
514                         DBA::escape($params['link']),
515                         intval($params['uid'])
516                 );
517                 if ($p && (count($p) > 1)) {
518                         for ($d = 1; $d < count($p); $d ++) {
519                                 DBA::delete('notify', ['id' => $p[$d]['id']]);
520                         }
521
522                         // only continue on if we stored the first one
523                         if ($notify_id != $p[0]['id']) {
524                                 L10n::popLang();
525                                 return false;
526                         }
527                 }
528
529                 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
530                 $msg = replace_macros($epreamble, ['$itemlink' => $itemlink]);
531                 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(BBCode::convert($msg)));
532                 q("UPDATE `notify` SET `msg` = '%s', `msg_cache` = '%s' WHERE `id` = %d AND `uid` = %d",
533                         DBA::escape($msg),
534                         DBA::escape($msg_cache),
535                         intval($notify_id),
536                         intval($params['uid'])
537                 );
538         }
539
540         // send email notification if notification preferences permit
541         if ((!empty($params['notify_flags']) & intval($params['type']))
542                 || $params['type'] == NOTIFY_SYSTEM
543                 || $params['type'] == SYSTEM_EMAIL) {
544
545                 logger('sending notification email');
546
547                 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
548                         $id_for_parent = $params['parent']."@".$hostname;
549
550                         // Is this the first email notification for this parent item and user?
551
552                         $r = q("SELECT `id` FROM `notify-threads` WHERE `master-parent-item` = %d AND `receiver-uid` = %d LIMIT 1",
553                                 intval($params['parent']),
554                                 intval($params['uid']));
555
556                         // If so, create the record of it and use a message-id smtp header.
557
558                         if (!$r) {
559                                 logger("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), LOGGER_DEBUG);
560                                 q("INSERT INTO `notify-threads` (`notify-id`, `master-parent-item`, `receiver-uid`, `parent-item`)
561                                         values(%d, %d, %d, %d)",
562                                         intval($notify_id),
563                                         intval($params['parent']),
564                                         intval($params['uid']),
565                                         0);
566
567                                 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
568                                 $log_msg = "include/enotify: No previous notification found for this parent:\n".
569                                                 "  parent: ${params['parent']}\n"."  uid   : ${params['uid']}\n";
570                                 logger($log_msg, LOGGER_DEBUG);
571                         } else {
572                                 // If not, just "follow" the thread.
573                                 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
574                                 logger("There's already a notification for this parent:\n".print_r($r, true), LOGGER_DEBUG);
575                         }
576                 }
577
578                 $textversion = BBCode::toPlaintext($body);
579                 $htmlversion = BBCode::convert($body);
580
581                 $datarray = [];
582                 $datarray['banner'] = $banner;
583                 $datarray['product'] = $product;
584                 $datarray['preamble'] = $preamble;
585                 $datarray['sitename'] = $sitename;
586                 $datarray['siteurl'] = $siteurl;
587                 $datarray['type'] = $params['type'];
588                 $datarray['parent'] = $parent_id;
589                 $datarray['source_name'] = defaults($params, 'source_name', '');
590                 $datarray['source_link'] = defaults($params, 'source_link', '');
591                 $datarray['source_photo'] = defaults($params, 'source_photo', '');
592                 $datarray['uid'] = $params['uid'];
593                 $datarray['username'] = defaults($params, 'to_name', '');
594                 $datarray['hsitelink'] = $hsitelink;
595                 $datarray['tsitelink'] = $tsitelink;
596                 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
597                 $datarray['titemlink'] = $itemlink;
598                 $datarray['thanks'] = $thanks;
599                 $datarray['site_admin'] = $site_admin;
600                 $datarray['title'] = stripslashes($title);
601                 $datarray['htmlversion'] = $htmlversion;
602                 $datarray['textversion'] = $textversion;
603                 $datarray['subject'] = $subject;
604                 $datarray['headers'] = $additional_mail_header;
605
606                 Addon::callHooks('enotify_mail', $datarray);
607
608                 // check whether sending post content in email notifications is allowed
609                 // always true for SYSTEM_EMAIL
610                 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
611
612                 // load the template for private message notifications
613                 $tpl = get_markup_template('email_notify_html.tpl');
614                 $email_html_body = replace_macros($tpl, [
615                         '$banner'       => $datarray['banner'],
616                         '$product'      => $datarray['product'],
617                         '$preamble'     => str_replace("\n", "<br>\n", $datarray['preamble']),
618                         '$sitename'     => $datarray['sitename'],
619                         '$siteurl'      => $datarray['siteurl'],
620                         '$source_name'  => $datarray['source_name'],
621                         '$source_link'  => $datarray['source_link'],
622                         '$source_photo' => $datarray['source_photo'],
623                         '$username'     => $datarray['username'],
624                         '$hsitelink'    => $datarray['hsitelink'],
625                         '$hitemlink'    => $datarray['hitemlink'],
626                         '$thanks'       => $datarray['thanks'],
627                         '$site_admin'   => $datarray['site_admin'],
628                         '$title'        => $datarray['title'],
629                         '$htmlversion'  => $datarray['htmlversion'],
630                         '$content_allowed'      => $content_allowed,
631                 ]);
632
633                 // load the template for private message notifications
634                 $tpl = get_markup_template('email_notify_text.tpl');
635                 $email_text_body = replace_macros($tpl, [
636                         '$banner'       => $datarray['banner'],
637                         '$product'      => $datarray['product'],
638                         '$preamble'     => $datarray['preamble'],
639                         '$sitename'     => $datarray['sitename'],
640                         '$siteurl'      => $datarray['siteurl'],
641                         '$source_name'  => $datarray['source_name'],
642                         '$source_link'  => $datarray['source_link'],
643                         '$source_photo' => $datarray['source_photo'],
644                         '$username'     => $datarray['username'],
645                         '$tsitelink'    => $datarray['tsitelink'],
646                         '$titemlink'    => $datarray['titemlink'],
647                         '$thanks'       => $datarray['thanks'],
648                         '$site_admin'   => $datarray['site_admin'],
649                         '$title'        => $datarray['title'],
650                         '$textversion'  => $datarray['textversion'],
651                         '$content_allowed'      => $content_allowed,
652                 ]);
653
654                 // use the Emailer class to send the message
655                 return Emailer::send(
656                         [
657                         'uid' => $params['uid'],
658                         'fromName' => $sender_name,
659                         'fromEmail' => $sender_email,
660                         'replyTo' => $sender_email,
661                         'toEmail' => $params['to_email'],
662                         'messageSubject' => $datarray['subject'],
663                         'htmlVersion' => $email_html_body,
664                         'textVersion' => $email_text_body,
665                         'additionalMailHeader' => $datarray['headers']]
666                 );
667         }
668
669         return false;
670 }
671
672 /**
673  * @brief Checks for users who should be notified
674  *
675  * @param int $itemid ID of the item for which the check should be done
676  */
677 function check_user_notification($itemid) {
678         // fetch all users in the thread
679         $users = DBA::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
680                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
681                         WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
682         while ($user = DBA::fetch($users)) {
683                 check_item_notification($itemid, $user['uid']);
684         }
685         DBA::close($users);
686 }
687
688 /**
689  * @brief Checks for item related notifications and sends them
690  *
691  * @param int $itemid ID of the item for which the check should be done
692  * @param int $uid User ID
693  * @param string $defaulttype (Optional) Forces a notification with this type.
694  */
695 function check_item_notification($itemid, $uid, $defaulttype = "") {
696         $notification_data = ["uid" => $uid, "profiles" => []];
697         Addon::callHooks('check_item_notification', $notification_data);
698
699         $profiles = $notification_data["profiles"];
700
701         $fields = ['notify-flags', 'language', 'username', 'email', 'nickname'];
702         $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
703         if (!DBA::isResult($user)) {
704                 return false;
705         }
706
707         $owner = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
708         if (!DBA::isResult($owner)) {
709                 return false;
710         }
711
712         // This is our regular URL format
713         $profiles[] = $owner["url"];
714
715         // Notifications from Diaspora are often with an URL in the Diaspora format
716         $profiles[] = System::baseUrl()."/u/".$user["nickname"];
717
718         $profiles2 = [];
719
720         foreach ($profiles AS $profile) {
721                 // Check for invalid profile urls. 13 should be the shortest possible profile length:
722                 // http://a.bc/d
723                 // Additionally check for invalid urls that would return the normalised value "http:"
724                 if ((strlen($profile) >= 13) && (normalise_link($profile) != "http:")) {
725                         if (!in_array($profile, $profiles2))
726                                 $profiles2[] = $profile;
727
728                         $profile = normalise_link($profile);
729                         if (!in_array($profile, $profiles2))
730                                 $profiles2[] = $profile;
731
732                         $profile = str_replace("http://", "https://", $profile);
733                         if (!in_array($profile, $profiles2))
734                                 $profiles2[] = $profile;
735                 }
736         }
737
738         $profiles = $profiles2;
739
740         $ret = DBA::select('contact', ['id'], ['uid' => 0, 'nurl' => $profiles]);
741
742         $contacts = [];
743
744         while ($contact = DBA::fetch($ret)) {
745                 $contacts[] = $contact['id'];
746         }
747
748         $contact_list = implode(',', $contacts);
749
750         DBA::close($ret);
751
752         // Only act if it is a "real" post
753         // We need the additional check for the "local_profile" because of mixed situations on connector networks
754         $fields = ['id', 'mention', 'tag', 'parent', 'title', 'body',
755                 'author-link', 'author-name', 'author-avatar', 'author-id',
756                 'guid', 'parent-uri', 'uri', 'contact-id', 'network'];
757         $condition = ['id' => $itemid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
758         $item = Item::selectFirst($fields, $condition);
759         if (!DBA::isResult($item) || in_array($item['author-id'], $contacts)) {
760                 return;
761         }
762
763         // Generate the notification array
764         $params = [];
765         $params["uid"] = $uid;
766         $params["notify_flags"] = $user["notify-flags"];
767         $params["language"] = $user["language"];
768         $params["to_name"] = $user["username"];
769         $params["to_email"] = $user["email"];
770         $params["item"] = $item;
771         $params["parent"] = $item["parent"];
772         $params["link"] = System::baseUrl().'/display/'.urlencode($item["guid"]);
773         $params["otype"] = 'item';
774         $params["source_name"] = $item["author-name"];
775         $params["source_link"] = $item["author-link"];
776         $params["source_photo"] = $item["author-avatar"];
777
778         if ($item["parent-uri"] === $item["uri"]) {
779                 // Send a notification for every new post?
780                 $send_notification = DBA::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true]);
781
782                 if (!$send_notification) {
783                         $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
784                                 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
785
786                         if (DBA::isResult($tags)) {
787                                 foreach ($tags AS $tag) {
788                                         $condition = ['nurl' => normalise_link($tag["url"]), 'uid' => $uid, 'notify_new_posts' => true];
789                                         $r = DBA::exists('contact', $condition);
790                                         if ($r) {
791                                                 $send_notification = true;
792                                         }
793                                 }
794                         }
795                 }
796
797                 if ($send_notification) {
798                         $params["type"] = NOTIFY_SHARE;
799                         $params["verb"] = ACTIVITY_TAG;
800                 }
801         }
802
803         // Is the user mentioned in this post?
804         $tagged = false;
805
806         foreach ($profiles AS $profile) {
807                 if (strpos($item["tag"], "=".$profile."]") || strpos($item["body"], "=".$profile."]"))
808                         $tagged = true;
809         }
810
811         if ($item["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
812                 $params["type"] = NOTIFY_TAGSELF;
813                 $params["verb"] = ACTIVITY_TAG;
814         }
815
816         // Is it a post that the user had started or where he interacted?
817         $fields = ['ignored', 'mention', 'author-id'];
818         $thread = Item::selectFirstThreadForUser($params['uid'], $fields, ['iid' => $item["parent"]]);
819
820         if (($thread['mention'] || in_array($thread['author-id'], $contacts)) && !$thread['ignored'] && !isset($params["type"])) {
821                 $params["type"] = NOTIFY_COMMENT;
822                 $params["verb"] = ACTIVITY_POST;
823         }
824
825         if (isset($params["type"]))
826                 notification($params);
827 }
828
829 /**
830  * @brief Formats a notification message with the notification author
831  *
832  * Replace the name with {0} but ensure to make that only once. The {0} is used
833  * later and prints the name in bold.
834  *
835  * @param string $name
836  * @param string $message
837  * @return string Formatted message
838  */
839 function format_notification_message($name, $message) {
840         if ($name != '') {
841                 $pos = strpos($message, $name);
842         } else {
843                 $pos = false;
844         }
845
846         if ($pos !== false) {
847                 $message = substr_replace($message, '{0}', $pos, strlen($name));
848         }
849
850         return $message;
851 }