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