]> git.mxchange.org Git - friendica.git/blob - include/enotify.php
aa5342dcc3104c2378819b4f81d020c0d35fa62a
[friendica.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\Content\Text\Plaintext;
24 use Friendica\Core\Hook;
25 use Friendica\Core\Logger;
26 use Friendica\Core\Renderer;
27 use Friendica\Core\System;
28 use Friendica\Database\DBA;
29 use Friendica\DI;
30 use Friendica\Model\Contact;
31 use Friendica\Model\Item;
32 use Friendica\Model\Notification;
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'] == Notification\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'] == Notification\Type::COMMENT || $params['type'] == Notification\Type::TAG_SELF) {
152                 if (Post\ThreadUser::getIgnored($parent_uri_id, $params['uid'])) {
153                         Logger::info('Thread is ignored', ['parent' => $parent_id, 'parent-uri-id' => $parent_uri_id]);
154                         return false;
155                 }
156
157                 // Check to see if there was already a tag notify or comment notify for this post.
158                 // If so don't create a second notification
159                 /// @todo In the future we should store the notification with the highest "value" and replace notifications
160                 $condition = ['type' => [Notification\Type::TAG_SELF, Notification\Type::COMMENT, Notification\Type::SHARE],
161                         'link' => $params['link'], 'uid' => $params['uid']];
162                 if (DBA::exists('notify', $condition)) {
163                         return false;
164                 }
165
166                 // if it's a post figure out who's post it is.
167                 $item = null;
168                 if ($params['otype'] === Notification\ObjectType::ITEM && $parent_id) {
169                         $item = Post::selectFirstForUser($params['uid'], Item::ITEM_FIELDLIST, ['id' => $parent_id, 'deleted' => false]);
170                 }
171
172                 if (empty($item)) {
173                         return false;
174                 }
175
176                 $item_post_type = Item::postType($item);
177
178                 $content = Plaintext::getPost($item, 70);
179                 if (!empty($content['text'])) {
180                         $title = '"' . trim(str_replace("\n", " ", $content['text'])) . '"';
181                 } else {
182                         $title = '';
183                 }
184
185                 // First go for the general message
186
187                 // "George Bull's post"
188                 if ($params['activity']['origin_comment']) {
189                         $message = $l10n->t('%1$s replied to you on %2$s\'s %3$s %4$s');
190                 } elseif ($params['activity']['explicit_tagged']) {
191                         $message = $l10n->t('%1$s tagged you on %2$s\'s %3$s %4$s');
192                 } else {
193                         $message = $l10n->t('%1$s commented on %2$s\'s %3$s %4$s');
194                 }
195
196                 $dest_str = sprintf($message, $params['source_name'], $item['author-name'], $item_post_type, $title);
197
198                 // Then look for the special cases
199
200                 // "your post"
201                 if ($params['activity']['origin_thread']) {
202                         if ($params['activity']['origin_comment']) {
203                                 $message = $l10n->t('%1$s replied to you on your %2$s %3$s');
204                         } elseif ($params['activity']['explicit_tagged']) {
205                                 $message = $l10n->t('%1$s tagged you on your %2$s %3$s');
206                         } else {
207                                 $message = $l10n->t('%1$s commented on your %2$s %3$s');
208                         }
209
210                         $dest_str = sprintf($message, $params['source_name'], $item_post_type, $title);
211                 // "their post"
212                 } elseif ($item['author-link'] == $params['source_link']) {
213                         if ($params['activity']['origin_comment']) {
214                                 $message = $l10n->t('%1$s replied to you on their %2$s %3$s');
215                         } elseif ($params['activity']['explicit_tagged']) {
216                                 $message = $l10n->t('%1$s tagged you on their %2$s %3$s');
217                         } else {
218                                 $message = $l10n->t('%1$s commented on their %2$s %3$s');
219                         }
220
221                         $dest_str = sprintf($message, $params['source_name'], $item_post_type, $title);
222                 }
223
224                 // Some mail software relies on subject field for threading.
225                 // So, we cannot have different subjects for notifications of the same thread.
226                 // Before this we have the name of the replier on the subject rendering
227                 // different subjects for messages on the same thread.
228                 if ($params['activity']['explicit_tagged']) {
229                         $subject = $l10n->t('%s %s tagged you', $subjectPrefix, $params['source_name']);
230
231                         $preamble = $l10n->t('%1$s tagged you at %2$s', $params['source_name'], $sitename);
232                 } else {
233                         $subject = $l10n->t('%1$s Comment to conversation #%2$d by %3$s', $subjectPrefix, $parent_id, $params['source_name']);
234
235                         $preamble = $l10n->t('%s commented on an item/conversation you have been following.', $params['source_name']);
236                 }
237
238                 $epreamble = $dest_str;
239
240                 $sitelink = $l10n->t('Please visit %s to view and/or reply to the conversation.');
241                 $tsitelink = sprintf($sitelink, $siteurl);
242                 $hsitelink = sprintf($sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
243                 $itemlink =  $params['link'];
244         }
245
246         if ($params['type'] == Notification\Type::WALL) {
247                 $subject = $l10n->t('%s %s posted to your profile wall', $subjectPrefix, $params['source_name']);
248
249                 $preamble = $l10n->t('%1$s posted to your profile wall at %2$s', $params['source_name'], $sitename);
250                 $epreamble = $l10n->t('%1$s posted to [url=%2$s]your wall[/url]',
251                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
252                         $params['link']
253                 );
254
255                 $sitelink = $l10n->t('Please visit %s to view and/or reply to the conversation.');
256                 $tsitelink = sprintf($sitelink, $siteurl);
257                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
258                 $itemlink =  $params['link'];
259         }
260
261         if ($params['type'] == Notification\Type::SHARE) {
262                 if ($params['origin_link'] == $params['source_link']) {
263                         $subject = $l10n->t('%s %s shared a new post', $subjectPrefix, $params['source_name']);
264
265                         $preamble = $l10n->t('%1$s shared a new post at %2$s', $params['source_name'], $sitename);
266                         $epreamble = $l10n->t('%1$s [url=%2$s]shared a post[/url].',
267                                 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
268                                 $params['link']
269                         );
270                 } else {
271                         $subject = $l10n->t('%s %s shared a post from %s', $subjectPrefix, $params['source_name'], $params['origin_name']);
272
273                         $preamble = $l10n->t('%1$s shared a post from %2$s at %3$s', $params['source_name'], $params['origin_name'], $sitename);
274                         $epreamble = $l10n->t('%1$s [url=%2$s]shared a post[/url] from %3$s.',
275                                 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
276                                 $params['link'], '[url='.$params['origin_link'].']'.$params['origin_name'].'[/url]'
277                         );                      
278                 }
279
280                 $sitelink = $l10n->t('Please visit %s to view and/or reply to the conversation.');
281                 $tsitelink = sprintf($sitelink, $siteurl);
282                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
283                 $itemlink =  $params['link'];
284         }
285
286         if ($params['type'] == Notification\Type::POKE) {
287                 $subject = $l10n->t('%1$s %2$s poked you', $subjectPrefix, $params['source_name']);
288
289                 $preamble = $l10n->t('%1$s poked you at %2$s', $params['source_name'], $sitename);
290                 $epreamble = $l10n->t('%1$s [url=%2$s]poked you[/url].',
291                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
292                         $params['link']
293                 );
294
295                 $subject = str_replace('poked', $l10n->t($params['activity']), $subject);
296                 $preamble = str_replace('poked', $l10n->t($params['activity']), $preamble);
297                 $epreamble = str_replace('poked', $l10n->t($params['activity']), $epreamble);
298
299                 $sitelink = $l10n->t('Please visit %s to view and/or reply to the conversation.');
300                 $tsitelink = sprintf($sitelink, $siteurl);
301                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
302                 $itemlink =  $params['link'];
303         }
304
305         if ($params['type'] == Notification\Type::TAG_SHARE) {
306                 $itemlink =  $params['link'];
307                 $subject = $l10n->t('%s %s tagged your post', $subjectPrefix, $params['source_name']);
308
309                 $preamble = $l10n->t('%1$s tagged your post at %2$s', $params['source_name'], $sitename);
310                 $epreamble = $l10n->t('%1$s tagged [url=%2$s]your post[/url]',
311                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
312                         $itemlink
313                 );
314
315                 $sitelink = $l10n->t('Please visit %s to view and/or reply to the conversation.');
316                 $tsitelink = sprintf($sitelink, $siteurl);
317                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
318         }
319
320         if ($params['type'] == Notification\Type::INTRO) {
321                 $itemlink = $params['link'];
322                 $subject = $l10n->t('%s Introduction received', $subjectPrefix);
323
324                 $preamble = $l10n->t('You\'ve received an introduction from \'%1$s\' at %2$s', $params['source_name'], $sitename);
325                 $epreamble = $l10n->t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.',
326                         $itemlink,
327                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
328                 );
329
330                 $body = $l10n->t('You may visit their profile at %s', $params['source_link']);
331
332                 $sitelink = $l10n->t('Please visit %s to approve or reject the introduction.');
333                 $tsitelink = sprintf($sitelink, $siteurl);
334                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
335
336                 switch ($params['verb']) {
337                         case Activity::FRIEND:
338                                 // someone started to share with user (mostly OStatus)
339                                 $subject = $l10n->t('%s A new person is sharing with you', $subjectPrefix);
340
341                                 $preamble = $l10n->t('%1$s is sharing with you at %2$s', $params['source_name'], $sitename);
342                                 $epreamble = $l10n->t('%1$s is sharing with you at %2$s',
343                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
344                                         $sitename
345                                 );
346                                 break;
347                         case Activity::FOLLOW:
348                                 // someone started to follow the user (mostly OStatus)
349                                 $subject = $l10n->t('%s You have a new follower', $subjectPrefix);
350
351                                 $preamble = $l10n->t('You have a new follower at %2$s : %1$s', $params['source_name'], $sitename);
352                                 $epreamble = $l10n->t('You have a new follower at %2$s : %1$s',
353                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
354                                         $sitename
355                                 );
356                                 break;
357                         default:
358                                 // ACTIVITY_REQ_FRIEND is default activity for notifications
359                                 break;
360                 }
361         }
362
363         if ($params['type'] == Notification\Type::SUGGEST) {
364                 $itemlink =  $params['link'];
365                 $subject = $l10n->t('%s Friend suggestion received', $subjectPrefix);
366
367                 $preamble = $l10n->t('You\'ve received a friend suggestion from \'%1$s\' at %2$s', $params['source_name'], $sitename);
368                 $epreamble = $l10n->t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.',
369                         $itemlink,
370                         '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
371                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
372                 );
373
374                 $body = $l10n->t('Name:').' '.$params['item']['name']."\n";
375                 $body .= $l10n->t('Photo:').' '.$params['item']['photo']."\n";
376                 $body .= $l10n->t('You may visit their profile at %s', $params['item']['url']);
377
378                 $sitelink = $l10n->t('Please visit %s to approve or reject the suggestion.');
379                 $tsitelink = sprintf($sitelink, $siteurl);
380                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
381         }
382
383         if ($params['type'] == Notification\Type::CONFIRM) {
384                 if ($params['verb'] == Activity::FRIEND) { // mutual connection
385                         $itemlink =  $params['link'];
386                         $subject = $l10n->t('%s Connection accepted', $subjectPrefix);
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('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
395
396                         $sitelink = $l10n->t('Please visit %s if you wish to make any changes to this relationship.');
397                         $tsitelink = sprintf($sitelink, $siteurl);
398                         $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
399                 } else { // ACTIVITY_FOLLOW
400                         $itemlink =  $params['link'];
401                         $subject = $l10n->t('%s Connection accepted', $subjectPrefix);
402
403                         $preamble = $l10n->t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
404                         $epreamble = $l10n->t('%2$s has accepted your [url=%1$s]connection request[/url].',
405                                 $itemlink,
406                                 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
407                         );
408
409                         $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']);
410                         $body .= "\n\n";
411                         $body .= $l10n->t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.', $params['source_name']);
412
413                         $sitelink = $l10n->t('Please visit %s  if you wish to make any changes to this relationship.');
414                         $tsitelink = sprintf($sitelink, $siteurl);
415                         $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
416                 }
417         }
418
419         if ($params['type'] == Notification\Type::SYSTEM) {
420                 switch($params['event']) {
421                         case "SYSTEM_REGISTER_REQUEST":
422                                 $itemlink =  $params['link'];
423                                 $subject = $l10n->t('[Friendica System Notify]') . ' ' . $l10n->t('registration request');
424
425                                 $preamble = $l10n->t('You\'ve received a registration request from \'%1$s\' at %2$s', $params['source_name'], $sitename);
426                                 $epreamble = $l10n->t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.',
427                                         $itemlink,
428                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
429                                 );
430
431                                 $body = $l10n->t("Full Name:    %s\nSite Location:      %s\nLogin Name: %s (%s)",
432                                         $params['source_name'],
433                                         $siteurl, $params['source_mail'],
434                                         $params['source_nick']
435                                 );
436
437                                 $sitelink = $l10n->t('Please visit %s to approve or reject the request.');
438                                 $tsitelink = sprintf($sitelink, $params['link']);
439                                 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
440                                 break;
441                         case "SYSTEM_DB_UPDATE_FAIL":
442                                 break;
443                 }
444         }
445
446         $subject .= " (".$nickname."@".$hostname.")";
447
448         $h = [
449                 'params'    => $params,
450                 'subject'   => $subject,
451                 'preamble'  => $preamble,
452                 'epreamble' => $epreamble,
453                 'body'      => $body,
454                 'sitelink'  => $sitelink,
455                 'tsitelink' => $tsitelink,
456                 'hsitelink' => $hsitelink,
457                 'itemlink'  => $itemlink
458         ];
459
460         Hook::callAll('enotify', $h);
461
462         $subject   = $h['subject'];
463
464         $preamble  = $h['preamble'];
465         $epreamble = $h['epreamble'];
466
467         $body      = $h['body'];
468
469         $tsitelink = $h['tsitelink'];
470         $hsitelink = $h['hsitelink'];
471         $itemlink  = $h['itemlink'];
472
473         $notify_id = 0;
474
475         if ($show_in_notification_page) {
476                 $fields = [
477                         'name'          => $params['source_name'] ?? '',
478                         'name_cache'    => substr(strip_tags(BBCode::convert($params['source_name'])), 0, 255),
479                         'url'           => $params['source_link'] ?? '',
480                         'photo'         => $params['source_photo'] ?? '',
481                         'link'          => $itemlink ?? '',
482                         'uid'           => $params['uid'] ?? 0,
483                         'type'          => $params['type'] ?? '',
484                         'verb'          => $params['verb'] ?? '',
485                         'otype'         => $params['otype'] ?? '',
486                 ];
487                 if (!empty($item_id)) {
488                         $fields['iid'] = $item_id;
489                 }
490                 if (!empty($uri_id)) {
491                         $fields['uri-id'] = $uri_id;
492                 }
493                 if (!empty($parent_id)) {
494                         $fields['parent'] = $parent_id;
495                 }
496                 if (!empty($parent_uri_id)) {
497                         $fields['parent-uri-id'] = $parent_uri_id;
498                 }
499                 $notification = DI::notify()->insert($fields);
500
501                 // Notification insertion can be intercepted by an addon registering the 'enotify_store' hook
502                 if (!$notification) {
503                         return false;
504                 }
505
506                 $notification->msg = Renderer::replaceMacros($epreamble, ['$itemlink' => $notification->link]);
507
508                 DI::notify()->update($notification);
509
510                 $itemlink  = DI::baseUrl() . '/notification/' . $notification->id;
511                 $notify_id = $notification->id;
512         }
513
514         // send email notification if notification preferences permit
515         if ((intval($params['notify_flags']) & intval($params['type']))
516                 || $params['type'] == Notification\Type::SYSTEM) {
517
518                 Logger::log('sending notification email');
519
520                 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
521                         $parent = Post::selectFirst(['guid'], ['id' => $params['parent']]);
522                         $message_id = "<" . $parent['guid'] . "@" . gethostname() . ">";
523
524                         // Is this the first email notification for this parent item and user?
525                         if (!DBA::exists('notify-threads', ['master-parent-item' => $params['parent'], 'receiver-uid' => $params['uid']])) {
526                                 Logger::log("notify_id:" . intval($notify_id) . ", parent: " . intval($params['parent']) . "uid: " . intval($params['uid']), Logger::DEBUG);
527
528                                 $fields = ['notify-id' => $notify_id, 'master-parent-item' => $params['parent'],
529                                         'master-parent-uri-id' => $parent_uri_id,
530                                         'receiver-uid' => $params['uid'], 'parent-item' => 0];
531                                 DBA::insert('notify-threads', $fields);
532
533                                 $emailBuilder->setHeader('Message-ID', $message_id);
534                                 $log_msg                = "include/enotify: No previous notification found for this parent:\n" .
535                                                           "  parent: ${params['parent']}\n" . "  uid   : ${params['uid']}\n";
536                                 Logger::log($log_msg, Logger::DEBUG);
537                         } else {
538                                 // If not, just "follow" the thread.
539                                 $emailBuilder->setHeader('References', $message_id);
540                                 $emailBuilder->setHeader('In-Reply-To', $message_id);
541                                 Logger::log("There's already a notification for this parent.", Logger::DEBUG);
542                         }
543                 }
544
545                 $datarray = [
546                         'preamble'     => $preamble,
547                         'type'         => $params['type'],
548                         'parent'       => $parent_id,
549                         'source_name'  => $params['source_name'] ?? null,
550                         'source_link'  => $params['source_link'] ?? null,
551                         'source_photo' => $params['source_photo'] ?? null,
552                         'uid'          => $params['uid'],
553                         'hsitelink'    => $hsitelink,
554                         'tsitelink'    => $tsitelink,
555                         'itemlink'     => $itemlink,
556                         'title'        => $title,
557                         'body'         => $body,
558                         'subject'      => $subject,
559                         'headers'      => $emailBuilder->getHeaders(),
560                 ];
561
562                 Hook::callAll('enotify_mail', $datarray);
563
564                 $emailBuilder
565                         ->withHeaders($datarray['headers'])
566                         ->withRecipient($params['to_email'])
567                         ->forUser([
568                                 'uid' => $datarray['uid'],
569                                 'language' => $params['language'],
570                         ])
571                         ->withNotification($datarray['subject'], $datarray['preamble'], $datarray['title'], $datarray['body'])
572                         ->withSiteLink($datarray['tsitelink'], $datarray['hsitelink'])
573                         ->withItemLink($datarray['itemlink']);
574
575                 // If a photo is present, add it to the email
576                 if (!empty($datarray['source_photo'])) {
577                         $emailBuilder->withPhoto(
578                                 $datarray['source_photo'],
579                                 $datarray['source_link'] ?? $sitelink,
580                                 $datarray['source_name'] ?? $sitename);
581                 }
582
583                 $email = $emailBuilder->build();
584
585                 // use the Emailer class to send the message
586                 return DI::emailer()->send($email);
587         }
588
589         return false;
590 }
591
592 /**
593  * Checks for users who should be notified
594  *
595  * @param int $itemid ID of the item for which the check should be done
596  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
597  */
598 function check_user_notification($itemid) {
599         // fetch all users with notifications
600         $useritems = DBA::select('user-item', ['uid', 'notification-type'], ['iid' => $itemid]);
601         while ($useritem = DBA::fetch($useritems)) {
602                 check_item_notification($itemid, $useritem['uid'], $useritem['notification-type']);
603         }
604         DBA::close($useritems);
605 }
606
607 /**
608  * Checks for item related notifications and sends them
609  *
610  * @param int    $itemid            ID of the item for which the check should be done
611  * @param int    $uid               User ID
612  * @param int    $notification_type Notification bits
613  * @return bool
614  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
615  */
616 function check_item_notification($itemid, $uid, $notification_type) {
617         $fields = ['id', 'uri-id', 'mention', 'parent', 'parent-uri-id', 'thr-parent-id',
618                 'title', 'body', 'author-link', 'author-name', 'author-avatar', 'author-id',
619                 'gravity', 'guid', 'parent-uri', 'uri', 'contact-id', 'network'];
620         $condition = ['id' => $itemid, 'deleted' => false];
621         $item = Post::selectFirstForUser($uid, $fields, $condition);
622         if (!DBA::isResult($item)) {
623                 return false;
624         }
625
626         if (!DI::pConfig()->get(local_user(), 'system', 'notify_ignored', true) && Contact\User::isIgnored($item['author-id'], $uid)) {
627                 Logger::info('Author is ignored, dropping notification', ['cid' => $item['author-id'], 'uid' =>  $uid]);
628                 return false;
629         }
630
631         // Generate the notification array
632         $params = [];
633         $params['otype'] = Notification\ObjectType::ITEM;
634         $params['uid'] = $uid;
635         $params['origin_cid'] = $params['cid'] = $item['author-id'];
636         $params['item'] = $item;
637         $params['link'] = DI::baseUrl() . '/display/' . urlencode($item['guid']);
638
639         // Set the activity flags
640         $params['activity']['explicit_tagged'] = ($notification_type & UserItem::NOTIF_EXPLICIT_TAGGED);
641         $params['activity']['implicit_tagged'] = ($notification_type & UserItem::NOTIF_IMPLICIT_TAGGED);
642         $params['activity']['origin_comment'] = ($notification_type & UserItem::NOTIF_DIRECT_COMMENT);
643         $params['activity']['origin_thread'] = ($notification_type & UserItem::NOTIF_THREAD_COMMENT);
644         $params['activity']['thread_comment'] = ($notification_type & UserItem::NOTIF_COMMENT_PARTICIPATION);
645         $params['activity']['thread_activity'] = ($notification_type & UserItem::NOTIF_ACTIVITY_PARTICIPATION);
646
647         // Tagging a user in a direct post (first comment level) means a direct comment
648         if ($params['activity']['explicit_tagged'] && ($notification_type & UserItem::NOTIF_DIRECT_THREAD_COMMENT)) {
649                 $params['activity']['origin_comment'] = true;
650         }
651
652         if ($notification_type & UserItem::NOTIF_SHARED) {
653                 $params['type'] = Notification\Type::SHARE;
654                 $params['verb'] = Activity::POST;
655
656                 // Special treatment for posts that had been shared via "announce"
657                 if ($item['gravity'] == GRAVITY_ACTIVITY) {
658                         $parent_item = Post::selectFirst($fields, ['uri-id' => $item['thr-parent-id'], 'uid' => [$uid, 0]]);
659                         if (DBA::isResult($parent_item)) {
660                                 // Don't notify on own entries
661                                 if (User::getIdForURL($parent_item['author-link']) == $uid) {
662                                         return false;
663                                 }
664
665                                 $params['origin_cid'] = $parent_item['author-id'];
666                                 $params['item'] = $parent_item;
667                         }
668                 }
669         } elseif ($notification_type & UserItem::NOTIF_EXPLICIT_TAGGED) {
670                 $params['type'] = Notification\Type::TAG_SELF;
671                 $params['verb'] = Activity::TAG;
672         } elseif ($notification_type & UserItem::NOTIF_IMPLICIT_TAGGED) {
673                 $params['type'] = Notification\Type::COMMENT;
674                 $params['verb'] = Activity::POST;
675         } elseif ($notification_type & UserItem::NOTIF_THREAD_COMMENT) {
676                 $params['type'] = Notification\Type::COMMENT;
677                 $params['verb'] = Activity::POST;
678         } elseif ($notification_type & UserItem::NOTIF_DIRECT_COMMENT) {
679                 $params['type'] = Notification\Type::COMMENT;
680                 $params['verb'] = Activity::POST;
681         } elseif ($notification_type & UserItem::NOTIF_COMMENT_PARTICIPATION) {
682                 $params['type'] = Notification\Type::COMMENT;
683                 $params['verb'] = Activity::POST;
684         } elseif ($notification_type & UserItem::NOTIF_ACTIVITY_PARTICIPATION) {
685                 $params['type'] = Notification\Type::COMMENT;
686                 $params['verb'] = Activity::POST;
687         } else {
688                 return false;
689         }
690
691         notification($params);
692 }