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