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