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