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