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