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