]> git.mxchange.org Git - friendica.git/blob - include/enotify.php
We have to check for the contact`s uid not the item`s uid
[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         push_lang($params['language']);
29
30         $banner = t('Friendica Notification');
31         $product = FRIENDICA_PLATFORM;
32         $siteurl = System::baseUrl(true);
33         $thanks = t('Thank You,');
34         $sitename = $a->config['sitename'];
35         if (!x($a->config['admin_name'])) {
36             $site_admin = sprintf(t('%s Administrator'), $sitename);
37         } else {
38             $site_admin = sprintf(t('%1$s, %2$s Administrator'), $a->config['admin_name'], $sitename);
39         }
40
41         $sender_name = $sitename;
42         $hostname = $a->get_hostname();
43         if (strpos($hostname, ':')) {
44                 $hostname = substr($hostname, 0, strpos($hostname, ':'));
45         }
46
47         $sender_email = $a->config['sender_email'];
48         if (empty($sender_email)) {
49                 $sender_email = t('noreply').'@'.$hostname;
50         }
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
84         if (isset($params['item']['id'])) {
85                 $item_id = $params['item']['id'];
86         } else {
87                 $item_id = 0;
88         }
89
90         if (isset($params['parent'])) {
91                 $parent_id = $params['parent'];
92         } else {
93                 $parent_id = 0;
94         }
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 LIMIT 1",
110                         intval($parent_id)
111                 );
112                 if ($p && count($p) && ($p[0]["ignored"])) {
113                         logger("Thread ".$parent_id." will be ignored", LOGGER_DEBUG);
114                         return;
115                 }
116
117                 // Check to see if there was already a tag notify or comment notify for this post.
118                 // If so don't create a second notification
119                 $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 LIMIT 1",
137                                 intval($parent_id)
138                         );
139                 }
140
141                 $item_post_type = item_post_type($p[0]);
142
143                 // "a post"
144                 $dest_str = sprintf(t('%1$s commented on [url=%2$s]a %3$s[/url]'),
145                                                                 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
146                                                                 $itemlink,
147                                                                 $item_post_type);
148
149                 // "George Bull's post"
150                 if ($p) {
151                         $dest_str = sprintf(t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]'),
152                                                 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
153                                                 $itemlink,
154                                                 $p[0]['author-name'],
155                                                 $item_post_type);
156                 }
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
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         $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                 q("INSERT INTO `notify` (`hash`, `name`, `url`, `photo`, `date`, `uid`, `link`, `iid`, `parent`, `type`, `verb`, `otype`, `name_cache`)
456                         values('%s', '%s', '%s', '%s', '%s', %d, '%s', %d, %d, %d, '%s', '%s', '%s')",
457                         dbesc($datarray['hash']),
458                         dbesc($datarray['name']),
459                         dbesc($datarray['url']),
460                         dbesc($datarray['photo']),
461                         dbesc($datarray['date']),
462                         intval($datarray['uid']),
463                         dbesc($datarray['link']),
464                         intval($datarray['iid']),
465                         intval($datarray['parent']),
466                         intval($datarray['type']),
467                         dbesc($datarray['verb']),
468                         dbesc($datarray['otype']),
469                         dbesc($datarray["name_cache"])
470                 );
471
472                 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' AND `uid` = %d LIMIT 1",
473                         dbesc($hash),
474                         intval($params['uid'])
475                 );
476                 if ($r) {
477                         $notify_id = $r[0]['id'];
478                 } else {
479                         pop_lang();
480                         return False;
481                 }
482
483                 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
484                 // After we've stored everything, look again to see if there are any duplicates and if so remove them
485                 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
486                         intval(NOTIFY_TAGSELF),
487                         intval(NOTIFY_COMMENT),
488                         dbesc($params['link']),
489                         intval($params['uid'])
490                 );
491                 if ($p && (count($p) > 1)) {
492                         for ($d = 1; $d < count($p); $d ++) {
493                                 dba::delete('notify', array('id' => $p[$d]['id']));
494                         }
495
496                         // only continue on if we stored the first one
497                         if ($notify_id != $p[0]['id']) {
498                                 pop_lang();
499                                 return False;
500                         }
501                 }
502
503                 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
504                 $msg = replace_macros($epreamble, array('$itemlink' => $itemlink));
505                 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(bbcode($msg)));
506                 q("UPDATE `notify` SET `msg` = '%s', `msg_cache` = '%s' WHERE `id` = %d AND `uid` = %d",
507                         dbesc($msg),
508                         dbesc($msg_cache),
509                         intval($notify_id),
510                         intval($params['uid'])
511                 );
512         }
513
514         // send email notification if notification preferences permit
515         if ((intval($params['notify_flags']) & intval($params['type']))
516                 || $params['type'] == NOTIFY_SYSTEM
517                 || $params['type'] == SYSTEM_EMAIL) {
518
519                 logger('sending notification email');
520
521                 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
522                         $id_for_parent = $params['parent']."@".$hostname;
523
524                         // Is this the first email notification for this parent item and user?
525
526                         $r = q("SELECT `id` FROM `notify-threads` WHERE `master-parent-item` = %d AND `receiver-uid` = %d LIMIT 1",
527                                 intval($params['parent']),
528                                 intval($params['uid']));
529
530                         // If so, create the record of it and use a message-id smtp header.
531
532                         if (!$r) {
533                                 logger("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), LOGGER_DEBUG);
534                                 q("INSERT INTO `notify-threads` (`notify-id`, `master-parent-item`, `receiver-uid`, `parent-item`)
535                                         values(%d, %d, %d, %d)",
536                                         intval($notify_id),
537                                         intval($params['parent']),
538                                         intval($params['uid']),
539                                         0);
540
541                                 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
542                                 $log_msg = "include/enotify: No previous notification found for this parent:\n".
543                                                 "  parent: ${params['parent']}\n"."  uid   : ${params['uid']}\n";
544                                 logger($log_msg, LOGGER_DEBUG);
545                         } else {
546                                 // If not, just "follow" the thread.
547                                 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
548                                 logger("There's already a notification for this parent:\n".print_r($r, true), LOGGER_DEBUG);
549                         }
550                 }
551
552                 // textversion keeps linebreaks
553                 $textversion = strip_tags(str_replace("<br>", "\n", html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n"), "\n",
554                         $body))),ENT_QUOTES, 'UTF-8')));
555                 $htmlversion = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n\\n", "\\n"),
556                         "<br />\n", $body))), ENT_QUOTES, 'UTF-8');
557
558                 $datarray = array();
559                 $datarray['banner'] = $banner;
560                 $datarray['product'] = $product;
561                 $datarray['preamble'] = $preamble;
562                 $datarray['sitename'] = $sitename;
563                 $datarray['siteurl'] = $siteurl;
564                 $datarray['type'] = $params['type'];
565                 $datarray['parent'] = $params['parent'];
566                 $datarray['source_name'] = $params['source_name'];
567                 $datarray['source_link'] = $params['source_link'];
568                 $datarray['source_photo'] = $params['source_photo'];
569                 $datarray['uid'] = $params['uid'];
570                 $datarray['username'] = $params['to_name'];
571                 $datarray['hsitelink'] = $hsitelink;
572                 $datarray['tsitelink'] = $tsitelink;
573                 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
574                 $datarray['titemlink'] = $itemlink;
575                 $datarray['thanks'] = $thanks;
576                 $datarray['site_admin'] = $site_admin;
577                 $datarray['title'] = stripslashes($title);
578                 $datarray['htmlversion'] = $htmlversion;
579                 $datarray['textversion'] = $textversion;
580                 $datarray['subject'] = $subject;
581                 $datarray['headers'] = $additional_mail_header;
582
583                 call_hooks('enotify_mail', $datarray);
584
585                 // check whether sending post content in email notifications is allowed
586                 // always true for SYSTEM_EMAIL
587                 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
588
589                 // load the template for private message notifications
590                 $tpl = get_markup_template('email_notify_html.tpl');
591                 $email_html_body = replace_macros($tpl, array(
592                         '$banner'       => $datarray['banner'],
593                         '$product'      => $datarray['product'],
594                         '$preamble'     => str_replace("\n", "<br>\n", $datarray['preamble']),
595                         '$sitename'     => $datarray['sitename'],
596                         '$siteurl'      => $datarray['siteurl'],
597                         '$source_name'  => $datarray['source_name'],
598                         '$source_link'  => $datarray['source_link'],
599                         '$source_photo' => $datarray['source_photo'],
600                         '$username'     => $datarray['to_name'],
601                         '$hsitelink'    => $datarray['hsitelink'],
602                         '$hitemlink'    => $datarray['hitemlink'],
603                         '$thanks'       => $datarray['thanks'],
604                         '$site_admin'   => $datarray['site_admin'],
605                         '$title'        => $datarray['title'],
606                         '$htmlversion'  => $datarray['htmlversion'],
607                         '$content_allowed'      => $content_allowed,
608                 ));
609
610                 // load the template for private message notifications
611                 $tpl = get_markup_template('email_notify_text.tpl');
612                 $email_text_body = replace_macros($tpl, array(
613                         '$banner'       => $datarray['banner'],
614                         '$product'      => $datarray['product'],
615                         '$preamble'     => $datarray['preamble'],
616                         '$sitename'     => $datarray['sitename'],
617                         '$siteurl'      => $datarray['siteurl'],
618                         '$source_name'  => $datarray['source_name'],
619                         '$source_link'  => $datarray['source_link'],
620                         '$source_photo' => $datarray['source_photo'],
621                         '$username'     => $datarray['to_name'],
622                         '$tsitelink'    => $datarray['tsitelink'],
623                         '$titemlink'    => $datarray['titemlink'],
624                         '$thanks'       => $datarray['thanks'],
625                         '$site_admin'   => $datarray['site_admin'],
626                         '$title'        => $datarray['title'],
627                         '$textversion'  => $datarray['textversion'],
628                         '$content_allowed'      => $content_allowed,
629                 ));
630
631                 // use the Emailer class to send the message
632                 return Emailer::send(
633                         array(
634                         'uid' => $params['uid'],
635                         'fromName' => $sender_name,
636                         'fromEmail' => $sender_email,
637                         'replyTo' => $sender_email,
638                         'toEmail' => $params['to_email'],
639                         'messageSubject' => $datarray['subject'],
640                         'htmlVersion' => $email_html_body,
641                         'textVersion' => $email_text_body,
642                         'additionalMailHeader' => $datarray['headers'])
643                 );
644         }
645
646         return false;
647 }
648
649 /**
650  * @brief Checks for users who should be notified
651  *
652  * @param int $itemid ID of the item for which the check should be done
653  */
654 function check_user_notification($itemid) {
655         // fetch all users in the thread
656         $users = dba::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
657                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
658                         WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
659         while ($user = dba::fetch($users)) {
660                 check_item_notification($itemid, $user['uid']);
661         }
662         dba::close($users);
663 }
664
665 /**
666  * @brief Checks for item related notifications and sends them
667  *
668  * @param int $itemid ID of the item for which the check should be done
669  * @param int $uid User ID
670  * @param str $defaulttype (Optional) Forces a notification with this type.
671  */
672 function check_item_notification($itemid, $uid, $defaulttype = "") {
673         $notification_data = array("uid" => $uid, "profiles" => array());
674         call_hooks('check_item_notification', $notification_data);
675
676         $profiles = $notification_data["profiles"];
677
678         $user = q("SELECT `notify-flags`, `language`, `username`, `email`, `nickname` FROM `user` WHERE `uid` = %d", intval($uid));
679         if (!$user)
680                 return false;
681
682         $owner = q("SELECT `id`, `url` FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1", intval($uid));
683         if (!$owner)
684                 return false;
685
686         // This is our regular URL format
687         $profiles[] = $owner[0]["url"];
688
689         // Notifications from Diaspora are often with an URL in the Diaspora format
690         $profiles[] = System::baseUrl()."/u/".$user[0]["nickname"];
691
692         $profiles2 = array();
693
694         foreach ($profiles AS $profile) {
695                 // Check for invalid profile urls. 13 should be the shortest possible profile length:
696                 // http://a.bc/d
697                 // Additionally check for invalid urls that would return the normalised value "http:"
698                 if ((strlen($profile) >= 13) && (normalise_link($profile) != "http:")) {
699                         if (!in_array($profile, $profiles2))
700                                 $profiles2[] = $profile;
701
702                         $profile = normalise_link($profile);
703                         if (!in_array($profile, $profiles2))
704                                 $profiles2[] = $profile;
705
706                         $profile = str_replace("http://", "https://", $profile);
707                         if (!in_array($profile, $profiles2))
708                                 $profiles2[] = $profile;
709                 }
710         }
711
712         $profiles = $profiles2;
713
714         $profile_list = "";
715
716         foreach ($profiles AS $profile) {
717                 if ($profile_list != "")
718                         $profile_list .= "', '";
719
720                 $profile_list .= dbesc($profile);
721         }
722
723         $profile_list = "'".$profile_list."'";
724
725         // Only act if it is a "real" post
726         // We need the additional check for the "local_profile" because of mixed situations on connector networks
727         $item = q("SELECT `id`, `mention`, `tag`,`parent`, `title`, `body`, `author-name`, `author-link`, `author-avatar`, `guid`,
728                         `parent-uri`, `uri`, `contact-id`
729                         FROM `item` WHERE `id` = %d AND `verb` IN ('%s', '') AND `type` != 'activity' AND
730                                 NOT (`author-link` IN ($profile_list))  LIMIT 1",
731                 intval($itemid), dbesc(ACTIVITY_POST));
732         if (!$item)
733                 return false;
734
735         // Generate the notification array
736         $params = array();
737         $params["uid"] = $uid;
738         $params["notify_flags"] = $user[0]["notify-flags"];
739         $params["language"] = $user[0]["language"];
740         $params["to_name"] = $user[0]["username"];
741         $params["to_email"] = $user[0]["email"];
742         $params["item"] = $item[0];
743         $params["parent"] = $item[0]["parent"];
744         $params["link"] = System::baseUrl().'/display/'.urlencode($item[0]["guid"]);
745         $params["otype"] = 'item';
746         $params["source_name"] = $item[0]["author-name"];
747         $params["source_link"] = $item[0]["author-link"];
748         $params["source_photo"] = $item[0]["author-avatar"];
749
750         if ($item[0]["parent-uri"] === $item[0]["uri"]) {
751                 // Send a notification for every new post?
752                 $r = q("SELECT `notify_new_posts` FROM `contact` WHERE `id` = %d AND `notify_new_posts` LIMIT 1",
753                         intval($item[0]['contact-id'])
754                 );
755                 $send_notification = DBM::is_result($r);
756
757                 if (!$send_notification) {
758                         $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
759                                 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
760
761                         if (DBM::is_result($tags)) {
762                                 foreach ($tags AS $tag) {
763                                         $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `notify_new_posts`",
764                                                 normalise_link($tag["url"]), intval($uid));
765                                         if (DBM::is_result($r))
766                                                 $send_notification = true;
767                                 }
768                         }
769                 }
770
771                 if ($send_notification) {
772                         $params["type"] = NOTIFY_SHARE;
773                         $params["verb"] = ACTIVITY_TAG;
774                 }
775         }
776
777         // Is the user mentioned in this post?
778         $tagged = false;
779
780         foreach ($profiles AS $profile) {
781                 if (strpos($item[0]["tag"], "=".$profile."]") || strpos($item[0]["body"], "=".$profile."]"))
782                         $tagged = true;
783         }
784
785         if ($item[0]["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
786                 $params["type"] = NOTIFY_TAGSELF;
787                 $params["verb"] = ACTIVITY_TAG;
788         }
789
790         // Is it a post that the user had started or where he interacted?
791         $parent = q("SELECT `thread`.`iid` FROM `thread` INNER JOIN `item` ON `item`.`parent` = `thread`.`iid`
792                         WHERE `thread`.`iid` = %d AND NOT `thread`.`ignored` AND
793                                 (`thread`.`mention` OR `item`.`author-link` IN ($profile_list))
794                         LIMIT 1",
795                         intval($item[0]["parent"]));
796
797         if ($parent && !isset($params["type"])) {
798                 $params["type"] = NOTIFY_COMMENT;
799                 $params["verb"] = ACTIVITY_POST;
800         }
801
802         if (isset($params["type"]))
803                 notification($params);
804 }
805
806 /**
807  * @brief Formats a notification message with the notification author
808  *
809  * Replace the name with {0} but ensure to make that only once. The {0} is used
810  * later and prints the name in bold.
811  *
812  * @param string $name
813  * @param string $message
814  * @return string Formatted message
815  */
816 function format_notification_message($name, $message) {
817         if ($name != '') {
818                 $pos = strpos($message, $name);
819         } else {
820                 $pos = false;
821         }
822
823         if ($pos !== false) {
824                 $message = substr_replace($message, '{0}', $pos, strlen($name));
825         }
826
827         return $message;
828 }