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