]> git.mxchange.org Git - friendica.git/blob - include/enotify.php
Merge pull request #8170 from nupplaphil/task/repo_notification
[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\Notify;
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 = DI::config()->get('config', 'sitename');
64         if (DI::config()->get('config', 'admin_name')) {
65                 $site_admin = $l10n->t('%1$s, %2$s Administrator', DI::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'] === Notify::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                 $notification = DI::notify()->insert([
487                         'name'   => $params['source_name'],
488                         'url'    => $params['source_link'],
489                         'photo'  => $params['source_photo'],
490                         'uid'    => $params['uid'],
491                         'iid'    => $item_id,
492                         'parent' => $parent_id,
493                         'type'   => $params['type'],
494                         'verb'   => $params['verb'],
495                         'otype'  => $params['otype'],
496                 ]);
497
498                 $notification->link = DI::baseUrl() . '/notification/view/' . $notification->id;
499                 $notification->msg  = Renderer::replaceMacros($epreamble, ['$itemlink' => $notification->link]);
500
501                 DI::notify()->update($notification);
502
503                 $itemlink  = $notification->link;
504                 $notify_id = $notification->id;
505         }
506
507         // send email notification if notification preferences permit
508         if ((intval($params['notify_flags']) & intval($params['type']))
509                 || $params['type'] == NOTIFY_SYSTEM
510                 || $params['type'] == SYSTEM_EMAIL) {
511
512                 Logger::log('sending notification email');
513
514                 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
515                         $id_for_parent = $params['parent']."@".$hostname;
516
517                         // Is this the first email notification for this parent item and user?
518                         if (!DBA::exists('notify-threads', ['master-parent-item' => $params['parent'], 'receiver-uid' => $params['uid']])) {
519                                 Logger::log("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), Logger::DEBUG);
520
521                                 $fields = ['notify-id' => $notify_id, 'master-parent-item' => $params['parent'],
522                                         'receiver-uid' => $params['uid'], 'parent-item' => 0];
523                                 DBA::insert('notify-threads', $fields);
524
525                                 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
526                                 $log_msg = "include/enotify: No previous notification found for this parent:\n".
527                                                 "  parent: ${params['parent']}\n"."  uid   : ${params['uid']}\n";
528                                 Logger::log($log_msg, Logger::DEBUG);
529                         } else {
530                                 // If not, just "follow" the thread.
531                                 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
532                                 Logger::log("There's already a notification for this parent.", Logger::DEBUG);
533                         }
534                 }
535
536                 $textversion = BBCode::toPlaintext($body);
537                 $htmlversion = BBCode::convert($body);
538
539                 $datarray = [];
540                 $datarray['banner'] = $banner;
541                 $datarray['product'] = $product;
542                 $datarray['preamble'] = $preamble;
543                 $datarray['sitename'] = $sitename;
544                 $datarray['siteurl'] = $siteurl;
545                 $datarray['type'] = $params['type'];
546                 $datarray['parent'] = $parent_id;
547                 $datarray['source_name'] = $params['source_name'] ?? '';
548                 $datarray['source_link'] = $params['source_link'] ?? '';
549                 $datarray['source_photo'] = $params['source_photo'] ?? '';
550                 $datarray['uid'] = $params['uid'];
551                 $datarray['username'] = $params['to_name'] ?? '';
552                 $datarray['hsitelink'] = $hsitelink;
553                 $datarray['tsitelink'] = $tsitelink;
554                 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
555                 $datarray['titemlink'] = $itemlink;
556                 $datarray['thanks'] = $thanks;
557                 $datarray['site_admin'] = $site_admin;
558                 $datarray['title'] = stripslashes($title);
559                 $datarray['htmlversion'] = $htmlversion;
560                 $datarray['textversion'] = $textversion;
561                 $datarray['subject'] = $subject;
562                 $datarray['headers'] = $additional_mail_header;
563
564                 Hook::callAll('enotify_mail', $datarray);
565
566                 // check whether sending post content in email notifications is allowed
567                 // always true for SYSTEM_EMAIL
568                 $content_allowed = ((!DI::config()->get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
569
570                 // load the template for private message notifications
571                 $tpl = Renderer::getMarkupTemplate('email_notify_html.tpl');
572                 $email_html_body = Renderer::replaceMacros($tpl, [
573                         '$banner'       => $datarray['banner'],
574                         '$product'      => $datarray['product'],
575                         '$preamble'     => str_replace("\n", "<br>\n", $datarray['preamble']),
576                         '$sitename'     => $datarray['sitename'],
577                         '$siteurl'      => $datarray['siteurl'],
578                         '$source_name'  => $datarray['source_name'],
579                         '$source_link'  => $datarray['source_link'],
580                         '$source_photo' => $datarray['source_photo'],
581                         '$username'     => $datarray['username'],
582                         '$hsitelink'    => $datarray['hsitelink'],
583                         '$hitemlink'    => $datarray['hitemlink'],
584                         '$thanks'       => $datarray['thanks'],
585                         '$site_admin'   => $datarray['site_admin'],
586                         '$title'        => $datarray['title'],
587                         '$htmlversion'  => $datarray['htmlversion'],
588                         '$content_allowed'      => $content_allowed,
589                 ]);
590
591                 // load the template for private message notifications
592                 $tpl = Renderer::getMarkupTemplate('email_notify_text.tpl');
593                 $email_text_body = Renderer::replaceMacros($tpl, [
594                         '$banner'       => $datarray['banner'],
595                         '$product'      => $datarray['product'],
596                         '$preamble'     => $datarray['preamble'],
597                         '$sitename'     => $datarray['sitename'],
598                         '$siteurl'      => $datarray['siteurl'],
599                         '$source_name'  => $datarray['source_name'],
600                         '$source_link'  => $datarray['source_link'],
601                         '$source_photo' => $datarray['source_photo'],
602                         '$username'     => $datarray['username'],
603                         '$tsitelink'    => $datarray['tsitelink'],
604                         '$titemlink'    => $datarray['titemlink'],
605                         '$thanks'       => $datarray['thanks'],
606                         '$site_admin'   => $datarray['site_admin'],
607                         '$title'        => $datarray['title'],
608                         '$textversion'  => $datarray['textversion'],
609                         '$content_allowed'      => $content_allowed,
610                 ]);
611
612                 // use the Emailer class to send the message
613                 return Emailer::send([
614                         'uid' => $params['uid'],
615                         'fromName' => $sender_name,
616                         'fromEmail' => $sender_email,
617                         'replyTo' => $sender_email,
618                         'toEmail' => $params['to_email'],
619                         'messageSubject' => $datarray['subject'],
620                         'htmlVersion' => $email_html_body,
621                         'textVersion' => $email_text_body,
622                         'additionalMailHeader' => $datarray['headers']
623                 ]);
624         }
625
626         return false;
627 }
628
629 /**
630  * Checks for users who should be notified
631  *
632  * @param int $itemid ID of the item for which the check should be done
633  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
634  */
635 function check_user_notification($itemid) {
636         // fetch all users with notifications
637         $useritems = DBA::select('user-item', ['uid', 'notification-type'], ['iid' => $itemid]);
638         while ($useritem = DBA::fetch($useritems)) {
639                 check_item_notification($itemid, $useritem['uid'], $useritem['notification-type']);
640         }
641         DBA::close($useritems);
642 }
643
644 /**
645  * Checks for item related notifications and sends them
646  *
647  * @param int    $itemid            ID of the item for which the check should be done
648  * @param int    $uid               User ID
649  * @param int    $notification_type Notification bits
650  * @return bool
651  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
652  */
653 function check_item_notification($itemid, $uid, $notification_type) {
654         $fields = ['id', 'mention', 'tag', 'parent', 'title', 'body',
655                 'author-link', 'author-name', 'author-avatar', 'author-id',
656                 'guid', 'parent-uri', 'uri', 'contact-id', 'network'];
657         $condition = ['id' => $itemid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'deleted' => false];
658         $item = Item::selectFirstForUser($uid, $fields, $condition);
659         if (!DBA::isResult($item)) {
660                 return false;
661         }
662
663         // Generate the notification array
664         $params = [];
665         $params['uid'] = $uid;
666         $params['item'] = $item;
667         $params['parent'] = $item['parent'];
668         $params['link'] = DI::baseUrl() . '/display/' . urlencode($item['guid']);
669         $params['otype'] = 'item';
670         $params['source_name'] = $item['author-name'];
671         $params['source_link'] = $item['author-link'];
672         $params['source_photo'] = $item['author-avatar'];
673
674         // Set the activity flags
675         $params['activity']['explicit_tagged'] = ($notification_type & UserItem::NOTIF_EXPLICIT_TAGGED);
676         $params['activity']['implicit_tagged'] = ($notification_type & UserItem::NOTIF_IMPLICIT_TAGGED);
677         $params['activity']['origin_comment'] = ($notification_type & UserItem::NOTIF_DIRECT_COMMENT);
678         $params['activity']['origin_thread'] = ($notification_type & UserItem::NOTIF_THREAD_COMMENT);
679         $params['activity']['thread_comment'] = ($notification_type & UserItem::NOTIF_COMMENT_PARTICIPATION);
680         $params['activity']['thread_activity'] = ($notification_type & UserItem::NOTIF_ACTIVITY_PARTICIPATION);
681
682         // Tagging a user in a direct post (first comment level) means a direct comment
683         if ($params['activity']['explicit_tagged'] && ($notification_type & UserItem::NOTIF_DIRECT_THREAD_COMMENT)) {
684                 $params['activity']['origin_comment'] = true;
685         }
686
687         if ($notification_type & UserItem::NOTIF_SHARED) {
688                 $params['type'] = NOTIFY_SHARE;
689                 $params['verb'] = Activity::POST;
690         } elseif ($notification_type & UserItem::NOTIF_EXPLICIT_TAGGED) {
691                 $params['type'] = NOTIFY_TAGSELF;
692                 $params['verb'] = Activity::TAG;
693         } elseif ($notification_type & UserItem::NOTIF_IMPLICIT_TAGGED) {
694                 $params['type'] = NOTIFY_COMMENT;
695                 $params['verb'] = Activity::POST;
696         } elseif ($notification_type & UserItem::NOTIF_THREAD_COMMENT) {
697                 $params['type'] = NOTIFY_COMMENT;
698                 $params['verb'] = Activity::POST;
699         } elseif ($notification_type & UserItem::NOTIF_DIRECT_COMMENT) {
700                 $params['type'] = NOTIFY_COMMENT;
701                 $params['verb'] = Activity::POST;
702         } elseif ($notification_type & UserItem::NOTIF_COMMENT_PARTICIPATION) {
703                 $params['type'] = NOTIFY_COMMENT;
704                 $params['verb'] = Activity::POST;
705         } elseif ($notification_type & UserItem::NOTIF_ACTIVITY_PARTICIPATION) {
706                 $params['type'] = NOTIFY_COMMENT;
707                 $params['verb'] = Activity::POST;
708         } else {
709                 return false;
710         }
711
712         notification($params);
713 }