]> git.mxchange.org Git - friendica.git/blob - include/enotify.php
Move Object\Image static methods to Util\Images
[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\Item;
15 use Friendica\Model\User;
16 use Friendica\Protocol\Activity;
17 use Friendica\Util\DateTimeFormat;
18 use Friendica\Util\Emailer;
19 use Friendica\Util\Strings;
20
21 /**
22  * @brief Creates a notification entry and possibly sends a mail
23  *
24  * @param array $params Array with the elements:
25  *                      uid, item, parent, type, otype, verb, event,
26  *                      link, subject, body, to_name, to_email, source_name,
27  *                      source_link, activity, preamble, notify_flags,
28  *                      language, show_in_notification_page
29  * @return bool
30  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
31  */
32 function notification($params)
33 {
34         $a = \get_app();
35
36         // Temporary logging for finding the origin
37         if (!isset($params['uid'])) {
38                 Logger::notice('Missing parameters "uid".', ['params' => $params, 'callstack' => System::callstack()]);
39         }
40
41         // Ensure that the important fields are set at any time
42         $fields = ['notify-flags', 'language', 'username', 'email'];
43         $user = DBA::selectFirst('user', $fields, ['uid' => $params['uid']]);
44
45         if (!DBA::isResult($user)) {
46                 Logger::error('Unknown user', ['uid' =>  $params['uid']]);
47                 return false;
48         }
49
50         $params['notify_flags'] = ($params['notify_flags'] ?? '') ?: $user['notify-flags'];
51         $params['language']     = ($params['language']     ?? '') ?: $user['language'];
52         $params['to_name']      = ($params['to_name']      ?? '') ?: $user['username'];
53         $params['to_email']     = ($params['to_email']     ?? '') ?: $user['email'];
54
55         // from here on everything is in the recipients language
56         L10n::pushLang($params['language']);
57
58         $banner = L10n::t('Friendica Notification');
59         $product = FRIENDICA_PLATFORM;
60         $siteurl = System::baseUrl(true);
61         $thanks = L10n::t('Thank You,');
62         $sitename = Config::get('config', 'sitename');
63         if (Config::get('config', 'admin_name')) {
64                 $site_admin = L10n::t('%1$s, %2$s Administrator', Config::get('config', 'admin_name'), $sitename);
65         } else {
66                 $site_admin = L10n::t('%s Administrator', $sitename);
67         }
68
69         $sender_name = $sitename;
70         $hostname = $a->getHostName();
71         if (strpos($hostname, ':')) {
72                 $hostname = substr($hostname, 0, strpos($hostname, ':'));
73         }
74
75         $sender_email = $a->getSenderEmailAddress();
76
77         if ($params['type'] != SYSTEM_EMAIL) {
78                 $user = DBA::selectFirst('user', ['nickname', 'page-flags'],
79                         ['uid' => $params['uid']]);
80
81                 // There is no need to create notifications for forum accounts
82                 if (!DBA::isResult($user) || in_array($user["page-flags"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
83                         return false;
84                 }
85                 $nickname = $user["nickname"];
86         } else {
87                 $nickname = '';
88         }
89
90         // with $params['show_in_notification_page'] == false, the notification isn't inserted into
91         // the database, and an email is sent if applicable.
92         // default, if not specified: true
93         $show_in_notification_page = isset($params['show_in_notification_page']) ? $params['show_in_notification_page'] : true;
94
95         $additional_mail_header = "";
96         $additional_mail_header .= "Precedence: list\n";
97         $additional_mail_header .= "X-Friendica-Host: ".$hostname."\n";
98         $additional_mail_header .= "X-Friendica-Account: <".$nickname."@".$hostname.">\n";
99         $additional_mail_header .= "X-Friendica-Platform: ".FRIENDICA_PLATFORM."\n";
100         $additional_mail_header .= "X-Friendica-Version: ".FRIENDICA_VERSION."\n";
101         $additional_mail_header .= "List-ID: <notification.".$hostname.">\n";
102         $additional_mail_header .= "List-Archive: <".System::baseUrl()."/notifications/system>\n";
103
104         if (array_key_exists('item', $params)) {
105                 $title = $params['item']['title'];
106                 $body = $params['item']['body'];
107         } else {
108                 $title = $body = '';
109         }
110
111         if (isset($params['item']['id'])) {
112                 $item_id = $params['item']['id'];
113         } else {
114                 $item_id = 0;
115         }
116
117         if (isset($params['parent'])) {
118                 $parent_id = $params['parent'];
119         } else {
120                 $parent_id = 0;
121         }
122
123         $epreamble = '';
124         $preamble  = '';
125         $subject   = '';
126         $sitelink  = '';
127         $tsitelink = '';
128         $hsitelink = '';
129         $itemlink  = '';
130
131         if ($params['type'] == NOTIFY_MAIL) {
132                 $itemlink = $siteurl.'/message/'.$params['item']['id'];
133                 $params["link"] = $itemlink;
134
135                 $subject = L10n::t('[Friendica:Notify] New mail received at %s', $sitename);
136
137                 $preamble = L10n::t('%1$s sent you a new private message at %2$s.', $params['source_name'], $sitename);
138                 $epreamble = L10n::t('%1$s sent you %2$s.', '[url='.$params['source_link'].']'.$params['source_name'].'[/url]', '[url=' . $itemlink . ']'.L10n::t('a private message').'[/url]');
139
140                 $sitelink = L10n::t('Please visit %s to view and/or reply to your private messages.');
141                 $tsitelink = sprintf($sitelink, $siteurl.'/message/'.$params['item']['id']);
142                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'/message/'.$params['item']['id'].'">'.$sitename.'</a>');
143         }
144
145         if ($params['type'] == NOTIFY_COMMENT || $params['type'] == NOTIFY_TAGSELF) {
146                 $thread = Item::selectFirstThreadForUser($params['uid'], ['ignored'], ['iid' => $parent_id, 'deleted' => false]);
147                 if (DBA::isResult($thread) && $thread['ignored']) {
148                         Logger::log('Thread ' . $parent_id . ' will be ignored', Logger::DEBUG);
149                         L10n::popLang();
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                         L10n::popLang();
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                 do {
507                         $dups = false;
508                         $hash = Strings::getRandomHex();
509                         if (DBA::exists('notify', ['hash' => $hash])) {
510                                 $dups = true;
511                         }
512                 } while ($dups == true);
513
514                 /// @TODO One statement is enough
515                 $datarray = [];
516                 $datarray['hash']  = $hash;
517                 $datarray['name']  = $params['source_name'];
518                 $datarray['name_cache'] = strip_tags(BBCode::convert($params['source_name']));
519                 $datarray['url']   = $params['source_link'];
520                 $datarray['photo'] = $params['source_photo'];
521                 $datarray['date']  = DateTimeFormat::utcNow();
522                 $datarray['uid']   = $params['uid'];
523                 $datarray['link']  = $itemlink;
524                 $datarray['iid']   = $item_id;
525                 $datarray['parent'] = $parent_id;
526                 $datarray['type']  = $params['type'];
527                 $datarray['verb']  = $params['verb'];
528                 $datarray['otype'] = $params['otype'];
529                 $datarray['abort'] = false;
530
531                 Hook::callAll('enotify_store', $datarray);
532
533                 if ($datarray['abort']) {
534                         L10n::popLang();
535                         return false;
536                 }
537
538                 // create notification entry in DB
539                 $fields = ['hash' => $datarray['hash'], 'name' => $datarray['name'], 'url' => $datarray['url'],
540                         'photo' => $datarray['photo'], 'date' => $datarray['date'], 'uid' => $datarray['uid'],
541                         'link' => $datarray['link'], 'iid' => $datarray['iid'], 'parent' => $datarray['parent'],
542                         'type' => $datarray['type'], 'verb' => $datarray['verb'], 'otype' => $datarray['otype'],
543                         'name_cache' => $datarray["name_cache"]];
544                 DBA::insert('notify', $fields);
545
546                 $notify_id = DBA::lastInsertId();
547
548                 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
549                 // After we've stored everything, look again to see if there are any duplicates and if so remove them
550                 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
551                         intval(NOTIFY_TAGSELF),
552                         intval(NOTIFY_COMMENT),
553                         DBA::escape($params['link']),
554                         intval($params['uid'])
555                 );
556                 if ($p && (count($p) > 1)) {
557                         for ($d = 1; $d < count($p); $d ++) {
558                                 DBA::delete('notify', ['id' => $p[$d]['id']]);
559                         }
560
561                         // only continue on if we stored the first one
562                         if ($notify_id != $p[0]['id']) {
563                                 L10n::popLang();
564                                 return false;
565                         }
566                 }
567
568                 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
569                 $msg = Renderer::replaceMacros($epreamble, ['$itemlink' => $itemlink]);
570                 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(BBCode::convert($msg)));
571
572                 $fields = ['msg' => $msg, 'msg_cache' => $msg_cache];
573                 $condition = ['id' => $notify_id, 'uid' => $params['uid']];
574                 DBA::update('notify', $fields, $condition);
575         }
576
577         // send email notification if notification preferences permit
578         if ((intval($params['notify_flags']) & intval($params['type']))
579                 || $params['type'] == NOTIFY_SYSTEM
580                 || $params['type'] == SYSTEM_EMAIL) {
581
582                 Logger::log('sending notification email');
583
584                 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
585                         $id_for_parent = $params['parent']."@".$hostname;
586
587                         // Is this the first email notification for this parent item and user?
588                         if (!DBA::exists('notify-threads', ['master-parent-item' => $params['parent'], 'receiver-uid' => $params['uid']])) {
589                                 Logger::log("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), Logger::DEBUG);
590
591                                 $fields = ['notify-id' => $notify_id, 'master-parent-item' => $params['parent'],
592                                         'receiver-uid' => $params['uid'], 'parent-item' => 0];
593                                 DBA::insert('notify-threads', $fields);
594
595                                 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
596                                 $log_msg = "include/enotify: No previous notification found for this parent:\n".
597                                                 "  parent: ${params['parent']}\n"."  uid   : ${params['uid']}\n";
598                                 Logger::log($log_msg, Logger::DEBUG);
599                         } else {
600                                 // If not, just "follow" the thread.
601                                 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
602                                 Logger::log("There's already a notification for this parent.", Logger::DEBUG);
603                         }
604                 }
605
606                 $textversion = BBCode::toPlaintext($body);
607                 $htmlversion = BBCode::convert($body);
608
609                 $datarray = [];
610                 $datarray['banner'] = $banner;
611                 $datarray['product'] = $product;
612                 $datarray['preamble'] = $preamble;
613                 $datarray['sitename'] = $sitename;
614                 $datarray['siteurl'] = $siteurl;
615                 $datarray['type'] = $params['type'];
616                 $datarray['parent'] = $parent_id;
617                 $datarray['source_name'] = $params['source_name'] ?? '';
618                 $datarray['source_link'] = $params['source_link'] ?? '';
619                 $datarray['source_photo'] = $params['source_photo'] ?? '';
620                 $datarray['uid'] = $params['uid'];
621                 $datarray['username'] = $params['to_name'] ?? '';
622                 $datarray['hsitelink'] = $hsitelink;
623                 $datarray['tsitelink'] = $tsitelink;
624                 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
625                 $datarray['titemlink'] = $itemlink;
626                 $datarray['thanks'] = $thanks;
627                 $datarray['site_admin'] = $site_admin;
628                 $datarray['title'] = stripslashes($title);
629                 $datarray['htmlversion'] = $htmlversion;
630                 $datarray['textversion'] = $textversion;
631                 $datarray['subject'] = $subject;
632                 $datarray['headers'] = $additional_mail_header;
633
634                 Hook::callAll('enotify_mail', $datarray);
635
636                 // check whether sending post content in email notifications is allowed
637                 // always true for SYSTEM_EMAIL
638                 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
639
640                 // load the template for private message notifications
641                 $tpl = Renderer::getMarkupTemplate('email_notify_html.tpl');
642                 $email_html_body = Renderer::replaceMacros($tpl, [
643                         '$banner'       => $datarray['banner'],
644                         '$product'      => $datarray['product'],
645                         '$preamble'     => str_replace("\n", "<br>\n", $datarray['preamble']),
646                         '$sitename'     => $datarray['sitename'],
647                         '$siteurl'      => $datarray['siteurl'],
648                         '$source_name'  => $datarray['source_name'],
649                         '$source_link'  => $datarray['source_link'],
650                         '$source_photo' => $datarray['source_photo'],
651                         '$username'     => $datarray['username'],
652                         '$hsitelink'    => $datarray['hsitelink'],
653                         '$hitemlink'    => $datarray['hitemlink'],
654                         '$thanks'       => $datarray['thanks'],
655                         '$site_admin'   => $datarray['site_admin'],
656                         '$title'        => $datarray['title'],
657                         '$htmlversion'  => $datarray['htmlversion'],
658                         '$content_allowed'      => $content_allowed,
659                 ]);
660
661                 // load the template for private message notifications
662                 $tpl = Renderer::getMarkupTemplate('email_notify_text.tpl');
663                 $email_text_body = Renderer::replaceMacros($tpl, [
664                         '$banner'       => $datarray['banner'],
665                         '$product'      => $datarray['product'],
666                         '$preamble'     => $datarray['preamble'],
667                         '$sitename'     => $datarray['sitename'],
668                         '$siteurl'      => $datarray['siteurl'],
669                         '$source_name'  => $datarray['source_name'],
670                         '$source_link'  => $datarray['source_link'],
671                         '$source_photo' => $datarray['source_photo'],
672                         '$username'     => $datarray['username'],
673                         '$tsitelink'    => $datarray['tsitelink'],
674                         '$titemlink'    => $datarray['titemlink'],
675                         '$thanks'       => $datarray['thanks'],
676                         '$site_admin'   => $datarray['site_admin'],
677                         '$title'        => $datarray['title'],
678                         '$textversion'  => $datarray['textversion'],
679                         '$content_allowed'      => $content_allowed,
680                 ]);
681
682                 L10n::popLang();
683                 // use the Emailer class to send the message
684                 return Emailer::send([
685                         'uid' => $params['uid'],
686                         'fromName' => $sender_name,
687                         'fromEmail' => $sender_email,
688                         'replyTo' => $sender_email,
689                         'toEmail' => $params['to_email'],
690                         'messageSubject' => $datarray['subject'],
691                         'htmlVersion' => $email_html_body,
692                         'textVersion' => $email_text_body,
693                         'additionalMailHeader' => $datarray['headers']
694                 ]);
695         }
696
697         L10n::popLang();
698         return false;
699 }
700
701 /**
702  * @brief Checks for users who should be notified
703  *
704  * @param int $itemid ID of the item for which the check should be done
705  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
706  */
707 function check_user_notification($itemid) {
708         // fetch all users in the thread
709         $users = DBA::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
710                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
711                         WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
712         while ($user = DBA::fetch($users)) {
713                 check_item_notification($itemid, $user['uid']);
714         }
715         DBA::close($users);
716 }
717
718 /**
719  * @brief Checks for item related notifications and sends them
720  *
721  * @param int    $itemid      ID of the item for which the check should be done
722  * @param int    $uid         User ID
723  * @param string $defaulttype (Optional) Forces a notification with this type.
724  * @return bool
725  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
726  */
727 function check_item_notification($itemid, $uid, $defaulttype = "") {
728         $notification_data = ["uid" => $uid, "profiles" => []];
729         Hook::callAll('check_item_notification', $notification_data);
730
731         $profiles = $notification_data["profiles"];
732
733         $fields = ['nickname'];
734         $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
735         if (!DBA::isResult($user)) {
736                 return false;
737         }
738
739         $owner = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
740         if (!DBA::isResult($owner)) {
741                 return false;
742         }
743
744         // This is our regular URL format
745         $profiles[] = $owner["url"];
746
747         // Notifications from Diaspora are often with an URL in the Diaspora format
748         $profiles[] = System::baseUrl()."/u/".$user["nickname"];
749
750         $profiles2 = [];
751
752         foreach ($profiles AS $profile) {
753                 // Check for invalid profile urls. 13 should be the shortest possible profile length:
754                 // http://a.bc/d
755                 // Additionally check for invalid urls that would return the normalised value "http:"
756                 if ((strlen($profile) >= 13) && (Strings::normaliseLink($profile) != "http:")) {
757                         if (!in_array($profile, $profiles2))
758                                 $profiles2[] = $profile;
759
760                         $profile = Strings::normaliseLink($profile);
761                         if (!in_array($profile, $profiles2))
762                                 $profiles2[] = $profile;
763
764                         $profile = str_replace("http://", "https://", $profile);
765                         if (!in_array($profile, $profiles2))
766                                 $profiles2[] = $profile;
767                 }
768         }
769
770         $profiles = $profiles2;
771
772         $ret = DBA::select('contact', ['id'], ['uid' => 0, 'nurl' => $profiles]);
773
774         $contacts = [];
775
776         while ($contact = DBA::fetch($ret)) {
777                 $contacts[] = $contact['id'];
778         }
779
780         DBA::close($ret);
781
782         // Only act if it is a "real" post
783         // We need the additional check for the "local_profile" because of mixed situations on connector networks
784         $fields = ['id', 'mention', 'tag', 'parent', 'title', 'body',
785                 'author-link', 'author-name', 'author-avatar', 'author-id',
786                 'guid', 'parent-uri', 'uri', 'contact-id', 'network'];
787         $condition = ['id' => $itemid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'deleted' => false];
788         $item = Item::selectFirstForUser($uid, $fields, $condition);
789         if (!DBA::isResult($item) || in_array($item['author-id'], $contacts)) {
790                 return false;
791         }
792
793         // Generate the notification array
794         $params = [];
795         $params["uid"] = $uid;
796         $params["item"] = $item;
797         $params["parent"] = $item["parent"];
798         $params["link"] = System::baseUrl().'/display/'.urlencode($item["guid"]);
799         $params["otype"] = 'item';
800         $params["source_name"] = $item["author-name"];
801         $params["source_link"] = $item["author-link"];
802         $params["source_photo"] = $item["author-avatar"];
803
804         if ($item["parent-uri"] === $item["uri"]) {
805                 // Send a notification for every new post?
806                 $send_notification = DBA::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true]);
807
808                 if (!$send_notification) {
809                         $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
810                                 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
811
812                         if (DBA::isResult($tags)) {
813                                 foreach ($tags AS $tag) {
814                                         $condition = ['nurl' => Strings::normaliseLink($tag["url"]), 'uid' => $uid, 'notify_new_posts' => true];
815                                         $r = DBA::exists('contact', $condition);
816                                         if ($r) {
817                                                 $send_notification = true;
818                                         }
819                                 }
820                         }
821                 }
822
823                 if ($send_notification) {
824                         $params["type"] = NOTIFY_SHARE;
825                         $params["verb"] = Activity::TAG;
826                 }
827         }
828
829         // Is the user mentioned in this post?
830         $tagged = false;
831
832         foreach ($profiles AS $profile) {
833                 if (strpos($item["tag"], "=".$profile."]") || strpos($item["body"], "=".$profile."]"))
834                         $tagged = true;
835         }
836
837         if ($item["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
838                 $params["type"] = NOTIFY_TAGSELF;
839                 $params["verb"] = Activity::TAG;
840         }
841
842         // Is it a post that the user had started?
843         $fields = ['ignored', 'mention'];
844         $thread = Item::selectFirstThreadForUser($params['uid'], $fields, ['iid' => $item["parent"], 'deleted' => false]);
845
846         if ($thread['mention'] && !$thread['ignored'] && !isset($params["type"])) {
847                 $params["type"] = NOTIFY_COMMENT;
848                 $params["verb"] = Activity::POST;
849         }
850
851         // And now we check for participation of one of our contacts in the thread
852         $condition = ['parent' => $item["parent"], 'author-id' => $contacts, 'deleted' => false];
853
854         if (!$thread['ignored'] && !isset($params["type"]) && Item::exists($condition)) {
855                 $params["type"] = NOTIFY_COMMENT;
856                 $params["verb"] = Activity::POST;
857         }
858
859         if (isset($params["type"])) {
860                 notification($params);
861         }
862 }
863
864 /**
865  * @brief Formats a notification message with the notification author
866  *
867  * Replace the name with {0} but ensure to make that only once. The {0} is used
868  * later and prints the name in bold.
869  *
870  * @param string $name
871  * @param string $message
872  * @return string Formatted message
873  */
874 function format_notification_message($name, $message) {
875         if ($name != '') {
876                 $pos = strpos($message, $name);
877         } else {
878                 $pos = false;
879         }
880
881         if ($pos !== false) {
882                 $message = substr_replace($message, '{0}', $pos, strlen($name));
883         }
884
885         return $message;
886 }