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