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