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