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