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