3 * @file include/enotify.php
6 use Friendica\Core\Config;
7 use Friendica\Core\System;
8 use Friendica\Database\DBM;
9 use Friendica\Util\Emailer;
11 require_once 'include/email.php';
12 require_once 'include/bbcode.php';
13 require_once 'include/html2bbcode.php';
16 * @brief Creates a notification entry and possibly sends a mail
18 * @param array $params Array with the elements:
19 uid, item, parent, type, otype, verb, event,
20 link, subject, body, to_name, to_email, source_name,
21 source_link, activity, preamble, notify_flags,
22 language, show_in_notification_page
24 function notification($params) {
28 // from here on everything is in the recipients language
30 push_lang($params['language']);
32 $banner = t('Friendica Notification');
33 $product = FRIENDICA_PLATFORM;
34 $siteurl = System::baseUrl(true);
35 $thanks = t('Thank You,');
36 $sitename = $a->config['sitename'];
37 if (!x($a->config['admin_name']))
38 $site_admin = sprintf(t('%s Administrator'), $sitename);
40 $site_admin = sprintf(t('%1$s, %2$s Administrator'), $a->config['admin_name'], $sitename);
44 $sender_name = $sitename;
45 $hostname = $a->get_hostname();
46 if (strpos($hostname, ':'))
47 $hostname = substr($hostname, 0, strpos($hostname, ':'));
49 $sender_email = $a->config['sender_email'];
50 if (empty($sender_email))
51 $sender_email = t('noreply').'@'.$hostname;
53 if ($params['type'] != SYSTEM_EMAIL) {
54 $user = dba::select('user', array('nickname', 'page-flags'),
55 array('uid' => $params['uid']), array('limit' => 1));
57 // There is no need to create notifications for forum accounts
58 if (!DBM::is_result($user) || in_array($user["page-flags"], array(PAGE_COMMUNITY, PAGE_PRVGROUP))) {
62 $nickname = $user["nickname"];
64 // with $params['show_in_notification_page'] == false, the notification isn't inserted into
65 // the database, and an email is sent if applicable.
66 // default, if not specified: true
67 $show_in_notification_page = ((x($params, 'show_in_notification_page')) ? $params['show_in_notification_page']:true);
69 $additional_mail_header = "";
70 $additional_mail_header .= "Precedence: list\n";
71 $additional_mail_header .= "X-Friendica-Host: ".$hostname."\n";
72 $additional_mail_header .= "X-Friendica-Account: <".$nickname."@".$hostname.">\n";
73 $additional_mail_header .= "X-Friendica-Platform: ".FRIENDICA_PLATFORM."\n";
74 $additional_mail_header .= "X-Friendica-Version: ".FRIENDICA_VERSION."\n";
75 $additional_mail_header .= "List-ID: <notification.".$hostname.">\n";
76 $additional_mail_header .= "List-Archive: <".System::baseUrl()."/notifications/system>\n";
78 if (array_key_exists('item', $params)) {
79 $title = $params['item']['title'];
80 $body = $params['item']['body'];
84 // e.g. "your post", "David's photo", etc.
85 $possess_desc = t('%s <!item_type!>');
87 if (isset($params['item']['id']))
88 $item_id = $params['item']['id'];
92 if (isset($params['parent']))
93 $parent_id = $params['parent'];
97 if ($params['type'] == NOTIFY_MAIL) {
98 $subject = sprintf(t('[Friendica:Notify] New mail received at %s'), $sitename);
100 $preamble = sprintf(t('%1$s sent you a new private message at %2$s.'), $params['source_name'], $sitename);
101 $epreamble = sprintf(t('%1$s sent you %2$s.'), '[url='.$params['source_link'].']'.$params['source_name'].'[/url]', '[url=$itemlink]'.t('a private message').'[/url]');
103 $sitelink = t('Please visit %s to view and/or reply to your private messages.');
104 $tsitelink = sprintf($sitelink, $siteurl.'/message/'.$params['item']['id']);
105 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'/message/'.$params['item']['id'].'">'.$sitename.'</a>');
106 $itemlink = $siteurl.'/message/'.$params['item']['id'];
109 if ($params['type'] == NOTIFY_COMMENT) {
110 $p = q("SELECT `ignored` FROM `thread` WHERE `iid` = %d AND `uid` = %d LIMIT 1",
112 intval($params['uid'])
114 if ($p && count($p) && ($p[0]["ignored"])) {
115 logger("Thread ".$parent_id." will be ignored", LOGGER_DEBUG);
119 // Check to see if there was already a tag notify or comment notify for this post.
120 // If so don't create a second notification
123 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d, %d) AND `link` = '%s' AND `uid` = %d LIMIT 1",
124 intval(NOTIFY_TAGSELF),
125 intval(NOTIFY_COMMENT),
126 intval(NOTIFY_SHARE),
127 dbesc($params['link']),
128 intval($params['uid'])
130 if ($p && count($p)) {
135 // if it's a post figure out who's post it is.
139 if ($params['otype'] === 'item' && $parent_id) {
140 $p = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
142 intval($params['uid'])
146 $item_post_type = item_post_type($p[0]);
149 $dest_str = sprintf(t('%1$s commented on [url=%2$s]a %3$s[/url]'),
150 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
154 // "George Bull's post"
156 $dest_str = sprintf(t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]'),
157 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
159 $p[0]['author-name'],
163 if ($p[0]['owner-name'] == $p[0]['author-name'] && $p[0]['wall'])
164 $dest_str = sprintf(t('%1$s commented on [url=%2$s]your %3$s[/url]'),
165 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
169 // Some mail softwares relies on subject field for threading.
170 // So, we cannot have different subjects for notifications of the same thread.
171 // Before this we have the name of the replier on the subject rendering
172 // differents subjects for messages on the same thread.
174 $subject = sprintf(t('[Friendica:Notify] Comment to conversation #%1$d by %2$s'), $parent_id, $params['source_name']);
176 $preamble = sprintf(t('%s commented on an item/conversation you have been following.'), $params['source_name']);
177 $epreamble = $dest_str;
179 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
180 $tsitelink = sprintf($sitelink, $siteurl);
181 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
182 $itemlink = $params['link'];
185 if ($params['type'] == NOTIFY_WALL) {
186 $subject = sprintf(t('[Friendica:Notify] %s posted to your profile wall'), $params['source_name']);
188 $preamble = sprintf(t('%1$s posted to your profile wall at %2$s'), $params['source_name'], $sitename);
189 $epreamble = sprintf(t('%1$s posted to [url=%2$s]your wall[/url]'),
190 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
193 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
194 $tsitelink = sprintf($sitelink, $siteurl);
195 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
196 $itemlink = $params['link'];
199 if ($params['type'] == NOTIFY_TAGSELF) {
200 $subject = sprintf(t('[Friendica:Notify] %s tagged you'), $params['source_name']);
202 $preamble = sprintf(t('%1$s tagged you at %2$s'), $params['source_name'], $sitename);
203 $epreamble = sprintf(t('%1$s [url=%2$s]tagged you[/url].'),
204 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
207 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
208 $tsitelink = sprintf($sitelink, $siteurl);
209 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
210 $itemlink = $params['link'];
213 if ($params['type'] == NOTIFY_SHARE) {
214 $subject = sprintf(t('[Friendica:Notify] %s shared a new post'), $params['source_name']);
216 $preamble = sprintf(t('%1$s shared a new post at %2$s'), $params['source_name'], $sitename);
217 $epreamble = sprintf(t('%1$s [url=%2$s]shared a post[/url].'),
218 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
221 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
222 $tsitelink = sprintf($sitelink, $siteurl);
223 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
224 $itemlink = $params['link'];
227 if ($params['type'] == NOTIFY_POKE) {
228 $subject = sprintf(t('[Friendica:Notify] %1$s poked you'), $params['source_name']);
230 $preamble = sprintf(t('%1$s poked you at %2$s'), $params['source_name'], $sitename);
231 $epreamble = sprintf(t('%1$s [url=%2$s]poked you[/url].'),
232 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
235 $subject = str_replace('poked', t($params['activity']), $subject);
236 $preamble = str_replace('poked', t($params['activity']), $preamble);
237 $epreamble = str_replace('poked', t($params['activity']), $epreamble);
239 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
240 $tsitelink = sprintf($sitelink, $siteurl);
241 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
242 $itemlink = $params['link'];
245 if ($params['type'] == NOTIFY_TAGSHARE) {
246 $subject = sprintf(t('[Friendica:Notify] %s tagged your post'), $params['source_name']);
248 $preamble = sprintf(t('%1$s tagged your post at %2$s'), $params['source_name'], $sitename);
249 $epreamble = sprintf(t('%1$s tagged [url=%2$s]your post[/url]'),
250 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
253 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
254 $tsitelink = sprintf($sitelink, $siteurl);
255 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
256 $itemlink = $params['link'];
259 if ($params['type'] == NOTIFY_INTRO) {
260 $subject = sprintf(t('[Friendica:Notify] Introduction received'));
262 $preamble = sprintf(t('You\'ve received an introduction from \'%1$s\' at %2$s'), $params['source_name'], $sitename);
263 $epreamble = sprintf(t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.'),
265 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
267 $body = sprintf(t('You may visit their profile at %s'), $params['source_link']);
269 $sitelink = t('Please visit %s to approve or reject the introduction.');
270 $tsitelink = sprintf($sitelink, $siteurl);
271 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
272 $itemlink = $params['link'];
274 switch ($params['verb']) {
275 case ACTIVITY_FRIEND:
276 // someone started to share with user (mostly OStatus)
277 $subject = sprintf(t('[Friendica:Notify] A new person is sharing with you'));
279 $preamble = sprintf(t('%1$s is sharing with you at %2$s'), $params['source_name'], $sitename);
280 $epreamble = sprintf(t('%1$s is sharing with you at %2$s'),
281 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
284 case ACTIVITY_FOLLOW:
285 // someone started to follow the user (mostly OStatus)
286 $subject = sprintf(t('[Friendica:Notify] You have a new follower'));
288 $preamble = sprintf(t('You have a new follower at %2$s : %1$s'), $params['source_name'], $sitename);
289 $epreamble = sprintf(t('You have a new follower at %2$s : %1$s'),
290 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
294 // ACTIVITY_REQ_FRIEND is default activity for notifications
299 if ($params['type'] == NOTIFY_SUGGEST) {
300 $subject = sprintf(t('[Friendica:Notify] Friend suggestion received'));
302 $preamble = sprintf(t('You\'ve received a friend suggestion from \'%1$s\' at %2$s'), $params['source_name'], $sitename);
303 $epreamble = sprintf(t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.'),
305 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
306 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
308 $body = t('Name:').' '.$params['item']['name']."\n";
309 $body .= t('Photo:').' '.$params['item']['photo']."\n";
310 $body .= sprintf(t('You may visit their profile at %s'), $params['item']['url']);
312 $sitelink = t('Please visit %s to approve or reject the suggestion.');
313 $tsitelink = sprintf($sitelink, $siteurl);
314 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
315 $itemlink = $params['link'];
318 if ($params['type'] == NOTIFY_CONFIRM) {
319 if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
320 $subject = sprintf(t('[Friendica:Notify] Connection accepted'));
322 $preamble = sprintf(t('\'%1$s\' has accepted your connection request at %2$s'), $params['source_name'], $sitename);
323 $epreamble = sprintf(t('%2$s has accepted your [url=%1$s]connection request[/url].'),
325 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
327 $body = t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
329 $sitelink = t('Please visit %s if you wish to make any changes to this relationship.');
330 $tsitelink = sprintf($sitelink, $siteurl);
331 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
332 $itemlink = $params['link'];
333 } else { // ACTIVITY_FOLLOW
334 $subject = sprintf(t('[Friendica:Notify] Connection accepted'));
336 $preamble = sprintf(t('\'%1$s\' has accepted your connection request at %2$s'), $params['source_name'], $sitename);
337 $epreamble = sprintf(t('%2$s has accepted your [url=%1$s]connection request[/url].'),
339 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
341 $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']);
343 $body .= sprintf(t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.'), $params['source_name']);
345 $sitelink = t('Please visit %s if you wish to make any changes to this relationship.');
346 $tsitelink = sprintf($sitelink, $siteurl);
347 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
348 $itemlink = $params['link'];
352 if ($params['type'] == NOTIFY_SYSTEM) {
353 switch($params['event']) {
354 case "SYSTEM_REGISTER_REQUEST":
355 $subject = sprintf(t('[Friendica System:Notify] registration request'));
357 $preamble = sprintf(t('You\'ve received a registration request from \'%1$s\' at %2$s'), $params['source_name'], $sitename);
358 $epreamble = sprintf(t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.'),
360 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
362 $body = sprintf(t('Full Name: %1$s\nSite Location: %2$s\nLogin Name: %3$s (%4$s)'),
363 $params['source_name'], $siteurl, $params['source_mail'], $params['source_nick']);
365 $sitelink = t('Please visit %s to approve or reject the request.');
366 $tsitelink = sprintf($sitelink, $params['link']);
367 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
368 $itemlink = $params['link'];
370 case "SYSTEM_DB_UPDATE_FAIL":
375 if ($params['type'] == SYSTEM_EMAIL) {
376 // not part of the notifications.
377 // it just send a mail to the user.
378 // It will be used by the system to send emails to users (like
379 // password reset, invitations and so) using one look (but without
380 // add a notification to the user, with could be inexistent)
381 $subject = $params['subject'];
383 $preamble = $params['preamble'];
385 $body = $params['body'];
391 $show_in_notification_page = false;
394 $subject .= " (".$nickname."@".$hostname.")";
398 'subject' => $subject,
399 'preamble' => $preamble,
400 'epreamble' => $epreamble,
402 'sitelink' => $sitelink,
403 'tsitelink' => $tsitelink,
404 'hsitelink' => $hsitelink,
405 'itemlink' => $itemlink
408 call_hooks('enotify', $h);
410 $subject = $h['subject'];
412 $preamble = $h['preamble'];
413 $epreamble = $h['epreamble'];
417 $sitelink = $h['sitelink'];
418 $tsitelink = $h['tsitelink'];
419 $hsitelink = $h['hsitelink'];
420 $itemlink = $h['itemlink'];
422 if ($show_in_notification_page) {
423 logger("adding notification entry", LOGGER_DEBUG);
426 $hash = random_string();
427 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' LIMIT 1",
429 if (DBM::is_result($r)) {
432 } while ($dups == true);
434 /// @TODO One statement is enough
436 $datarray['hash'] = $hash;
437 $datarray['name'] = $params['source_name'];
438 $datarray['name_cache'] = strip_tags(bbcode($params['source_name']));
439 $datarray['url'] = $params['source_link'];
440 $datarray['photo'] = $params['source_photo'];
441 $datarray['date'] = datetime_convert();
442 $datarray['uid'] = $params['uid'];
443 $datarray['link'] = $itemlink;
444 $datarray['iid'] = $item_id;
445 $datarray['parent'] = $parent_id;
446 $datarray['type'] = $params['type'];
447 $datarray['verb'] = $params['verb'];
448 $datarray['otype'] = $params['otype'];
449 $datarray['abort'] = false;
451 call_hooks('enotify_store', $datarray);
453 if ($datarray['abort']) {
458 // create notification entry in DB
460 $r = q("INSERT INTO `notify` (`hash`, `name`, `url`, `photo`, `date`, `uid`, `link`, `iid`, `parent`, `type`, `verb`, `otype`, `name_cache`)
461 values('%s', '%s', '%s', '%s', '%s', %d, '%s', %d, %d, %d, '%s', '%s', '%s')",
462 dbesc($datarray['hash']),
463 dbesc($datarray['name']),
464 dbesc($datarray['url']),
465 dbesc($datarray['photo']),
466 dbesc($datarray['date']),
467 intval($datarray['uid']),
468 dbesc($datarray['link']),
469 intval($datarray['iid']),
470 intval($datarray['parent']),
471 intval($datarray['type']),
472 dbesc($datarray['verb']),
473 dbesc($datarray['otype']),
474 dbesc($datarray["name_cache"])
477 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' AND `uid` = %d LIMIT 1",
479 intval($params['uid'])
482 $notify_id = $r[0]['id'];
488 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
489 // After we've stored everything, look again to see if there are any duplicates and if so remove them
492 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
493 intval(NOTIFY_TAGSELF),
494 intval(NOTIFY_COMMENT),
495 dbesc($params['link']),
496 intval($params['uid'])
498 if ($p && (count($p) > 1)) {
499 for ($d = 1; $d < count($p); $d ++) {
500 dba::delete('notify', array('id' => $p[$d]['id']));
503 // only continue on if we stored the first one
505 if ($notify_id != $p[0]['id']) {
512 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
513 $msg = replace_macros($epreamble, array('$itemlink' => $itemlink));
514 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(bbcode($msg)));
515 $r = q("UPDATE `notify` SET `msg` = '%s', `msg_cache` = '%s' WHERE `id` = %d AND `uid` = %d",
519 intval($params['uid'])
523 // send email notification if notification preferences permit
524 if ((intval($params['notify_flags']) & intval($params['type']))
525 || $params['type'] == NOTIFY_SYSTEM
526 || $params['type'] == SYSTEM_EMAIL) {
528 logger('sending notification email');
530 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
531 $id_for_parent = $params['parent']."@".$hostname;
533 // Is this the first email notification for this parent item and user?
535 $r = q("SELECT `id` FROM `notify-threads` WHERE `master-parent-item` = %d AND `receiver-uid` = %d LIMIT 1",
536 intval($params['parent']),
537 intval($params['uid']));
539 // If so, create the record of it and use a message-id smtp header.
542 logger("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), LOGGER_DEBUG);
543 $r = q("INSERT INTO `notify-threads` (`notify-id`, `master-parent-item`, `receiver-uid`, `parent-item`)
544 values(%d, %d, %d, %d)",
546 intval($params['parent']),
547 intval($params['uid']),
550 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
551 $log_msg = "include/enotify: No previous notification found for this parent:\n".
552 " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
553 logger($log_msg, LOGGER_DEBUG);
555 // If not, just "follow" the thread.
556 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
557 logger("There's already a notification for this parent:\n".print_r($r, true), LOGGER_DEBUG);
561 // textversion keeps linebreaks
562 $textversion = strip_tags(str_replace("<br>", "\n", html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n"), "\n",
563 $body))),ENT_QUOTES, 'UTF-8')));
564 $htmlversion = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n\\n", "\\n"),
565 "<br />\n", $body))), ENT_QUOTES, 'UTF-8');
568 $datarray['banner'] = $banner;
569 $datarray['product'] = $product;
570 $datarray['preamble'] = $preamble;
571 $datarray['sitename'] = $sitename;
572 $datarray['siteurl'] = $siteurl;
573 $datarray['type'] = $params['type'];
574 $datarray['parent'] = $params['parent'];
575 $datarray['source_name'] = $params['source_name'];
576 $datarray['source_link'] = $params['source_link'];
577 $datarray['source_photo'] = $params['source_photo'];
578 $datarray['uid'] = $params['uid'];
579 $datarray['username'] = $params['to_name'];
580 $datarray['hsitelink'] = $hsitelink;
581 $datarray['tsitelink'] = $tsitelink;
582 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
583 $datarray['titemlink'] = $itemlink;
584 $datarray['thanks'] = $thanks;
585 $datarray['site_admin'] = $site_admin;
586 $datarray['title'] = stripslashes($title);
587 $datarray['htmlversion'] = $htmlversion;
588 $datarray['textversion'] = $textversion;
589 $datarray['subject'] = $subject;
590 $datarray['headers'] = $additional_mail_header;
592 call_hooks('enotify_mail', $datarray);
594 // check whether sending post content in email notifications is allowed
595 // always true for SYSTEM_EMAIL
596 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
598 // load the template for private message notifications
599 $tpl = get_markup_template('email_notify_html.tpl');
600 $email_html_body = replace_macros($tpl, array(
601 '$banner' => $datarray['banner'],
602 '$product' => $datarray['product'],
603 '$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
604 '$sitename' => $datarray['sitename'],
605 '$siteurl' => $datarray['siteurl'],
606 '$source_name' => $datarray['source_name'],
607 '$source_link' => $datarray['source_link'],
608 '$source_photo' => $datarray['source_photo'],
609 '$username' => $datarray['to_name'],
610 '$hsitelink' => $datarray['hsitelink'],
611 '$hitemlink' => $datarray['hitemlink'],
612 '$thanks' => $datarray['thanks'],
613 '$site_admin' => $datarray['site_admin'],
614 '$title' => $datarray['title'],
615 '$htmlversion' => $datarray['htmlversion'],
616 '$content_allowed' => $content_allowed,
619 // load the template for private message notifications
620 $tpl = get_markup_template('email_notify_text.tpl');
621 $email_text_body = replace_macros($tpl, array(
622 '$banner' => $datarray['banner'],
623 '$product' => $datarray['product'],
624 '$preamble' => $datarray['preamble'],
625 '$sitename' => $datarray['sitename'],
626 '$siteurl' => $datarray['siteurl'],
627 '$source_name' => $datarray['source_name'],
628 '$source_link' => $datarray['source_link'],
629 '$source_photo' => $datarray['source_photo'],
630 '$username' => $datarray['to_name'],
631 '$tsitelink' => $datarray['tsitelink'],
632 '$titemlink' => $datarray['titemlink'],
633 '$thanks' => $datarray['thanks'],
634 '$site_admin' => $datarray['site_admin'],
635 '$title' => $datarray['title'],
636 '$textversion' => $datarray['textversion'],
637 '$content_allowed' => $content_allowed,
640 // use the Emailer class to send the message
642 return Emailer::send(
644 'uid' => $params['uid'],
645 'fromName' => $sender_name,
646 'fromEmail' => $sender_email,
647 'replyTo' => $sender_email,
648 'toEmail' => $params['to_email'],
649 'messageSubject' => $datarray['subject'],
650 'htmlVersion' => $email_html_body,
651 'textVersion' => $email_text_body,
652 'additionalMailHeader' => $datarray['headers'])
660 * @brief Checks for item related notifications and sends them
662 * @param int $itemid ID of the item for which the check should be done
663 * @param int $uid User ID
664 * @param str $defaulttype (Optional) Forces a notification with this type.
666 function check_item_notification($itemid, $uid, $defaulttype = "") {
667 $notification_data = array("uid" => $uid, "profiles" => array());
668 call_hooks('check_item_notification', $notification_data);
670 $profiles = $notification_data["profiles"];
672 $user = q("SELECT `notify-flags`, `language`, `username`, `email`, `nickname` FROM `user` WHERE `uid` = %d", intval($uid));
676 $owner = q("SELECT `id`, `url` FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1", intval($uid));
680 // This is our regular URL format
681 $profiles[] = $owner[0]["url"];
683 // Notifications from Diaspora are often with an URL in the Diaspora format
684 $profiles[] = System::baseUrl()."/u/".$user[0]["nickname"];
686 $profiles2 = array();
688 foreach ($profiles AS $profile) {
689 // Check for invalid profile urls. 13 should be the shortest possible profile length:
691 // Additionally check for invalid urls that would return the normalised value "http:"
692 if ((strlen($profile) >= 13) && (normalise_link($profile) != "http:")) {
693 if (!in_array($profile, $profiles2))
694 $profiles2[] = $profile;
696 $profile = normalise_link($profile);
697 if (!in_array($profile, $profiles2))
698 $profiles2[] = $profile;
700 $profile = str_replace("http://", "https://", $profile);
701 if (!in_array($profile, $profiles2))
702 $profiles2[] = $profile;
706 $profiles = $profiles2;
710 foreach ($profiles AS $profile) {
711 if ($profile_list != "")
712 $profile_list .= "', '";
714 $profile_list .= dbesc($profile);
717 $profile_list = "'".$profile_list."'";
719 // Only act if it is a "real" post
720 // We need the additional check for the "local_profile" because of mixed situations on connector networks
721 $item = q("SELECT `id`, `mention`, `tag`,`parent`, `title`, `body`, `author-name`, `author-link`, `author-avatar`, `guid`,
722 `parent-uri`, `uri`, `contact-id`
723 FROM `item` WHERE `id` = %d AND `verb` IN ('%s', '') AND `type` != 'activity' AND
724 NOT (`author-link` IN ($profile_list)) LIMIT 1",
725 intval($itemid), dbesc(ACTIVITY_POST));
729 // Generate the notification array
731 $params["uid"] = $uid;
732 $params["notify_flags"] = $user[0]["notify-flags"];
733 $params["language"] = $user[0]["language"];
734 $params["to_name"] = $user[0]["username"];
735 $params["to_email"] = $user[0]["email"];
736 $params["item"] = $item[0];
737 $params["parent"] = $item[0]["parent"];
738 $params["link"] = System::baseUrl().'/display/'.urlencode($item[0]["guid"]);
739 $params["otype"] = 'item';
740 $params["source_name"] = $item[0]["author-name"];
741 $params["source_link"] = $item[0]["author-link"];
742 $params["source_photo"] = $item[0]["author-avatar"];
744 if ($item[0]["parent-uri"] === $item[0]["uri"]) {
745 // Send a notification for every new post?
746 $r = q("SELECT `notify_new_posts` FROM `contact` WHERE `id` = %d AND `uid` = %d AND `notify_new_posts` LIMIT 1",
747 intval($item[0]['contact-id']),
750 $send_notification = DBM::is_result($r);
752 if (!$send_notification) {
753 $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
754 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
756 if (DBM::is_result($tags)) {
757 foreach ($tags AS $tag) {
758 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `notify_new_posts`",
759 normalise_link($tag["url"]), intval($uid));
760 if (DBM::is_result($r))
761 $send_notification = true;
766 if ($send_notification) {
767 $params["type"] = NOTIFY_SHARE;
768 $params["verb"] = ACTIVITY_TAG;
772 // Is the user mentioned in this post?
775 foreach ($profiles AS $profile) {
776 if (strpos($item[0]["tag"], "=".$profile."]") || strpos($item[0]["body"], "=".$profile."]"))
780 if ($item[0]["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
781 $params["type"] = NOTIFY_TAGSELF;
782 $params["verb"] = ACTIVITY_TAG;
785 // Is it a post that the user had started or where he interacted?
786 $parent = q("SELECT `thread`.`iid` FROM `thread` INNER JOIN `item` ON `item`.`parent` = `thread`.`iid`
787 WHERE `thread`.`iid` = %d AND `thread`.`uid` = %d AND NOT `thread`.`ignored` AND
788 (`thread`.`mention` OR `item`.`author-link` IN ($profile_list))
790 intval($item[0]["parent"]), intval($uid));
792 if ($parent && !isset($params["type"])) {
793 $params["type"] = NOTIFY_COMMENT;
794 $params["verb"] = ACTIVITY_POST;
797 if (isset($params["type"]))
798 notification($params);
802 * @brief Formats a notification message with the notification author
804 * Replace the name with {0} but ensure to make that only once. The {0} is used
805 * later and prints the name in bold.
807 * @param string $name
808 * @param string $message
809 * @return string Formatted message
811 function format_notification_message($name, $message) {
813 $pos = strpos($message, $name);
818 if ($pos !== false) {
819 $message = substr_replace($message, '{0}', $pos, strlen($name));