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