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