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