4 use Friendica\Core\Config;
5 use Friendica\Core\System;
6 use Friendica\Database\DBM;
8 require_once('include/Emailer.php');
9 require_once('include/email.php');
10 require_once('include/bbcode.php');
11 require_once('include/html2bbcode.php');
14 * @brief Creates a notification entry and possibly sends a mail
16 * @param array $params Array with the elements:
17 uid, item, parent, type, otype, verb, event,
18 link, subject, body, to_name, to_email, source_name,
19 source_link, activity, preamble, notify_flags,
20 language, show_in_notification_page
22 function notification($params) {
26 // 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);
42 $sender_name = $sitename;
43 $hostname = $a->get_hostname();
44 if (strpos($hostname, ':'))
45 $hostname = substr($hostname, 0, strpos($hostname, ':'));
47 $sender_email = $a->config['sender_email'];
48 if (empty($sender_email))
49 $sender_email = t('noreply').'@'.$hostname;
51 if ($params['type'] != SYSTEM_EMAIL) {
52 $user = dba::select('user', array('nickname', 'page-flags'),
53 array('uid' => $params['uid']), array('limit' => 1));
55 // There is no need to create notifications for forum accounts
56 if (!DBM::is_result($user) || in_array($user["page-flags"], array(PAGE_COMMUNITY, PAGE_PRVGROUP))) {
60 $nickname = $user["nickname"];
62 // with $params['show_in_notification_page'] == false, the notification isn't inserted into
63 // the database, and an email is sent if applicable.
64 // default, if not specified: true
65 $show_in_notification_page = ((x($params, 'show_in_notification_page')) ? $params['show_in_notification_page']:true);
67 $additional_mail_header = "";
68 $additional_mail_header .= "Precedence: list\n";
69 $additional_mail_header .= "X-Friendica-Host: ".$hostname."\n";
70 $additional_mail_header .= "X-Friendica-Account: <".$nickname."@".$hostname.">\n";
71 $additional_mail_header .= "X-Friendica-Platform: ".FRIENDICA_PLATFORM."\n";
72 $additional_mail_header .= "X-Friendica-Version: ".FRIENDICA_VERSION."\n";
73 $additional_mail_header .= "List-ID: <notification.".$hostname.">\n";
74 $additional_mail_header .= "List-Archive: <".System::baseUrl()."/notifications/system>\n";
76 if (array_key_exists('item', $params)) {
77 $title = $params['item']['title'];
78 $body = $params['item']['body'];
82 // e.g. "your post", "David's photo", etc.
83 $possess_desc = t('%s <!item_type!>');
85 if (isset($params['item']['id']))
86 $item_id = $params['item']['id'];
90 if (isset($params['parent']))
91 $parent_id = $params['parent'];
95 if ($params['type'] == NOTIFY_MAIL) {
96 $subject = sprintf(t('[Friendica:Notify] New mail received at %s'), $sitename);
98 $preamble = sprintf(t('%1$s sent you a new private message at %2$s.'), $params['source_name'], $sitename);
99 $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 $sitelink = t('Please visit %s to view and/or reply to your private messages.');
102 $tsitelink = sprintf($sitelink, $siteurl.'/message/'.$params['item']['id']);
103 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'/message/'.$params['item']['id'].'">'.$sitename.'</a>');
104 $itemlink = $siteurl.'/message/'.$params['item']['id'];
107 if ($params['type'] == NOTIFY_COMMENT) {
108 $p = q("SELECT `ignored` FROM `thread` WHERE `iid` = %d AND `uid` = %d LIMIT 1",
110 intval($params['uid'])
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
121 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d, %d) AND `link` = '%s' AND `uid` = %d LIMIT 1",
122 intval(NOTIFY_TAGSELF),
123 intval(NOTIFY_COMMENT),
124 intval(NOTIFY_SHARE),
125 dbesc($params['link']),
126 intval($params['uid'])
128 if ($p && count($p)) {
133 // if it's a post figure out who's post it is.
137 if ($params['otype'] === 'item' && $parent_id) {
138 $p = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
140 intval($params['uid'])
144 $item_post_type = item_post_type($p[0]);
147 $dest_str = sprintf(t('%1$s commented on [url=%2$s]a %3$s[/url]'),
148 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
152 // "George Bull's post"
154 $dest_str = sprintf(t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]'),
155 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
157 $p[0]['author-name'],
161 if ($p[0]['owner-name'] == $p[0]['author-name'] && $p[0]['wall'])
162 $dest_str = sprintf(t('%1$s commented on [url=%2$s]your %3$s[/url]'),
163 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
167 // Some mail softwares relies on subject field for threading.
168 // So, we cannot have different subjects for notifications of the same thread.
169 // Before this we have the name of the replier on the subject rendering
170 // differents subjects for messages on the same thread.
172 $subject = sprintf(t('[Friendica:Notify] Comment to conversation #%1$d by %2$s'), $parent_id, $params['source_name']);
174 $preamble = sprintf(t('%s commented on an item/conversation you have been following.'), $params['source_name']);
175 $epreamble = $dest_str;
177 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
178 $tsitelink = sprintf($sitelink, $siteurl);
179 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
180 $itemlink = $params['link'];
183 if ($params['type'] == NOTIFY_WALL) {
184 $subject = sprintf(t('[Friendica:Notify] %s posted to your profile wall'), $params['source_name']);
186 $preamble = sprintf(t('%1$s posted to your profile wall at %2$s'), $params['source_name'], $sitename);
187 $epreamble = sprintf(t('%1$s posted to [url=%2$s]your wall[/url]'),
188 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
191 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
192 $tsitelink = sprintf($sitelink, $siteurl);
193 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
194 $itemlink = $params['link'];
197 if ($params['type'] == NOTIFY_TAGSELF) {
198 $subject = sprintf(t('[Friendica:Notify] %s tagged you'), $params['source_name']);
200 $preamble = sprintf(t('%1$s tagged you at %2$s'), $params['source_name'], $sitename);
201 $epreamble = sprintf(t('%1$s [url=%2$s]tagged you[/url].'),
202 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
205 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
206 $tsitelink = sprintf($sitelink, $siteurl);
207 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
208 $itemlink = $params['link'];
211 if ($params['type'] == NOTIFY_SHARE) {
212 $subject = sprintf(t('[Friendica:Notify] %s shared a new post'), $params['source_name']);
214 $preamble = sprintf(t('%1$s shared a new post at %2$s'), $params['source_name'], $sitename);
215 $epreamble = sprintf(t('%1$s [url=%2$s]shared a post[/url].'),
216 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
219 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
220 $tsitelink = sprintf($sitelink, $siteurl);
221 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
222 $itemlink = $params['link'];
225 if ($params['type'] == NOTIFY_POKE) {
226 $subject = sprintf(t('[Friendica:Notify] %1$s poked you'), $params['source_name']);
228 $preamble = sprintf(t('%1$s poked you at %2$s'), $params['source_name'], $sitename);
229 $epreamble = sprintf(t('%1$s [url=%2$s]poked you[/url].'),
230 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
233 $subject = str_replace('poked', t($params['activity']), $subject);
234 $preamble = str_replace('poked', t($params['activity']), $preamble);
235 $epreamble = str_replace('poked', t($params['activity']), $epreamble);
237 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
238 $tsitelink = sprintf($sitelink, $siteurl);
239 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
240 $itemlink = $params['link'];
243 if ($params['type'] == NOTIFY_TAGSHARE) {
244 $subject = sprintf(t('[Friendica:Notify] %s tagged your post'), $params['source_name']);
246 $preamble = sprintf(t('%1$s tagged your post at %2$s'), $params['source_name'], $sitename);
247 $epreamble = sprintf(t('%1$s tagged [url=%2$s]your post[/url]'),
248 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
251 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
252 $tsitelink = sprintf($sitelink, $siteurl);
253 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
254 $itemlink = $params['link'];
257 if ($params['type'] == NOTIFY_INTRO) {
258 $subject = sprintf(t('[Friendica:Notify] Introduction received'));
260 $preamble = sprintf(t('You\'ve received an introduction from \'%1$s\' at %2$s'), $params['source_name'], $sitename);
261 $epreamble = sprintf(t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.'),
263 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
265 $body = sprintf(t('You may visit their profile at %s'), $params['source_link']);
267 $sitelink = t('Please visit %s to approve or reject the introduction.');
268 $tsitelink = sprintf($sitelink, $siteurl);
269 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
270 $itemlink = $params['link'];
272 switch ($params['verb']) {
273 case ACTIVITY_FRIEND:
274 // someone started to share with user (mostly OStatus)
275 $subject = sprintf(t('[Friendica:Notify] A new person is sharing with you'));
277 $preamble = sprintf(t('%1$s is sharing with you at %2$s'), $params['source_name'], $sitename);
278 $epreamble = sprintf(t('%1$s is sharing with you at %2$s'),
279 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
282 case ACTIVITY_FOLLOW:
283 // someone started to follow the user (mostly OStatus)
284 $subject = sprintf(t('[Friendica:Notify] You have a new follower'));
286 $preamble = sprintf(t('You have a new follower at %2$s : %1$s'), $params['source_name'], $sitename);
287 $epreamble = sprintf(t('You have a new follower at %2$s : %1$s'),
288 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
292 // ACTIVITY_REQ_FRIEND is default activity for notifications
297 if ($params['type'] == NOTIFY_SUGGEST) {
298 $subject = sprintf(t('[Friendica:Notify] Friend suggestion received'));
300 $preamble = sprintf(t('You\'ve received a friend suggestion from \'%1$s\' at %2$s'), $params['source_name'], $sitename);
301 $epreamble = sprintf(t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.'),
303 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
304 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
306 $body = t('Name:').' '.$params['item']['name']."\n";
307 $body .= t('Photo:').' '.$params['item']['photo']."\n";
308 $body .= sprintf(t('You may visit their profile at %s'), $params['item']['url']);
310 $sitelink = t('Please visit %s to approve or reject the suggestion.');
311 $tsitelink = sprintf($sitelink, $siteurl);
312 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
313 $itemlink = $params['link'];
316 if ($params['type'] == NOTIFY_CONFIRM) {
317 if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
318 $subject = sprintf(t('[Friendica:Notify] Connection accepted'));
320 $preamble = sprintf(t('\'%1$s\' has accepted your connection request at %2$s'), $params['source_name'], $sitename);
321 $epreamble = sprintf(t('%2$s has accepted your [url=%1$s]connection request[/url].'),
323 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
325 $body = t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
327 $sitelink = t('Please visit %s if you wish to make any changes to this relationship.');
328 $tsitelink = sprintf($sitelink, $siteurl);
329 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
330 $itemlink = $params['link'];
331 } else { // ACTIVITY_FOLLOW
332 $subject = sprintf(t('[Friendica:Notify] Connection accepted'));
334 $preamble = sprintf(t('\'%1$s\' has accepted your connection request at %2$s'), $params['source_name'], $sitename);
335 $epreamble = sprintf(t('%2$s has accepted your [url=%1$s]connection request[/url].'),
337 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
339 $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']);
341 $body .= sprintf(t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.'), $params['source_name']);
343 $sitelink = t('Please visit %s if you wish to make any changes to this relationship.');
344 $tsitelink = sprintf($sitelink, $siteurl);
345 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
346 $itemlink = $params['link'];
350 if ($params['type'] == NOTIFY_SYSTEM) {
351 switch($params['event']) {
352 case "SYSTEM_REGISTER_REQUEST":
353 $subject = sprintf(t('[Friendica System:Notify] registration request'));
355 $preamble = sprintf(t('You\'ve received a registration request from \'%1$s\' at %2$s'), $params['source_name'], $sitename);
356 $epreamble = sprintf(t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.'),
358 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
360 $body = sprintf(t('Full Name: %1$s\nSite Location: %2$s\nLogin Name: %3$s (%4$s)'),
361 $params['source_name'], $siteurl, $params['source_mail'], $params['source_nick']);
363 $sitelink = t('Please visit %s to approve or reject the request.');
364 $tsitelink = sprintf($sitelink, $params['link']);
365 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
366 $itemlink = $params['link'];
368 case "SYSTEM_DB_UPDATE_FAIL":
373 if ($params['type'] == SYSTEM_EMAIL) {
374 // not part of the notifications.
375 // it just send a mail to the user.
376 // It will be used by the system to send emails to users (like
377 // password reset, invitations and so) using one look (but without
378 // add a notification to the user, with could be inexistent)
379 $subject = $params['subject'];
381 $preamble = $params['preamble'];
383 $body = $params['body'];
389 $show_in_notification_page = false;
392 $subject .= " (".$nickname."@".$hostname.")";
396 'subject' => $subject,
397 'preamble' => $preamble,
398 'epreamble' => $epreamble,
400 'sitelink' => $sitelink,
401 'tsitelink' => $tsitelink,
402 'hsitelink' => $hsitelink,
403 'itemlink' => $itemlink
406 call_hooks('enotify', $h);
408 $subject = $h['subject'];
410 $preamble = $h['preamble'];
411 $epreamble = $h['epreamble'];
415 $sitelink = $h['sitelink'];
416 $tsitelink = $h['tsitelink'];
417 $hsitelink = $h['hsitelink'];
418 $itemlink = $h['itemlink'];
420 if ($show_in_notification_page) {
421 logger("adding notification entry", LOGGER_DEBUG);
424 $hash = random_string();
425 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' LIMIT 1",
427 if (DBM::is_result($r)) {
430 } while ($dups == true);
432 /// @TODO One statement is enough
434 $datarray['hash'] = $hash;
435 $datarray['name'] = $params['source_name'];
436 $datarray['name_cache'] = strip_tags(bbcode($params['source_name']));
437 $datarray['url'] = $params['source_link'];
438 $datarray['photo'] = $params['source_photo'];
439 $datarray['date'] = datetime_convert();
440 $datarray['uid'] = $params['uid'];
441 $datarray['link'] = $itemlink;
442 $datarray['iid'] = $item_id;
443 $datarray['parent'] = $parent_id;
444 $datarray['type'] = $params['type'];
445 $datarray['verb'] = $params['verb'];
446 $datarray['otype'] = $params['otype'];
447 $datarray['abort'] = false;
449 call_hooks('enotify_store', $datarray);
451 if ($datarray['abort']) {
456 // create notification entry in DB
458 $r = q("INSERT INTO `notify` (`hash`, `name`, `url`, `photo`, `date`, `uid`, `link`, `iid`, `parent`, `type`, `verb`, `otype`, `name_cache`)
459 values('%s', '%s', '%s', '%s', '%s', %d, '%s', %d, %d, %d, '%s', '%s', '%s')",
460 dbesc($datarray['hash']),
461 dbesc($datarray['name']),
462 dbesc($datarray['url']),
463 dbesc($datarray['photo']),
464 dbesc($datarray['date']),
465 intval($datarray['uid']),
466 dbesc($datarray['link']),
467 intval($datarray['iid']),
468 intval($datarray['parent']),
469 intval($datarray['type']),
470 dbesc($datarray['verb']),
471 dbesc($datarray['otype']),
472 dbesc($datarray["name_cache"])
475 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' AND `uid` = %d LIMIT 1",
477 intval($params['uid'])
480 $notify_id = $r[0]['id'];
486 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
487 // After we've stored everything, look again to see if there are any duplicates and if so remove them
490 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
491 intval(NOTIFY_TAGSELF),
492 intval(NOTIFY_COMMENT),
493 dbesc($params['link']),
494 intval($params['uid'])
496 if ($p && (count($p) > 1)) {
497 for ($d = 1; $d < count($p); $d ++) {
498 dba::delete('notify', array('id' => $p[$d]['id']));
501 // only continue on if we stored the first one
503 if ($notify_id != $p[0]['id']) {
510 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
511 $msg = replace_macros($epreamble, array('$itemlink' => $itemlink));
512 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(bbcode($msg)));
513 $r = q("UPDATE `notify` SET `msg` = '%s', `msg_cache` = '%s' WHERE `id` = %d AND `uid` = %d",
517 intval($params['uid'])
521 // send email notification if notification preferences permit
522 if ((intval($params['notify_flags']) & intval($params['type']))
523 || $params['type'] == NOTIFY_SYSTEM
524 || $params['type'] == SYSTEM_EMAIL) {
526 logger('sending notification email');
528 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
529 $id_for_parent = $params['parent']."@".$hostname;
531 // Is this the first email notification for this parent item and user?
533 $r = q("SELECT `id` FROM `notify-threads` WHERE `master-parent-item` = %d AND `receiver-uid` = %d LIMIT 1",
534 intval($params['parent']),
535 intval($params['uid']));
537 // If so, create the record of it and use a message-id smtp header.
540 logger("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), LOGGER_DEBUG);
541 $r = q("INSERT INTO `notify-threads` (`notify-id`, `master-parent-item`, `receiver-uid`, `parent-item`)
542 values(%d, %d, %d, %d)",
544 intval($params['parent']),
545 intval($params['uid']),
548 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
549 $log_msg = "include/enotify: No previous notification found for this parent:\n".
550 " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
551 logger($log_msg, LOGGER_DEBUG);
553 // If not, just "follow" the thread.
554 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
555 logger("There's already a notification for this parent:\n".print_r($r, true), LOGGER_DEBUG);
559 // textversion keeps linebreaks
560 $textversion = strip_tags(str_replace("<br>", "\n", html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n"), "\n",
561 $body))),ENT_QUOTES, 'UTF-8')));
562 $htmlversion = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n\\n", "\\n"),
563 "<br />\n", $body))), ENT_QUOTES, 'UTF-8');
566 $datarray['banner'] = $banner;
567 $datarray['product'] = $product;
568 $datarray['preamble'] = $preamble;
569 $datarray['sitename'] = $sitename;
570 $datarray['siteurl'] = $siteurl;
571 $datarray['type'] = $params['type'];
572 $datarray['parent'] = $params['parent'];
573 $datarray['source_name'] = $params['source_name'];
574 $datarray['source_link'] = $params['source_link'];
575 $datarray['source_photo'] = $params['source_photo'];
576 $datarray['uid'] = $params['uid'];
577 $datarray['username'] = $params['to_name'];
578 $datarray['hsitelink'] = $hsitelink;
579 $datarray['tsitelink'] = $tsitelink;
580 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
581 $datarray['titemlink'] = $itemlink;
582 $datarray['thanks'] = $thanks;
583 $datarray['site_admin'] = $site_admin;
584 $datarray['title'] = stripslashes($title);
585 $datarray['htmlversion'] = $htmlversion;
586 $datarray['textversion'] = $textversion;
587 $datarray['subject'] = $subject;
588 $datarray['headers'] = $additional_mail_header;
590 call_hooks('enotify_mail', $datarray);
592 // check whether sending post content in email notifications is allowed
593 // always true for SYSTEM_EMAIL
594 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
596 // load the template for private message notifications
597 $tpl = get_markup_template('email_notify_html.tpl');
598 $email_html_body = replace_macros($tpl, array(
599 '$banner' => $datarray['banner'],
600 '$product' => $datarray['product'],
601 '$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
602 '$sitename' => $datarray['sitename'],
603 '$siteurl' => $datarray['siteurl'],
604 '$source_name' => $datarray['source_name'],
605 '$source_link' => $datarray['source_link'],
606 '$source_photo' => $datarray['source_photo'],
607 '$username' => $datarray['to_name'],
608 '$hsitelink' => $datarray['hsitelink'],
609 '$hitemlink' => $datarray['hitemlink'],
610 '$thanks' => $datarray['thanks'],
611 '$site_admin' => $datarray['site_admin'],
612 '$title' => $datarray['title'],
613 '$htmlversion' => $datarray['htmlversion'],
614 '$content_allowed' => $content_allowed,
617 // load the template for private message notifications
618 $tpl = get_markup_template('email_notify_text.tpl');
619 $email_text_body = replace_macros($tpl, array(
620 '$banner' => $datarray['banner'],
621 '$product' => $datarray['product'],
622 '$preamble' => $datarray['preamble'],
623 '$sitename' => $datarray['sitename'],
624 '$siteurl' => $datarray['siteurl'],
625 '$source_name' => $datarray['source_name'],
626 '$source_link' => $datarray['source_link'],
627 '$source_photo' => $datarray['source_photo'],
628 '$username' => $datarray['to_name'],
629 '$tsitelink' => $datarray['tsitelink'],
630 '$titemlink' => $datarray['titemlink'],
631 '$thanks' => $datarray['thanks'],
632 '$site_admin' => $datarray['site_admin'],
633 '$title' => $datarray['title'],
634 '$textversion' => $datarray['textversion'],
635 '$content_allowed' => $content_allowed,
638 // use the Emailer class to send the message
640 return Emailer::send(array(
641 'uid' => $params['uid'],
642 'fromName' => $sender_name,
643 'fromEmail' => $sender_email,
644 'replyTo' => $sender_email,
645 'toEmail' => $params['to_email'],
646 'messageSubject' => $datarray['subject'],
647 'htmlVersion' => $email_html_body,
648 'textVersion' => $email_text_body,
649 'additionalMailHeader' => $datarray['headers'],
657 * @brief Checks for item related notifications and sends them
659 * @param int $itemid ID of the item for which the check should be done
660 * @param int $uid User ID
661 * @param str $defaulttype (Optional) Forces a notification with this type.
663 function check_item_notification($itemid, $uid, $defaulttype = "") {
664 $notification_data = array("uid" => $uid, "profiles" => array());
665 call_hooks('check_item_notification', $notification_data);
667 $profiles = $notification_data["profiles"];
669 $user = q("SELECT `notify-flags`, `language`, `username`, `email`, `nickname` FROM `user` WHERE `uid` = %d", intval($uid));
673 $owner = q("SELECT `id`, `url` FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1", intval($uid));
677 // This is our regular URL format
678 $profiles[] = $owner[0]["url"];
680 // Notifications from Diaspora are often with an URL in the Diaspora format
681 $profiles[] = System::baseUrl()."/u/".$user[0]["nickname"];
683 $profiles2 = array();
685 foreach ($profiles AS $profile) {
686 // Check for invalid profile urls. 13 should be the shortest possible profile length:
688 // Additionally check for invalid urls that would return the normalised value "http:"
689 if ((strlen($profile) >= 13) && (normalise_link($profile) != "http:")) {
690 if (!in_array($profile, $profiles2))
691 $profiles2[] = $profile;
693 $profile = normalise_link($profile);
694 if (!in_array($profile, $profiles2))
695 $profiles2[] = $profile;
697 $profile = str_replace("http://", "https://", $profile);
698 if (!in_array($profile, $profiles2))
699 $profiles2[] = $profile;
703 $profiles = $profiles2;
707 foreach ($profiles AS $profile) {
708 if ($profile_list != "")
709 $profile_list .= "', '";
711 $profile_list .= dbesc($profile);
714 $profile_list = "'".$profile_list."'";
716 // Only act if it is a "real" post
717 // We need the additional check for the "local_profile" because of mixed situations on connector networks
718 $item = q("SELECT `id`, `mention`, `tag`,`parent`, `title`, `body`, `author-name`, `author-link`, `author-avatar`, `guid`,
719 `parent-uri`, `uri`, `contact-id`
720 FROM `item` WHERE `id` = %d AND `verb` IN ('%s', '') AND `type` != 'activity' AND
721 NOT (`author-link` IN ($profile_list)) LIMIT 1",
722 intval($itemid), dbesc(ACTIVITY_POST));
726 // Generate the notification array
728 $params["uid"] = $uid;
729 $params["notify_flags"] = $user[0]["notify-flags"];
730 $params["language"] = $user[0]["language"];
731 $params["to_name"] = $user[0]["username"];
732 $params["to_email"] = $user[0]["email"];
733 $params["item"] = $item[0];
734 $params["parent"] = $item[0]["parent"];
735 $params["link"] = System::baseUrl().'/display/'.urlencode($item[0]["guid"]);
736 $params["otype"] = 'item';
737 $params["source_name"] = $item[0]["author-name"];
738 $params["source_link"] = $item[0]["author-link"];
739 $params["source_photo"] = $item[0]["author-avatar"];
741 if ($item[0]["parent-uri"] === $item[0]["uri"]) {
742 // Send a notification for every new post?
743 $r = q("SELECT `notify_new_posts` FROM `contact` WHERE `id` = %d AND `uid` = %d AND `notify_new_posts` LIMIT 1",
744 intval($item[0]['contact-id']),
747 $send_notification = DBM::is_result($r);
749 if (!$send_notification) {
750 $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
751 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
753 if (DBM::is_result($tags)) {
754 foreach ($tags AS $tag) {
755 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `notify_new_posts`",
756 normalise_link($tag["url"]), intval($uid));
757 if (DBM::is_result($r))
758 $send_notification = true;
763 if ($send_notification) {
764 $params["type"] = NOTIFY_SHARE;
765 $params["verb"] = ACTIVITY_TAG;
769 // Is the user mentioned in this post?
772 foreach ($profiles AS $profile) {
773 if (strpos($item[0]["tag"], "=".$profile."]") || strpos($item[0]["body"], "=".$profile."]"))
777 if ($item[0]["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
778 $params["type"] = NOTIFY_TAGSELF;
779 $params["verb"] = ACTIVITY_TAG;
782 // Is it a post that the user had started or where he interacted?
783 $parent = q("SELECT `thread`.`iid` FROM `thread` INNER JOIN `item` ON `item`.`parent` = `thread`.`iid`
784 WHERE `thread`.`iid` = %d AND `thread`.`uid` = %d AND NOT `thread`.`ignored` AND
785 (`thread`.`mention` OR `item`.`author-link` IN ($profile_list))
787 intval($item[0]["parent"]), intval($uid));
789 if ($parent && !isset($params["type"])) {
790 $params["type"] = NOTIFY_COMMENT;
791 $params["verb"] = ACTIVITY_POST;
794 if (isset($params["type"]))
795 notification($params);
799 * @brief Formats a notification message with the notification author
801 * Replace the name with {0} but ensure to make that only once. The {0} is used
802 * later and prints the name in bold.
804 * @param string $name
805 * @param string $message
806 * @return string Formatted message
808 function format_notification_message($name, $message) {
810 $pos = strpos($message, $name);
815 if ($pos !== false) {
816 $message = substr_replace($message, '{0}', $pos, strlen($name));