2 require_once('include/Emailer.php');
3 require_once('include/email.php');
4 require_once('include/bbcode.php');
5 require_once('include/html2bbcode.php');
8 * @brief Creates a notification entry and possibly sends a mail
10 * @param array $params Array with the elements:
11 uid, item, parent, type, otype, verb, event,
12 link, subject, body, to_name, to_email, source_name,
13 source_link, activity, preamble, notify_flags,
14 language, show_in_notification_page
16 function notification($params) {
20 // from here on everything is in the recipients language
22 push_lang($params['language']);
24 $banner = t('Friendica Notification');
25 $product = FRIENDICA_PLATFORM;
26 $siteurl = $a->get_baseurl(true);
27 $thanks = t('Thank You,');
28 $sitename = $a->config['sitename'];
29 if (!x($a->config['admin_name']))
30 $site_admin = sprintf(t('%s Administrator'), $sitename);
32 $site_admin = sprintf(t('%1$s, %2$s Administrator'), $a->config['admin_name'], $sitename);
36 $sender_name = $sitename;
37 $hostname = $a->get_hostname();
38 if (strpos($hostname, ':'))
39 $hostname = substr($hostname, 0, strpos($hostname, ':'));
41 $sender_email = $a->config['sender_email'];
42 if (empty($sender_email))
43 $sender_email = t('noreply').'@'.$hostname;
45 $user = q("SELECT `nickname` FROM `user` WHERE `uid` = %d", intval($params['uid']));
47 $nickname = $user[0]["nickname"];
49 // with $params['show_in_notification_page'] == false, the notification isn't inserted into
50 // the database, and an email is sent if applicable.
51 // default, if not specified: true
52 $show_in_notification_page = ((x($params, 'show_in_notification_page')) ? $params['show_in_notification_page']:true);
54 $additional_mail_header = "";
55 $additional_mail_header .= "Precedence: list\n";
56 $additional_mail_header .= "X-Friendica-Host: ".$hostname."\n";
57 $additional_mail_header .= "X-Friendica-Account: <".$nickname."@".$hostname.">\n";
58 $additional_mail_header .= "X-Friendica-Platform: ".FRIENDICA_PLATFORM."\n";
59 $additional_mail_header .= "X-Friendica-Version: ".FRIENDICA_VERSION."\n";
60 $additional_mail_header .= "List-ID: <notification.".$hostname.">\n";
61 $additional_mail_header .= "List-Archive: <".$a->get_baseurl()."/notifications/system>\n";
63 if (array_key_exists('item', $params)) {
64 $title = $params['item']['title'];
65 $body = $params['item']['body'];
69 // e.g. "your post", "David's photo", etc.
70 $possess_desc = t('%s <!item_type!>');
72 if (isset($params['item']['id']))
73 $item_id = $params['item']['id'];
77 if (isset($params['parent']))
78 $parent_id = $params['parent'];
82 if ($params['type'] == NOTIFY_MAIL) {
83 $subject = sprintf(t('[Friendica:Notify] New mail received at %s'), $sitename);
85 $preamble = sprintf(t('%1$s sent you a new private message at %2$s.'), $params['source_name'], $sitename);
86 $epreamble = sprintf(t('%1$s sent you %2$s.'), '[url='.$params['source_link'].']'.$params['source_name'].'[/url]', '[url=$itemlink]'.t('a private message').'[/url]');
88 $sitelink = t('Please visit %s to view and/or reply to your private messages.');
89 $tsitelink = sprintf($sitelink, $siteurl.'/message/'.$params['item']['id']);
90 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'/message/'.$params['item']['id'].'">'.$sitename.'</a>');
91 $itemlink = $siteurl.'/message/'.$params['item']['id'];
94 if ($params['type'] == NOTIFY_COMMENT) {
95 $p = q("SELECT `ignored` FROM `thread` WHERE `iid` = %d AND `uid` = %d LIMIT 1",
97 intval($params['uid'])
99 if ($p AND count($p) AND ($p[0]["ignored"])) {
100 logger("Thread ".$parent_id." will be ignored", LOGGER_DEBUG);
104 // Check to see if there was already a tag notify or comment notify for this post.
105 // If so don't create a second notification
108 $p = q("SELECT `id` FROM `notify` WHERE (`type` = %d OR `type` = %d OR `type` = %d) AND `link` = '%s' AND `uid` = %d LIMIT 1",
109 intval(NOTIFY_TAGSELF),
110 intval(NOTIFY_COMMENT),
111 intval(NOTIFY_SHARE),
112 dbesc($params['link']),
113 intval($params['uid'])
115 if ($p and count($p)) {
120 // if it's a post figure out who's post it is.
124 if ($params['otype'] === 'item' && $parent_id) {
125 $p = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
127 intval($params['uid'])
131 $item_post_type = item_post_type($p[0]);
134 $dest_str = sprintf(t('%1$s commented on [url=%2$s]a %3$s[/url]'),
135 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
139 // "George Bull's post"
141 $dest_str = sprintf(t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]'),
142 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
144 $p[0]['author-name'],
148 if ($p[0]['owner-name'] == $p[0]['author-name'] && $p[0]['wall'])
149 $dest_str = sprintf(t('%1$s commented on [url=%2$s]your %3$s[/url]'),
150 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
154 // Some mail softwares relies on subject field for threading.
155 // So, we cannot have different subjects for notifications of the same thread.
156 // Before this we have the name of the replier on the subject rendering
157 // differents subjects for messages on the same thread.
159 $subject = sprintf(t('[Friendica:Notify] Comment to conversation #%1$d by %2$s'), $parent_id, $params['source_name']);
161 $preamble = sprintf(t('%s commented on an item/conversation you have been following.'), $params['source_name']);
162 $epreamble = $dest_str;
164 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
165 $tsitelink = sprintf($sitelink, $siteurl);
166 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
167 $itemlink = $params['link'];
170 if ($params['type'] == NOTIFY_WALL) {
171 $subject = sprintf(t('[Friendica:Notify] %s posted to your profile wall'), $params['source_name']);
173 $preamble = sprintf(t('%1$s posted to your profile wall at %2$s'), $params['source_name'], $sitename);
174 $epreamble = sprintf(t('%1$s posted to [url=%2$s]your wall[/url]'),
175 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
178 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
179 $tsitelink = sprintf($sitelink, $siteurl);
180 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
181 $itemlink = $params['link'];
184 if ($params['type'] == NOTIFY_TAGSELF) {
185 $subject = sprintf(t('[Friendica:Notify] %s tagged you'), $params['source_name']);
187 $preamble = sprintf(t('%1$s tagged you at %2$s'), $params['source_name'], $sitename);
188 $epreamble = sprintf(t('%1$s [url=%2$s]tagged you[/url].'),
189 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
192 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
193 $tsitelink = sprintf($sitelink, $siteurl);
194 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
195 $itemlink = $params['link'];
198 if ($params['type'] == NOTIFY_SHARE) {
199 $subject = sprintf(t('[Friendica:Notify] %s shared a new post'), $params['source_name']);
201 $preamble = sprintf(t('%1$s shared a new post at %2$s'), $params['source_name'], $sitename);
202 $epreamble = sprintf(t('%1$s [url=%2$s]shared a post[/url].'),
203 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
206 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
207 $tsitelink = sprintf($sitelink, $siteurl);
208 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
209 $itemlink = $params['link'];
212 if ($params['type'] == NOTIFY_POKE) {
213 $subject = sprintf(t('[Friendica:Notify] %1$s poked you'), $params['source_name']);
215 $preamble = sprintf(t('%1$s poked you at %2$s'), $params['source_name'], $sitename);
216 $epreamble = sprintf(t('%1$s [url=%2$s]poked you[/url].'),
217 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
220 $subject = str_replace('poked', t($params['activity']), $subject);
221 $preamble = str_replace('poked', t($params['activity']), $preamble);
222 $epreamble = str_replace('poked', t($params['activity']), $epreamble);
224 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
225 $tsitelink = sprintf($sitelink, $siteurl);
226 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
227 $itemlink = $params['link'];
230 if ($params['type'] == NOTIFY_TAGSHARE) {
231 $subject = sprintf(t('[Friendica:Notify] %s tagged your post'), $params['source_name']);
233 $preamble = sprintf(t('%1$s tagged your post at %2$s'), $params['source_name'], $sitename);
234 $epreamble = sprintf(t('%1$s tagged [url=%2$s]your post[/url]'),
235 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
238 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
239 $tsitelink = sprintf($sitelink, $siteurl);
240 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
241 $itemlink = $params['link'];
244 if ($params['type'] == NOTIFY_INTRO) {
245 $subject = sprintf(t('[Friendica:Notify] Introduction received'));
247 $preamble = sprintf(t('You\'ve received an introduction from \'%1$s\' at %2$s'), $params['source_name'], $sitename);
248 $epreamble = sprintf(t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.'),
250 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
252 $body = sprintf(t('You may visit their profile at %s'), $params['source_link']);
254 $sitelink = t('Please visit %s to approve or reject the introduction.');
255 $tsitelink = sprintf($sitelink, $siteurl);
256 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
257 $itemlink = $params['link'];
259 switch ($params['verb']) {
260 case ACTIVITY_FRIEND:
261 // someone started to share with user (mostly OStatus)
262 $subject = sprintf(t('[Friendica:Notify] A new person is sharing with you'));
264 $preamble = sprintf(t('%1$s is sharing with you at %2$s'), $params['source_name'], $sitename);
265 $epreamble = sprintf(t('%1$s is sharing with you at %2$s'),
266 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
269 case ACTIVITY_FOLLOW:
270 // someone started to follow the user (mostly OStatus)
271 $subject = sprintf(t('[Friendica:Notify] You have a new follower'));
273 $preamble = sprintf(t('You have a new follower at %2$s : %1$s'), $params['source_name'], $sitename);
274 $epreamble = sprintf(t('You have a new follower at %2$s : %1$s'),
275 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
279 // ACTIVITY_REQ_FRIEND is default activity for notifications
284 if ($params['type'] == NOTIFY_SUGGEST) {
285 $subject = sprintf(t('[Friendica:Notify] Friend suggestion received'));
287 $preamble = sprintf(t('You\'ve received a friend suggestion from \'%1$s\' at %2$s'), $params['source_name'], $sitename);
288 $epreamble = sprintf(t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.'),
290 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
291 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
293 $body = t('Name:').' '.$params['item']['name']."\n";
294 $body .= t('Photo:').' '.$params['item']['photo']."\n";
295 $body .= sprintf(t('You may visit their profile at %s'), $params['item']['url']);
297 $sitelink = t('Please visit %s to approve or reject the suggestion.');
298 $tsitelink = sprintf($sitelink, $siteurl);
299 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
300 $itemlink = $params['link'];
303 if ($params['type'] == NOTIFY_CONFIRM) {
304 if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
305 $subject = sprintf(t('[Friendica:Notify] Connection accepted'));
307 $preamble = sprintf(t('\'%1$s\' has accepted your connection request at %2$s'), $params['source_name'], $sitename);
308 $epreamble = sprintf(t('%2$s has accepted your [url=%1$s]connection request[/url].'),
310 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
312 $body = t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
314 $sitelink = t('Please visit %s if you wish to make any changes to this relationship.');
315 $tsitelink = sprintf($sitelink, $siteurl);
316 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
317 $itemlink = $params['link'];
318 } else { // ACTIVITY_FOLLOW
319 $subject = sprintf(t('[Friendica:Notify] Connection accepted'));
321 $preamble = sprintf(t('\'%1$s\' has accepted your connection request at %2$s'), $params['source_name'], $sitename);
322 $epreamble = sprintf(t('%2$s has accepted your [url=%1$s]connection request[/url].'),
324 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
326 $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']);
328 $body .= sprintf(t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.'), $params['source_name']);
330 $sitelink = t('Please visit %s if you wish to make any changes to this relationship.');
331 $tsitelink = sprintf($sitelink, $siteurl);
332 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
333 $itemlink = $params['link'];
337 if ($params['type'] == NOTIFY_SYSTEM) {
338 switch($params['event']) {
339 case "SYSTEM_REGISTER_REQUEST":
340 $subject = sprintf(t('[Friendica System:Notify] registration request'));
342 $preamble = sprintf(t('You\'ve received a registration request from \'%1$s\' at %2$s'), $params['source_name'], $sitename);
343 $epreamble = sprintf(t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.'),
345 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
347 $body = sprintf(t('Full Name: %1$s\nSite Location: %2$s\nLogin Name: %3$s (%4$s)'),
348 $params['source_name'], $siteurl, $params['source_mail'], $params['source_nick']);
350 $sitelink = t('Please visit %s to approve or reject the request.');
351 $tsitelink = sprintf($sitelink, $params['link']);
352 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
353 $itemlink = $params['link'];
355 case "SYSTEM_DB_UPDATE_FAIL":
360 if ($params['type'] == "SYSTEM_EMAIL") {
361 // not part of the notifications.
362 // it just send a mail to the user.
363 // It will be used by the system to send emails to users (like
364 // password reset, invitations and so) using one look (but without
365 // add a notification to the user, with could be inexistent)
366 $subject = $params['subject'];
368 $preamble = $params['preamble'];
370 $body = $params['body'];
376 $show_in_notification_page = false;
379 $subject .= " (".$nickname."@".$hostname.")";
383 'subject' => $subject,
384 'preamble' => $preamble,
385 'epreamble' => $epreamble,
387 'sitelink' => $sitelink,
388 'tsitelink' => $tsitelink,
389 'hsitelink' => $hsitelink,
390 'itemlink' => $itemlink
393 call_hooks('enotify', $h);
395 $subject = $h['subject'];
397 $preamble = $h['preamble'];
398 $epreamble = $h['epreamble'];
402 $sitelink = $h['sitelink'];
403 $tsitelink = $h['tsitelink'];
404 $hsitelink = $h['hsitelink'];
405 $itemlink = $h['itemlink'];
407 if ($show_in_notification_page) {
408 logger("adding notification entry", LOGGER_DEBUG);
411 $hash = random_string();
412 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' LIMIT 1",
414 if (dbm::is_result($r))
416 } while($dups == true);
419 $datarray['hash'] = $hash;
420 $datarray['name'] = $params['source_name'];
421 $datarray['name_cache'] = strip_tags(bbcode($params['source_name']));
422 $datarray['url'] = $params['source_link'];
423 $datarray['photo'] = $params['source_photo'];
424 $datarray['date'] = datetime_convert();
425 $datarray['uid'] = $params['uid'];
426 $datarray['link'] = $itemlink;
427 $datarray['iid'] = $item_id;
428 $datarray['parent'] = $parent_id;
429 $datarray['type'] = $params['type'];
430 $datarray['verb'] = $params['verb'];
431 $datarray['otype'] = $params['otype'];
432 $datarray['abort'] = false;
434 call_hooks('enotify_store', $datarray);
436 if ($datarray['abort']) {
441 // create notification entry in DB
443 $r = q("INSERT INTO `notify` (`hash`, `name`, `url`, `photo`, `date`, `uid`, `link`, `iid`, `parent`, `type`, `verb`, `otype`, `name_cache`)
444 values('%s', '%s', '%s', '%s', '%s', %d, '%s', %d, %d, %d, '%s', '%s', '%s')",
445 dbesc($datarray['hash']),
446 dbesc($datarray['name']),
447 dbesc($datarray['url']),
448 dbesc($datarray['photo']),
449 dbesc($datarray['date']),
450 intval($datarray['uid']),
451 dbesc($datarray['link']),
452 intval($datarray['iid']),
453 intval($datarray['parent']),
454 intval($datarray['type']),
455 dbesc($datarray['verb']),
456 dbesc($datarray['otype']),
457 dbesc($datarray["name_cache"])
460 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' AND `uid` = %d LIMIT 1",
462 intval($params['uid'])
465 $notify_id = $r[0]['id'];
471 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
472 // After we've stored everything, look again to see if there are any duplicates and if so remove them
475 $p = q("SELECT `id` FROM `notify` WHERE (`type` = %d OR `type` = %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
476 intval(NOTIFY_TAGSELF),
477 intval(NOTIFY_COMMENT),
478 dbesc($params['link']),
479 intval($params['uid'])
481 if ($p && (count($p) > 1)) {
482 for ($d = 1; $d < count($p); $d ++) {
483 q("DELETE FROM `notify` WHERE `id` = %d",
488 // only continue on if we stored the first one
490 if ($notify_id != $p[0]['id']) {
497 $itemlink = $a->get_baseurl().'/notify/view/'.$notify_id;
498 $msg = replace_macros($epreamble, array('$itemlink' => $itemlink));
499 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(bbcode($msg)));
500 $r = q("UPDATE `notify` SET `msg` = '%s', `msg_cache` = '%s' WHERE `id` = %d AND `uid` = %d",
504 intval($params['uid'])
508 // send email notification if notification preferences permit
509 if ((intval($params['notify_flags']) & intval($params['type']))
510 || $params['type'] == NOTIFY_SYSTEM
511 || $params['type'] == "SYSTEM_EMAIL") {
513 logger('sending notification email');
515 if (isset($params['parent']) AND (intval($params['parent']) != 0)) {
516 $id_for_parent = $params['parent']."@".$hostname;
518 // Is this the first email notification for this parent item and user?
520 $r = q("SELECT `id` FROM `notify-threads` WHERE `master-parent-item` = %d AND `receiver-uid` = %d LIMIT 1",
521 intval($params['parent']),
522 intval($params['uid']));
524 // If so, create the record of it and use a message-id smtp header.
527 logger("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), LOGGER_DEBUG);
528 $r = q("INSERT INTO `notify-threads` (`notify-id`, `master-parent-item`, `receiver-uid`, `parent-item`)
529 values(%d, %d, %d, %d)",
531 intval($params['parent']),
532 intval($params['uid']),
535 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
536 $log_msg = "include/enotify: No previous notification found for this parent:\n".
537 " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
538 logger($log_msg, LOGGER_DEBUG);
540 // If not, just "follow" the thread.
541 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
542 logger("There's already a notification for this parent:\n".print_r($r, true), LOGGER_DEBUG);
546 // textversion keeps linebreaks
547 $textversion = strip_tags(str_replace("<br>", "\n", html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n"), "\n",
548 $body))),ENT_QUOTES, 'UTF-8')));
549 $htmlversion = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n\\n", "\\n"),
550 "<br />\n", $body))), ENT_QUOTES, 'UTF-8');
553 $datarray['banner'] = $banner;
554 $datarray['product'] = $product;
555 $datarray['preamble'] = $preamble;
556 $datarray['sitename'] = $sitename;
557 $datarray['siteurl'] = $siteurl;
558 $datarray['type'] = $params['type'];
559 $datarray['parent'] = $params['parent'];
560 $datarray['source_name'] = $params['source_name'];
561 $datarray['source_link'] = $params['source_link'];
562 $datarray['source_photo'] = $params['source_photo'];
563 $datarray['uid'] = $params['uid'];
564 $datarray['username'] = $params['to_name'];
565 $datarray['hsitelink'] = $hsitelink;
566 $datarray['tsitelink'] = $tsitelink;
567 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
568 $datarray['titemlink'] = $itemlink;
569 $datarray['thanks'] = $thanks;
570 $datarray['site_admin'] = $site_admin;
571 $datarray['title'] = stripslashes($title);
572 $datarray['htmlversion'] = $htmlversion;
573 $datarray['textversion'] = $textversion;
574 $datarray['subject'] = $subject;
575 $datarray['headers'] = $additional_mail_header;
577 call_hooks('enotify_mail', $datarray);
579 // check whether sending post content in email notifications is allowed
580 // always true for "SYSTEM_EMAIL"
581 $content_allowed = ((!get_config('system', 'enotify_no_content')) || ($params['type'] == "SYSTEM_EMAIL"));
583 // load the template for private message notifications
584 $tpl = get_markup_template('email_notify_html.tpl');
585 $email_html_body = replace_macros($tpl, array(
586 '$banner' => $datarray['banner'],
587 '$product' => $datarray['product'],
588 '$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
589 '$sitename' => $datarray['sitename'],
590 '$siteurl' => $datarray['siteurl'],
591 '$source_name' => $datarray['source_name'],
592 '$source_link' => $datarray['source_link'],
593 '$source_photo' => $datarray['source_photo'],
594 '$username' => $datarray['to_name'],
595 '$hsitelink' => $datarray['hsitelink'],
596 '$hitemlink' => $datarray['hitemlink'],
597 '$thanks' => $datarray['thanks'],
598 '$site_admin' => $datarray['site_admin'],
599 '$title' => $datarray['title'],
600 '$htmlversion' => $datarray['htmlversion'],
601 '$content_allowed' => $content_allowed,
604 // load the template for private message notifications
605 $tpl = get_markup_template('email_notify_text.tpl');
606 $email_text_body = replace_macros($tpl, array(
607 '$banner' => $datarray['banner'],
608 '$product' => $datarray['product'],
609 '$preamble' => $datarray['preamble'],
610 '$sitename' => $datarray['sitename'],
611 '$siteurl' => $datarray['siteurl'],
612 '$source_name' => $datarray['source_name'],
613 '$source_link' => $datarray['source_link'],
614 '$source_photo' => $datarray['source_photo'],
615 '$username' => $datarray['to_name'],
616 '$tsitelink' => $datarray['tsitelink'],
617 '$titemlink' => $datarray['titemlink'],
618 '$thanks' => $datarray['thanks'],
619 '$site_admin' => $datarray['site_admin'],
620 '$title' => $datarray['title'],
621 '$textversion' => $datarray['textversion'],
622 '$content_allowed' => $content_allowed,
625 // use the Emailer class to send the message
627 return Emailer::send(array(
628 'uid' => $params['uid'],
629 'fromName' => $sender_name,
630 'fromEmail' => $sender_email,
631 'replyTo' => $sender_email,
632 'toEmail' => $params['to_email'],
633 'messageSubject' => $datarray['subject'],
634 'htmlVersion' => $email_html_body,
635 'textVersion' => $email_text_body,
636 'additionalMailHeader' => $datarray['headers'],
644 * @brief Checks for item related notifications and sends them
646 * @param int $itemid ID of the item for which the check should be done
647 * @param int $uid User ID
648 * @param str $defaulttype (Optional) Forces a notification with this type.
650 function check_item_notification($itemid, $uid, $defaulttype = "") {
653 $notification_data = array("uid" => $uid, "profiles" => array());
654 call_hooks('check_item_notification', $notification_data);
656 $profiles = $notification_data["profiles"];
658 $user = q("SELECT `notify-flags`, `language`, `username`, `email`, `nickname` FROM `user` WHERE `uid` = %d", intval($uid));
662 $owner = q("SELECT `id`, `url` FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1", intval($uid));
666 // This is our regular URL format
667 $profiles[] = $owner[0]["url"];
669 // Notifications from Diaspora are often with an URL in the Diaspora format
670 $profiles[] = $a->get_baseurl()."/u/".$user[0]["nickname"];
672 $profiles2 = array();
674 foreach ($profiles AS $profile) {
675 // Check for invalid profile urls. 13 should be the shortest possible profile length:
677 // Additionally check for invalid urls that would return the normalised value "http:"
678 if ((strlen($profile) >= 13) AND (normalise_link($profile) != "http:")) {
679 if (!in_array($profile, $profiles2))
680 $profiles2[] = $profile;
682 $profile = normalise_link($profile);
683 if (!in_array($profile, $profiles2))
684 $profiles2[] = $profile;
686 $profile = str_replace("http://", "https://", $profile);
687 if (!in_array($profile, $profiles2))
688 $profiles2[] = $profile;
692 $profiles = $profiles2;
696 foreach ($profiles AS $profile) {
697 if ($profile_list != "")
698 $profile_list .= "', '";
700 $profile_list .= dbesc($profile);
703 $profile_list = "'".$profile_list."'";
705 // Only act if it is a "real" post
706 // We need the additional check for the "local_profile" because of mixed situations on connector networks
707 $item = q("SELECT `id`, `mention`, `tag`,`parent`, `title`, `body`, `author-name`, `author-link`, `author-avatar`, `guid`,
708 `parent-uri`, `uri`, `contact-id`
709 FROM `item` WHERE `id` = %d AND `verb` IN ('%s', '') AND `type` != 'activity' AND
710 NOT (`author-link` IN ($profile_list)) LIMIT 1",
711 intval($itemid), dbesc(ACTIVITY_POST));
715 // Generate the notification array
717 $params["uid"] = $uid;
718 $params["notify_flags"] = $user[0]["notify-flags"];
719 $params["language"] = $user[0]["language"];
720 $params["to_name"] = $user[0]["username"];
721 $params["to_email"] = $user[0]["email"];
722 $params["item"] = $item[0];
723 $params["parent"] = $item[0]["parent"];
724 $params["link"] = App::get_baseurl().'/display/'.urlencode($item[0]["guid"]);
725 $params["otype"] = 'item';
726 $params["source_name"] = $item[0]["author-name"];
727 $params["source_link"] = $item[0]["author-link"];
728 $params["source_photo"] = $item[0]["author-avatar"];
730 if ($item[0]["parent-uri"] === $item[0]["uri"]) {
731 // Send a notification for every new post?
732 $r = q("SELECT `notify_new_posts` FROM `contact` WHERE `id` = %d AND `uid` = %d AND `notify_new_posts` LIMIT 1",
733 intval($item[0]['contact-id']),
736 $send_notification = dbm::is_result($r);
738 if (!$send_notification) {
739 $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
740 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
742 if (dbm::is_result($tags)) {
743 foreach ($tags AS $tag) {
744 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `notify_new_posts`",
745 normalise_link($tag["url"]), intval($uid));
746 if (dbm::is_result($r))
747 $send_notification = true;
752 if ($send_notification) {
753 $params["type"] = NOTIFY_SHARE;
754 $params["verb"] = ACTIVITY_TAG;
758 // Is the user mentioned in this post?
761 foreach ($profiles AS $profile) {
762 if (strpos($item[0]["tag"], "=".$profile."]") OR strpos($item[0]["body"], "=".$profile."]"))
766 if ($item[0]["mention"] OR $tagged OR ($defaulttype == NOTIFY_TAGSELF)) {
767 $params["type"] = NOTIFY_TAGSELF;
768 $params["verb"] = ACTIVITY_TAG;
771 // Is it a post that the user had started or where he interacted?
772 $parent = q("SELECT `thread`.`iid` FROM `thread` INNER JOIN `item` ON `item`.`parent` = `thread`.`iid`
773 WHERE `thread`.`iid` = %d AND `thread`.`uid` = %d AND NOT `thread`.`ignored` AND
774 (`thread`.`mention` OR `item`.`author-link` IN ($profile_list))
776 intval($item[0]["parent"]), intval($uid));
778 if ($parent AND !isset($params["type"])) {
779 $params["type"] = NOTIFY_COMMENT;
780 $params["verb"] = ACTIVITY_POST;
783 if (isset($params["type"]))
784 notification($params);
788 * @brief Formats a notification message with the notification author
790 * Replace the name with {0} but ensure to make that only once. The {0} is used
791 * later and prints the name in bold.
793 * @param string $name
794 * @param string $message
795 * @return string Formatted message
797 function format_notification_message($name, $message) {
799 $pos = strpos($message, $name);
804 if ($pos !== false) {
805 $message = substr_replace($message, '{0}', $pos, strlen($name));