]> git.mxchange.org Git - friendica.git/blob - include/enotify.php
Move subscribe_to_hub function to Worker/OnePoll from include/items
[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\Core\Hook;
24 use Friendica\Core\Logger;
25 use Friendica\Core\Renderer;
26 use Friendica\Core\System;
27 use Friendica\Database\DBA;
28 use Friendica\DI;
29 use Friendica\Model\Item;
30 use Friendica\Model\ItemContent;
31 use Friendica\Model\Notify;
32 use Friendica\Model\User;
33 use Friendica\Model\UserItem;
34 use Friendica\Protocol\Activity;
35
36 /**
37  * Creates a notification entry and possibly sends a mail
38  *
39  * @param array $params Array with the elements:
40  *                      uid, item, parent, type, otype, verb, event,
41  *                      link, subject, body, to_name, to_email, source_name,
42  *                      source_link, activity, preamble, notify_flags,
43  *                      language, show_in_notification_page
44  * @return bool
45  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
46  */
47 function notification($params)
48 {
49         /** @var string the common prefix of a notification subject */
50         $subjectPrefix = DI::l10n()->t('[Friendica:Notify]');
51
52         // Temporary logging for finding the origin
53         if (!isset($params['uid'])) {
54                 Logger::notice('Missing parameters "uid".', ['params' => $params, 'callstack' => System::callstack()]);
55         }
56
57         // Ensure that the important fields are set at any time
58         $fields = ['notify-flags', 'language', 'username', 'email'];
59         $user = DBA::selectFirst('user', $fields, ['uid' => $params['uid']]);
60
61         if (!DBA::isResult($user)) {
62                 Logger::error('Unknown user', ['uid' =>  $params['uid']]);
63                 return false;
64         }
65
66         $params['notify_flags'] = ($params['notify_flags'] ?? '') ?: $user['notify-flags'];
67         $params['language']     = ($params['language']     ?? '') ?: $user['language'];
68         $params['to_name']      = ($params['to_name']      ?? '') ?: $user['username'];
69         $params['to_email']     = ($params['to_email']     ?? '') ?: $user['email'];
70
71         // from here on everything is in the recipients language
72         $l10n = DI::l10n()->withLang($params['language']);
73
74         $siteurl = DI::baseUrl()->get(true);
75         $sitename = DI::config()->get('config', 'sitename');
76
77         $hostname = DI::baseUrl()->getHostname();
78         if (strpos($hostname, ':')) {
79                 $hostname = substr($hostname, 0, strpos($hostname, ':'));
80         }
81
82         $user = User::getById($params['uid'], ['nickname', 'page-flags']);
83
84         // There is no need to create notifications for forum accounts
85         if (!DBA::isResult($user) || in_array($user["page-flags"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
86                 return false;
87         }
88         $nickname = $user["nickname"];
89
90         // with $params['show_in_notification_page'] == false, the notification isn't inserted into
91         // the database, and an email is sent if applicable.
92         // default, if not specified: true
93         $show_in_notification_page = isset($params['show_in_notification_page']) ? $params['show_in_notification_page'] : true;
94
95         $additional_mail_header = "X-Friendica-Account: <".$nickname."@".$hostname.">\n";
96
97         if (array_key_exists('item', $params)) {
98                 $title = $params['item']['title'];
99                 $body = $params['item']['body'];
100         } else {
101                 $title = $body = '';
102         }
103
104         if (isset($params['item']['id'])) {
105                 $item_id = $params['item']['id'];
106         } else {
107                 $item_id = 0;
108         }
109
110         if (isset($params['item']['uri-id'])) {
111                 $uri_id = $params['item']['uri-id'];
112         } else {
113                 $uri_id = 0;
114         }
115
116         if (isset($params['parent'])) {
117                 $parent_id = $params['parent'];
118         } else {
119                 $parent_id = 0;
120         }
121
122         if (isset($params['item']['parent-uri-id'])) {
123                 $parent_uri_id = $params['item']['parent-uri-id'];
124         } else {
125                 $parent_uri_id = 0;
126         }
127
128         $epreamble = '';
129         $preamble  = '';
130         $subject   = '';
131         $sitelink  = '';
132         $tsitelink = '';
133         $hsitelink = '';
134         $itemlink  = '';
135
136         if ($params['type'] == Notify\Type::MAIL) {
137                 $itemlink = $siteurl.'/message/'.$params['item']['id'];
138                 $params["link"] = $itemlink;
139
140                 $subject = $l10n->t('%s New mail received at %s', $subjectPrefix, $sitename);
141
142                 $preamble = $l10n->t('%1$s sent you a new private message at %2$s.', $params['source_name'], $sitename);
143                 $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]');
144
145                 $sitelink = $l10n->t('Please visit %s to view and/or reply to your private messages.');
146                 $tsitelink = sprintf($sitelink, $siteurl.'/message/'.$params['item']['id']);
147                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'/message/'.$params['item']['id'].'">'.$sitename.'</a>');
148         }
149
150         if ($params['type'] == Notify\Type::COMMENT || $params['type'] == Notify\Type::TAG_SELF) {
151                 $thread = Item::selectFirstThreadForUser($params['uid'], ['ignored'], ['iid' => $parent_id, 'deleted' => false]);
152                 if (DBA::isResult($thread) && $thread['ignored']) {
153                         Logger::log('Thread ' . $parent_id . ' will be ignored', Logger::DEBUG);
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' => [Notify\Type::TAG_SELF, Notify\Type::COMMENT, Notify\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'] === Notify\ObjectType::ITEM && $parent_id) {
169                         $item = Item::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 = ItemContent::getPlaintextPost($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'] == Notify\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'] == Notify\Type::SHARE) {
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
270                 $sitelink = $l10n->t('Please visit %s to view and/or reply to the conversation.');
271                 $tsitelink = sprintf($sitelink, $siteurl);
272                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
273                 $itemlink =  $params['link'];
274         }
275
276         if ($params['type'] == Notify\Type::POKE) {
277                 $subject = $l10n->t('%1$s %2$s poked you', $subjectPrefix, $params['source_name']);
278
279                 $preamble = $l10n->t('%1$s poked you at %2$s', $params['source_name'], $sitename);
280                 $epreamble = $l10n->t('%1$s [url=%2$s]poked you[/url].',
281                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
282                         $params['link']
283                 );
284
285                 $subject = str_replace('poked', $l10n->t($params['activity']), $subject);
286                 $preamble = str_replace('poked', $l10n->t($params['activity']), $preamble);
287                 $epreamble = str_replace('poked', $l10n->t($params['activity']), $epreamble);
288
289                 $sitelink = $l10n->t('Please visit %s to view and/or reply to the conversation.');
290                 $tsitelink = sprintf($sitelink, $siteurl);
291                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
292                 $itemlink =  $params['link'];
293         }
294
295         if ($params['type'] == Notify\Type::TAG_SHARE) {
296                 $itemlink =  $params['link'];
297                 $subject = $l10n->t('%s %s tagged your post', $subjectPrefix, $params['source_name']);
298
299                 $preamble = $l10n->t('%1$s tagged your post at %2$s', $params['source_name'], $sitename);
300                 $epreamble = $l10n->t('%1$s tagged [url=%2$s]your post[/url]',
301                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
302                         $itemlink
303                 );
304
305                 $sitelink = $l10n->t('Please visit %s to view and/or reply to the conversation.');
306                 $tsitelink = sprintf($sitelink, $siteurl);
307                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
308         }
309
310         if ($params['type'] == Notify\Type::INTRO) {
311                 $itemlink = $params['link'];
312                 $subject = $l10n->t('%s Introduction received', $subjectPrefix);
313
314                 $preamble = $l10n->t('You\'ve received an introduction from \'%1$s\' at %2$s', $params['source_name'], $sitename);
315                 $epreamble = $l10n->t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.',
316                         $itemlink,
317                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
318                 );
319
320                 $body = $l10n->t('You may visit their profile at %s', $params['source_link']);
321
322                 $sitelink = $l10n->t('Please visit %s to approve or reject the introduction.');
323                 $tsitelink = sprintf($sitelink, $siteurl);
324                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
325
326                 switch ($params['verb']) {
327                         case Activity::FRIEND:
328                                 // someone started to share with user (mostly OStatus)
329                                 $subject = $l10n->t('%s A new person is sharing with you', $subjectPrefix);
330
331                                 $preamble = $l10n->t('%1$s is sharing with you at %2$s', $params['source_name'], $sitename);
332                                 $epreamble = $l10n->t('%1$s is sharing with you at %2$s',
333                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
334                                         $sitename
335                                 );
336                                 break;
337                         case Activity::FOLLOW:
338                                 // someone started to follow the user (mostly OStatus)
339                                 $subject = $l10n->t('%s You have a new follower', $subjectPrefix);
340
341                                 $preamble = $l10n->t('You have a new follower at %2$s : %1$s', $params['source_name'], $sitename);
342                                 $epreamble = $l10n->t('You have a new follower at %2$s : %1$s',
343                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
344                                         $sitename
345                                 );
346                                 break;
347                         default:
348                                 // ACTIVITY_REQ_FRIEND is default activity for notifications
349                                 break;
350                 }
351         }
352
353         if ($params['type'] == Notify\Type::SUGGEST) {
354                 $itemlink =  $params['link'];
355                 $subject = $l10n->t('%s Friend suggestion received', $subjectPrefix);
356
357                 $preamble = $l10n->t('You\'ve received a friend suggestion from \'%1$s\' at %2$s', $params['source_name'], $sitename);
358                 $epreamble = $l10n->t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.',
359                         $itemlink,
360                         '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
361                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
362                 );
363
364                 $body = $l10n->t('Name:').' '.$params['item']['name']."\n";
365                 $body .= $l10n->t('Photo:').' '.$params['item']['photo']."\n";
366                 $body .= $l10n->t('You may visit their profile at %s', $params['item']['url']);
367
368                 $sitelink = $l10n->t('Please visit %s to approve or reject the suggestion.');
369                 $tsitelink = sprintf($sitelink, $siteurl);
370                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
371         }
372
373         if ($params['type'] == Notify\Type::CONFIRM) {
374                 if ($params['verb'] == Activity::FRIEND) { // mutual connection
375                         $itemlink =  $params['link'];
376                         $subject = $l10n->t('%s Connection accepted', $subjectPrefix);
377
378                         $preamble = $l10n->t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
379                         $epreamble = $l10n->t('%2$s has accepted your [url=%1$s]connection request[/url].',
380                                 $itemlink,
381                                 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
382                         );
383
384                         $body =  $l10n->t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
385
386                         $sitelink = $l10n->t('Please visit %s if you wish to make any changes to this relationship.');
387                         $tsitelink = sprintf($sitelink, $siteurl);
388                         $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
389                 } else { // ACTIVITY_FOLLOW
390                         $itemlink =  $params['link'];
391                         $subject = $l10n->t('%s Connection accepted', $subjectPrefix);
392
393                         $preamble = $l10n->t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
394                         $epreamble = $l10n->t('%2$s has accepted your [url=%1$s]connection request[/url].',
395                                 $itemlink,
396                                 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
397                         );
398
399                         $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']);
400                         $body .= "\n\n";
401                         $body .= $l10n->t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.', $params['source_name']);
402
403                         $sitelink = $l10n->t('Please visit %s  if you wish to make any changes to this relationship.');
404                         $tsitelink = sprintf($sitelink, $siteurl);
405                         $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
406                 }
407         }
408
409         if ($params['type'] == Notify\Type::SYSTEM) {
410                 switch($params['event']) {
411                         case "SYSTEM_REGISTER_REQUEST":
412                                 $itemlink =  $params['link'];
413                                 $subject = $l10n->t('[Friendica System Notify]') . ' ' . $l10n->t('registration request');
414
415                                 $preamble = $l10n->t('You\'ve received a registration request from \'%1$s\' at %2$s', $params['source_name'], $sitename);
416                                 $epreamble = $l10n->t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.',
417                                         $itemlink,
418                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
419                                 );
420
421                                 $body = $l10n->t("Full Name:    %s\nSite Location:      %s\nLogin Name: %s (%s)",
422                                         $params['source_name'],
423                                         $siteurl, $params['source_mail'],
424                                         $params['source_nick']
425                                 );
426
427                                 $sitelink = $l10n->t('Please visit %s to approve or reject the request.');
428                                 $tsitelink = sprintf($sitelink, $params['link']);
429                                 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
430                                 break;
431                         case "SYSTEM_DB_UPDATE_FAIL":
432                                 break;
433                 }
434         }
435
436         $subject .= " (".$nickname."@".$hostname.")";
437
438         $h = [
439                 'params'    => $params,
440                 'subject'   => $subject,
441                 'preamble'  => $preamble,
442                 'epreamble' => $epreamble,
443                 'body'      => $body,
444                 'sitelink'  => $sitelink,
445                 'tsitelink' => $tsitelink,
446                 'hsitelink' => $hsitelink,
447                 'itemlink'  => $itemlink
448         ];
449
450         Hook::callAll('enotify', $h);
451
452         $subject   = $h['subject'];
453
454         $preamble  = $h['preamble'];
455         $epreamble = $h['epreamble'];
456
457         $body      = $h['body'];
458
459         $tsitelink = $h['tsitelink'];
460         $hsitelink = $h['hsitelink'];
461         $itemlink  = $h['itemlink'];
462
463         $notify_id = 0;
464
465         if ($show_in_notification_page) {
466                 $notification = DI::notify()->insert([
467                         'name'          => $params['source_name'] ?? '',
468                         'name_cache'    => substr(strip_tags(BBCode::convert($params['source_name'])), 0, 255),
469                         'url'           => $params['source_link'] ?? '',
470                         'photo'         => $params['source_photo'] ?? '',
471                         'link'          => $itemlink ?? '',
472                         'uid'           => $params['uid'] ?? 0,
473                         'iid'           => $item_id,
474                         'uri-id'        => $uri_id,
475                         'parent'        => $parent_id,
476                         'parent-uri-id' => $parent_uri_id,
477                         'type'          => $params['type'] ?? '',
478                         'verb'          => $params['verb'] ?? '',
479                         'otype'         => $params['otype'] ?? '',
480                 ]);
481
482                 $notification->msg = Renderer::replaceMacros($epreamble, ['$itemlink' => $notification->link]);
483
484                 DI::notify()->update($notification);
485
486                 $itemlink  = DI::baseUrl() . '/notification/' . $notification->id;
487                 $notify_id = $notification->id;
488         }
489
490         // send email notification if notification preferences permit
491         if ((intval($params['notify_flags']) & intval($params['type']))
492                 || $params['type'] == Notify\Type::SYSTEM) {
493
494                 Logger::log('sending notification email');
495
496                 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
497                         $id_for_parent = $params['parent'] . "@" . $hostname;
498
499                         // Is this the first email notification for this parent item and user?
500                         if (!DBA::exists('notify-threads', ['master-parent-item' => $params['parent'], 'receiver-uid' => $params['uid']])) {
501                                 Logger::log("notify_id:" . intval($notify_id) . ", parent: " . intval($params['parent']) . "uid: " . intval($params['uid']), Logger::DEBUG);
502
503                                 $fields = ['notify-id' => $notify_id, 'master-parent-item' => $params['parent'],
504                                         'master-parent-uri-id' => $parent_uri_id,
505                                         'receiver-uid' => $params['uid'], 'parent-item' => 0];
506                                 DBA::insert('notify-threads', $fields);
507
508                                 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
509                                 $log_msg                = "include/enotify: No previous notification found for this parent:\n" .
510                                                           "  parent: ${params['parent']}\n" . "  uid   : ${params['uid']}\n";
511                                 Logger::log($log_msg, Logger::DEBUG);
512                         } else {
513                                 // If not, just "follow" the thread.
514                                 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
515                                 Logger::log("There's already a notification for this parent.", Logger::DEBUG);
516                         }
517                 }
518
519                 $datarray = [
520                         'preamble'     => $preamble,
521                         'type'         => $params['type'],
522                         'parent'       => $parent_id,
523                         'source_name'  => $params['source_name'] ?? null,
524                         'source_link'  => $params['source_link'] ?? null,
525                         'source_photo' => $params['source_photo'] ?? null,
526                         'uid'          => $params['uid'],
527                         'hsitelink'    => $hsitelink,
528                         'tsitelink'    => $tsitelink,
529                         'itemlink'     => $itemlink,
530                         'title'        => $title,
531                         'body'         => $body,
532                         'subject'      => $subject,
533                         'headers'      => $additional_mail_header,
534                 ];
535
536                 Hook::callAll('enotify_mail', $datarray);
537
538                 $builder = DI::emailer()
539                         ->newNotifyMail()
540                         ->addHeaders($datarray['headers'])
541                         ->withRecipient($params['to_email'])
542                         ->forUser([
543                                 'uid' => $datarray['uid'],
544                                 'language' => $params['language'],
545                         ])
546                         ->withNotification($datarray['subject'], $datarray['preamble'], $datarray['title'], $datarray['body'])
547                         ->withSiteLink($datarray['tsitelink'], $datarray['hsitelink'])
548                         ->withItemLink($datarray['itemlink']);
549
550                 // If a photo is present, add it to the email
551                 if (!empty($datarray['source_photo'])) {
552                         $builder->withPhoto(
553                                 $datarray['source_photo'],
554                                 $datarray['source_link'] ?? $sitelink,
555                                 $datarray['source_name'] ?? $sitename);
556                 }
557
558                 $email = $builder->build();
559
560                 // use the Emailer class to send the message
561                 return DI::emailer()->send($email);
562         }
563
564         return false;
565 }
566
567 /**
568  * Checks for users who should be notified
569  *
570  * @param int $itemid ID of the item for which the check should be done
571  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
572  */
573 function check_user_notification($itemid) {
574         // fetch all users with notifications
575         $useritems = DBA::select('user-item', ['uid', 'notification-type'], ['iid' => $itemid]);
576         while ($useritem = DBA::fetch($useritems)) {
577                 check_item_notification($itemid, $useritem['uid'], $useritem['notification-type']);
578         }
579         DBA::close($useritems);
580 }
581
582 /**
583  * Checks for item related notifications and sends them
584  *
585  * @param int    $itemid            ID of the item for which the check should be done
586  * @param int    $uid               User ID
587  * @param int    $notification_type Notification bits
588  * @return bool
589  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
590  */
591 function check_item_notification($itemid, $uid, $notification_type) {
592         $fields = ['id', 'uri-id', 'mention', 'parent', 'parent-uri-id', 'title', 'body',
593                 'author-link', 'author-name', 'author-avatar', 'author-id',
594                 'guid', 'parent-uri', 'uri', 'contact-id', 'network'];
595         $condition = ['id' => $itemid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'deleted' => false];
596         $item = Item::selectFirstForUser($uid, $fields, $condition);
597         if (!DBA::isResult($item)) {
598                 return false;
599         }
600
601         // Generate the notification array
602         $params = [];
603         $params['uid'] = $uid;
604         $params['item'] = $item;
605         $params['parent'] = $item['parent'];
606         $params['link'] = DI::baseUrl() . '/display/' . urlencode($item['guid']);
607         $params['otype'] = 'item';
608         $params['source_name'] = $item['author-name'];
609         $params['source_link'] = $item['author-link'];
610         $params['source_photo'] = $item['author-avatar'];
611
612         // Set the activity flags
613         $params['activity']['explicit_tagged'] = ($notification_type & UserItem::NOTIF_EXPLICIT_TAGGED);
614         $params['activity']['implicit_tagged'] = ($notification_type & UserItem::NOTIF_IMPLICIT_TAGGED);
615         $params['activity']['origin_comment'] = ($notification_type & UserItem::NOTIF_DIRECT_COMMENT);
616         $params['activity']['origin_thread'] = ($notification_type & UserItem::NOTIF_THREAD_COMMENT);
617         $params['activity']['thread_comment'] = ($notification_type & UserItem::NOTIF_COMMENT_PARTICIPATION);
618         $params['activity']['thread_activity'] = ($notification_type & UserItem::NOTIF_ACTIVITY_PARTICIPATION);
619
620         // Tagging a user in a direct post (first comment level) means a direct comment
621         if ($params['activity']['explicit_tagged'] && ($notification_type & UserItem::NOTIF_DIRECT_THREAD_COMMENT)) {
622                 $params['activity']['origin_comment'] = true;
623         }
624
625         if ($notification_type & UserItem::NOTIF_SHARED) {
626                 $params['type'] = Notify\Type::SHARE;
627                 $params['verb'] = Activity::POST;
628         } elseif ($notification_type & UserItem::NOTIF_EXPLICIT_TAGGED) {
629                 $params['type'] = Notify\Type::TAG_SELF;
630                 $params['verb'] = Activity::TAG;
631         } elseif ($notification_type & UserItem::NOTIF_IMPLICIT_TAGGED) {
632                 $params['type'] = Notify\Type::COMMENT;
633                 $params['verb'] = Activity::POST;
634         } elseif ($notification_type & UserItem::NOTIF_THREAD_COMMENT) {
635                 $params['type'] = Notify\Type::COMMENT;
636                 $params['verb'] = Activity::POST;
637         } elseif ($notification_type & UserItem::NOTIF_DIRECT_COMMENT) {
638                 $params['type'] = Notify\Type::COMMENT;
639                 $params['verb'] = Activity::POST;
640         } elseif ($notification_type & UserItem::NOTIF_COMMENT_PARTICIPATION) {
641                 $params['type'] = Notify\Type::COMMENT;
642                 $params['verb'] = Activity::POST;
643         } elseif ($notification_type & UserItem::NOTIF_ACTIVITY_PARTICIPATION) {
644                 $params['type'] = Notify\Type::COMMENT;
645                 $params['verb'] = Activity::POST;
646         } else {
647                 return false;
648         }
649
650         notification($params);
651 }