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