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