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