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