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