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