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