]> git.mxchange.org Git - friendica.git/blob - include/enotify.php
Improve dba::selectFirst calls
[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::selectFirst('user', ['nickname', 'page-flags'],
54                         ['uid' => $params['uid']]);
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                 $thread = dba::selectFirst('thread', ['ignored'], ['iid' => $parent_id]);
110                 if (DBM::is_result($thread) && $thread["ignored"]) {
111                         logger("Thread ".$parent_id." will be ignored", LOGGER_DEBUG);
112                         return;
113                 }
114
115                 // Check to see if there was already a tag notify or comment notify for this post.
116                 // If so don't create a second notification
117                 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d, %d) AND `link` = '%s' AND `uid` = %d LIMIT 1",
118                         intval(NOTIFY_TAGSELF),
119                         intval(NOTIFY_COMMENT),
120                         intval(NOTIFY_SHARE),
121                         dbesc($params['link']),
122                         intval($params['uid'])
123                 );
124                 if ($p && count($p)) {
125                         pop_lang();
126                         return;
127                 }
128
129                 // if it's a post figure out who's post it is.
130
131                 $item = null;
132
133                 if ($params['otype'] === 'item' && $parent_id) {
134                         $item = dba::selectFirst('item', [], ['id' => $parent_id]);
135                 }
136
137                 $item_post_type = item_post_type($item);
138
139                 // "a post"
140                 $dest_str = sprintf(t('%1$s commented on [url=%2$s]a %3$s[/url]'),
141                                                                 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
142                                                                 $itemlink,
143                                                                 $item_post_type);
144
145                 // "George Bull's post"
146                 if ($item) {
147                         $dest_str = sprintf(t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]'),
148                                                 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
149                                                 $itemlink,
150                                                 $p['author-name'],
151                                                 $item_post_type);
152                 }
153
154                 // "your post"
155                 if (DBM::is_result($item) && $item['owner-name'] == $item['author-name'] && $item['wall']) {
156                         $dest_str = sprintf(t('%1$s commented on [url=%2$s]your %3$s[/url]'),
157                                                                 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
158                                                                 $itemlink,
159                                                                 $item_post_type);
160                 }
161
162                 // Some mail softwares relies on subject field for threading.
163                 // So, we cannot have different subjects for notifications of the same thread.
164                 // Before this we have the name of the replier on the subject rendering
165                 // differents subjects for messages on the same thread.
166
167                 $subject = sprintf(t('[Friendica:Notify] Comment to conversation #%1$d by %2$s'), $parent_id, $params['source_name']);
168
169                 $preamble = sprintf(t('%s commented on an item/conversation you have been following.'), $params['source_name']);
170                 $epreamble = $dest_str;
171
172                 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
173                 $tsitelink = sprintf($sitelink, $siteurl);
174                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
175                 $itemlink =  $params['link'];
176         }
177
178         if ($params['type'] == NOTIFY_WALL) {
179                 $subject = sprintf(t('[Friendica:Notify] %s posted to your profile wall'), $params['source_name']);
180
181                 $preamble = sprintf(t('%1$s posted to your profile wall at %2$s'), $params['source_name'], $sitename);
182                 $epreamble = sprintf(t('%1$s posted to [url=%2$s]your wall[/url]'),
183                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
184                                         $params['link']);
185
186                 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
187                 $tsitelink = sprintf($sitelink, $siteurl);
188                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
189                 $itemlink =  $params['link'];
190         }
191
192         if ($params['type'] == NOTIFY_TAGSELF) {
193                 $subject = sprintf(t('[Friendica:Notify] %s tagged you'), $params['source_name']);
194
195                 $preamble = sprintf(t('%1$s tagged you at %2$s'), $params['source_name'], $sitename);
196                 $epreamble = sprintf(t('%1$s [url=%2$s]tagged you[/url].'),
197                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
198                                         $params['link']);
199
200                 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
201                 $tsitelink = sprintf($sitelink, $siteurl);
202                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
203                 $itemlink =  $params['link'];
204         }
205
206         if ($params['type'] == NOTIFY_SHARE) {
207                 $subject = sprintf(t('[Friendica:Notify] %s shared a new post'), $params['source_name']);
208
209                 $preamble = sprintf(t('%1$s shared a new post at %2$s'), $params['source_name'], $sitename);
210                 $epreamble = sprintf(t('%1$s [url=%2$s]shared a post[/url].'),
211                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
212                                         $params['link']);
213
214                 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
215                 $tsitelink = sprintf($sitelink, $siteurl);
216                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
217                 $itemlink =  $params['link'];
218         }
219
220         if ($params['type'] == NOTIFY_POKE) {
221                 $subject = sprintf(t('[Friendica:Notify] %1$s poked you'), $params['source_name']);
222
223                 $preamble = sprintf(t('%1$s poked you at %2$s'), $params['source_name'], $sitename);
224                 $epreamble = sprintf(t('%1$s [url=%2$s]poked you[/url].'),
225                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
226                                         $params['link']);
227
228                 $subject = str_replace('poked', t($params['activity']), $subject);
229                 $preamble = str_replace('poked', t($params['activity']), $preamble);
230                 $epreamble = str_replace('poked', t($params['activity']), $epreamble);
231
232                 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
233                 $tsitelink = sprintf($sitelink, $siteurl);
234                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
235                 $itemlink =  $params['link'];
236         }
237
238         if ($params['type'] == NOTIFY_TAGSHARE) {
239                 $subject = sprintf(t('[Friendica:Notify] %s tagged your post'), $params['source_name']);
240
241                 $preamble = sprintf(t('%1$s tagged your post at %2$s'), $params['source_name'], $sitename);
242                 $epreamble = sprintf(t('%1$s tagged [url=%2$s]your post[/url]'),
243                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
244                                         $itemlink);
245
246                 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
247                 $tsitelink = sprintf($sitelink, $siteurl);
248                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
249                 $itemlink =  $params['link'];
250         }
251
252         if ($params['type'] == NOTIFY_INTRO) {
253                 $subject = sprintf(t('[Friendica:Notify] Introduction received'));
254
255                 $preamble = sprintf(t('You\'ve received an introduction from \'%1$s\' at %2$s'), $params['source_name'], $sitename);
256                 $epreamble = sprintf(t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.'),
257                                         $itemlink,
258                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
259
260                 $body = sprintf(t('You may visit their profile at %s'), $params['source_link']);
261
262                 $sitelink = t('Please visit %s to approve or reject the introduction.');
263                 $tsitelink = sprintf($sitelink, $siteurl);
264                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
265                 $itemlink =  $params['link'];
266
267                 switch ($params['verb']) {
268                         case ACTIVITY_FRIEND:
269                                 // someone started to share with user (mostly OStatus)
270                                 $subject = sprintf(t('[Friendica:Notify] A new person is sharing with you'));
271
272                                 $preamble = sprintf(t('%1$s is sharing with you at %2$s'), $params['source_name'], $sitename);
273                                 $epreamble = sprintf(t('%1$s is sharing with you at %2$s'),
274                                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
275                                                         $sitename);
276                                 break;
277                         case ACTIVITY_FOLLOW:
278                                 // someone started to follow the user (mostly OStatus)
279                                 $subject = sprintf(t('[Friendica:Notify] You have a new follower'));
280
281                                 $preamble = sprintf(t('You have a new follower at %2$s : %1$s'), $params['source_name'], $sitename);
282                                 $epreamble = sprintf(t('You have a new follower at %2$s : %1$s'),
283                                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
284                                                         $sitename);
285                                 break;
286                         default:
287                                 // ACTIVITY_REQ_FRIEND is default activity for notifications
288                                 break;
289                 }
290         }
291
292         if ($params['type'] == NOTIFY_SUGGEST) {
293                 $subject = sprintf(t('[Friendica:Notify] Friend suggestion received'));
294
295                 $preamble = sprintf(t('You\'ve received a friend suggestion from \'%1$s\' at %2$s'), $params['source_name'], $sitename);
296                 $epreamble = sprintf(t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.'),
297                                         $itemlink,
298                                         '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
299                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
300
301                 $body = t('Name:').' '.$params['item']['name']."\n";
302                 $body .= t('Photo:').' '.$params['item']['photo']."\n";
303                 $body .= sprintf(t('You may visit their profile at %s'), $params['item']['url']);
304
305                 $sitelink = t('Please visit %s to approve or reject the suggestion.');
306                 $tsitelink = sprintf($sitelink, $siteurl);
307                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
308                 $itemlink =  $params['link'];
309         }
310
311         if ($params['type'] == NOTIFY_CONFIRM) {
312                 if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
313                         $subject = sprintf(t('[Friendica:Notify] Connection accepted'));
314
315                         $preamble = sprintf(t('\'%1$s\' has accepted your connection request at %2$s'), $params['source_name'], $sitename);
316                         $epreamble = sprintf(t('%2$s has accepted your [url=%1$s]connection request[/url].'),
317                                                 $itemlink,
318                                                 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
319
320                         $body =  t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
321
322                         $sitelink = t('Please visit %s if you wish to make any changes to this relationship.');
323                         $tsitelink = sprintf($sitelink, $siteurl);
324                         $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
325                         $itemlink =  $params['link'];
326                 } else { // ACTIVITY_FOLLOW
327                         $subject = sprintf(t('[Friendica:Notify] Connection accepted'));
328
329                         $preamble = sprintf(t('\'%1$s\' has accepted your connection request at %2$s'), $params['source_name'], $sitename);
330                         $epreamble = sprintf(t('%2$s has accepted your [url=%1$s]connection request[/url].'),
331                                                 $itemlink,
332                                                 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
333
334                         $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']);
335                         $body .= "\n\n";
336                         $body .= sprintf(t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.'), $params['source_name']);
337
338                         $sitelink = t('Please visit %s  if you wish to make any changes to this relationship.');
339                         $tsitelink = sprintf($sitelink, $siteurl);
340                         $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
341                         $itemlink =  $params['link'];
342                 }
343         }
344
345         if ($params['type'] == NOTIFY_SYSTEM) {
346                 switch($params['event']) {
347                         case "SYSTEM_REGISTER_REQUEST":
348                                 $subject = sprintf(t('[Friendica System:Notify] registration request'));
349
350                                 $preamble = sprintf(t('You\'ve received a registration request from \'%1$s\' at %2$s'), $params['source_name'], $sitename);
351                                 $epreamble = sprintf(t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.'),
352                                                         $itemlink,
353                                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
354
355                                 $body = sprintf(t('Full Name:   %1$s\nSite Location:    %2$s\nLogin Name:       %3$s (%4$s)'),
356                                                                         $params['source_name'], $siteurl, $params['source_mail'], $params['source_nick']);
357
358                                 $sitelink = t('Please visit %s to approve or reject the request.');
359                                 $tsitelink = sprintf($sitelink, $params['link']);
360                                 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
361                                 $itemlink =  $params['link'];
362                                 break;
363                         case "SYSTEM_DB_UPDATE_FAIL":
364                                 break;
365                 }
366         }
367
368         if ($params['type'] == SYSTEM_EMAIL) {
369                 // not part of the notifications.
370                 // it just send a mail to the user.
371                 // It will be used by the system to send emails to users (like
372                 // password reset, invitations and so) using one look (but without
373                 // add a notification to the user, with could be inexistent)
374                 $subject = $params['subject'];
375
376                 $preamble = $params['preamble'];
377
378                 $body =  $params['body'];
379
380                 $sitelink = "";
381                 $tsitelink = "";
382                 $hsitelink = "";
383                 $itemlink =  "";
384                 $show_in_notification_page = false;
385         }
386
387         $subject .= " (".$nickname."@".$hostname.")";
388
389         $h = array(
390                 'params'    => $params,
391                 'subject'   => $subject,
392                 'preamble'  => $preamble,
393                 'epreamble' => $epreamble,
394                 'body'      => $body,
395                 'sitelink'  => $sitelink,
396                 'tsitelink' => $tsitelink,
397                 'hsitelink' => $hsitelink,
398                 'itemlink'  => $itemlink
399         );
400
401         call_hooks('enotify', $h);
402
403         $subject   = $h['subject'];
404
405         $preamble  = $h['preamble'];
406         $epreamble = $h['epreamble'];
407
408         $body      = $h['body'];
409
410         $tsitelink = $h['tsitelink'];
411         $hsitelink = $h['hsitelink'];
412         $itemlink  = $h['itemlink'];
413
414         if ($show_in_notification_page) {
415                 logger("adding notification entry", LOGGER_DEBUG);
416                 do {
417                         $dups = false;
418                         $hash = random_string();
419                         $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' LIMIT 1",
420                                 dbesc($hash));
421                         if (DBM::is_result($r)) {
422                                 $dups = true;
423                         }
424                 } while ($dups == true);
425
426                 /// @TODO One statement is enough
427                 $datarray = array();
428                 $datarray['hash']  = $hash;
429                 $datarray['name']  = $params['source_name'];
430                 $datarray['name_cache'] = strip_tags(bbcode($params['source_name']));
431                 $datarray['url']   = $params['source_link'];
432                 $datarray['photo'] = $params['source_photo'];
433                 $datarray['date']  = datetime_convert();
434                 $datarray['uid']   = $params['uid'];
435                 $datarray['link']  = $itemlink;
436                 $datarray['iid']   = $item_id;
437                 $datarray['parent'] = $parent_id;
438                 $datarray['type']  = $params['type'];
439                 $datarray['verb']  = $params['verb'];
440                 $datarray['otype'] = $params['otype'];
441                 $datarray['abort'] = false;
442
443                 call_hooks('enotify_store', $datarray);
444
445                 if ($datarray['abort']) {
446                         pop_lang();
447                         return False;
448                 }
449
450                 // create notification entry in DB
451                 q("INSERT INTO `notify` (`hash`, `name`, `url`, `photo`, `date`, `uid`, `link`, `iid`, `parent`, `type`, `verb`, `otype`, `name_cache`)
452                         values('%s', '%s', '%s', '%s', '%s', %d, '%s', %d, %d, %d, '%s', '%s', '%s')",
453                         dbesc($datarray['hash']),
454                         dbesc($datarray['name']),
455                         dbesc($datarray['url']),
456                         dbesc($datarray['photo']),
457                         dbesc($datarray['date']),
458                         intval($datarray['uid']),
459                         dbesc($datarray['link']),
460                         intval($datarray['iid']),
461                         intval($datarray['parent']),
462                         intval($datarray['type']),
463                         dbesc($datarray['verb']),
464                         dbesc($datarray['otype']),
465                         dbesc($datarray["name_cache"])
466                 );
467
468                 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' AND `uid` = %d LIMIT 1",
469                         dbesc($hash),
470                         intval($params['uid'])
471                 );
472                 if ($r) {
473                         $notify_id = $r[0]['id'];
474                 } else {
475                         pop_lang();
476                         return False;
477                 }
478
479                 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
480                 // After we've stored everything, look again to see if there are any duplicates and if so remove them
481                 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
482                         intval(NOTIFY_TAGSELF),
483                         intval(NOTIFY_COMMENT),
484                         dbesc($params['link']),
485                         intval($params['uid'])
486                 );
487                 if ($p && (count($p) > 1)) {
488                         for ($d = 1; $d < count($p); $d ++) {
489                                 dba::delete('notify', array('id' => $p[$d]['id']));
490                         }
491
492                         // only continue on if we stored the first one
493                         if ($notify_id != $p[0]['id']) {
494                                 pop_lang();
495                                 return False;
496                         }
497                 }
498
499                 $itemlink = System::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                 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']) && (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                                 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 = ((!Config::get('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                 return Emailer::send(
629                         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 users who should be notified
647  *
648  * @param int $itemid ID of the item for which the check should be done
649  */
650 function check_user_notification($itemid) {
651         // fetch all users in the thread
652         $users = dba::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
653                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
654                         WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
655         while ($user = dba::fetch($users)) {
656                 check_item_notification($itemid, $user['uid']);
657         }
658         dba::close($users);
659 }
660
661 /**
662  * @brief Checks for item related notifications and sends them
663  *
664  * @param int $itemid ID of the item for which the check should be done
665  * @param int $uid User ID
666  * @param str $defaulttype (Optional) Forces a notification with this type.
667  */
668 function check_item_notification($itemid, $uid, $defaulttype = "") {
669         $notification_data = array("uid" => $uid, "profiles" => array());
670         call_hooks('check_item_notification', $notification_data);
671
672         $profiles = $notification_data["profiles"];
673
674         $fields = ['notify-flags', 'language', 'username', 'email', 'nickname'];
675         $user = dba::selectFirst('user', $fields, ['uid' => $uid]);
676         if (!DBM::is_result($user)) {
677                 return false;
678         }
679
680         $owner = dba::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
681         if (!DBM::is_result($owner)) {
682                 return false;
683         }
684
685         // This is our regular URL format
686         $profiles[] = $owner["url"];
687
688         // Notifications from Diaspora are often with an URL in the Diaspora format
689         $profiles[] = System::baseUrl()."/u/".$user["nickname"];
690
691         $profiles2 = array();
692
693         foreach ($profiles AS $profile) {
694                 // Check for invalid profile urls. 13 should be the shortest possible profile length:
695                 // http://a.bc/d
696                 // Additionally check for invalid urls that would return the normalised value "http:"
697                 if ((strlen($profile) >= 13) && (normalise_link($profile) != "http:")) {
698                         if (!in_array($profile, $profiles2))
699                                 $profiles2[] = $profile;
700
701                         $profile = normalise_link($profile);
702                         if (!in_array($profile, $profiles2))
703                                 $profiles2[] = $profile;
704
705                         $profile = str_replace("http://", "https://", $profile);
706                         if (!in_array($profile, $profiles2))
707                                 $profiles2[] = $profile;
708                 }
709         }
710
711         $profiles = $profiles2;
712
713         $profile_list = "";
714
715         foreach ($profiles AS $profile) {
716                 if ($profile_list != "")
717                         $profile_list .= "', '";
718
719                 $profile_list .= dbesc($profile);
720         }
721
722         $profile_list = "'".$profile_list."'";
723
724         // Only act if it is a "real" post
725         // We need the additional check for the "local_profile" because of mixed situations on connector networks
726         $item = q("SELECT `id`, `mention`, `tag`,`parent`, `title`, `body`, `author-name`, `author-link`, `author-avatar`, `guid`,
727                         `parent-uri`, `uri`, `contact-id`
728                         FROM `item` WHERE `id` = %d AND `verb` IN ('%s', '') AND `type` != 'activity' AND
729                                 NOT (`author-link` IN ($profile_list))  LIMIT 1",
730                 intval($itemid), dbesc(ACTIVITY_POST));
731         if (!$item)
732                 return false;
733
734         // Generate the notification array
735         $params = array();
736         $params["uid"] = $uid;
737         $params["notify_flags"] = $user["notify-flags"];
738         $params["language"] = $user["language"];
739         $params["to_name"] = $user["username"];
740         $params["to_email"] = $user["email"];
741         $params["item"] = $item[0];
742         $params["parent"] = $item[0]["parent"];
743         $params["link"] = System::baseUrl().'/display/'.urlencode($item[0]["guid"]);
744         $params["otype"] = 'item';
745         $params["source_name"] = $item[0]["author-name"];
746         $params["source_link"] = $item[0]["author-link"];
747         $params["source_photo"] = $item[0]["author-avatar"];
748
749         if ($item[0]["parent-uri"] === $item[0]["uri"]) {
750                 // Send a notification for every new post?
751                 $send_notification = dba::exists('contact', ['id' => $item[0]['contact-id'], 'notify_new_posts' => true]);
752
753                 if (!$send_notification) {
754                         $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
755                                 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
756
757                         if (DBM::is_result($tags)) {
758                                 foreach ($tags AS $tag) {
759                                         $condition = ['nurl' => normalise_link($tag["url"]), 'uid' => $uid, 'notify_new_posts' => true];
760                                         $r = dba::exists('contact', $condition);
761                                         if ($r) {
762                                                 $send_notification = true;
763                                         }
764                                 }
765                         }
766                 }
767
768                 if ($send_notification) {
769                         $params["type"] = NOTIFY_SHARE;
770                         $params["verb"] = ACTIVITY_TAG;
771                 }
772         }
773
774         // Is the user mentioned in this post?
775         $tagged = false;
776
777         foreach ($profiles AS $profile) {
778                 if (strpos($item[0]["tag"], "=".$profile."]") || strpos($item[0]["body"], "=".$profile."]"))
779                         $tagged = true;
780         }
781
782         if ($item[0]["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
783                 $params["type"] = NOTIFY_TAGSELF;
784                 $params["verb"] = ACTIVITY_TAG;
785         }
786
787         // Is it a post that the user had started or where he interacted?
788         $parent = q("SELECT `thread`.`iid` FROM `thread` INNER JOIN `item` ON `item`.`parent` = `thread`.`iid`
789                         WHERE `thread`.`iid` = %d AND NOT `thread`.`ignored` AND
790                                 (`thread`.`mention` OR `item`.`author-link` IN ($profile_list))
791                         LIMIT 1",
792                         intval($item[0]["parent"]));
793
794         if ($parent && !isset($params["type"])) {
795                 $params["type"] = NOTIFY_COMMENT;
796                 $params["verb"] = ACTIVITY_POST;
797         }
798
799         if (isset($params["type"]))
800                 notification($params);
801 }
802
803 /**
804  * @brief Formats a notification message with the notification author
805  *
806  * Replace the name with {0} but ensure to make that only once. The {0} is used
807  * later and prints the name in bold.
808  *
809  * @param string $name
810  * @param string $message
811  * @return string Formatted message
812  */
813 function format_notification_message($name, $message) {
814         if ($name != '') {
815                 $pos = strpos($message, $name);
816         } else {
817                 $pos = false;
818         }
819
820         if ($pos !== false) {
821                 $message = substr_replace($message, '{0}', $pos, strlen($name));
822         }
823
824         return $message;
825 }