3 * @file include/enotify.php
6 use Friendica\Core\Config;
7 use Friendica\Core\System;
8 use Friendica\Database\DBM;
9 use Friendica\Util\Emailer;
11 require_once 'include/bbcode.php';
12 require_once 'include/html2bbcode.php';
15 * @brief Creates a notification entry and possibly sends a mail
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
23 function notification($params)
27 // from here on everything is in the recipients language
28 push_lang($params['language']);
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);
38 $site_admin = sprintf(t('%1$s, %2$s Administrator'), $a->config['admin_name'], $sitename);
41 $sender_name = $sitename;
42 $hostname = $a->get_hostname();
43 if (strpos($hostname, ':')) {
44 $hostname = substr($hostname, 0, strpos($hostname, ':'));
47 $sender_email = $a->config['sender_email'];
48 if (empty($sender_email)) {
49 $sender_email = t('noreply').'@'.$hostname;
52 if ($params['type'] != SYSTEM_EMAIL) {
53 $user = dba::selectFirst('user', ['nickname', 'page-flags'],
54 ['uid' => $params['uid']]);
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))) {
61 $nickname = $user["nickname"];
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);
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";
77 if (array_key_exists('item', $params)) {
78 $title = $params['item']['title'];
79 $body = $params['item']['body'];
84 if (isset($params['item']['id'])) {
85 $item_id = $params['item']['id'];
90 if (isset($params['parent'])) {
91 $parent_id = $params['parent'];
96 if ($params['type'] == NOTIFY_MAIL) {
97 $subject = sprintf(t('[Friendica:Notify] New mail received at %s'), $sitename);
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]');
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'];
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);
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'])
124 if ($p && count($p)) {
129 // if it's a post figure out who's post it is.
133 if ($params['otype'] === 'item' && $parent_id) {
134 $item = dba::selectFirst('item', [], ['id' => $parent_id]);
137 $item_post_type = item_post_type($item);
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]',
145 // "George Bull's post"
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]',
150 $item['author-name'],
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]',
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.
167 $subject = sprintf(t('[Friendica:Notify] Comment to conversation #%1$d by %2$s'), $parent_id, $params['source_name']);
169 $preamble = sprintf(t('%s commented on an item/conversation you have been following.'), $params['source_name']);
170 $epreamble = $dest_str;
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'];
178 if ($params['type'] == NOTIFY_WALL) {
179 $subject = sprintf(t('[Friendica:Notify] %s posted to your profile wall'), $params['source_name']);
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]',
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'];
192 if ($params['type'] == NOTIFY_TAGSELF) {
193 $subject = sprintf(t('[Friendica:Notify] %s tagged you'), $params['source_name']);
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]',
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'];
206 if ($params['type'] == NOTIFY_SHARE) {
207 $subject = sprintf(t('[Friendica:Notify] %s shared a new post'), $params['source_name']);
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]',
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'];
220 if ($params['type'] == NOTIFY_POKE) {
221 $subject = sprintf(t('[Friendica:Notify] %1$s poked you'), $params['source_name']);
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]',
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);
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'];
238 if ($params['type'] == NOTIFY_TAGSHARE) {
239 $subject = sprintf(t('[Friendica:Notify] %s tagged your post'), $params['source_name']);
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]',
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'];
252 if ($params['type'] == NOTIFY_INTRO) {
253 $subject = sprintf(t('[Friendica:Notify] Introduction received'));
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.'),
258 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
260 $body = sprintf(t('You may visit their profile at %s'), $params['source_link']);
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'];
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'));
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]',
277 case ACTIVITY_FOLLOW:
278 // someone started to follow the user (mostly OStatus)
279 $subject = sprintf(t('[Friendica:Notify] You have a new follower'));
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]',
287 // ACTIVITY_REQ_FRIEND is default activity for notifications
292 if ($params['type'] == NOTIFY_SUGGEST) {
293 $subject = sprintf(t('[Friendica:Notify] Friend suggestion received'));
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.'),
298 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
299 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
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']);
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'];
311 if ($params['type'] == NOTIFY_CONFIRM) {
312 if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
313 $subject = sprintf(t('[Friendica:Notify] Connection accepted'));
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].'),
318 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
320 $body = t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
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'));
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].'),
332 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
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']);
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']);
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'];
345 if ($params['type'] == NOTIFY_SYSTEM) {
346 switch($params['event']) {
347 case "SYSTEM_REGISTER_REQUEST":
348 $subject = sprintf(t('[Friendica System:Notify] registration request'));
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.'),
353 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
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']);
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'];
363 case "SYSTEM_DB_UPDATE_FAIL":
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'];
376 $preamble = $params['preamble'];
378 $body = $params['body'];
384 $show_in_notification_page = false;
387 $subject .= " (".$nickname."@".$hostname.")";
391 'subject' => $subject,
392 'preamble' => $preamble,
393 'epreamble' => $epreamble,
395 'sitelink' => $sitelink,
396 'tsitelink' => $tsitelink,
397 'hsitelink' => $hsitelink,
398 'itemlink' => $itemlink
401 call_hooks('enotify', $h);
403 $subject = $h['subject'];
405 $preamble = $h['preamble'];
406 $epreamble = $h['epreamble'];
410 $tsitelink = $h['tsitelink'];
411 $hsitelink = $h['hsitelink'];
412 $itemlink = $h['itemlink'];
414 if ($show_in_notification_page) {
415 logger("adding notification entry", LOGGER_DEBUG);
418 $hash = random_string();
419 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' LIMIT 1",
421 if (DBM::is_result($r)) {
424 } while ($dups == true);
426 /// @TODO One statement is enough
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;
443 call_hooks('enotify_store', $datarray);
445 if ($datarray['abort']) {
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"])
468 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' AND `uid` = %d LIMIT 1",
470 intval($params['uid'])
473 $notify_id = $r[0]['id'];
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'])
487 if ($p && (count($p) > 1)) {
488 for ($d = 1; $d < count($p); $d ++) {
489 dba::delete('notify', array('id' => $p[$d]['id']));
492 // only continue on if we stored the first one
493 if ($notify_id != $p[0]['id']) {
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",
506 intval($params['uid'])
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) {
515 logger('sending notification email');
517 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
518 $id_for_parent = $params['parent']."@".$hostname;
520 // Is this the first email notification for this parent item and user?
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']));
526 // If so, create the record of it and use a message-id smtp header.
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)",
533 intval($params['parent']),
534 intval($params['uid']),
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);
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);
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');
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;
579 call_hooks('enotify_mail', $datarray);
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));
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,
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,
627 // use the Emailer class to send the message
628 return Emailer::send(
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'])
646 * @brief Checks for users who should be notified
648 * @param int $itemid ID of the item for which the check should be done
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']);
662 * @brief Checks for item related notifications and sends them
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.
668 function check_item_notification($itemid, $uid, $defaulttype = "") {
669 $notification_data = array("uid" => $uid, "profiles" => array());
670 call_hooks('check_item_notification', $notification_data);
672 $profiles = $notification_data["profiles"];
674 $fields = ['notify-flags', 'language', 'username', 'email', 'nickname'];
675 $user = dba::selectFirst('user', $fields, ['uid' => $uid]);
676 if (!DBM::is_result($user)) {
680 $owner = dba::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
681 if (!DBM::is_result($owner)) {
685 // This is our regular URL format
686 $profiles[] = $owner["url"];
688 // Notifications from Diaspora are often with an URL in the Diaspora format
689 $profiles[] = System::baseUrl()."/u/".$user["nickname"];
691 $profiles2 = array();
693 foreach ($profiles AS $profile) {
694 // Check for invalid profile urls. 13 should be the shortest possible profile length:
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;
701 $profile = normalise_link($profile);
702 if (!in_array($profile, $profiles2))
703 $profiles2[] = $profile;
705 $profile = str_replace("http://", "https://", $profile);
706 if (!in_array($profile, $profiles2))
707 $profiles2[] = $profile;
711 $profiles = $profiles2;
715 foreach ($profiles AS $profile) {
716 if ($profile_list != "")
717 $profile_list .= "', '";
719 $profile_list .= dbesc($profile);
722 $profile_list = "'".$profile_list."'";
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));
734 // Generate the notification 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"];
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]);
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));
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);
762 $send_notification = true;
768 if ($send_notification) {
769 $params["type"] = NOTIFY_SHARE;
770 $params["verb"] = ACTIVITY_TAG;
774 // Is the user mentioned in this post?
777 foreach ($profiles AS $profile) {
778 if (strpos($item[0]["tag"], "=".$profile."]") || strpos($item[0]["body"], "=".$profile."]"))
782 if ($item[0]["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
783 $params["type"] = NOTIFY_TAGSELF;
784 $params["verb"] = ACTIVITY_TAG;
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))
792 intval($item[0]["parent"]));
794 if ($parent && !isset($params["type"])) {
795 $params["type"] = NOTIFY_COMMENT;
796 $params["verb"] = ACTIVITY_POST;
799 if (isset($params["type"]))
800 notification($params);
804 * @brief Formats a notification message with the notification author
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.
809 * @param string $name
810 * @param string $message
811 * @return string Formatted message
813 function format_notification_message($name, $message) {
815 $pos = strpos($message, $name);
820 if ($pos !== false) {
821 $message = substr_replace($message, '{0}', $pos, strlen($name));