]> git.mxchange.org Git - friendica.git/blob - include/enotify.php
Merge remote-tracking branch 'upstream/2019.03-RC' into worker2
[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                 $subject = $params['subject'];
457
458                 $preamble = $params['preamble'];
459
460                 $body =  $params['body'];
461
462                 $show_in_notification_page = false;
463         }
464
465         $subject .= " (".$nickname."@".$hostname.")";
466
467         $h = [
468                 'params'    => $params,
469                 'subject'   => $subject,
470                 'preamble'  => $preamble,
471                 'epreamble' => $epreamble,
472                 'body'      => $body,
473                 'sitelink'  => $sitelink,
474                 'tsitelink' => $tsitelink,
475                 'hsitelink' => $hsitelink,
476                 'itemlink'  => $itemlink
477         ];
478
479         Hook::callAll('enotify', $h);
480
481         $subject   = $h['subject'];
482
483         $preamble  = $h['preamble'];
484         $epreamble = $h['epreamble'];
485
486         $body      = $h['body'];
487
488         $tsitelink = $h['tsitelink'];
489         $hsitelink = $h['hsitelink'];
490         $itemlink  = $h['itemlink'];
491
492         $notify_id = 0;
493
494         if ($show_in_notification_page) {
495                 Logger::log("adding notification entry", Logger::DEBUG);
496                 do {
497                         $dups = false;
498                         $hash = Strings::getRandomHex();
499                         if (DBA::exists('notify', ['hash' => $hash])) {
500                                 $dups = true;
501                         }
502                 } while ($dups == true);
503
504                 /// @TODO One statement is enough
505                 $datarray = [];
506                 $datarray['hash']  = $hash;
507                 $datarray['name']  = $params['source_name'];
508                 $datarray['name_cache'] = strip_tags(BBCode::convert($params['source_name']));
509                 $datarray['url']   = $params['source_link'];
510                 $datarray['photo'] = $params['source_photo'];
511                 $datarray['date']  = DateTimeFormat::utcNow();
512                 $datarray['uid']   = $params['uid'];
513                 $datarray['link']  = $itemlink;
514                 $datarray['iid']   = $item_id;
515                 $datarray['parent'] = $parent_id;
516                 $datarray['type']  = $params['type'];
517                 $datarray['verb']  = $params['verb'];
518                 $datarray['otype'] = $params['otype'];
519                 $datarray['abort'] = false;
520
521                 Hook::callAll('enotify_store', $datarray);
522
523                 if ($datarray['abort']) {
524                         L10n::popLang();
525                         return false;
526                 }
527
528                 // create notification entry in DB
529                 $fields = ['hash' => $datarray['hash'], 'name' => $datarray['name'], 'url' => $datarray['url'],
530                         'photo' => $datarray['photo'], 'date' => $datarray['date'], 'uid' => $datarray['uid'],
531                         'link' => $datarray['link'], 'iid' => $datarray['iid'], 'parent' => $datarray['parent'],
532                         'type' => $datarray['type'], 'verb' => $datarray['verb'], 'otype' => $datarray['otype'],
533                         'name_cache' => $datarray["name_cache"]];
534                 DBA::insert('notify', $fields);
535
536                 $notify_id = DBA::lastInsertId();
537
538                 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
539                 // After we've stored everything, look again to see if there are any duplicates and if so remove them
540                 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
541                         intval(NOTIFY_TAGSELF),
542                         intval(NOTIFY_COMMENT),
543                         DBA::escape($params['link']),
544                         intval($params['uid'])
545                 );
546                 if ($p && (count($p) > 1)) {
547                         for ($d = 1; $d < count($p); $d ++) {
548                                 DBA::delete('notify', ['id' => $p[$d]['id']]);
549                         }
550
551                         // only continue on if we stored the first one
552                         if ($notify_id != $p[0]['id']) {
553                                 L10n::popLang();
554                                 return false;
555                         }
556                 }
557
558                 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
559                 $msg = Renderer::replaceMacros($epreamble, ['$itemlink' => $itemlink]);
560                 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(BBCode::convert($msg)));
561
562                 $fields = ['msg' => $msg, 'msg_cache' => $msg_cache];
563                 $condition = ['id' => $notify_id, 'uid' => $params['uid']];
564                 DBA::update('notify', $fields, $condition);
565         }
566
567         // send email notification if notification preferences permit
568         if ((intval($params['notify_flags']) & intval($params['type']))
569                 || $params['type'] == NOTIFY_SYSTEM
570                 || $params['type'] == SYSTEM_EMAIL) {
571
572                 Logger::log('sending notification email');
573
574                 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
575                         $id_for_parent = $params['parent']."@".$hostname;
576
577                         // Is this the first email notification for this parent item and user?
578                         if (!DBA::exists('notify-threads', ['master-parent-item' => $params['parent'], 'receiver-uid' => $params['uid']])) {
579                                 Logger::log("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), Logger::DEBUG);
580
581                                 $fields = ['notify-id' => $notify_id, 'master-parent-item' => $params['parent'],
582                                         'receiver-uid' => $params['uid'], 'parent-item' => 0];
583                                 DBA::insert('notify-threads', $fields);
584
585                                 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
586                                 $log_msg = "include/enotify: No previous notification found for this parent:\n".
587                                                 "  parent: ${params['parent']}\n"."  uid   : ${params['uid']}\n";
588                                 Logger::log($log_msg, Logger::DEBUG);
589                         } else {
590                                 // If not, just "follow" the thread.
591                                 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
592                                 Logger::log("There's already a notification for this parent.", Logger::DEBUG);
593                         }
594                 }
595
596                 $textversion = BBCode::toPlaintext($body);
597                 $htmlversion = BBCode::convert($body);
598
599                 $datarray = [];
600                 $datarray['banner'] = $banner;
601                 $datarray['product'] = $product;
602                 $datarray['preamble'] = $preamble;
603                 $datarray['sitename'] = $sitename;
604                 $datarray['siteurl'] = $siteurl;
605                 $datarray['type'] = $params['type'];
606                 $datarray['parent'] = $parent_id;
607                 $datarray['source_name'] = defaults($params, 'source_name', '');
608                 $datarray['source_link'] = defaults($params, 'source_link', '');
609                 $datarray['source_photo'] = defaults($params, 'source_photo', '');
610                 $datarray['uid'] = $params['uid'];
611                 $datarray['username'] = defaults($params, 'to_name', '');
612                 $datarray['hsitelink'] = $hsitelink;
613                 $datarray['tsitelink'] = $tsitelink;
614                 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
615                 $datarray['titemlink'] = $itemlink;
616                 $datarray['thanks'] = $thanks;
617                 $datarray['site_admin'] = $site_admin;
618                 $datarray['title'] = stripslashes($title);
619                 $datarray['htmlversion'] = $htmlversion;
620                 $datarray['textversion'] = $textversion;
621                 $datarray['subject'] = $subject;
622                 $datarray['headers'] = $additional_mail_header;
623
624                 Hook::callAll('enotify_mail', $datarray);
625
626                 // check whether sending post content in email notifications is allowed
627                 // always true for SYSTEM_EMAIL
628                 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
629
630                 // load the template for private message notifications
631                 $tpl = Renderer::getMarkupTemplate('email_notify_html.tpl');
632                 $email_html_body = Renderer::replaceMacros($tpl, [
633                         '$banner'       => $datarray['banner'],
634                         '$product'      => $datarray['product'],
635                         '$preamble'     => str_replace("\n", "<br>\n", $datarray['preamble']),
636                         '$sitename'     => $datarray['sitename'],
637                         '$siteurl'      => $datarray['siteurl'],
638                         '$source_name'  => $datarray['source_name'],
639                         '$source_link'  => $datarray['source_link'],
640                         '$source_photo' => $datarray['source_photo'],
641                         '$username'     => $datarray['username'],
642                         '$hsitelink'    => $datarray['hsitelink'],
643                         '$hitemlink'    => $datarray['hitemlink'],
644                         '$thanks'       => $datarray['thanks'],
645                         '$site_admin'   => $datarray['site_admin'],
646                         '$title'        => $datarray['title'],
647                         '$htmlversion'  => $datarray['htmlversion'],
648                         '$content_allowed'      => $content_allowed,
649                 ]);
650
651                 // load the template for private message notifications
652                 $tpl = Renderer::getMarkupTemplate('email_notify_text.tpl');
653                 $email_text_body = Renderer::replaceMacros($tpl, [
654                         '$banner'       => $datarray['banner'],
655                         '$product'      => $datarray['product'],
656                         '$preamble'     => $datarray['preamble'],
657                         '$sitename'     => $datarray['sitename'],
658                         '$siteurl'      => $datarray['siteurl'],
659                         '$source_name'  => $datarray['source_name'],
660                         '$source_link'  => $datarray['source_link'],
661                         '$source_photo' => $datarray['source_photo'],
662                         '$username'     => $datarray['username'],
663                         '$tsitelink'    => $datarray['tsitelink'],
664                         '$titemlink'    => $datarray['titemlink'],
665                         '$thanks'       => $datarray['thanks'],
666                         '$site_admin'   => $datarray['site_admin'],
667                         '$title'        => $datarray['title'],
668                         '$textversion'  => $datarray['textversion'],
669                         '$content_allowed'      => $content_allowed,
670                 ]);
671
672                 L10n::popLang();
673                 // use the Emailer class to send the message
674                 return Emailer::send([
675                         'uid' => $params['uid'],
676                         'fromName' => $sender_name,
677                         'fromEmail' => $sender_email,
678                         'replyTo' => $sender_email,
679                         'toEmail' => $params['to_email'],
680                         'messageSubject' => $datarray['subject'],
681                         'htmlVersion' => $email_html_body,
682                         'textVersion' => $email_text_body,
683                         'additionalMailHeader' => $datarray['headers']
684                 ]);
685         }
686
687         L10n::popLang();
688         return false;
689 }
690
691 /**
692  * @brief Checks for users who should be notified
693  *
694  * @param int $itemid ID of the item for which the check should be done
695  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
696  */
697 function check_user_notification($itemid) {
698         // fetch all users in the thread
699         $users = DBA::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
700                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
701                         WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
702         while ($user = DBA::fetch($users)) {
703                 check_item_notification($itemid, $user['uid']);
704         }
705         DBA::close($users);
706 }
707
708 /**
709  * @brief Checks for item related notifications and sends them
710  *
711  * @param int    $itemid      ID of the item for which the check should be done
712  * @param int    $uid         User ID
713  * @param string $defaulttype (Optional) Forces a notification with this type.
714  * @return bool
715  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
716  */
717 function check_item_notification($itemid, $uid, $defaulttype = "") {
718         $notification_data = ["uid" => $uid, "profiles" => []];
719         Hook::callAll('check_item_notification', $notification_data);
720
721         $profiles = $notification_data["profiles"];
722
723         $fields = ['nickname'];
724         $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
725         if (!DBA::isResult($user)) {
726                 return false;
727         }
728
729         $owner = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
730         if (!DBA::isResult($owner)) {
731                 return false;
732         }
733
734         // This is our regular URL format
735         $profiles[] = $owner["url"];
736
737         // Notifications from Diaspora are often with an URL in the Diaspora format
738         $profiles[] = System::baseUrl()."/u/".$user["nickname"];
739
740         $profiles2 = [];
741
742         foreach ($profiles AS $profile) {
743                 // Check for invalid profile urls. 13 should be the shortest possible profile length:
744                 // http://a.bc/d
745                 // Additionally check for invalid urls that would return the normalised value "http:"
746                 if ((strlen($profile) >= 13) && (Strings::normaliseLink($profile) != "http:")) {
747                         if (!in_array($profile, $profiles2))
748                                 $profiles2[] = $profile;
749
750                         $profile = Strings::normaliseLink($profile);
751                         if (!in_array($profile, $profiles2))
752                                 $profiles2[] = $profile;
753
754                         $profile = str_replace("http://", "https://", $profile);
755                         if (!in_array($profile, $profiles2))
756                                 $profiles2[] = $profile;
757                 }
758         }
759
760         $profiles = $profiles2;
761
762         $ret = DBA::select('contact', ['id'], ['uid' => 0, 'nurl' => $profiles]);
763
764         $contacts = [];
765
766         while ($contact = DBA::fetch($ret)) {
767                 $contacts[] = $contact['id'];
768         }
769
770         DBA::close($ret);
771
772         // Only act if it is a "real" post
773         // We need the additional check for the "local_profile" because of mixed situations on connector networks
774         $fields = ['id', 'mention', 'tag', 'parent', 'title', 'body',
775                 'author-link', 'author-name', 'author-avatar', 'author-id',
776                 'guid', 'parent-uri', 'uri', 'contact-id', 'network'];
777         $condition = ['id' => $itemid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
778         $item = Item::selectFirst($fields, $condition);
779         if (!DBA::isResult($item) || in_array($item['author-id'], $contacts)) {
780                 return false;
781         }
782
783         // Generate the notification array
784         $params = [];
785         $params["uid"] = $uid;
786         $params["item"] = $item;
787         $params["parent"] = $item["parent"];
788         $params["link"] = System::baseUrl().'/display/'.urlencode($item["guid"]);
789         $params["otype"] = 'item';
790         $params["source_name"] = $item["author-name"];
791         $params["source_link"] = $item["author-link"];
792         $params["source_photo"] = $item["author-avatar"];
793
794         if ($item["parent-uri"] === $item["uri"]) {
795                 // Send a notification for every new post?
796                 $send_notification = DBA::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true]);
797
798                 if (!$send_notification) {
799                         $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
800                                 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
801
802                         if (DBA::isResult($tags)) {
803                                 foreach ($tags AS $tag) {
804                                         $condition = ['nurl' => Strings::normaliseLink($tag["url"]), 'uid' => $uid, 'notify_new_posts' => true];
805                                         $r = DBA::exists('contact', $condition);
806                                         if ($r) {
807                                                 $send_notification = true;
808                                         }
809                                 }
810                         }
811                 }
812
813                 if ($send_notification) {
814                         $params["type"] = NOTIFY_SHARE;
815                         $params["verb"] = ACTIVITY_TAG;
816                 }
817         }
818
819         // Is the user mentioned in this post?
820         $tagged = false;
821
822         foreach ($profiles AS $profile) {
823                 if (strpos($item["tag"], "=".$profile."]") || strpos($item["body"], "=".$profile."]"))
824                         $tagged = true;
825         }
826
827         if ($item["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
828                 $params["type"] = NOTIFY_TAGSELF;
829                 $params["verb"] = ACTIVITY_TAG;
830         }
831
832         // Is it a post that the user had started?
833         $fields = ['ignored', 'mention'];
834         $thread = Item::selectFirstThreadForUser($params['uid'], $fields, ['iid' => $item["parent"]]);
835
836         if ($thread['mention'] && !$thread['ignored'] && !isset($params["type"])) {
837                 $params["type"] = NOTIFY_COMMENT;
838                 $params["verb"] = ACTIVITY_POST;
839         }
840
841         // And now we check for participation of one of our contacts in the thread
842         $condition = ['parent' => $item["parent"], 'author-id' => $contacts];
843
844         if (!$thread['ignored'] && !isset($params["type"]) && Item::exists($condition)) {
845                 $params["type"] = NOTIFY_COMMENT;
846                 $params["verb"] = ACTIVITY_POST;
847         }
848
849         if (isset($params["type"])) {
850                 notification($params);
851         }
852 }
853
854 /**
855  * @brief Formats a notification message with the notification author
856  *
857  * Replace the name with {0} but ensure to make that only once. The {0} is used
858  * later and prints the name in bold.
859  *
860  * @param string $name
861  * @param string $message
862  * @return string Formatted message
863  */
864 function format_notification_message($name, $message) {
865         if ($name != '') {
866                 $pos = strpos($message, $name);
867         } else {
868                 $pos = false;
869         }
870
871         if ($pos !== false) {
872                 $message = substr_replace($message, '{0}', $pos, strlen($name));
873         }
874
875         return $message;
876 }