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