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