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