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