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