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