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