]> git.mxchange.org Git - friendica.git/blob - include/enotify.php
Merge pull request #3112 from Quix0r/rewrites/coding-convention
[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 = App::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: <".App::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` IN (%d, %d, %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 (dbm::is_result($r)) {
415                                 $dups = true;
416                         }
417                 } while ($dups == true);
418
419                 /// @TODO One statement is enough
420                 $datarray = array();
421                 $datarray['hash']  = $hash;
422                 $datarray['name']  = $params['source_name'];
423                 $datarray['name_cache'] = strip_tags(bbcode($params['source_name']));
424                 $datarray['url']   = $params['source_link'];
425                 $datarray['photo'] = $params['source_photo'];
426                 $datarray['date']  = datetime_convert();
427                 $datarray['uid']   = $params['uid'];
428                 $datarray['link']  = $itemlink;
429                 $datarray['iid']   = $item_id;
430                 $datarray['parent'] = $parent_id;
431                 $datarray['type']  = $params['type'];
432                 $datarray['verb']  = $params['verb'];
433                 $datarray['otype'] = $params['otype'];
434                 $datarray['abort'] = false;
435
436                 call_hooks('enotify_store', $datarray);
437
438                 if ($datarray['abort']) {
439                         pop_lang();
440                         return False;
441                 }
442
443                 // create notification entry in DB
444
445                 $r = q("INSERT INTO `notify` (`hash`, `name`, `url`, `photo`, `date`, `uid`, `link`, `iid`, `parent`, `type`, `verb`, `otype`, `name_cache`)
446                         values('%s', '%s', '%s', '%s', '%s', %d, '%s', %d, %d, %d, '%s', '%s', '%s')",
447                         dbesc($datarray['hash']),
448                         dbesc($datarray['name']),
449                         dbesc($datarray['url']),
450                         dbesc($datarray['photo']),
451                         dbesc($datarray['date']),
452                         intval($datarray['uid']),
453                         dbesc($datarray['link']),
454                         intval($datarray['iid']),
455                         intval($datarray['parent']),
456                         intval($datarray['type']),
457                         dbesc($datarray['verb']),
458                         dbesc($datarray['otype']),
459                         dbesc($datarray["name_cache"])
460                 );
461
462                 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' AND `uid` = %d LIMIT 1",
463                         dbesc($hash),
464                         intval($params['uid'])
465                 );
466                 if ($r)
467                         $notify_id = $r[0]['id'];
468                 else {
469                         pop_lang();
470                         return False;
471                 }
472
473                 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
474                 // After we've stored everything, look again to see if there are any duplicates and if so remove them
475
476                 $p = null;
477                 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
478                         intval(NOTIFY_TAGSELF),
479                         intval(NOTIFY_COMMENT),
480                         dbesc($params['link']),
481                         intval($params['uid'])
482                 );
483                 if ($p && (count($p) > 1)) {
484                         for ($d = 1; $d < count($p); $d ++) {
485                                 q("DELETE FROM `notify` WHERE `id` = %d",
486                                         intval($p[$d]['id'])
487                                 );
488                         }
489
490                         // only continue on if we stored the first one
491
492                         if ($notify_id != $p[0]['id']) {
493                                 pop_lang();
494                                 return False;
495                         }
496                 }
497
498
499                 $itemlink = App::get_baseurl().'/notify/view/'.$notify_id;
500                 $msg = replace_macros($epreamble, array('$itemlink' => $itemlink));
501                 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(bbcode($msg)));
502                 $r = q("UPDATE `notify` SET `msg` = '%s', `msg_cache` = '%s' WHERE `id` = %d AND `uid` = %d",
503                         dbesc($msg),
504                         dbesc($msg_cache),
505                         intval($notify_id),
506                         intval($params['uid'])
507                 );
508         }
509
510         // send email notification if notification preferences permit
511         if ((intval($params['notify_flags']) & intval($params['type']))
512                 || $params['type'] == NOTIFY_SYSTEM
513                 || $params['type'] == "SYSTEM_EMAIL") {
514
515                 logger('sending notification email');
516
517                 if (isset($params['parent']) AND (intval($params['parent']) != 0)) {
518                         $id_for_parent = $params['parent']."@".$hostname;
519
520                         // Is this the first email notification for this parent item and user?
521
522                         $r = q("SELECT `id` FROM `notify-threads` WHERE `master-parent-item` = %d AND `receiver-uid` = %d LIMIT 1",
523                                 intval($params['parent']),
524                                 intval($params['uid']));
525
526                         // If so, create the record of it and use a message-id smtp header.
527
528                         if (!$r) {
529                                 logger("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), LOGGER_DEBUG);
530                                 $r = q("INSERT INTO `notify-threads` (`notify-id`, `master-parent-item`, `receiver-uid`, `parent-item`)
531                                         values(%d, %d, %d, %d)",
532                                         intval($notify_id),
533                                         intval($params['parent']),
534                                         intval($params['uid']),
535                                         0);
536
537                                 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
538                                 $log_msg = "include/enotify: No previous notification found for this parent:\n".
539                                                 "  parent: ${params['parent']}\n"."  uid   : ${params['uid']}\n";
540                                 logger($log_msg, LOGGER_DEBUG);
541                         } else {
542                                 // If not, just "follow" the thread.
543                                 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
544                                 logger("There's already a notification for this parent:\n".print_r($r, true), LOGGER_DEBUG);
545                         }
546                 }
547
548                 // textversion keeps linebreaks
549                 $textversion = strip_tags(str_replace("<br>", "\n", html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n"), "\n",
550                         $body))),ENT_QUOTES, 'UTF-8')));
551                 $htmlversion = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n\\n", "\\n"),
552                         "<br />\n", $body))), ENT_QUOTES, 'UTF-8');
553
554                 $datarray = array();
555                 $datarray['banner'] = $banner;
556                 $datarray['product'] = $product;
557                 $datarray['preamble'] = $preamble;
558                 $datarray['sitename'] = $sitename;
559                 $datarray['siteurl'] = $siteurl;
560                 $datarray['type'] = $params['type'];
561                 $datarray['parent'] = $params['parent'];
562                 $datarray['source_name'] = $params['source_name'];
563                 $datarray['source_link'] = $params['source_link'];
564                 $datarray['source_photo'] = $params['source_photo'];
565                 $datarray['uid'] = $params['uid'];
566                 $datarray['username'] = $params['to_name'];
567                 $datarray['hsitelink'] = $hsitelink;
568                 $datarray['tsitelink'] = $tsitelink;
569                 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
570                 $datarray['titemlink'] = $itemlink;
571                 $datarray['thanks'] = $thanks;
572                 $datarray['site_admin'] = $site_admin;
573                 $datarray['title'] = stripslashes($title);
574                 $datarray['htmlversion'] = $htmlversion;
575                 $datarray['textversion'] = $textversion;
576                 $datarray['subject'] = $subject;
577                 $datarray['headers'] = $additional_mail_header;
578
579                 call_hooks('enotify_mail', $datarray);
580
581                 // check whether sending post content in email notifications is allowed
582                 // always true for "SYSTEM_EMAIL"
583                 $content_allowed = ((!get_config('system', 'enotify_no_content')) || ($params['type'] == "SYSTEM_EMAIL"));
584
585                 // load the template for private message notifications
586                 $tpl = get_markup_template('email_notify_html.tpl');
587                 $email_html_body = replace_macros($tpl, array(
588                         '$banner'       => $datarray['banner'],
589                         '$product'      => $datarray['product'],
590                         '$preamble'     => str_replace("\n", "<br>\n", $datarray['preamble']),
591                         '$sitename'     => $datarray['sitename'],
592                         '$siteurl'      => $datarray['siteurl'],
593                         '$source_name'  => $datarray['source_name'],
594                         '$source_link'  => $datarray['source_link'],
595                         '$source_photo' => $datarray['source_photo'],
596                         '$username'     => $datarray['to_name'],
597                         '$hsitelink'    => $datarray['hsitelink'],
598                         '$hitemlink'    => $datarray['hitemlink'],
599                         '$thanks'       => $datarray['thanks'],
600                         '$site_admin'   => $datarray['site_admin'],
601                         '$title'        => $datarray['title'],
602                         '$htmlversion'  => $datarray['htmlversion'],
603                         '$content_allowed'      => $content_allowed,
604                 ));
605
606                 // load the template for private message notifications
607                 $tpl = get_markup_template('email_notify_text.tpl');
608                 $email_text_body = replace_macros($tpl, array(
609                         '$banner'       => $datarray['banner'],
610                         '$product'      => $datarray['product'],
611                         '$preamble'     => $datarray['preamble'],
612                         '$sitename'     => $datarray['sitename'],
613                         '$siteurl'      => $datarray['siteurl'],
614                         '$source_name'  => $datarray['source_name'],
615                         '$source_link'  => $datarray['source_link'],
616                         '$source_photo' => $datarray['source_photo'],
617                         '$username'     => $datarray['to_name'],
618                         '$tsitelink'    => $datarray['tsitelink'],
619                         '$titemlink'    => $datarray['titemlink'],
620                         '$thanks'       => $datarray['thanks'],
621                         '$site_admin'   => $datarray['site_admin'],
622                         '$title'        => $datarray['title'],
623                         '$textversion'  => $datarray['textversion'],
624                         '$content_allowed'      => $content_allowed,
625                 ));
626
627                 // use the Emailer class to send the message
628
629                 return Emailer::send(array(
630                         'uid' => $params['uid'],
631                         'fromName' => $sender_name,
632                         'fromEmail' => $sender_email,
633                         'replyTo' => $sender_email,
634                         'toEmail' => $params['to_email'],
635                         'messageSubject' => $datarray['subject'],
636                         'htmlVersion' => $email_html_body,
637                         'textVersion' => $email_text_body,
638                         'additionalMailHeader' => $datarray['headers'],
639                 ));
640         }
641
642     return False;
643 }
644
645 /**
646  * @brief Checks for item related notifications and sends them
647  *
648  * @param int $itemid ID of the item for which the check should be done
649  * @param int $uid User ID
650  * @param str $defaulttype (Optional) Forces a notification with this type.
651  */
652 function check_item_notification($itemid, $uid, $defaulttype = "") {
653         $notification_data = array("uid" => $uid, "profiles" => array());
654         call_hooks('check_item_notification', $notification_data);
655
656         $profiles = $notification_data["profiles"];
657
658         $user = q("SELECT `notify-flags`, `language`, `username`, `email`, `nickname` FROM `user` WHERE `uid` = %d", intval($uid));
659         if (!$user)
660                 return false;
661
662         $owner = q("SELECT `id`, `url` FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1", intval($uid));
663         if (!$owner)
664                 return false;
665
666         // This is our regular URL format
667         $profiles[] = $owner[0]["url"];
668
669         // Notifications from Diaspora are often with an URL in the Diaspora format
670         $profiles[] = App::get_baseurl()."/u/".$user[0]["nickname"];
671
672         $profiles2 = array();
673
674         foreach ($profiles AS $profile) {
675                 // Check for invalid profile urls. 13 should be the shortest possible profile length:
676                 // http://a.bc/d
677                 // Additionally check for invalid urls that would return the normalised value "http:"
678                 if ((strlen($profile) >= 13) AND (normalise_link($profile) != "http:")) {
679                         if (!in_array($profile, $profiles2))
680                                 $profiles2[] = $profile;
681
682                         $profile = normalise_link($profile);
683                         if (!in_array($profile, $profiles2))
684                                 $profiles2[] = $profile;
685
686                         $profile = str_replace("http://", "https://", $profile);
687                         if (!in_array($profile, $profiles2))
688                                 $profiles2[] = $profile;
689                 }
690         }
691
692         $profiles = $profiles2;
693
694         $profile_list = "";
695
696         foreach ($profiles AS $profile) {
697                 if ($profile_list != "")
698                         $profile_list .= "', '";
699
700                 $profile_list .= dbesc($profile);
701         }
702
703         $profile_list = "'".$profile_list."'";
704
705         // Only act if it is a "real" post
706         // We need the additional check for the "local_profile" because of mixed situations on connector networks
707         $item = q("SELECT `id`, `mention`, `tag`,`parent`, `title`, `body`, `author-name`, `author-link`, `author-avatar`, `guid`,
708                         `parent-uri`, `uri`, `contact-id`
709                         FROM `item` WHERE `id` = %d AND `verb` IN ('%s', '') AND `type` != 'activity' AND
710                                 NOT (`author-link` IN ($profile_list))  LIMIT 1",
711                 intval($itemid), dbesc(ACTIVITY_POST));
712         if (!$item)
713                 return false;
714
715         // Generate the notification array
716         $params = array();
717         $params["uid"] = $uid;
718         $params["notify_flags"] = $user[0]["notify-flags"];
719         $params["language"] = $user[0]["language"];
720         $params["to_name"] = $user[0]["username"];
721         $params["to_email"] = $user[0]["email"];
722         $params["item"] = $item[0];
723         $params["parent"] = $item[0]["parent"];
724         $params["link"] = App::get_baseurl().'/display/'.urlencode($item[0]["guid"]);
725         $params["otype"] = 'item';
726         $params["source_name"] = $item[0]["author-name"];
727         $params["source_link"] = $item[0]["author-link"];
728         $params["source_photo"] = $item[0]["author-avatar"];
729
730         if ($item[0]["parent-uri"] === $item[0]["uri"]) {
731                 // Send a notification for every new post?
732                 $r = q("SELECT `notify_new_posts` FROM `contact` WHERE `id` = %d AND `uid` = %d AND `notify_new_posts` LIMIT 1",
733                         intval($item[0]['contact-id']),
734                         intval($uid)
735                 );
736                 $send_notification = dbm::is_result($r);
737
738                 if (!$send_notification) {
739                         $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
740                                 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
741
742                         if (dbm::is_result($tags)) {
743                                 foreach ($tags AS $tag) {
744                                         $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `notify_new_posts`",
745                                                 normalise_link($tag["url"]), intval($uid));
746                                         if (dbm::is_result($r))
747                                                 $send_notification = true;
748                                 }
749                         }
750                 }
751
752                 if ($send_notification) {
753                         $params["type"] = NOTIFY_SHARE;
754                         $params["verb"] = ACTIVITY_TAG;
755                 }
756         }
757
758         // Is the user mentioned in this post?
759         $tagged = false;
760
761         foreach ($profiles AS $profile) {
762                 if (strpos($item[0]["tag"], "=".$profile."]") OR strpos($item[0]["body"], "=".$profile."]"))
763                         $tagged = true;
764         }
765
766         if ($item[0]["mention"] OR $tagged OR ($defaulttype == NOTIFY_TAGSELF)) {
767                 $params["type"] = NOTIFY_TAGSELF;
768                 $params["verb"] = ACTIVITY_TAG;
769         }
770
771         // Is it a post that the user had started or where he interacted?
772         $parent = q("SELECT `thread`.`iid` FROM `thread` INNER JOIN `item` ON `item`.`parent` = `thread`.`iid`
773                         WHERE `thread`.`iid` = %d AND `thread`.`uid` = %d AND NOT `thread`.`ignored` AND
774                                 (`thread`.`mention` OR `item`.`author-link` IN ($profile_list))
775                         LIMIT 1",
776                         intval($item[0]["parent"]), intval($uid));
777
778         if ($parent AND !isset($params["type"])) {
779                 $params["type"] = NOTIFY_COMMENT;
780                 $params["verb"] = ACTIVITY_POST;
781         }
782
783         if (isset($params["type"]))
784                 notification($params);
785 }
786
787 /**
788  * @brief Formats a notification message with the notification author
789  *
790  * Replace the name with {0} but ensure to make that only once. The {0} is used
791  * later and prints the name in bold.
792  *
793  * @param string $name
794  * @param string $message
795  * @return string Formatted message
796  */
797 function format_notification_message($name, $message) {
798         if ($name != '') {
799                 $pos = strpos($message, $name);
800         } else {
801                 $pos = false;
802         }
803
804         if ($pos !== false) {
805                 $message = substr_replace($message, '{0}', $pos, strlen($name));
806         }
807
808         return $message;
809 }