4 use Friendica\Core\System;
6 require_once('include/Emailer.php');
7 require_once('include/email.php');
8 require_once('include/bbcode.php');
9 require_once('include/html2bbcode.php');
12 * @brief Creates a notification entry and possibly sends a mail
14 * @param array $params Array with the elements:
15 uid, item, parent, type, otype, verb, event,
16 link, subject, body, to_name, to_email, source_name,
17 source_link, activity, preamble, notify_flags,
18 language, show_in_notification_page
20 function notification($params) {
24 // from here on everything is in the recipients language
26 push_lang($params['language']);
28 $banner = t('Friendica Notification');
29 $product = FRIENDICA_PLATFORM;
30 $siteurl = System::baseUrl(true);
31 $thanks = t('Thank You,');
32 $sitename = $a->config['sitename'];
33 if (!x($a->config['admin_name']))
34 $site_admin = sprintf(t('%s Administrator'), $sitename);
36 $site_admin = sprintf(t('%1$s, %2$s Administrator'), $a->config['admin_name'], $sitename);
40 $sender_name = $sitename;
41 $hostname = $a->get_hostname();
42 if (strpos($hostname, ':'))
43 $hostname = substr($hostname, 0, strpos($hostname, ':'));
45 $sender_email = $a->config['sender_email'];
46 if (empty($sender_email))
47 $sender_email = t('noreply').'@'.$hostname;
49 if ($params['type'] != SYSTEM_EMAIL) {
50 $user = dba::select('user', array('nickname', 'page-flags'),
51 array('uid' => $params['uid']), array('limit' => 1));
53 // There is no need to create notifications for forum accounts
54 if (!dbm::is_result($user) || in_array($user["page-flags"], array(PAGE_COMMUNITY, PAGE_PRVGROUP))) {
58 $nickname = $user["nickname"];
60 // with $params['show_in_notification_page'] == false, the notification isn't inserted into
61 // the database, and an email is sent if applicable.
62 // default, if not specified: true
63 $show_in_notification_page = ((x($params, 'show_in_notification_page')) ? $params['show_in_notification_page']:true);
65 $additional_mail_header = "";
66 $additional_mail_header .= "Precedence: list\n";
67 $additional_mail_header .= "X-Friendica-Host: ".$hostname."\n";
68 $additional_mail_header .= "X-Friendica-Account: <".$nickname."@".$hostname.">\n";
69 $additional_mail_header .= "X-Friendica-Platform: ".FRIENDICA_PLATFORM."\n";
70 $additional_mail_header .= "X-Friendica-Version: ".FRIENDICA_VERSION."\n";
71 $additional_mail_header .= "List-ID: <notification.".$hostname.">\n";
72 $additional_mail_header .= "List-Archive: <".System::baseUrl()."/notifications/system>\n";
74 if (array_key_exists('item', $params)) {
75 $title = $params['item']['title'];
76 $body = $params['item']['body'];
80 // e.g. "your post", "David's photo", etc.
81 $possess_desc = t('%s <!item_type!>');
83 if (isset($params['item']['id']))
84 $item_id = $params['item']['id'];
88 if (isset($params['parent']))
89 $parent_id = $params['parent'];
93 if ($params['type'] == NOTIFY_MAIL) {
94 $subject = sprintf(t('[Friendica:Notify] New mail received at %s'), $sitename);
96 $preamble = sprintf(t('%1$s sent you a new private message at %2$s.'), $params['source_name'], $sitename);
97 $epreamble = sprintf(t('%1$s sent you %2$s.'), '[url='.$params['source_link'].']'.$params['source_name'].'[/url]', '[url=$itemlink]'.t('a private message').'[/url]');
99 $sitelink = t('Please visit %s to view and/or reply to your private messages.');
100 $tsitelink = sprintf($sitelink, $siteurl.'/message/'.$params['item']['id']);
101 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'/message/'.$params['item']['id'].'">'.$sitename.'</a>');
102 $itemlink = $siteurl.'/message/'.$params['item']['id'];
105 if ($params['type'] == NOTIFY_COMMENT) {
106 $p = q("SELECT `ignored` FROM `thread` WHERE `iid` = %d AND `uid` = %d LIMIT 1",
108 intval($params['uid'])
110 if ($p && count($p) && ($p[0]["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
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 AND `uid` = %d LIMIT 1",
138 intval($params['uid'])
142 $item_post_type = item_post_type($p[0]);
145 $dest_str = sprintf(t('%1$s commented on [url=%2$s]a %3$s[/url]'),
146 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
150 // "George Bull's post"
152 $dest_str = sprintf(t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]'),
153 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
155 $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]',
165 // Some mail softwares relies on subject field for threading.
166 // So, we cannot have different subjects for notifications of the same thread.
167 // Before this we have the name of the replier on the subject rendering
168 // differents subjects for messages on the same thread.
170 $subject = sprintf(t('[Friendica:Notify] Comment to conversation #%1$d by %2$s'), $parent_id, $params['source_name']);
172 $preamble = sprintf(t('%s commented on an item/conversation you have been following.'), $params['source_name']);
173 $epreamble = $dest_str;
175 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
176 $tsitelink = sprintf($sitelink, $siteurl);
177 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
178 $itemlink = $params['link'];
181 if ($params['type'] == NOTIFY_WALL) {
182 $subject = sprintf(t('[Friendica:Notify] %s posted to your profile wall'), $params['source_name']);
184 $preamble = sprintf(t('%1$s posted to your profile wall at %2$s'), $params['source_name'], $sitename);
185 $epreamble = sprintf(t('%1$s posted to [url=%2$s]your wall[/url]'),
186 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
189 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
190 $tsitelink = sprintf($sitelink, $siteurl);
191 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
192 $itemlink = $params['link'];
195 if ($params['type'] == NOTIFY_TAGSELF) {
196 $subject = sprintf(t('[Friendica:Notify] %s tagged you'), $params['source_name']);
198 $preamble = sprintf(t('%1$s tagged you at %2$s'), $params['source_name'], $sitename);
199 $epreamble = sprintf(t('%1$s [url=%2$s]tagged you[/url].'),
200 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
203 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
204 $tsitelink = sprintf($sitelink, $siteurl);
205 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
206 $itemlink = $params['link'];
209 if ($params['type'] == NOTIFY_SHARE) {
210 $subject = sprintf(t('[Friendica:Notify] %s shared a new post'), $params['source_name']);
212 $preamble = sprintf(t('%1$s shared a new post at %2$s'), $params['source_name'], $sitename);
213 $epreamble = sprintf(t('%1$s [url=%2$s]shared a post[/url].'),
214 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
217 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
218 $tsitelink = sprintf($sitelink, $siteurl);
219 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
220 $itemlink = $params['link'];
223 if ($params['type'] == NOTIFY_POKE) {
224 $subject = sprintf(t('[Friendica:Notify] %1$s poked you'), $params['source_name']);
226 $preamble = sprintf(t('%1$s poked you at %2$s'), $params['source_name'], $sitename);
227 $epreamble = sprintf(t('%1$s [url=%2$s]poked you[/url].'),
228 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
231 $subject = str_replace('poked', t($params['activity']), $subject);
232 $preamble = str_replace('poked', t($params['activity']), $preamble);
233 $epreamble = str_replace('poked', t($params['activity']), $epreamble);
235 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
236 $tsitelink = sprintf($sitelink, $siteurl);
237 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
238 $itemlink = $params['link'];
241 if ($params['type'] == NOTIFY_TAGSHARE) {
242 $subject = sprintf(t('[Friendica:Notify] %s tagged your post'), $params['source_name']);
244 $preamble = sprintf(t('%1$s tagged your post at %2$s'), $params['source_name'], $sitename);
245 $epreamble = sprintf(t('%1$s tagged [url=%2$s]your post[/url]'),
246 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
249 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
250 $tsitelink = sprintf($sitelink, $siteurl);
251 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
252 $itemlink = $params['link'];
255 if ($params['type'] == NOTIFY_INTRO) {
256 $subject = sprintf(t('[Friendica:Notify] Introduction received'));
258 $preamble = sprintf(t('You\'ve received an introduction from \'%1$s\' at %2$s'), $params['source_name'], $sitename);
259 $epreamble = sprintf(t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.'),
261 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
263 $body = sprintf(t('You may visit their profile at %s'), $params['source_link']);
265 $sitelink = t('Please visit %s to approve or reject the introduction.');
266 $tsitelink = sprintf($sitelink, $siteurl);
267 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
268 $itemlink = $params['link'];
270 switch ($params['verb']) {
271 case ACTIVITY_FRIEND:
272 // someone started to share with user (mostly OStatus)
273 $subject = sprintf(t('[Friendica:Notify] A new person is sharing with you'));
275 $preamble = sprintf(t('%1$s is sharing with you at %2$s'), $params['source_name'], $sitename);
276 $epreamble = sprintf(t('%1$s is sharing with you at %2$s'),
277 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
280 case ACTIVITY_FOLLOW:
281 // someone started to follow the user (mostly OStatus)
282 $subject = sprintf(t('[Friendica:Notify] You have a new follower'));
284 $preamble = sprintf(t('You have a new follower at %2$s : %1$s'), $params['source_name'], $sitename);
285 $epreamble = sprintf(t('You have a new follower at %2$s : %1$s'),
286 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
290 // ACTIVITY_REQ_FRIEND is default activity for notifications
295 if ($params['type'] == NOTIFY_SUGGEST) {
296 $subject = sprintf(t('[Friendica:Notify] Friend suggestion received'));
298 $preamble = sprintf(t('You\'ve received a friend suggestion from \'%1$s\' at %2$s'), $params['source_name'], $sitename);
299 $epreamble = sprintf(t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.'),
301 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
302 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
304 $body = t('Name:').' '.$params['item']['name']."\n";
305 $body .= t('Photo:').' '.$params['item']['photo']."\n";
306 $body .= sprintf(t('You may visit their profile at %s'), $params['item']['url']);
308 $sitelink = t('Please visit %s to approve or reject the suggestion.');
309 $tsitelink = sprintf($sitelink, $siteurl);
310 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
311 $itemlink = $params['link'];
314 if ($params['type'] == NOTIFY_CONFIRM) {
315 if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
316 $subject = sprintf(t('[Friendica:Notify] Connection accepted'));
318 $preamble = sprintf(t('\'%1$s\' has accepted your connection request at %2$s'), $params['source_name'], $sitename);
319 $epreamble = sprintf(t('%2$s has accepted your [url=%1$s]connection request[/url].'),
321 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
323 $body = t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
325 $sitelink = t('Please visit %s if you wish to make any changes to this relationship.');
326 $tsitelink = sprintf($sitelink, $siteurl);
327 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
328 $itemlink = $params['link'];
329 } else { // ACTIVITY_FOLLOW
330 $subject = sprintf(t('[Friendica:Notify] Connection accepted'));
332 $preamble = sprintf(t('\'%1$s\' has accepted your connection request at %2$s'), $params['source_name'], $sitename);
333 $epreamble = sprintf(t('%2$s has accepted your [url=%1$s]connection request[/url].'),
335 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
337 $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']);
339 $body .= sprintf(t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.'), $params['source_name']);
341 $sitelink = t('Please visit %s if you wish to make any changes to this relationship.');
342 $tsitelink = sprintf($sitelink, $siteurl);
343 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
344 $itemlink = $params['link'];
348 if ($params['type'] == NOTIFY_SYSTEM) {
349 switch($params['event']) {
350 case "SYSTEM_REGISTER_REQUEST":
351 $subject = sprintf(t('[Friendica System:Notify] registration request'));
353 $preamble = sprintf(t('You\'ve received a registration request from \'%1$s\' at %2$s'), $params['source_name'], $sitename);
354 $epreamble = sprintf(t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.'),
356 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
358 $body = sprintf(t('Full Name: %1$s\nSite Location: %2$s\nLogin Name: %3$s (%4$s)'),
359 $params['source_name'], $siteurl, $params['source_mail'], $params['source_nick']);
361 $sitelink = t('Please visit %s to approve or reject the request.');
362 $tsitelink = sprintf($sitelink, $params['link']);
363 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
364 $itemlink = $params['link'];
366 case "SYSTEM_DB_UPDATE_FAIL":
371 if ($params['type'] == SYSTEM_EMAIL) {
372 // not part of the notifications.
373 // it just send a mail to the user.
374 // It will be used by the system to send emails to users (like
375 // password reset, invitations and so) using one look (but without
376 // add a notification to the user, with could be inexistent)
377 $subject = $params['subject'];
379 $preamble = $params['preamble'];
381 $body = $params['body'];
387 $show_in_notification_page = false;
390 $subject .= " (".$nickname."@".$hostname.")";
394 'subject' => $subject,
395 'preamble' => $preamble,
396 'epreamble' => $epreamble,
398 'sitelink' => $sitelink,
399 'tsitelink' => $tsitelink,
400 'hsitelink' => $hsitelink,
401 'itemlink' => $itemlink
404 call_hooks('enotify', $h);
406 $subject = $h['subject'];
408 $preamble = $h['preamble'];
409 $epreamble = $h['epreamble'];
413 $sitelink = $h['sitelink'];
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
456 $r = q("INSERT INTO `notify` (`hash`, `name`, `url`, `photo`, `date`, `uid`, `link`, `iid`, `parent`, `type`, `verb`, `otype`, `name_cache`)
457 values('%s', '%s', '%s', '%s', '%s', %d, '%s', %d, %d, %d, '%s', '%s', '%s')",
458 dbesc($datarray['hash']),
459 dbesc($datarray['name']),
460 dbesc($datarray['url']),
461 dbesc($datarray['photo']),
462 dbesc($datarray['date']),
463 intval($datarray['uid']),
464 dbesc($datarray['link']),
465 intval($datarray['iid']),
466 intval($datarray['parent']),
467 intval($datarray['type']),
468 dbesc($datarray['verb']),
469 dbesc($datarray['otype']),
470 dbesc($datarray["name_cache"])
473 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' AND `uid` = %d LIMIT 1",
475 intval($params['uid'])
478 $notify_id = $r[0]['id'];
484 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
485 // After we've stored everything, look again to see if there are any duplicates and if so remove them
488 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
489 intval(NOTIFY_TAGSELF),
490 intval(NOTIFY_COMMENT),
491 dbesc($params['link']),
492 intval($params['uid'])
494 if ($p && (count($p) > 1)) {
495 for ($d = 1; $d < count($p); $d ++) {
496 dba::delete('notify', array('id' => $p[$d]['id']));
499 // only continue on if we stored the first one
501 if ($notify_id != $p[0]['id']) {
508 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
509 $msg = replace_macros($epreamble, array('$itemlink' => $itemlink));
510 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(bbcode($msg)));
511 $r = q("UPDATE `notify` SET `msg` = '%s', `msg_cache` = '%s' WHERE `id` = %d AND `uid` = %d",
515 intval($params['uid'])
519 // send email notification if notification preferences permit
520 if ((intval($params['notify_flags']) & intval($params['type']))
521 || $params['type'] == NOTIFY_SYSTEM
522 || $params['type'] == SYSTEM_EMAIL) {
524 logger('sending notification email');
526 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
527 $id_for_parent = $params['parent']."@".$hostname;
529 // Is this the first email notification for this parent item and user?
531 $r = q("SELECT `id` FROM `notify-threads` WHERE `master-parent-item` = %d AND `receiver-uid` = %d LIMIT 1",
532 intval($params['parent']),
533 intval($params['uid']));
535 // If so, create the record of it and use a message-id smtp header.
538 logger("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), LOGGER_DEBUG);
539 $r = q("INSERT INTO `notify-threads` (`notify-id`, `master-parent-item`, `receiver-uid`, `parent-item`)
540 values(%d, %d, %d, %d)",
542 intval($params['parent']),
543 intval($params['uid']),
546 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
547 $log_msg = "include/enotify: No previous notification found for this parent:\n".
548 " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
549 logger($log_msg, LOGGER_DEBUG);
551 // If not, just "follow" the thread.
552 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
553 logger("There's already a notification for this parent:\n".print_r($r, true), LOGGER_DEBUG);
557 // textversion keeps linebreaks
558 $textversion = strip_tags(str_replace("<br>", "\n", html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n"), "\n",
559 $body))),ENT_QUOTES, 'UTF-8')));
560 $htmlversion = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n\\n", "\\n"),
561 "<br />\n", $body))), ENT_QUOTES, 'UTF-8');
564 $datarray['banner'] = $banner;
565 $datarray['product'] = $product;
566 $datarray['preamble'] = $preamble;
567 $datarray['sitename'] = $sitename;
568 $datarray['siteurl'] = $siteurl;
569 $datarray['type'] = $params['type'];
570 $datarray['parent'] = $params['parent'];
571 $datarray['source_name'] = $params['source_name'];
572 $datarray['source_link'] = $params['source_link'];
573 $datarray['source_photo'] = $params['source_photo'];
574 $datarray['uid'] = $params['uid'];
575 $datarray['username'] = $params['to_name'];
576 $datarray['hsitelink'] = $hsitelink;
577 $datarray['tsitelink'] = $tsitelink;
578 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
579 $datarray['titemlink'] = $itemlink;
580 $datarray['thanks'] = $thanks;
581 $datarray['site_admin'] = $site_admin;
582 $datarray['title'] = stripslashes($title);
583 $datarray['htmlversion'] = $htmlversion;
584 $datarray['textversion'] = $textversion;
585 $datarray['subject'] = $subject;
586 $datarray['headers'] = $additional_mail_header;
588 call_hooks('enotify_mail', $datarray);
590 // check whether sending post content in email notifications is allowed
591 // always true for SYSTEM_EMAIL
592 $content_allowed = ((!get_config('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
594 // load the template for private message notifications
595 $tpl = get_markup_template('email_notify_html.tpl');
596 $email_html_body = replace_macros($tpl, array(
597 '$banner' => $datarray['banner'],
598 '$product' => $datarray['product'],
599 '$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
600 '$sitename' => $datarray['sitename'],
601 '$siteurl' => $datarray['siteurl'],
602 '$source_name' => $datarray['source_name'],
603 '$source_link' => $datarray['source_link'],
604 '$source_photo' => $datarray['source_photo'],
605 '$username' => $datarray['to_name'],
606 '$hsitelink' => $datarray['hsitelink'],
607 '$hitemlink' => $datarray['hitemlink'],
608 '$thanks' => $datarray['thanks'],
609 '$site_admin' => $datarray['site_admin'],
610 '$title' => $datarray['title'],
611 '$htmlversion' => $datarray['htmlversion'],
612 '$content_allowed' => $content_allowed,
615 // load the template for private message notifications
616 $tpl = get_markup_template('email_notify_text.tpl');
617 $email_text_body = replace_macros($tpl, array(
618 '$banner' => $datarray['banner'],
619 '$product' => $datarray['product'],
620 '$preamble' => $datarray['preamble'],
621 '$sitename' => $datarray['sitename'],
622 '$siteurl' => $datarray['siteurl'],
623 '$source_name' => $datarray['source_name'],
624 '$source_link' => $datarray['source_link'],
625 '$source_photo' => $datarray['source_photo'],
626 '$username' => $datarray['to_name'],
627 '$tsitelink' => $datarray['tsitelink'],
628 '$titemlink' => $datarray['titemlink'],
629 '$thanks' => $datarray['thanks'],
630 '$site_admin' => $datarray['site_admin'],
631 '$title' => $datarray['title'],
632 '$textversion' => $datarray['textversion'],
633 '$content_allowed' => $content_allowed,
636 // use the Emailer class to send the message
638 return Emailer::send(array(
639 'uid' => $params['uid'],
640 'fromName' => $sender_name,
641 'fromEmail' => $sender_email,
642 'replyTo' => $sender_email,
643 'toEmail' => $params['to_email'],
644 'messageSubject' => $datarray['subject'],
645 'htmlVersion' => $email_html_body,
646 'textVersion' => $email_text_body,
647 'additionalMailHeader' => $datarray['headers'],
655 * @brief Checks for item related notifications and sends them
657 * @param int $itemid ID of the item for which the check should be done
658 * @param int $uid User ID
659 * @param str $defaulttype (Optional) Forces a notification with this type.
661 function check_item_notification($itemid, $uid, $defaulttype = "") {
662 $notification_data = array("uid" => $uid, "profiles" => array());
663 call_hooks('check_item_notification', $notification_data);
665 $profiles = $notification_data["profiles"];
667 $user = q("SELECT `notify-flags`, `language`, `username`, `email`, `nickname` FROM `user` WHERE `uid` = %d", intval($uid));
671 $owner = q("SELECT `id`, `url` FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1", intval($uid));
675 // This is our regular URL format
676 $profiles[] = $owner[0]["url"];
678 // Notifications from Diaspora are often with an URL in the Diaspora format
679 $profiles[] = System::baseUrl()."/u/".$user[0]["nickname"];
681 $profiles2 = array();
683 foreach ($profiles AS $profile) {
684 // Check for invalid profile urls. 13 should be the shortest possible profile length:
686 // Additionally check for invalid urls that would return the normalised value "http:"
687 if ((strlen($profile) >= 13) && (normalise_link($profile) != "http:")) {
688 if (!in_array($profile, $profiles2))
689 $profiles2[] = $profile;
691 $profile = normalise_link($profile);
692 if (!in_array($profile, $profiles2))
693 $profiles2[] = $profile;
695 $profile = str_replace("http://", "https://", $profile);
696 if (!in_array($profile, $profiles2))
697 $profiles2[] = $profile;
701 $profiles = $profiles2;
705 foreach ($profiles AS $profile) {
706 if ($profile_list != "")
707 $profile_list .= "', '";
709 $profile_list .= dbesc($profile);
712 $profile_list = "'".$profile_list."'";
714 // Only act if it is a "real" post
715 // We need the additional check for the "local_profile" because of mixed situations on connector networks
716 $item = q("SELECT `id`, `mention`, `tag`,`parent`, `title`, `body`, `author-name`, `author-link`, `author-avatar`, `guid`,
717 `parent-uri`, `uri`, `contact-id`
718 FROM `item` WHERE `id` = %d AND `verb` IN ('%s', '') AND `type` != 'activity' AND
719 NOT (`author-link` IN ($profile_list)) LIMIT 1",
720 intval($itemid), dbesc(ACTIVITY_POST));
724 // Generate the notification array
726 $params["uid"] = $uid;
727 $params["notify_flags"] = $user[0]["notify-flags"];
728 $params["language"] = $user[0]["language"];
729 $params["to_name"] = $user[0]["username"];
730 $params["to_email"] = $user[0]["email"];
731 $params["item"] = $item[0];
732 $params["parent"] = $item[0]["parent"];
733 $params["link"] = System::baseUrl().'/display/'.urlencode($item[0]["guid"]);
734 $params["otype"] = 'item';
735 $params["source_name"] = $item[0]["author-name"];
736 $params["source_link"] = $item[0]["author-link"];
737 $params["source_photo"] = $item[0]["author-avatar"];
739 if ($item[0]["parent-uri"] === $item[0]["uri"]) {
740 // Send a notification for every new post?
741 $r = q("SELECT `notify_new_posts` FROM `contact` WHERE `id` = %d AND `uid` = %d AND `notify_new_posts` LIMIT 1",
742 intval($item[0]['contact-id']),
745 $send_notification = dbm::is_result($r);
747 if (!$send_notification) {
748 $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
749 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
751 if (dbm::is_result($tags)) {
752 foreach ($tags AS $tag) {
753 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `notify_new_posts`",
754 normalise_link($tag["url"]), intval($uid));
755 if (dbm::is_result($r))
756 $send_notification = true;
761 if ($send_notification) {
762 $params["type"] = NOTIFY_SHARE;
763 $params["verb"] = ACTIVITY_TAG;
767 // Is the user mentioned in this post?
770 foreach ($profiles AS $profile) {
771 if (strpos($item[0]["tag"], "=".$profile."]") || strpos($item[0]["body"], "=".$profile."]"))
775 if ($item[0]["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
776 $params["type"] = NOTIFY_TAGSELF;
777 $params["verb"] = ACTIVITY_TAG;
780 // Is it a post that the user had started or where he interacted?
781 $parent = q("SELECT `thread`.`iid` FROM `thread` INNER JOIN `item` ON `item`.`parent` = `thread`.`iid`
782 WHERE `thread`.`iid` = %d AND `thread`.`uid` = %d AND NOT `thread`.`ignored` AND
783 (`thread`.`mention` OR `item`.`author-link` IN ($profile_list))
785 intval($item[0]["parent"]), intval($uid));
787 if ($parent && !isset($params["type"])) {
788 $params["type"] = NOTIFY_COMMENT;
789 $params["verb"] = ACTIVITY_POST;
792 if (isset($params["type"]))
793 notification($params);
797 * @brief Formats a notification message with the notification author
799 * Replace the name with {0} but ensure to make that only once. The {0} is used
800 * later and prints the name in bold.
802 * @param string $name
803 * @param string $message
804 * @return string Formatted message
806 function format_notification_message($name, $message) {
808 $pos = strpos($message, $name);
813 if ($pos !== false) {
814 $message = substr_replace($message, '{0}', $pos, strlen($name));