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