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::select('user', array('nickname', 'page-flags'),
54 array('uid' => $params['uid']), array('limit' => 1));
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 $p = q("SELECT `ignored` FROM `thread` WHERE `iid` = %d LIMIT 1",
112 if ($p && count($p) && ($p[0]["ignored"])) {
113 logger("Thread ".$parent_id." will be ignored", LOGGER_DEBUG);
117 // Check to see if there was already a tag notify or comment notify for this post.
118 // If so don't create a second notification
119 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d, %d) AND `link` = '%s' AND `uid` = %d LIMIT 1",
120 intval(NOTIFY_TAGSELF),
121 intval(NOTIFY_COMMENT),
122 intval(NOTIFY_SHARE),
123 dbesc($params['link']),
124 intval($params['uid'])
126 if ($p && count($p)) {
131 // if it's a post figure out who's post it is.
135 if ($params['otype'] === 'item' && $parent_id) {
136 $p = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
141 $item_post_type = item_post_type($p[0]);
144 $dest_str = sprintf(t('%1$s commented on [url=%2$s]a %3$s[/url]'),
145 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
149 // "George Bull's post"
151 $dest_str = sprintf(t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]'),
152 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
154 $p[0]['author-name'],
159 if ($p[0]['owner-name'] == $p[0]['author-name'] && $p[0]['wall']) {
160 $dest_str = sprintf(t('%1$s commented on [url=%2$s]your %3$s[/url]'),
161 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
166 // Some mail softwares relies on subject field for threading.
167 // So, we cannot have different subjects for notifications of the same thread.
168 // Before this we have the name of the replier on the subject rendering
169 // differents subjects for messages on the same thread.
171 $subject = sprintf(t('[Friendica:Notify] Comment to conversation #%1$d by %2$s'), $parent_id, $params['source_name']);
173 $preamble = sprintf(t('%s commented on an item/conversation you have been following.'), $params['source_name']);
174 $epreamble = $dest_str;
176 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
177 $tsitelink = sprintf($sitelink, $siteurl);
178 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
179 $itemlink = $params['link'];
182 if ($params['type'] == NOTIFY_WALL) {
183 $subject = sprintf(t('[Friendica:Notify] %s posted to your profile wall'), $params['source_name']);
185 $preamble = sprintf(t('%1$s posted to your profile wall at %2$s'), $params['source_name'], $sitename);
186 $epreamble = sprintf(t('%1$s posted to [url=%2$s]your wall[/url]'),
187 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
190 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
191 $tsitelink = sprintf($sitelink, $siteurl);
192 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
193 $itemlink = $params['link'];
196 if ($params['type'] == NOTIFY_TAGSELF) {
197 $subject = sprintf(t('[Friendica:Notify] %s tagged you'), $params['source_name']);
199 $preamble = sprintf(t('%1$s tagged you at %2$s'), $params['source_name'], $sitename);
200 $epreamble = sprintf(t('%1$s [url=%2$s]tagged you[/url].'),
201 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
204 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
205 $tsitelink = sprintf($sitelink, $siteurl);
206 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
207 $itemlink = $params['link'];
210 if ($params['type'] == NOTIFY_SHARE) {
211 $subject = sprintf(t('[Friendica:Notify] %s shared a new post'), $params['source_name']);
213 $preamble = sprintf(t('%1$s shared a new post at %2$s'), $params['source_name'], $sitename);
214 $epreamble = sprintf(t('%1$s [url=%2$s]shared a post[/url].'),
215 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
218 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
219 $tsitelink = sprintf($sitelink, $siteurl);
220 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
221 $itemlink = $params['link'];
224 if ($params['type'] == NOTIFY_POKE) {
225 $subject = sprintf(t('[Friendica:Notify] %1$s poked you'), $params['source_name']);
227 $preamble = sprintf(t('%1$s poked you at %2$s'), $params['source_name'], $sitename);
228 $epreamble = sprintf(t('%1$s [url=%2$s]poked you[/url].'),
229 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
232 $subject = str_replace('poked', t($params['activity']), $subject);
233 $preamble = str_replace('poked', t($params['activity']), $preamble);
234 $epreamble = str_replace('poked', t($params['activity']), $epreamble);
236 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
237 $tsitelink = sprintf($sitelink, $siteurl);
238 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
239 $itemlink = $params['link'];
242 if ($params['type'] == NOTIFY_TAGSHARE) {
243 $subject = sprintf(t('[Friendica:Notify] %s tagged your post'), $params['source_name']);
245 $preamble = sprintf(t('%1$s tagged your post at %2$s'), $params['source_name'], $sitename);
246 $epreamble = sprintf(t('%1$s tagged [url=%2$s]your post[/url]'),
247 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
250 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
251 $tsitelink = sprintf($sitelink, $siteurl);
252 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
253 $itemlink = $params['link'];
256 if ($params['type'] == NOTIFY_INTRO) {
257 $subject = sprintf(t('[Friendica:Notify] Introduction received'));
259 $preamble = sprintf(t('You\'ve received an introduction from \'%1$s\' at %2$s'), $params['source_name'], $sitename);
260 $epreamble = sprintf(t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.'),
262 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
264 $body = sprintf(t('You may visit their profile at %s'), $params['source_link']);
266 $sitelink = t('Please visit %s to approve or reject the introduction.');
267 $tsitelink = sprintf($sitelink, $siteurl);
268 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
269 $itemlink = $params['link'];
271 switch ($params['verb']) {
272 case ACTIVITY_FRIEND:
273 // someone started to share with user (mostly OStatus)
274 $subject = sprintf(t('[Friendica:Notify] A new person is sharing with you'));
276 $preamble = sprintf(t('%1$s is sharing with you at %2$s'), $params['source_name'], $sitename);
277 $epreamble = sprintf(t('%1$s is sharing with you at %2$s'),
278 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
281 case ACTIVITY_FOLLOW:
282 // someone started to follow the user (mostly OStatus)
283 $subject = sprintf(t('[Friendica:Notify] You have a new follower'));
285 $preamble = sprintf(t('You have a new follower at %2$s : %1$s'), $params['source_name'], $sitename);
286 $epreamble = sprintf(t('You have a new follower at %2$s : %1$s'),
287 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
291 // ACTIVITY_REQ_FRIEND is default activity for notifications
296 if ($params['type'] == NOTIFY_SUGGEST) {
297 $subject = sprintf(t('[Friendica:Notify] Friend suggestion received'));
299 $preamble = sprintf(t('You\'ve received a friend suggestion from \'%1$s\' at %2$s'), $params['source_name'], $sitename);
300 $epreamble = sprintf(t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.'),
302 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
303 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
305 $body = t('Name:').' '.$params['item']['name']."\n";
306 $body .= t('Photo:').' '.$params['item']['photo']."\n";
307 $body .= sprintf(t('You may visit their profile at %s'), $params['item']['url']);
309 $sitelink = t('Please visit %s to approve or reject the suggestion.');
310 $tsitelink = sprintf($sitelink, $siteurl);
311 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
312 $itemlink = $params['link'];
315 if ($params['type'] == NOTIFY_CONFIRM) {
316 if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
317 $subject = sprintf(t('[Friendica:Notify] Connection accepted'));
319 $preamble = sprintf(t('\'%1$s\' has accepted your connection request at %2$s'), $params['source_name'], $sitename);
320 $epreamble = sprintf(t('%2$s has accepted your [url=%1$s]connection request[/url].'),
322 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
324 $body = t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
326 $sitelink = t('Please visit %s if you wish to make any changes to this relationship.');
327 $tsitelink = sprintf($sitelink, $siteurl);
328 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
329 $itemlink = $params['link'];
330 } else { // ACTIVITY_FOLLOW
331 $subject = sprintf(t('[Friendica:Notify] Connection accepted'));
333 $preamble = sprintf(t('\'%1$s\' has accepted your connection request at %2$s'), $params['source_name'], $sitename);
334 $epreamble = sprintf(t('%2$s has accepted your [url=%1$s]connection request[/url].'),
336 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
338 $body = sprintf(t('\'%1$s\' has chosen to accept you a "fan", which restricts some forms of communication - such as private messaging and some profile interactions. If this is a celebrity or community page, these settings were applied automatically.'), $params['source_name']);
340 $body .= sprintf(t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.'), $params['source_name']);
342 $sitelink = t('Please visit %s if you wish to make any changes to this relationship.');
343 $tsitelink = sprintf($sitelink, $siteurl);
344 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
345 $itemlink = $params['link'];
349 if ($params['type'] == NOTIFY_SYSTEM) {
350 switch($params['event']) {
351 case "SYSTEM_REGISTER_REQUEST":
352 $subject = sprintf(t('[Friendica System:Notify] registration request'));
354 $preamble = sprintf(t('You\'ve received a registration request from \'%1$s\' at %2$s'), $params['source_name'], $sitename);
355 $epreamble = sprintf(t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.'),
357 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
359 $body = sprintf(t('Full Name: %1$s\nSite Location: %2$s\nLogin Name: %3$s (%4$s)'),
360 $params['source_name'], $siteurl, $params['source_mail'], $params['source_nick']);
362 $sitelink = t('Please visit %s to approve or reject the request.');
363 $tsitelink = sprintf($sitelink, $params['link']);
364 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
365 $itemlink = $params['link'];
367 case "SYSTEM_DB_UPDATE_FAIL":
372 if ($params['type'] == SYSTEM_EMAIL) {
373 // not part of the notifications.
374 // it just send a mail to the user.
375 // It will be used by the system to send emails to users (like
376 // password reset, invitations and so) using one look (but without
377 // add a notification to the user, with could be inexistent)
378 $subject = $params['subject'];
380 $preamble = $params['preamble'];
382 $body = $params['body'];
388 $show_in_notification_page = false;
391 $subject .= " (".$nickname."@".$hostname.")";
395 'subject' => $subject,
396 'preamble' => $preamble,
397 'epreamble' => $epreamble,
399 'sitelink' => $sitelink,
400 'tsitelink' => $tsitelink,
401 'hsitelink' => $hsitelink,
402 'itemlink' => $itemlink
405 call_hooks('enotify', $h);
407 $subject = $h['subject'];
409 $preamble = $h['preamble'];
410 $epreamble = $h['epreamble'];
414 $tsitelink = $h['tsitelink'];
415 $hsitelink = $h['hsitelink'];
416 $itemlink = $h['itemlink'];
418 if ($show_in_notification_page) {
419 logger("adding notification entry", LOGGER_DEBUG);
422 $hash = random_string();
423 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' LIMIT 1",
425 if (DBM::is_result($r)) {
428 } while ($dups == true);
430 /// @TODO One statement is enough
432 $datarray['hash'] = $hash;
433 $datarray['name'] = $params['source_name'];
434 $datarray['name_cache'] = strip_tags(bbcode($params['source_name']));
435 $datarray['url'] = $params['source_link'];
436 $datarray['photo'] = $params['source_photo'];
437 $datarray['date'] = datetime_convert();
438 $datarray['uid'] = $params['uid'];
439 $datarray['link'] = $itemlink;
440 $datarray['iid'] = $item_id;
441 $datarray['parent'] = $parent_id;
442 $datarray['type'] = $params['type'];
443 $datarray['verb'] = $params['verb'];
444 $datarray['otype'] = $params['otype'];
445 $datarray['abort'] = false;
447 call_hooks('enotify_store', $datarray);
449 if ($datarray['abort']) {
454 // create notification entry in DB
455 q("INSERT INTO `notify` (`hash`, `name`, `url`, `photo`, `date`, `uid`, `link`, `iid`, `parent`, `type`, `verb`, `otype`, `name_cache`)
456 values('%s', '%s', '%s', '%s', '%s', %d, '%s', %d, %d, %d, '%s', '%s', '%s')",
457 dbesc($datarray['hash']),
458 dbesc($datarray['name']),
459 dbesc($datarray['url']),
460 dbesc($datarray['photo']),
461 dbesc($datarray['date']),
462 intval($datarray['uid']),
463 dbesc($datarray['link']),
464 intval($datarray['iid']),
465 intval($datarray['parent']),
466 intval($datarray['type']),
467 dbesc($datarray['verb']),
468 dbesc($datarray['otype']),
469 dbesc($datarray["name_cache"])
472 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' AND `uid` = %d LIMIT 1",
474 intval($params['uid'])
477 $notify_id = $r[0]['id'];
483 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
484 // After we've stored everything, look again to see if there are any duplicates and if so remove them
485 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
486 intval(NOTIFY_TAGSELF),
487 intval(NOTIFY_COMMENT),
488 dbesc($params['link']),
489 intval($params['uid'])
491 if ($p && (count($p) > 1)) {
492 for ($d = 1; $d < count($p); $d ++) {
493 dba::delete('notify', array('id' => $p[$d]['id']));
496 // only continue on if we stored the first one
497 if ($notify_id != $p[0]['id']) {
503 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
504 $msg = replace_macros($epreamble, array('$itemlink' => $itemlink));
505 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(bbcode($msg)));
506 q("UPDATE `notify` SET `msg` = '%s', `msg_cache` = '%s' WHERE `id` = %d AND `uid` = %d",
510 intval($params['uid'])
514 // send email notification if notification preferences permit
515 if ((intval($params['notify_flags']) & intval($params['type']))
516 || $params['type'] == NOTIFY_SYSTEM
517 || $params['type'] == SYSTEM_EMAIL) {
519 logger('sending notification email');
521 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
522 $id_for_parent = $params['parent']."@".$hostname;
524 // Is this the first email notification for this parent item and user?
526 $r = q("SELECT `id` FROM `notify-threads` WHERE `master-parent-item` = %d AND `receiver-uid` = %d LIMIT 1",
527 intval($params['parent']),
528 intval($params['uid']));
530 // If so, create the record of it and use a message-id smtp header.
533 logger("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), LOGGER_DEBUG);
534 q("INSERT INTO `notify-threads` (`notify-id`, `master-parent-item`, `receiver-uid`, `parent-item`)
535 values(%d, %d, %d, %d)",
537 intval($params['parent']),
538 intval($params['uid']),
541 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
542 $log_msg = "include/enotify: No previous notification found for this parent:\n".
543 " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
544 logger($log_msg, LOGGER_DEBUG);
546 // If not, just "follow" the thread.
547 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
548 logger("There's already a notification for this parent:\n".print_r($r, true), LOGGER_DEBUG);
552 // textversion keeps linebreaks
553 $textversion = strip_tags(str_replace("<br>", "\n", html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n"), "\n",
554 $body))),ENT_QUOTES, 'UTF-8')));
555 $htmlversion = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n\\n", "\\n"),
556 "<br />\n", $body))), ENT_QUOTES, 'UTF-8');
559 $datarray['banner'] = $banner;
560 $datarray['product'] = $product;
561 $datarray['preamble'] = $preamble;
562 $datarray['sitename'] = $sitename;
563 $datarray['siteurl'] = $siteurl;
564 $datarray['type'] = $params['type'];
565 $datarray['parent'] = $params['parent'];
566 $datarray['source_name'] = $params['source_name'];
567 $datarray['source_link'] = $params['source_link'];
568 $datarray['source_photo'] = $params['source_photo'];
569 $datarray['uid'] = $params['uid'];
570 $datarray['username'] = $params['to_name'];
571 $datarray['hsitelink'] = $hsitelink;
572 $datarray['tsitelink'] = $tsitelink;
573 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
574 $datarray['titemlink'] = $itemlink;
575 $datarray['thanks'] = $thanks;
576 $datarray['site_admin'] = $site_admin;
577 $datarray['title'] = stripslashes($title);
578 $datarray['htmlversion'] = $htmlversion;
579 $datarray['textversion'] = $textversion;
580 $datarray['subject'] = $subject;
581 $datarray['headers'] = $additional_mail_header;
583 call_hooks('enotify_mail', $datarray);
585 // check whether sending post content in email notifications is allowed
586 // always true for SYSTEM_EMAIL
587 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
589 // load the template for private message notifications
590 $tpl = get_markup_template('email_notify_html.tpl');
591 $email_html_body = replace_macros($tpl, array(
592 '$banner' => $datarray['banner'],
593 '$product' => $datarray['product'],
594 '$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
595 '$sitename' => $datarray['sitename'],
596 '$siteurl' => $datarray['siteurl'],
597 '$source_name' => $datarray['source_name'],
598 '$source_link' => $datarray['source_link'],
599 '$source_photo' => $datarray['source_photo'],
600 '$username' => $datarray['to_name'],
601 '$hsitelink' => $datarray['hsitelink'],
602 '$hitemlink' => $datarray['hitemlink'],
603 '$thanks' => $datarray['thanks'],
604 '$site_admin' => $datarray['site_admin'],
605 '$title' => $datarray['title'],
606 '$htmlversion' => $datarray['htmlversion'],
607 '$content_allowed' => $content_allowed,
610 // load the template for private message notifications
611 $tpl = get_markup_template('email_notify_text.tpl');
612 $email_text_body = replace_macros($tpl, array(
613 '$banner' => $datarray['banner'],
614 '$product' => $datarray['product'],
615 '$preamble' => $datarray['preamble'],
616 '$sitename' => $datarray['sitename'],
617 '$siteurl' => $datarray['siteurl'],
618 '$source_name' => $datarray['source_name'],
619 '$source_link' => $datarray['source_link'],
620 '$source_photo' => $datarray['source_photo'],
621 '$username' => $datarray['to_name'],
622 '$tsitelink' => $datarray['tsitelink'],
623 '$titemlink' => $datarray['titemlink'],
624 '$thanks' => $datarray['thanks'],
625 '$site_admin' => $datarray['site_admin'],
626 '$title' => $datarray['title'],
627 '$textversion' => $datarray['textversion'],
628 '$content_allowed' => $content_allowed,
631 // use the Emailer class to send the message
632 return Emailer::send(
634 'uid' => $params['uid'],
635 'fromName' => $sender_name,
636 'fromEmail' => $sender_email,
637 'replyTo' => $sender_email,
638 'toEmail' => $params['to_email'],
639 'messageSubject' => $datarray['subject'],
640 'htmlVersion' => $email_html_body,
641 'textVersion' => $email_text_body,
642 'additionalMailHeader' => $datarray['headers'])
650 * @brief Checks for users who should be notified
652 * @param int $itemid ID of the item for which the check should be done
654 function check_user_notification($itemid) {
655 // fetch all users in the thread
656 $users = dba::p("SELECT DISTINCT(`uid`) FROM `item` WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?) AND `uid` != 0", $itemid);
657 while ($user = dba::fetch($users)) {
658 check_item_notification($itemid, $user['uid']);
664 * @brief Checks for item related notifications and sends them
666 * @param int $itemid ID of the item for which the check should be done
667 * @param int $uid User ID
668 * @param str $defaulttype (Optional) Forces a notification with this type.
670 function check_item_notification($itemid, $uid, $defaulttype = "") {
671 $notification_data = array("uid" => $uid, "profiles" => array());
672 call_hooks('check_item_notification', $notification_data);
674 $profiles = $notification_data["profiles"];
676 $user = q("SELECT `notify-flags`, `language`, `username`, `email`, `nickname` FROM `user` WHERE `uid` = %d", intval($uid));
680 $owner = q("SELECT `id`, `url` FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1", intval($uid));
684 // This is our regular URL format
685 $profiles[] = $owner[0]["url"];
687 // Notifications from Diaspora are often with an URL in the Diaspora format
688 $profiles[] = System::baseUrl()."/u/".$user[0]["nickname"];
690 $profiles2 = array();
692 foreach ($profiles AS $profile) {
693 // Check for invalid profile urls. 13 should be the shortest possible profile length:
695 // Additionally check for invalid urls that would return the normalised value "http:"
696 if ((strlen($profile) >= 13) && (normalise_link($profile) != "http:")) {
697 if (!in_array($profile, $profiles2))
698 $profiles2[] = $profile;
700 $profile = normalise_link($profile);
701 if (!in_array($profile, $profiles2))
702 $profiles2[] = $profile;
704 $profile = str_replace("http://", "https://", $profile);
705 if (!in_array($profile, $profiles2))
706 $profiles2[] = $profile;
710 $profiles = $profiles2;
714 foreach ($profiles AS $profile) {
715 if ($profile_list != "")
716 $profile_list .= "', '";
718 $profile_list .= dbesc($profile);
721 $profile_list = "'".$profile_list."'";
723 // Only act if it is a "real" post
724 // We need the additional check for the "local_profile" because of mixed situations on connector networks
725 $item = q("SELECT `id`, `mention`, `tag`,`parent`, `title`, `body`, `author-name`, `author-link`, `author-avatar`, `guid`,
726 `parent-uri`, `uri`, `contact-id`
727 FROM `item` WHERE `id` = %d AND `verb` IN ('%s', '') AND `type` != 'activity' AND
728 NOT (`author-link` IN ($profile_list)) LIMIT 1",
729 intval($itemid), dbesc(ACTIVITY_POST));
733 // Generate the notification array
735 $params["uid"] = $uid;
736 $params["notify_flags"] = $user[0]["notify-flags"];
737 $params["language"] = $user[0]["language"];
738 $params["to_name"] = $user[0]["username"];
739 $params["to_email"] = $user[0]["email"];
740 $params["item"] = $item[0];
741 $params["parent"] = $item[0]["parent"];
742 $params["link"] = System::baseUrl().'/display/'.urlencode($item[0]["guid"]);
743 $params["otype"] = 'item';
744 $params["source_name"] = $item[0]["author-name"];
745 $params["source_link"] = $item[0]["author-link"];
746 $params["source_photo"] = $item[0]["author-avatar"];
748 if ($item[0]["parent-uri"] === $item[0]["uri"]) {
749 // Send a notification for every new post?
750 $r = q("SELECT `notify_new_posts` FROM `contact` WHERE `id` = %d AND `notify_new_posts` LIMIT 1",
751 intval($item[0]['contact-id'])
753 $send_notification = DBM::is_result($r);
755 if (!$send_notification) {
756 $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
757 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
759 if (DBM::is_result($tags)) {
760 foreach ($tags AS $tag) {
761 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `notify_new_posts`",
762 normalise_link($tag["url"]), intval($uid));
763 if (DBM::is_result($r))
764 $send_notification = true;
769 if ($send_notification) {
770 $params["type"] = NOTIFY_SHARE;
771 $params["verb"] = ACTIVITY_TAG;
775 // Is the user mentioned in this post?
778 foreach ($profiles AS $profile) {
779 if (strpos($item[0]["tag"], "=".$profile."]") || strpos($item[0]["body"], "=".$profile."]"))
783 if ($item[0]["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
784 $params["type"] = NOTIFY_TAGSELF;
785 $params["verb"] = ACTIVITY_TAG;
788 // Is it a post that the user had started or where he interacted?
789 $parent = q("SELECT `thread`.`iid` FROM `thread` INNER JOIN `item` ON `item`.`parent` = `thread`.`iid`
790 WHERE `thread`.`iid` = %d AND NOT `thread`.`ignored` AND
791 (`thread`.`mention` OR `item`.`author-link` IN ($profile_list))
793 intval($item[0]["parent"]));
795 if ($parent && !isset($params["type"])) {
796 $params["type"] = NOTIFY_COMMENT;
797 $params["verb"] = ACTIVITY_POST;
800 if (isset($params["type"]))
801 notification($params);
805 * @brief Formats a notification message with the notification author
807 * Replace the name with {0} but ensure to make that only once. The {0} is used
808 * later and prints the name in bold.
810 * @param string $name
811 * @param string $message
812 * @return string Formatted message
814 function format_notification_message($name, $message) {
816 $pos = strpos($message, $name);
821 if ($pos !== false) {
822 $message = substr_replace($message, '{0}', $pos, strlen($name));