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