4 use Friendica\Core\Config;
5 use Friendica\Core\System;
7 require_once('include/Emailer.php');
8 require_once('include/email.php');
9 require_once('include/bbcode.php');
10 require_once('include/html2bbcode.php');
13 * @brief Creates a notification entry and possibly sends a mail
15 * @param array $params Array with the elements:
16 uid, item, parent, type, otype, verb, event,
17 link, subject, body, to_name, to_email, source_name,
18 source_link, activity, preamble, notify_flags,
19 language, show_in_notification_page
21 function notification($params) {
25 // from here on everything is in the recipients language
27 push_lang($params['language']);
29 $banner = t('Friendica Notification');
30 $product = FRIENDICA_PLATFORM;
31 $siteurl = System::baseUrl(true);
32 $thanks = t('Thank You,');
33 $sitename = $a->config['sitename'];
34 if (!x($a->config['admin_name']))
35 $site_admin = sprintf(t('%s Administrator'), $sitename);
37 $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, ':'));
46 $sender_email = $a->config['sender_email'];
47 if (empty($sender_email))
48 $sender_email = t('noreply').'@'.$hostname;
50 if ($params['type'] != SYSTEM_EMAIL) {
51 $user = dba::select('user', array('nickname', 'page-flags'),
52 array('uid' => $params['uid']), array('limit' => 1));
54 // There is no need to create notifications for forum accounts
55 if (!dbm::is_result($user) || in_array($user["page-flags"], array(PAGE_COMMUNITY, PAGE_PRVGROUP))) {
59 $nickname = $user["nickname"];
61 // with $params['show_in_notification_page'] == false, the notification isn't inserted into
62 // the database, and an email is sent if applicable.
63 // default, if not specified: true
64 $show_in_notification_page = ((x($params, 'show_in_notification_page')) ? $params['show_in_notification_page']:true);
66 $additional_mail_header = "";
67 $additional_mail_header .= "Precedence: list\n";
68 $additional_mail_header .= "X-Friendica-Host: ".$hostname."\n";
69 $additional_mail_header .= "X-Friendica-Account: <".$nickname."@".$hostname.">\n";
70 $additional_mail_header .= "X-Friendica-Platform: ".FRIENDICA_PLATFORM."\n";
71 $additional_mail_header .= "X-Friendica-Version: ".FRIENDICA_VERSION."\n";
72 $additional_mail_header .= "List-ID: <notification.".$hostname.">\n";
73 $additional_mail_header .= "List-Archive: <".System::baseUrl()."/notifications/system>\n";
75 if (array_key_exists('item', $params)) {
76 $title = $params['item']['title'];
77 $body = $params['item']['body'];
81 // e.g. "your post", "David's photo", etc.
82 $possess_desc = t('%s <!item_type!>');
84 if (isset($params['item']['id']))
85 $item_id = $params['item']['id'];
89 if (isset($params['parent']))
90 $parent_id = $params['parent'];
94 if ($params['type'] == NOTIFY_MAIL) {
95 $subject = sprintf(t('[Friendica:Notify] New mail received at %s'), $sitename);
97 $preamble = sprintf(t('%1$s sent you a new private message at %2$s.'), $params['source_name'], $sitename);
98 $epreamble = sprintf(t('%1$s sent you %2$s.'), '[url='.$params['source_link'].']'.$params['source_name'].'[/url]', '[url=$itemlink]'.t('a private message').'[/url]');
100 $sitelink = t('Please visit %s to view and/or reply to your private messages.');
101 $tsitelink = sprintf($sitelink, $siteurl.'/message/'.$params['item']['id']);
102 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'/message/'.$params['item']['id'].'">'.$sitename.'</a>');
103 $itemlink = $siteurl.'/message/'.$params['item']['id'];
106 if ($params['type'] == NOTIFY_COMMENT) {
107 $p = q("SELECT `ignored` FROM `thread` WHERE `iid` = %d AND `uid` = %d LIMIT 1",
109 intval($params['uid'])
111 if ($p && count($p) && ($p[0]["ignored"])) {
112 logger("Thread ".$parent_id." will be ignored", LOGGER_DEBUG);
116 // Check to see if there was already a tag notify or comment notify for this post.
117 // If so don't create a second notification
120 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d, %d) AND `link` = '%s' AND `uid` = %d LIMIT 1",
121 intval(NOTIFY_TAGSELF),
122 intval(NOTIFY_COMMENT),
123 intval(NOTIFY_SHARE),
124 dbesc($params['link']),
125 intval($params['uid'])
127 if ($p && count($p)) {
132 // if it's a post figure out who's post it is.
136 if ($params['otype'] === 'item' && $parent_id) {
137 $p = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
139 intval($params['uid'])
143 $item_post_type = item_post_type($p[0]);
146 $dest_str = sprintf(t('%1$s commented on [url=%2$s]a %3$s[/url]'),
147 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
151 // "George Bull's post"
153 $dest_str = sprintf(t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]'),
154 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
156 $p[0]['author-name'],
160 if ($p[0]['owner-name'] == $p[0]['author-name'] && $p[0]['wall'])
161 $dest_str = sprintf(t('%1$s commented on [url=%2$s]your %3$s[/url]'),
162 '[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 $sitelink = $h['sitelink'];
415 $tsitelink = $h['tsitelink'];
416 $hsitelink = $h['hsitelink'];
417 $itemlink = $h['itemlink'];
419 if ($show_in_notification_page) {
420 logger("adding notification entry", LOGGER_DEBUG);
423 $hash = random_string();
424 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' LIMIT 1",
426 if (dbm::is_result($r)) {
429 } while ($dups == true);
431 /// @TODO One statement is enough
433 $datarray['hash'] = $hash;
434 $datarray['name'] = $params['source_name'];
435 $datarray['name_cache'] = strip_tags(bbcode($params['source_name']));
436 $datarray['url'] = $params['source_link'];
437 $datarray['photo'] = $params['source_photo'];
438 $datarray['date'] = datetime_convert();
439 $datarray['uid'] = $params['uid'];
440 $datarray['link'] = $itemlink;
441 $datarray['iid'] = $item_id;
442 $datarray['parent'] = $parent_id;
443 $datarray['type'] = $params['type'];
444 $datarray['verb'] = $params['verb'];
445 $datarray['otype'] = $params['otype'];
446 $datarray['abort'] = false;
448 call_hooks('enotify_store', $datarray);
450 if ($datarray['abort']) {
455 // create notification entry in DB
457 $r = q("INSERT INTO `notify` (`hash`, `name`, `url`, `photo`, `date`, `uid`, `link`, `iid`, `parent`, `type`, `verb`, `otype`, `name_cache`)
458 values('%s', '%s', '%s', '%s', '%s', %d, '%s', %d, %d, %d, '%s', '%s', '%s')",
459 dbesc($datarray['hash']),
460 dbesc($datarray['name']),
461 dbesc($datarray['url']),
462 dbesc($datarray['photo']),
463 dbesc($datarray['date']),
464 intval($datarray['uid']),
465 dbesc($datarray['link']),
466 intval($datarray['iid']),
467 intval($datarray['parent']),
468 intval($datarray['type']),
469 dbesc($datarray['verb']),
470 dbesc($datarray['otype']),
471 dbesc($datarray["name_cache"])
474 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' AND `uid` = %d LIMIT 1",
476 intval($params['uid'])
479 $notify_id = $r[0]['id'];
485 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
486 // After we've stored everything, look again to see if there are any duplicates and if so remove them
489 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
490 intval(NOTIFY_TAGSELF),
491 intval(NOTIFY_COMMENT),
492 dbesc($params['link']),
493 intval($params['uid'])
495 if ($p && (count($p) > 1)) {
496 for ($d = 1; $d < count($p); $d ++) {
497 dba::delete('notify', array('id' => $p[$d]['id']));
500 // only continue on if we stored the first one
502 if ($notify_id != $p[0]['id']) {
509 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
510 $msg = replace_macros($epreamble, array('$itemlink' => $itemlink));
511 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(bbcode($msg)));
512 $r = q("UPDATE `notify` SET `msg` = '%s', `msg_cache` = '%s' WHERE `id` = %d AND `uid` = %d",
516 intval($params['uid'])
520 // send email notification if notification preferences permit
521 if ((intval($params['notify_flags']) & intval($params['type']))
522 || $params['type'] == NOTIFY_SYSTEM
523 || $params['type'] == SYSTEM_EMAIL) {
525 logger('sending notification email');
527 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
528 $id_for_parent = $params['parent']."@".$hostname;
530 // Is this the first email notification for this parent item and user?
532 $r = q("SELECT `id` FROM `notify-threads` WHERE `master-parent-item` = %d AND `receiver-uid` = %d LIMIT 1",
533 intval($params['parent']),
534 intval($params['uid']));
536 // If so, create the record of it and use a message-id smtp header.
539 logger("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), LOGGER_DEBUG);
540 $r = q("INSERT INTO `notify-threads` (`notify-id`, `master-parent-item`, `receiver-uid`, `parent-item`)
541 values(%d, %d, %d, %d)",
543 intval($params['parent']),
544 intval($params['uid']),
547 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
548 $log_msg = "include/enotify: No previous notification found for this parent:\n".
549 " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
550 logger($log_msg, LOGGER_DEBUG);
552 // If not, just "follow" the thread.
553 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
554 logger("There's already a notification for this parent:\n".print_r($r, true), LOGGER_DEBUG);
558 // textversion keeps linebreaks
559 $textversion = strip_tags(str_replace("<br>", "\n", html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n"), "\n",
560 $body))),ENT_QUOTES, 'UTF-8')));
561 $htmlversion = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n\\n", "\\n"),
562 "<br />\n", $body))), ENT_QUOTES, 'UTF-8');
565 $datarray['banner'] = $banner;
566 $datarray['product'] = $product;
567 $datarray['preamble'] = $preamble;
568 $datarray['sitename'] = $sitename;
569 $datarray['siteurl'] = $siteurl;
570 $datarray['type'] = $params['type'];
571 $datarray['parent'] = $params['parent'];
572 $datarray['source_name'] = $params['source_name'];
573 $datarray['source_link'] = $params['source_link'];
574 $datarray['source_photo'] = $params['source_photo'];
575 $datarray['uid'] = $params['uid'];
576 $datarray['username'] = $params['to_name'];
577 $datarray['hsitelink'] = $hsitelink;
578 $datarray['tsitelink'] = $tsitelink;
579 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
580 $datarray['titemlink'] = $itemlink;
581 $datarray['thanks'] = $thanks;
582 $datarray['site_admin'] = $site_admin;
583 $datarray['title'] = stripslashes($title);
584 $datarray['htmlversion'] = $htmlversion;
585 $datarray['textversion'] = $textversion;
586 $datarray['subject'] = $subject;
587 $datarray['headers'] = $additional_mail_header;
589 call_hooks('enotify_mail', $datarray);
591 // check whether sending post content in email notifications is allowed
592 // always true for SYSTEM_EMAIL
593 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
595 // load the template for private message notifications
596 $tpl = get_markup_template('email_notify_html.tpl');
597 $email_html_body = replace_macros($tpl, array(
598 '$banner' => $datarray['banner'],
599 '$product' => $datarray['product'],
600 '$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
601 '$sitename' => $datarray['sitename'],
602 '$siteurl' => $datarray['siteurl'],
603 '$source_name' => $datarray['source_name'],
604 '$source_link' => $datarray['source_link'],
605 '$source_photo' => $datarray['source_photo'],
606 '$username' => $datarray['to_name'],
607 '$hsitelink' => $datarray['hsitelink'],
608 '$hitemlink' => $datarray['hitemlink'],
609 '$thanks' => $datarray['thanks'],
610 '$site_admin' => $datarray['site_admin'],
611 '$title' => $datarray['title'],
612 '$htmlversion' => $datarray['htmlversion'],
613 '$content_allowed' => $content_allowed,
616 // load the template for private message notifications
617 $tpl = get_markup_template('email_notify_text.tpl');
618 $email_text_body = replace_macros($tpl, array(
619 '$banner' => $datarray['banner'],
620 '$product' => $datarray['product'],
621 '$preamble' => $datarray['preamble'],
622 '$sitename' => $datarray['sitename'],
623 '$siteurl' => $datarray['siteurl'],
624 '$source_name' => $datarray['source_name'],
625 '$source_link' => $datarray['source_link'],
626 '$source_photo' => $datarray['source_photo'],
627 '$username' => $datarray['to_name'],
628 '$tsitelink' => $datarray['tsitelink'],
629 '$titemlink' => $datarray['titemlink'],
630 '$thanks' => $datarray['thanks'],
631 '$site_admin' => $datarray['site_admin'],
632 '$title' => $datarray['title'],
633 '$textversion' => $datarray['textversion'],
634 '$content_allowed' => $content_allowed,
637 // use the Emailer class to send the message
639 return Emailer::send(array(
640 'uid' => $params['uid'],
641 'fromName' => $sender_name,
642 'fromEmail' => $sender_email,
643 'replyTo' => $sender_email,
644 'toEmail' => $params['to_email'],
645 'messageSubject' => $datarray['subject'],
646 'htmlVersion' => $email_html_body,
647 'textVersion' => $email_text_body,
648 'additionalMailHeader' => $datarray['headers'],
656 * @brief Checks for item related notifications and sends them
658 * @param int $itemid ID of the item for which the check should be done
659 * @param int $uid User ID
660 * @param str $defaulttype (Optional) Forces a notification with this type.
662 function check_item_notification($itemid, $uid, $defaulttype = "") {
663 $notification_data = array("uid" => $uid, "profiles" => array());
664 call_hooks('check_item_notification', $notification_data);
666 $profiles = $notification_data["profiles"];
668 $user = q("SELECT `notify-flags`, `language`, `username`, `email`, `nickname` FROM `user` WHERE `uid` = %d", intval($uid));
672 $owner = q("SELECT `id`, `url` FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1", intval($uid));
676 // This is our regular URL format
677 $profiles[] = $owner[0]["url"];
679 // Notifications from Diaspora are often with an URL in the Diaspora format
680 $profiles[] = System::baseUrl()."/u/".$user[0]["nickname"];
682 $profiles2 = array();
684 foreach ($profiles AS $profile) {
685 // Check for invalid profile urls. 13 should be the shortest possible profile length:
687 // Additionally check for invalid urls that would return the normalised value "http:"
688 if ((strlen($profile) >= 13) && (normalise_link($profile) != "http:")) {
689 if (!in_array($profile, $profiles2))
690 $profiles2[] = $profile;
692 $profile = normalise_link($profile);
693 if (!in_array($profile, $profiles2))
694 $profiles2[] = $profile;
696 $profile = str_replace("http://", "https://", $profile);
697 if (!in_array($profile, $profiles2))
698 $profiles2[] = $profile;
702 $profiles = $profiles2;
706 foreach ($profiles AS $profile) {
707 if ($profile_list != "")
708 $profile_list .= "', '";
710 $profile_list .= dbesc($profile);
713 $profile_list = "'".$profile_list."'";
715 // Only act if it is a "real" post
716 // We need the additional check for the "local_profile" because of mixed situations on connector networks
717 $item = q("SELECT `id`, `mention`, `tag`,`parent`, `title`, `body`, `author-name`, `author-link`, `author-avatar`, `guid`,
718 `parent-uri`, `uri`, `contact-id`
719 FROM `item` WHERE `id` = %d AND `verb` IN ('%s', '') AND `type` != 'activity' AND
720 NOT (`author-link` IN ($profile_list)) LIMIT 1",
721 intval($itemid), dbesc(ACTIVITY_POST));
725 // Generate the notification array
727 $params["uid"] = $uid;
728 $params["notify_flags"] = $user[0]["notify-flags"];
729 $params["language"] = $user[0]["language"];
730 $params["to_name"] = $user[0]["username"];
731 $params["to_email"] = $user[0]["email"];
732 $params["item"] = $item[0];
733 $params["parent"] = $item[0]["parent"];
734 $params["link"] = System::baseUrl().'/display/'.urlencode($item[0]["guid"]);
735 $params["otype"] = 'item';
736 $params["source_name"] = $item[0]["author-name"];
737 $params["source_link"] = $item[0]["author-link"];
738 $params["source_photo"] = $item[0]["author-avatar"];
740 if ($item[0]["parent-uri"] === $item[0]["uri"]) {
741 // Send a notification for every new post?
742 $r = q("SELECT `notify_new_posts` FROM `contact` WHERE `id` = %d AND `uid` = %d AND `notify_new_posts` LIMIT 1",
743 intval($item[0]['contact-id']),
746 $send_notification = dbm::is_result($r);
748 if (!$send_notification) {
749 $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
750 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
752 if (dbm::is_result($tags)) {
753 foreach ($tags AS $tag) {
754 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `notify_new_posts`",
755 normalise_link($tag["url"]), intval($uid));
756 if (dbm::is_result($r))
757 $send_notification = true;
762 if ($send_notification) {
763 $params["type"] = NOTIFY_SHARE;
764 $params["verb"] = ACTIVITY_TAG;
768 // Is the user mentioned in this post?
771 foreach ($profiles AS $profile) {
772 if (strpos($item[0]["tag"], "=".$profile."]") || strpos($item[0]["body"], "=".$profile."]"))
776 if ($item[0]["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
777 $params["type"] = NOTIFY_TAGSELF;
778 $params["verb"] = ACTIVITY_TAG;
781 // Is it a post that the user had started or where he interacted?
782 $parent = q("SELECT `thread`.`iid` FROM `thread` INNER JOIN `item` ON `item`.`parent` = `thread`.`iid`
783 WHERE `thread`.`iid` = %d AND `thread`.`uid` = %d AND NOT `thread`.`ignored` AND
784 (`thread`.`mention` OR `item`.`author-link` IN ($profile_list))
786 intval($item[0]["parent"]), intval($uid));
788 if ($parent && !isset($params["type"])) {
789 $params["type"] = NOTIFY_COMMENT;
790 $params["verb"] = ACTIVITY_POST;
793 if (isset($params["type"]))
794 notification($params);
798 * @brief Formats a notification message with the notification author
800 * Replace the name with {0} but ensure to make that only once. The {0} is used
801 * later and prints the name in bold.
803 * @param string $name
804 * @param string $message
805 * @return string Formatted message
807 function format_notification_message($name, $message) {
809 $pos = strpos($message, $name);
814 if ($pos !== false) {
815 $message = substr_replace($message, '{0}', $pos, strlen($name));