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