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