]> git.mxchange.org Git - friendica.git/blob - include/enotify.php
Fix tests (#5400)
[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 use Friendica\Model\Item;
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 = Config::get('config', 'sitename');
37         if (Config::get('config', 'admin_name')) {
38                 $site_admin = L10n::t('%1$s, %2$s Administrator', Config::get('config', 'admin_name'), $sitename);
39         } else {
40                 $site_admin = L10n::t('%s Administrator', $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->getSenderEmailAddress();
50
51         if ($params['type'] != SYSTEM_EMAIL) {
52                 $user = dba::selectFirst('user', ['nickname', 'page-flags'],
53                         ['uid' => $params['uid']]);
54
55                 // There is no need to create notifications for forum accounts
56                 if (!DBM::is_result($user) || in_array($user["page-flags"], [PAGE_COMMUNITY, PAGE_PRVGROUP])) {
57                         return;
58                 }
59         }
60         $nickname = $user["nickname"];
61
62         // with $params['show_in_notification_page'] == false, the notification isn't inserted into
63         // the database, and an email is sent if applicable.
64         // default, if not specified: true
65         $show_in_notification_page = ((x($params, 'show_in_notification_page')) ? $params['show_in_notification_page']:true);
66
67         $additional_mail_header = "";
68         $additional_mail_header .= "Precedence: list\n";
69         $additional_mail_header .= "X-Friendica-Host: ".$hostname."\n";
70         $additional_mail_header .= "X-Friendica-Account: <".$nickname."@".$hostname.">\n";
71         $additional_mail_header .= "X-Friendica-Platform: ".FRIENDICA_PLATFORM."\n";
72         $additional_mail_header .= "X-Friendica-Version: ".FRIENDICA_VERSION."\n";
73         $additional_mail_header .= "List-ID: <notification.".$hostname.">\n";
74         $additional_mail_header .= "List-Archive: <".System::baseUrl()."/notifications/system>\n";
75
76         if (array_key_exists('item', $params)) {
77                 $title = $params['item']['title'];
78                 $body = $params['item']['body'];
79         } else {
80                 $title = $body = '';
81         }
82
83         if (isset($params['item']['id'])) {
84                 $item_id = $params['item']['id'];
85         } else {
86                 $item_id = 0;
87         }
88
89         if (isset($params['parent'])) {
90                 $parent_id = $params['parent'];
91         } else {
92                 $parent_id = 0;
93         }
94
95         if ($params['type'] == NOTIFY_MAIL) {
96                 $itemlink = $siteurl.'/message/'.$params['item']['id'];
97
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         }
107
108         if ($params['type'] == NOTIFY_COMMENT) {
109                 $thread = dba::selectFirst('thread', ['ignored'], ['iid' => $parent_id]);
110                 if (DBM::is_result($thread) && $thread["ignored"]) {
111                         logger("Thread ".$parent_id." will be ignored", LOGGER_DEBUG);
112                         return;
113                 }
114
115                 // Check to see if there was already a tag notify or comment notify for this post.
116                 // If so don't create a second notification
117                 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d, %d) AND `link` = '%s' AND `uid` = %d LIMIT 1",
118                         intval(NOTIFY_TAGSELF),
119                         intval(NOTIFY_COMMENT),
120                         intval(NOTIFY_SHARE),
121                         dbesc($params['link']),
122                         intval($params['uid'])
123                 );
124                 if ($p && count($p)) {
125                         L10n::popLang();
126                         return;
127                 }
128
129                 // if it's a post figure out who's post it is.
130
131                 $item = null;
132
133                 if ($params['otype'] === 'item' && $parent_id) {
134                         $item = Item::selectFirstForUser($params['uid'], Item::ITEM_FIELDLIST, ['id' => $parent_id]);
135                 }
136
137                 $item_post_type = item_post_type($item);
138                 $itemlink = $item['plink'];
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-id'] == $item['author-id'] && $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                 $itemlink =  $params['link'];
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         }
260
261         if ($params['type'] == NOTIFY_INTRO) {
262                 $itemlink = $params['link'];
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
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                 $itemlink =  $params['link'];
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         }
323
324         if ($params['type'] == NOTIFY_CONFIRM) {
325                 if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
326                         $itemlink =  $params['link'];
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                 } else { // ACTIVITY_FOLLOW
341                         $itemlink =  $params['link'];
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                 }
358         }
359
360         if ($params['type'] == NOTIFY_SYSTEM) {
361                 switch($params['event']) {
362                         case "SYSTEM_REGISTER_REQUEST":
363                                 $itemlink =  $params['link'];
364                                 $subject = L10n::t('[Friendica System Notify]') . ' ' . L10n::t('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:     %s\nSite Location:      %s\nLogin Name: %s (%s)",
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                                 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 = BBCode::toPlaintext($body);
568                 $htmlversion = BBCode::convert($body);
569
570                 $datarray = [];
571                 $datarray['banner'] = $banner;
572                 $datarray['product'] = $product;
573                 $datarray['preamble'] = $preamble;
574                 $datarray['sitename'] = $sitename;
575                 $datarray['siteurl'] = $siteurl;
576                 $datarray['type'] = $params['type'];
577                 $datarray['parent'] = $parent_id;
578                 $datarray['source_name'] = $params['source_name'];
579                 $datarray['source_link'] = $params['source_link'];
580                 $datarray['source_photo'] = $params['source_photo'];
581                 $datarray['uid'] = $params['uid'];
582                 $datarray['username'] = $params['to_name'];
583                 $datarray['hsitelink'] = $hsitelink;
584                 $datarray['tsitelink'] = $tsitelink;
585                 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
586                 $datarray['titemlink'] = $itemlink;
587                 $datarray['thanks'] = $thanks;
588                 $datarray['site_admin'] = $site_admin;
589                 $datarray['title'] = stripslashes($title);
590                 $datarray['htmlversion'] = $htmlversion;
591                 $datarray['textversion'] = $textversion;
592                 $datarray['subject'] = $subject;
593                 $datarray['headers'] = $additional_mail_header;
594
595                 Addon::callHooks('enotify_mail', $datarray);
596
597                 // check whether sending post content in email notifications is allowed
598                 // always true for SYSTEM_EMAIL
599                 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
600
601                 // load the template for private message notifications
602                 $tpl = get_markup_template('email_notify_html.tpl');
603                 $email_html_body = replace_macros($tpl, [
604                         '$banner'       => $datarray['banner'],
605                         '$product'      => $datarray['product'],
606                         '$preamble'     => str_replace("\n", "<br>\n", $datarray['preamble']),
607                         '$sitename'     => $datarray['sitename'],
608                         '$siteurl'      => $datarray['siteurl'],
609                         '$source_name'  => $datarray['source_name'],
610                         '$source_link'  => $datarray['source_link'],
611                         '$source_photo' => $datarray['source_photo'],
612                         '$username'     => $datarray['username'],
613                         '$hsitelink'    => $datarray['hsitelink'],
614                         '$hitemlink'    => $datarray['hitemlink'],
615                         '$thanks'       => $datarray['thanks'],
616                         '$site_admin'   => $datarray['site_admin'],
617                         '$title'        => $datarray['title'],
618                         '$htmlversion'  => $datarray['htmlversion'],
619                         '$content_allowed'      => $content_allowed,
620                 ]);
621
622                 // load the template for private message notifications
623                 $tpl = get_markup_template('email_notify_text.tpl');
624                 $email_text_body = replace_macros($tpl, [
625                         '$banner'       => $datarray['banner'],
626                         '$product'      => $datarray['product'],
627                         '$preamble'     => $datarray['preamble'],
628                         '$sitename'     => $datarray['sitename'],
629                         '$siteurl'      => $datarray['siteurl'],
630                         '$source_name'  => $datarray['source_name'],
631                         '$source_link'  => $datarray['source_link'],
632                         '$source_photo' => $datarray['source_photo'],
633                         '$username'     => $datarray['username'],
634                         '$tsitelink'    => $datarray['tsitelink'],
635                         '$titemlink'    => $datarray['titemlink'],
636                         '$thanks'       => $datarray['thanks'],
637                         '$site_admin'   => $datarray['site_admin'],
638                         '$title'        => $datarray['title'],
639                         '$textversion'  => $datarray['textversion'],
640                         '$content_allowed'      => $content_allowed,
641                 ]);
642
643                 // use the Emailer class to send the message
644                 return Emailer::send(
645                         [
646                         'uid' => $params['uid'],
647                         'fromName' => $sender_name,
648                         'fromEmail' => $sender_email,
649                         'replyTo' => $sender_email,
650                         'toEmail' => $params['to_email'],
651                         'messageSubject' => $datarray['subject'],
652                         'htmlVersion' => $email_html_body,
653                         'textVersion' => $email_text_body,
654                         'additionalMailHeader' => $datarray['headers']]
655                 );
656         }
657
658         return false;
659 }
660
661 /**
662  * @brief Checks for users who should be notified
663  *
664  * @param int $itemid ID of the item for which the check should be done
665  */
666 function check_user_notification($itemid) {
667         // fetch all users in the thread
668         $users = dba::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
669                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
670                         WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
671         while ($user = dba::fetch($users)) {
672                 check_item_notification($itemid, $user['uid']);
673         }
674         dba::close($users);
675 }
676
677 /**
678  * @brief Checks for item related notifications and sends them
679  *
680  * @param int $itemid ID of the item for which the check should be done
681  * @param int $uid User ID
682  * @param str $defaulttype (Optional) Forces a notification with this type.
683  */
684 function check_item_notification($itemid, $uid, $defaulttype = "") {
685         $notification_data = ["uid" => $uid, "profiles" => []];
686         Addon::callHooks('check_item_notification', $notification_data);
687
688         $profiles = $notification_data["profiles"];
689
690         $fields = ['notify-flags', 'language', 'username', 'email', 'nickname'];
691         $user = dba::selectFirst('user', $fields, ['uid' => $uid]);
692         if (!DBM::is_result($user)) {
693                 return false;
694         }
695
696         $owner = dba::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
697         if (!DBM::is_result($owner)) {
698                 return false;
699         }
700
701         // This is our regular URL format
702         $profiles[] = $owner["url"];
703
704         // Notifications from Diaspora are often with an URL in the Diaspora format
705         $profiles[] = System::baseUrl()."/u/".$user["nickname"];
706
707         $profiles2 = [];
708
709         foreach ($profiles AS $profile) {
710                 // Check for invalid profile urls. 13 should be the shortest possible profile length:
711                 // http://a.bc/d
712                 // Additionally check for invalid urls that would return the normalised value "http:"
713                 if ((strlen($profile) >= 13) && (normalise_link($profile) != "http:")) {
714                         if (!in_array($profile, $profiles2))
715                                 $profiles2[] = $profile;
716
717                         $profile = normalise_link($profile);
718                         if (!in_array($profile, $profiles2))
719                                 $profiles2[] = $profile;
720
721                         $profile = str_replace("http://", "https://", $profile);
722                         if (!in_array($profile, $profiles2))
723                                 $profiles2[] = $profile;
724                 }
725         }
726
727         $profiles = $profiles2;
728
729         $ret = dba::select('contact', ['id'], ['uid' => 0, 'nurl' => $profiles]);
730
731         $contacts = [];
732
733         while ($contact = dba::fetch($ret)) {
734                 $contacts[] = $contact['id'];
735         }
736
737         $contact_list = implode(',', $contacts);
738
739         dba::close($ret);
740
741         // Only act if it is a "real" post
742         // We need the additional check for the "local_profile" because of mixed situations on connector networks
743         $fields = ['id', 'mention', 'tag', 'parent', 'title', 'body',
744                 'author-link', 'author-name', 'author-avatar', 'author-id',
745                 'guid', 'parent-uri', 'uri', 'contact-id', 'network'];
746         $condition = ['id' => $itemid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
747         $item = Item::selectFirst($fields, $condition);
748         if (!DBM::is_result($item) || in_array($item['author-id'], $contacts)) {
749                 return;
750         }
751
752         // Generate the notification array
753         $params = [];
754         $params["uid"] = $uid;
755         $params["notify_flags"] = $user["notify-flags"];
756         $params["language"] = $user["language"];
757         $params["to_name"] = $user["username"];
758         $params["to_email"] = $user["email"];
759         $params["item"] = $item;
760         $params["parent"] = $item["parent"];
761         $params["link"] = System::baseUrl().'/display/'.urlencode($item["guid"]);
762         $params["otype"] = 'item';
763         $params["source_name"] = $item["author-name"];
764         $params["source_link"] = $item["author-link"];
765         $params["source_photo"] = $item["author-avatar"];
766
767         if ($item["parent-uri"] === $item["uri"]) {
768                 // Send a notification for every new post?
769                 $send_notification = dba::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true]);
770
771                 if (!$send_notification) {
772                         $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
773                                 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
774
775                         if (DBM::is_result($tags)) {
776                                 foreach ($tags AS $tag) {
777                                         $condition = ['nurl' => normalise_link($tag["url"]), 'uid' => $uid, 'notify_new_posts' => true];
778                                         $r = dba::exists('contact', $condition);
779                                         if ($r) {
780                                                 $send_notification = true;
781                                         }
782                                 }
783                         }
784                 }
785
786                 if ($send_notification) {
787                         $params["type"] = NOTIFY_SHARE;
788                         $params["verb"] = ACTIVITY_TAG;
789                 }
790         }
791
792         // Is the user mentioned in this post?
793         $tagged = false;
794
795         foreach ($profiles AS $profile) {
796                 if (strpos($item["tag"], "=".$profile."]") || strpos($item["body"], "=".$profile."]"))
797                         $tagged = true;
798         }
799
800         if ($item["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
801                 $params["type"] = NOTIFY_TAGSELF;
802                 $params["verb"] = ACTIVITY_TAG;
803         }
804
805         // Is it a post that the user had started or where he interacted?
806         $parent = q("SELECT `thread`.`iid` FROM `thread` INNER JOIN `item` ON `item`.`parent` = `thread`.`iid`
807                         WHERE `thread`.`iid` = %d AND NOT `thread`.`ignored` AND
808                                 (`thread`.`mention` OR `item`.`author-id` IN ($contact_list))
809                         LIMIT 1",
810                         intval($item["parent"]));
811
812         if ($parent && !isset($params["type"])) {
813                 $params["type"] = NOTIFY_COMMENT;
814                 $params["verb"] = ACTIVITY_POST;
815         }
816
817         if (isset($params["type"]))
818                 notification($params);
819 }
820
821 /**
822  * @brief Formats a notification message with the notification author
823  *
824  * Replace the name with {0} but ensure to make that only once. The {0} is used
825  * later and prints the name in bold.
826  *
827  * @param string $name
828  * @param string $message
829  * @return string Formatted message
830  */
831 function format_notification_message($name, $message) {
832         if ($name != '') {
833                 $pos = strpos($message, $name);
834         } else {
835                 $pos = false;
836         }
837
838         if ($pos !== false) {
839                 $message = substr_replace($message, '{0}', $pos, strlen($name));
840         }
841
842         return $message;
843 }