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