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