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 $user = dba::select('user', array('nickname', 'page-flags'),
50 array('uid' => $params['uid']), array('limit' => 1));
52 // There is no need to create notifications for forum accounts
53 if (!dbm::is_result($user) || in_array($user["page-flags"], array(PAGE_COMMUNITY, PAGE_PRVGROUP))) {
56 $nickname = $user["nickname"];
58 // with $params['show_in_notification_page'] == false, the notification isn't inserted into
59 // the database, and an email is sent if applicable.
60 // default, if not specified: true
61 $show_in_notification_page = ((x($params, 'show_in_notification_page')) ? $params['show_in_notification_page']:true);
63 $additional_mail_header = "";
64 $additional_mail_header .= "Precedence: list\n";
65 $additional_mail_header .= "X-Friendica-Host: ".$hostname."\n";
66 $additional_mail_header .= "X-Friendica-Account: <".$nickname."@".$hostname.">\n";
67 $additional_mail_header .= "X-Friendica-Platform: ".FRIENDICA_PLATFORM."\n";
68 $additional_mail_header .= "X-Friendica-Version: ".FRIENDICA_VERSION."\n";
69 $additional_mail_header .= "List-ID: <notification.".$hostname.">\n";
70 $additional_mail_header .= "List-Archive: <".System::baseUrl()."/notifications/system>\n";
72 if (array_key_exists('item', $params)) {
73 $title = $params['item']['title'];
74 $body = $params['item']['body'];
78 // e.g. "your post", "David's photo", etc.
79 $possess_desc = t('%s <!item_type!>');
81 if (isset($params['item']['id']))
82 $item_id = $params['item']['id'];
86 if (isset($params['parent']))
87 $parent_id = $params['parent'];
91 if ($params['type'] == NOTIFY_MAIL) {
92 $subject = sprintf(t('[Friendica:Notify] New mail received at %s'), $sitename);
94 $preamble = sprintf(t('%1$s sent you a new private message at %2$s.'), $params['source_name'], $sitename);
95 $epreamble = sprintf(t('%1$s sent you %2$s.'), '[url='.$params['source_link'].']'.$params['source_name'].'[/url]', '[url=$itemlink]'.t('a private message').'[/url]');
97 $sitelink = t('Please visit %s to view and/or reply to your private messages.');
98 $tsitelink = sprintf($sitelink, $siteurl.'/message/'.$params['item']['id']);
99 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'/message/'.$params['item']['id'].'">'.$sitename.'</a>');
100 $itemlink = $siteurl.'/message/'.$params['item']['id'];
103 if ($params['type'] == NOTIFY_COMMENT) {
104 $p = q("SELECT `ignored` FROM `thread` WHERE `iid` = %d AND `uid` = %d LIMIT 1",
106 intval($params['uid'])
108 if ($p && count($p) && ($p[0]["ignored"])) {
109 logger("Thread ".$parent_id." will be ignored", LOGGER_DEBUG);
113 // Check to see if there was already a tag notify or comment notify for this post.
114 // If so don't create a second notification
117 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d, %d) AND `link` = '%s' AND `uid` = %d LIMIT 1",
118 intval(NOTIFY_TAGSELF),
119 intval(NOTIFY_COMMENT),
120 intval(NOTIFY_SHARE),
121 dbesc($params['link']),
122 intval($params['uid'])
124 if ($p && count($p)) {
129 // if it's a post figure out who's post it is.
133 if ($params['otype'] === 'item' && $parent_id) {
134 $p = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
136 intval($params['uid'])
140 $item_post_type = item_post_type($p[0]);
143 $dest_str = sprintf(t('%1$s commented on [url=%2$s]a %3$s[/url]'),
144 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
148 // "George Bull's post"
150 $dest_str = sprintf(t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]'),
151 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
153 $p[0]['author-name'],
157 if ($p[0]['owner-name'] == $p[0]['author-name'] && $p[0]['wall'])
158 $dest_str = sprintf(t('%1$s commented on [url=%2$s]your %3$s[/url]'),
159 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
163 // Some mail softwares relies on subject field for threading.
164 // So, we cannot have different subjects for notifications of the same thread.
165 // Before this we have the name of the replier on the subject rendering
166 // differents subjects for messages on the same thread.
168 $subject = sprintf(t('[Friendica:Notify] Comment to conversation #%1$d by %2$s'), $parent_id, $params['source_name']);
170 $preamble = sprintf(t('%s commented on an item/conversation you have been following.'), $params['source_name']);
171 $epreamble = $dest_str;
173 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
174 $tsitelink = sprintf($sitelink, $siteurl);
175 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
176 $itemlink = $params['link'];
179 if ($params['type'] == NOTIFY_WALL) {
180 $subject = sprintf(t('[Friendica:Notify] %s posted to your profile wall'), $params['source_name']);
182 $preamble = sprintf(t('%1$s posted to your profile wall at %2$s'), $params['source_name'], $sitename);
183 $epreamble = sprintf(t('%1$s posted to [url=%2$s]your wall[/url]'),
184 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
187 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
188 $tsitelink = sprintf($sitelink, $siteurl);
189 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
190 $itemlink = $params['link'];
193 if ($params['type'] == NOTIFY_TAGSELF) {
194 $subject = sprintf(t('[Friendica:Notify] %s tagged you'), $params['source_name']);
196 $preamble = sprintf(t('%1$s tagged you at %2$s'), $params['source_name'], $sitename);
197 $epreamble = sprintf(t('%1$s [url=%2$s]tagged you[/url].'),
198 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
201 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
202 $tsitelink = sprintf($sitelink, $siteurl);
203 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
204 $itemlink = $params['link'];
207 if ($params['type'] == NOTIFY_SHARE) {
208 $subject = sprintf(t('[Friendica:Notify] %s shared a new post'), $params['source_name']);
210 $preamble = sprintf(t('%1$s shared a new post at %2$s'), $params['source_name'], $sitename);
211 $epreamble = sprintf(t('%1$s [url=%2$s]shared a post[/url].'),
212 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
215 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
216 $tsitelink = sprintf($sitelink, $siteurl);
217 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
218 $itemlink = $params['link'];
221 if ($params['type'] == NOTIFY_POKE) {
222 $subject = sprintf(t('[Friendica:Notify] %1$s poked you'), $params['source_name']);
224 $preamble = sprintf(t('%1$s poked you at %2$s'), $params['source_name'], $sitename);
225 $epreamble = sprintf(t('%1$s [url=%2$s]poked you[/url].'),
226 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
229 $subject = str_replace('poked', t($params['activity']), $subject);
230 $preamble = str_replace('poked', t($params['activity']), $preamble);
231 $epreamble = str_replace('poked', t($params['activity']), $epreamble);
233 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
234 $tsitelink = sprintf($sitelink, $siteurl);
235 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
236 $itemlink = $params['link'];
239 if ($params['type'] == NOTIFY_TAGSHARE) {
240 $subject = sprintf(t('[Friendica:Notify] %s tagged your post'), $params['source_name']);
242 $preamble = sprintf(t('%1$s tagged your post at %2$s'), $params['source_name'], $sitename);
243 $epreamble = sprintf(t('%1$s tagged [url=%2$s]your post[/url]'),
244 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
247 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
248 $tsitelink = sprintf($sitelink, $siteurl);
249 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
250 $itemlink = $params['link'];
253 if ($params['type'] == NOTIFY_INTRO) {
254 $subject = sprintf(t('[Friendica:Notify] Introduction received'));
256 $preamble = sprintf(t('You\'ve received an introduction from \'%1$s\' at %2$s'), $params['source_name'], $sitename);
257 $epreamble = sprintf(t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.'),
259 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
261 $body = sprintf(t('You may visit their profile at %s'), $params['source_link']);
263 $sitelink = t('Please visit %s to approve or reject the introduction.');
264 $tsitelink = sprintf($sitelink, $siteurl);
265 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
266 $itemlink = $params['link'];
268 switch ($params['verb']) {
269 case ACTIVITY_FRIEND:
270 // someone started to share with user (mostly OStatus)
271 $subject = sprintf(t('[Friendica:Notify] A new person is sharing with you'));
273 $preamble = sprintf(t('%1$s is sharing with you at %2$s'), $params['source_name'], $sitename);
274 $epreamble = sprintf(t('%1$s is sharing with you at %2$s'),
275 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
278 case ACTIVITY_FOLLOW:
279 // someone started to follow the user (mostly OStatus)
280 $subject = sprintf(t('[Friendica:Notify] You have a new follower'));
282 $preamble = sprintf(t('You have a new follower at %2$s : %1$s'), $params['source_name'], $sitename);
283 $epreamble = sprintf(t('You have a new follower at %2$s : %1$s'),
284 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
288 // ACTIVITY_REQ_FRIEND is default activity for notifications
293 if ($params['type'] == NOTIFY_SUGGEST) {
294 $subject = sprintf(t('[Friendica:Notify] Friend suggestion received'));
296 $preamble = sprintf(t('You\'ve received a friend suggestion from \'%1$s\' at %2$s'), $params['source_name'], $sitename);
297 $epreamble = sprintf(t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.'),
299 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
300 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
302 $body = t('Name:').' '.$params['item']['name']."\n";
303 $body .= t('Photo:').' '.$params['item']['photo']."\n";
304 $body .= sprintf(t('You may visit their profile at %s'), $params['item']['url']);
306 $sitelink = t('Please visit %s to approve or reject the suggestion.');
307 $tsitelink = sprintf($sitelink, $siteurl);
308 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
309 $itemlink = $params['link'];
312 if ($params['type'] == NOTIFY_CONFIRM) {
313 if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
314 $subject = sprintf(t('[Friendica:Notify] Connection accepted'));
316 $preamble = sprintf(t('\'%1$s\' has accepted your connection request at %2$s'), $params['source_name'], $sitename);
317 $epreamble = sprintf(t('%2$s has accepted your [url=%1$s]connection request[/url].'),
319 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
321 $body = t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
323 $sitelink = t('Please visit %s if you wish to make any changes to this relationship.');
324 $tsitelink = sprintf($sitelink, $siteurl);
325 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
326 $itemlink = $params['link'];
327 } else { // ACTIVITY_FOLLOW
328 $subject = sprintf(t('[Friendica:Notify] Connection accepted'));
330 $preamble = sprintf(t('\'%1$s\' has accepted your connection request at %2$s'), $params['source_name'], $sitename);
331 $epreamble = sprintf(t('%2$s has accepted your [url=%1$s]connection request[/url].'),
333 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
335 $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']);
337 $body .= sprintf(t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.'), $params['source_name']);
339 $sitelink = t('Please visit %s if you wish to make any changes to this relationship.');
340 $tsitelink = sprintf($sitelink, $siteurl);
341 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
342 $itemlink = $params['link'];
346 if ($params['type'] == NOTIFY_SYSTEM) {
347 switch($params['event']) {
348 case "SYSTEM_REGISTER_REQUEST":
349 $subject = sprintf(t('[Friendica System:Notify] registration request'));
351 $preamble = sprintf(t('You\'ve received a registration request from \'%1$s\' at %2$s'), $params['source_name'], $sitename);
352 $epreamble = sprintf(t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.'),
354 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
356 $body = sprintf(t('Full Name: %1$s\nSite Location: %2$s\nLogin Name: %3$s (%4$s)'),
357 $params['source_name'], $siteurl, $params['source_mail'], $params['source_nick']);
359 $sitelink = t('Please visit %s to approve or reject the request.');
360 $tsitelink = sprintf($sitelink, $params['link']);
361 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
362 $itemlink = $params['link'];
364 case "SYSTEM_DB_UPDATE_FAIL":
369 if ($params['type'] == "SYSTEM_EMAIL") {
370 // not part of the notifications.
371 // it just send a mail to the user.
372 // It will be used by the system to send emails to users (like
373 // password reset, invitations and so) using one look (but without
374 // add a notification to the user, with could be inexistent)
375 $subject = $params['subject'];
377 $preamble = $params['preamble'];
379 $body = $params['body'];
385 $show_in_notification_page = false;
388 $subject .= " (".$nickname."@".$hostname.")";
392 'subject' => $subject,
393 'preamble' => $preamble,
394 'epreamble' => $epreamble,
396 'sitelink' => $sitelink,
397 'tsitelink' => $tsitelink,
398 'hsitelink' => $hsitelink,
399 'itemlink' => $itemlink
402 call_hooks('enotify', $h);
404 $subject = $h['subject'];
406 $preamble = $h['preamble'];
407 $epreamble = $h['epreamble'];
411 $sitelink = $h['sitelink'];
412 $tsitelink = $h['tsitelink'];
413 $hsitelink = $h['hsitelink'];
414 $itemlink = $h['itemlink'];
416 if ($show_in_notification_page) {
417 logger("adding notification entry", LOGGER_DEBUG);
420 $hash = random_string();
421 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' LIMIT 1",
423 if (dbm::is_result($r)) {
426 } while ($dups == true);
428 /// @TODO One statement is enough
430 $datarray['hash'] = $hash;
431 $datarray['name'] = $params['source_name'];
432 $datarray['name_cache'] = strip_tags(bbcode($params['source_name']));
433 $datarray['url'] = $params['source_link'];
434 $datarray['photo'] = $params['source_photo'];
435 $datarray['date'] = datetime_convert();
436 $datarray['uid'] = $params['uid'];
437 $datarray['link'] = $itemlink;
438 $datarray['iid'] = $item_id;
439 $datarray['parent'] = $parent_id;
440 $datarray['type'] = $params['type'];
441 $datarray['verb'] = $params['verb'];
442 $datarray['otype'] = $params['otype'];
443 $datarray['abort'] = false;
445 call_hooks('enotify_store', $datarray);
447 if ($datarray['abort']) {
452 // create notification entry in DB
454 $r = q("INSERT INTO `notify` (`hash`, `name`, `url`, `photo`, `date`, `uid`, `link`, `iid`, `parent`, `type`, `verb`, `otype`, `name_cache`)
455 values('%s', '%s', '%s', '%s', '%s', %d, '%s', %d, %d, %d, '%s', '%s', '%s')",
456 dbesc($datarray['hash']),
457 dbesc($datarray['name']),
458 dbesc($datarray['url']),
459 dbesc($datarray['photo']),
460 dbesc($datarray['date']),
461 intval($datarray['uid']),
462 dbesc($datarray['link']),
463 intval($datarray['iid']),
464 intval($datarray['parent']),
465 intval($datarray['type']),
466 dbesc($datarray['verb']),
467 dbesc($datarray['otype']),
468 dbesc($datarray["name_cache"])
471 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' AND `uid` = %d LIMIT 1",
473 intval($params['uid'])
476 $notify_id = $r[0]['id'];
482 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
483 // After we've stored everything, look again to see if there are any duplicates and if so remove them
486 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
487 intval(NOTIFY_TAGSELF),
488 intval(NOTIFY_COMMENT),
489 dbesc($params['link']),
490 intval($params['uid'])
492 if ($p && (count($p) > 1)) {
493 for ($d = 1; $d < count($p); $d ++) {
494 dba::delete('notify', array('id' => $p[$d]['id']));
497 // only continue on if we stored the first one
499 if ($notify_id != $p[0]['id']) {
506 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
507 $msg = replace_macros($epreamble, array('$itemlink' => $itemlink));
508 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(bbcode($msg)));
509 $r = q("UPDATE `notify` SET `msg` = '%s', `msg_cache` = '%s' WHERE `id` = %d AND `uid` = %d",
513 intval($params['uid'])
517 // send email notification if notification preferences permit
518 if ((intval($params['notify_flags']) & intval($params['type']))
519 || $params['type'] == NOTIFY_SYSTEM
520 || $params['type'] == "SYSTEM_EMAIL") {
522 logger('sending notification email');
524 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
525 $id_for_parent = $params['parent']."@".$hostname;
527 // Is this the first email notification for this parent item and user?
529 $r = q("SELECT `id` FROM `notify-threads` WHERE `master-parent-item` = %d AND `receiver-uid` = %d LIMIT 1",
530 intval($params['parent']),
531 intval($params['uid']));
533 // If so, create the record of it and use a message-id smtp header.
536 logger("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), LOGGER_DEBUG);
537 $r = q("INSERT INTO `notify-threads` (`notify-id`, `master-parent-item`, `receiver-uid`, `parent-item`)
538 values(%d, %d, %d, %d)",
540 intval($params['parent']),
541 intval($params['uid']),
544 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
545 $log_msg = "include/enotify: No previous notification found for this parent:\n".
546 " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
547 logger($log_msg, LOGGER_DEBUG);
549 // If not, just "follow" the thread.
550 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
551 logger("There's already a notification for this parent:\n".print_r($r, true), LOGGER_DEBUG);
555 // textversion keeps linebreaks
556 $textversion = strip_tags(str_replace("<br>", "\n", html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n"), "\n",
557 $body))),ENT_QUOTES, 'UTF-8')));
558 $htmlversion = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n\\n", "\\n"),
559 "<br />\n", $body))), ENT_QUOTES, 'UTF-8');
562 $datarray['banner'] = $banner;
563 $datarray['product'] = $product;
564 $datarray['preamble'] = $preamble;
565 $datarray['sitename'] = $sitename;
566 $datarray['siteurl'] = $siteurl;
567 $datarray['type'] = $params['type'];
568 $datarray['parent'] = $params['parent'];
569 $datarray['source_name'] = $params['source_name'];
570 $datarray['source_link'] = $params['source_link'];
571 $datarray['source_photo'] = $params['source_photo'];
572 $datarray['uid'] = $params['uid'];
573 $datarray['username'] = $params['to_name'];
574 $datarray['hsitelink'] = $hsitelink;
575 $datarray['tsitelink'] = $tsitelink;
576 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
577 $datarray['titemlink'] = $itemlink;
578 $datarray['thanks'] = $thanks;
579 $datarray['site_admin'] = $site_admin;
580 $datarray['title'] = stripslashes($title);
581 $datarray['htmlversion'] = $htmlversion;
582 $datarray['textversion'] = $textversion;
583 $datarray['subject'] = $subject;
584 $datarray['headers'] = $additional_mail_header;
586 call_hooks('enotify_mail', $datarray);
588 // check whether sending post content in email notifications is allowed
589 // always true for "SYSTEM_EMAIL"
590 $content_allowed = ((!get_config('system', 'enotify_no_content')) || ($params['type'] == "SYSTEM_EMAIL"));
592 // load the template for private message notifications
593 $tpl = get_markup_template('email_notify_html.tpl');
594 $email_html_body = replace_macros($tpl, array(
595 '$banner' => $datarray['banner'],
596 '$product' => $datarray['product'],
597 '$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
598 '$sitename' => $datarray['sitename'],
599 '$siteurl' => $datarray['siteurl'],
600 '$source_name' => $datarray['source_name'],
601 '$source_link' => $datarray['source_link'],
602 '$source_photo' => $datarray['source_photo'],
603 '$username' => $datarray['to_name'],
604 '$hsitelink' => $datarray['hsitelink'],
605 '$hitemlink' => $datarray['hitemlink'],
606 '$thanks' => $datarray['thanks'],
607 '$site_admin' => $datarray['site_admin'],
608 '$title' => $datarray['title'],
609 '$htmlversion' => $datarray['htmlversion'],
610 '$content_allowed' => $content_allowed,
613 // load the template for private message notifications
614 $tpl = get_markup_template('email_notify_text.tpl');
615 $email_text_body = replace_macros($tpl, array(
616 '$banner' => $datarray['banner'],
617 '$product' => $datarray['product'],
618 '$preamble' => $datarray['preamble'],
619 '$sitename' => $datarray['sitename'],
620 '$siteurl' => $datarray['siteurl'],
621 '$source_name' => $datarray['source_name'],
622 '$source_link' => $datarray['source_link'],
623 '$source_photo' => $datarray['source_photo'],
624 '$username' => $datarray['to_name'],
625 '$tsitelink' => $datarray['tsitelink'],
626 '$titemlink' => $datarray['titemlink'],
627 '$thanks' => $datarray['thanks'],
628 '$site_admin' => $datarray['site_admin'],
629 '$title' => $datarray['title'],
630 '$textversion' => $datarray['textversion'],
631 '$content_allowed' => $content_allowed,
634 // use the Emailer class to send the message
636 return Emailer::send(array(
637 'uid' => $params['uid'],
638 'fromName' => $sender_name,
639 'fromEmail' => $sender_email,
640 'replyTo' => $sender_email,
641 'toEmail' => $params['to_email'],
642 'messageSubject' => $datarray['subject'],
643 'htmlVersion' => $email_html_body,
644 'textVersion' => $email_text_body,
645 'additionalMailHeader' => $datarray['headers'],
653 * @brief Checks for item related notifications and sends them
655 * @param int $itemid ID of the item for which the check should be done
656 * @param int $uid User ID
657 * @param str $defaulttype (Optional) Forces a notification with this type.
659 function check_item_notification($itemid, $uid, $defaulttype = "") {
660 $notification_data = array("uid" => $uid, "profiles" => array());
661 call_hooks('check_item_notification', $notification_data);
663 $profiles = $notification_data["profiles"];
665 $user = q("SELECT `notify-flags`, `language`, `username`, `email`, `nickname` FROM `user` WHERE `uid` = %d", intval($uid));
669 $owner = q("SELECT `id`, `url` FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1", intval($uid));
673 // This is our regular URL format
674 $profiles[] = $owner[0]["url"];
676 // Notifications from Diaspora are often with an URL in the Diaspora format
677 $profiles[] = System::baseUrl()."/u/".$user[0]["nickname"];
679 $profiles2 = array();
681 foreach ($profiles AS $profile) {
682 // Check for invalid profile urls. 13 should be the shortest possible profile length:
684 // Additionally check for invalid urls that would return the normalised value "http:"
685 if ((strlen($profile) >= 13) && (normalise_link($profile) != "http:")) {
686 if (!in_array($profile, $profiles2))
687 $profiles2[] = $profile;
689 $profile = normalise_link($profile);
690 if (!in_array($profile, $profiles2))
691 $profiles2[] = $profile;
693 $profile = str_replace("http://", "https://", $profile);
694 if (!in_array($profile, $profiles2))
695 $profiles2[] = $profile;
699 $profiles = $profiles2;
703 foreach ($profiles AS $profile) {
704 if ($profile_list != "")
705 $profile_list .= "', '";
707 $profile_list .= dbesc($profile);
710 $profile_list = "'".$profile_list."'";
712 // Only act if it is a "real" post
713 // We need the additional check for the "local_profile" because of mixed situations on connector networks
714 $item = q("SELECT `id`, `mention`, `tag`,`parent`, `title`, `body`, `author-name`, `author-link`, `author-avatar`, `guid`,
715 `parent-uri`, `uri`, `contact-id`
716 FROM `item` WHERE `id` = %d AND `verb` IN ('%s', '') AND `type` != 'activity' AND
717 NOT (`author-link` IN ($profile_list)) LIMIT 1",
718 intval($itemid), dbesc(ACTIVITY_POST));
722 // Generate the notification array
724 $params["uid"] = $uid;
725 $params["notify_flags"] = $user[0]["notify-flags"];
726 $params["language"] = $user[0]["language"];
727 $params["to_name"] = $user[0]["username"];
728 $params["to_email"] = $user[0]["email"];
729 $params["item"] = $item[0];
730 $params["parent"] = $item[0]["parent"];
731 $params["link"] = System::baseUrl().'/display/'.urlencode($item[0]["guid"]);
732 $params["otype"] = 'item';
733 $params["source_name"] = $item[0]["author-name"];
734 $params["source_link"] = $item[0]["author-link"];
735 $params["source_photo"] = $item[0]["author-avatar"];
737 if ($item[0]["parent-uri"] === $item[0]["uri"]) {
738 // Send a notification for every new post?
739 $r = q("SELECT `notify_new_posts` FROM `contact` WHERE `id` = %d AND `uid` = %d AND `notify_new_posts` LIMIT 1",
740 intval($item[0]['contact-id']),
743 $send_notification = dbm::is_result($r);
745 if (!$send_notification) {
746 $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
747 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
749 if (dbm::is_result($tags)) {
750 foreach ($tags AS $tag) {
751 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `notify_new_posts`",
752 normalise_link($tag["url"]), intval($uid));
753 if (dbm::is_result($r))
754 $send_notification = true;
759 if ($send_notification) {
760 $params["type"] = NOTIFY_SHARE;
761 $params["verb"] = ACTIVITY_TAG;
765 // Is the user mentioned in this post?
768 foreach ($profiles AS $profile) {
769 if (strpos($item[0]["tag"], "=".$profile."]") || strpos($item[0]["body"], "=".$profile."]"))
773 if ($item[0]["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
774 $params["type"] = NOTIFY_TAGSELF;
775 $params["verb"] = ACTIVITY_TAG;
778 // Is it a post that the user had started or where he interacted?
779 $parent = q("SELECT `thread`.`iid` FROM `thread` INNER JOIN `item` ON `item`.`parent` = `thread`.`iid`
780 WHERE `thread`.`iid` = %d AND `thread`.`uid` = %d AND NOT `thread`.`ignored` AND
781 (`thread`.`mention` OR `item`.`author-link` IN ($profile_list))
783 intval($item[0]["parent"]), intval($uid));
785 if ($parent && !isset($params["type"])) {
786 $params["type"] = NOTIFY_COMMENT;
787 $params["verb"] = ACTIVITY_POST;
790 if (isset($params["type"]))
791 notification($params);
795 * @brief Formats a notification message with the notification author
797 * Replace the name with {0} but ensure to make that only once. The {0} is used
798 * later and prints the name in bold.
800 * @param string $name
801 * @param string $message
802 * @return string Formatted message
804 function format_notification_message($name, $message) {
806 $pos = strpos($message, $name);
811 if ($pos !== false) {
812 $message = substr_replace($message, '{0}', $pos, strlen($name));