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