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