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