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/bbcode.php';
12 require_once 'include/html2bbcode.php';
15 * @brief Creates a notification entry and possibly sends a mail
17 * @param array $params Array with the elements:
18 uid, item, parent, type, otype, verb, event,
19 link, subject, body, to_name, to_email, source_name,
20 source_link, activity, preamble, notify_flags,
21 language, show_in_notification_page
23 function notification($params)
27 // from here on everything is in the recipients language
28 push_lang($params['language']);
30 $banner = t('Friendica Notification');
31 $product = FRIENDICA_PLATFORM;
32 $siteurl = System::baseUrl(true);
33 $thanks = t('Thank You,');
34 $sitename = $a->config['sitename'];
35 if (!x($a->config['admin_name'])) {
36 $site_admin = sprintf(t('%s Administrator'), $sitename);
38 $site_admin = sprintf(t('%1$s, %2$s Administrator'), $a->config['admin_name'], $sitename);
41 $sender_name = $sitename;
42 $hostname = $a->get_hostname();
43 if (strpos($hostname, ':')) {
44 $hostname = substr($hostname, 0, strpos($hostname, ':'));
47 $sender_email = $a->config['sender_email'];
48 if (empty($sender_email)) {
49 $sender_email = t('noreply').'@'.$hostname;
52 if ($params['type'] != SYSTEM_EMAIL) {
53 $user = dba::select('user', array('nickname', 'page-flags'),
54 array('uid' => $params['uid']), array('limit' => 1));
56 // There is no need to create notifications for forum accounts
57 if (!DBM::is_result($user) || in_array($user["page-flags"], array(PAGE_COMMUNITY, PAGE_PRVGROUP))) {
61 $nickname = $user["nickname"];
63 // with $params['show_in_notification_page'] == false, the notification isn't inserted into
64 // the database, and an email is sent if applicable.
65 // default, if not specified: true
66 $show_in_notification_page = ((x($params, 'show_in_notification_page')) ? $params['show_in_notification_page']:true);
68 $additional_mail_header = "";
69 $additional_mail_header .= "Precedence: list\n";
70 $additional_mail_header .= "X-Friendica-Host: ".$hostname."\n";
71 $additional_mail_header .= "X-Friendica-Account: <".$nickname."@".$hostname.">\n";
72 $additional_mail_header .= "X-Friendica-Platform: ".FRIENDICA_PLATFORM."\n";
73 $additional_mail_header .= "X-Friendica-Version: ".FRIENDICA_VERSION."\n";
74 $additional_mail_header .= "List-ID: <notification.".$hostname.">\n";
75 $additional_mail_header .= "List-Archive: <".System::baseUrl()."/notifications/system>\n";
77 if (array_key_exists('item', $params)) {
78 $title = $params['item']['title'];
79 $body = $params['item']['body'];
84 if (isset($params['item']['id'])) {
85 $item_id = $params['item']['id'];
90 if (isset($params['parent'])) {
91 $parent_id = $params['parent'];
96 if ($params['type'] == NOTIFY_MAIL) {
97 $subject = sprintf(t('[Friendica:Notify] New mail received at %s'), $sitename);
99 $preamble = sprintf(t('%1$s sent you a new private message at %2$s.'), $params['source_name'], $sitename);
100 $epreamble = sprintf(t('%1$s sent you %2$s.'), '[url='.$params['source_link'].']'.$params['source_name'].'[/url]', '[url=$itemlink]'.t('a private message').'[/url]');
102 $sitelink = t('Please visit %s to view and/or reply to your private messages.');
103 $tsitelink = sprintf($sitelink, $siteurl.'/message/'.$params['item']['id']);
104 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'/message/'.$params['item']['id'].'">'.$sitename.'</a>');
105 $itemlink = $siteurl.'/message/'.$params['item']['id'];
108 if ($params['type'] == NOTIFY_COMMENT) {
109 $p = dba::select('thread', ['ignored'], ['iid' => $parent_id], ['limit' => 1]);
110 if (DBM::is_result($p) && $p["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
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 LIMIT 1",
139 $item_post_type = item_post_type($p[0]);
142 $dest_str = sprintf(t('%1$s commented on [url=%2$s]a %3$s[/url]'),
143 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
147 // "George Bull's post"
149 $dest_str = sprintf(t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]'),
150 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
152 $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]',
164 // Some mail softwares relies on subject field for threading.
165 // So, we cannot have different subjects for notifications of the same thread.
166 // Before this we have the name of the replier on the subject rendering
167 // differents subjects for messages on the same thread.
169 $subject = sprintf(t('[Friendica:Notify] Comment to conversation #%1$d by %2$s'), $parent_id, $params['source_name']);
171 $preamble = sprintf(t('%s commented on an item/conversation you have been following.'), $params['source_name']);
172 $epreamble = $dest_str;
174 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
175 $tsitelink = sprintf($sitelink, $siteurl);
176 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
177 $itemlink = $params['link'];
180 if ($params['type'] == NOTIFY_WALL) {
181 $subject = sprintf(t('[Friendica:Notify] %s posted to your profile wall'), $params['source_name']);
183 $preamble = sprintf(t('%1$s posted to your profile wall at %2$s'), $params['source_name'], $sitename);
184 $epreamble = sprintf(t('%1$s posted to [url=%2$s]your wall[/url]'),
185 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
188 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
189 $tsitelink = sprintf($sitelink, $siteurl);
190 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
191 $itemlink = $params['link'];
194 if ($params['type'] == NOTIFY_TAGSELF) {
195 $subject = sprintf(t('[Friendica:Notify] %s tagged you'), $params['source_name']);
197 $preamble = sprintf(t('%1$s tagged you at %2$s'), $params['source_name'], $sitename);
198 $epreamble = sprintf(t('%1$s [url=%2$s]tagged you[/url].'),
199 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
202 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
203 $tsitelink = sprintf($sitelink, $siteurl);
204 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
205 $itemlink = $params['link'];
208 if ($params['type'] == NOTIFY_SHARE) {
209 $subject = sprintf(t('[Friendica:Notify] %s shared a new post'), $params['source_name']);
211 $preamble = sprintf(t('%1$s shared a new post at %2$s'), $params['source_name'], $sitename);
212 $epreamble = sprintf(t('%1$s [url=%2$s]shared a post[/url].'),
213 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
216 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
217 $tsitelink = sprintf($sitelink, $siteurl);
218 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
219 $itemlink = $params['link'];
222 if ($params['type'] == NOTIFY_POKE) {
223 $subject = sprintf(t('[Friendica:Notify] %1$s poked you'), $params['source_name']);
225 $preamble = sprintf(t('%1$s poked you at %2$s'), $params['source_name'], $sitename);
226 $epreamble = sprintf(t('%1$s [url=%2$s]poked you[/url].'),
227 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
230 $subject = str_replace('poked', t($params['activity']), $subject);
231 $preamble = str_replace('poked', t($params['activity']), $preamble);
232 $epreamble = str_replace('poked', t($params['activity']), $epreamble);
234 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
235 $tsitelink = sprintf($sitelink, $siteurl);
236 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
237 $itemlink = $params['link'];
240 if ($params['type'] == NOTIFY_TAGSHARE) {
241 $subject = sprintf(t('[Friendica:Notify] %s tagged your post'), $params['source_name']);
243 $preamble = sprintf(t('%1$s tagged your post at %2$s'), $params['source_name'], $sitename);
244 $epreamble = sprintf(t('%1$s tagged [url=%2$s]your post[/url]'),
245 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
248 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
249 $tsitelink = sprintf($sitelink, $siteurl);
250 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
251 $itemlink = $params['link'];
254 if ($params['type'] == NOTIFY_INTRO) {
255 $subject = sprintf(t('[Friendica:Notify] Introduction received'));
257 $preamble = sprintf(t('You\'ve received an introduction from \'%1$s\' at %2$s'), $params['source_name'], $sitename);
258 $epreamble = sprintf(t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.'),
260 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
262 $body = sprintf(t('You may visit their profile at %s'), $params['source_link']);
264 $sitelink = t('Please visit %s to approve or reject the introduction.');
265 $tsitelink = sprintf($sitelink, $siteurl);
266 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
267 $itemlink = $params['link'];
269 switch ($params['verb']) {
270 case ACTIVITY_FRIEND:
271 // someone started to share with user (mostly OStatus)
272 $subject = sprintf(t('[Friendica:Notify] A new person is sharing with you'));
274 $preamble = sprintf(t('%1$s is sharing with you at %2$s'), $params['source_name'], $sitename);
275 $epreamble = sprintf(t('%1$s is sharing with you at %2$s'),
276 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
279 case ACTIVITY_FOLLOW:
280 // someone started to follow the user (mostly OStatus)
281 $subject = sprintf(t('[Friendica:Notify] You have a new follower'));
283 $preamble = sprintf(t('You have a new follower at %2$s : %1$s'), $params['source_name'], $sitename);
284 $epreamble = sprintf(t('You have a new follower at %2$s : %1$s'),
285 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
289 // ACTIVITY_REQ_FRIEND is default activity for notifications
294 if ($params['type'] == NOTIFY_SUGGEST) {
295 $subject = sprintf(t('[Friendica:Notify] Friend suggestion received'));
297 $preamble = sprintf(t('You\'ve received a friend suggestion from \'%1$s\' at %2$s'), $params['source_name'], $sitename);
298 $epreamble = sprintf(t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.'),
300 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
301 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
303 $body = t('Name:').' '.$params['item']['name']."\n";
304 $body .= t('Photo:').' '.$params['item']['photo']."\n";
305 $body .= sprintf(t('You may visit their profile at %s'), $params['item']['url']);
307 $sitelink = t('Please visit %s to approve or reject the suggestion.');
308 $tsitelink = sprintf($sitelink, $siteurl);
309 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
310 $itemlink = $params['link'];
313 if ($params['type'] == NOTIFY_CONFIRM) {
314 if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
315 $subject = sprintf(t('[Friendica:Notify] Connection accepted'));
317 $preamble = sprintf(t('\'%1$s\' has accepted your connection request at %2$s'), $params['source_name'], $sitename);
318 $epreamble = sprintf(t('%2$s has accepted your [url=%1$s]connection request[/url].'),
320 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
322 $body = t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
324 $sitelink = t('Please visit %s if you wish to make any changes to this relationship.');
325 $tsitelink = sprintf($sitelink, $siteurl);
326 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
327 $itemlink = $params['link'];
328 } else { // ACTIVITY_FOLLOW
329 $subject = sprintf(t('[Friendica:Notify] Connection accepted'));
331 $preamble = sprintf(t('\'%1$s\' has accepted your connection request at %2$s'), $params['source_name'], $sitename);
332 $epreamble = sprintf(t('%2$s has accepted your [url=%1$s]connection request[/url].'),
334 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
336 $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']);
338 $body .= sprintf(t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.'), $params['source_name']);
340 $sitelink = t('Please visit %s if you wish to make any changes to this relationship.');
341 $tsitelink = sprintf($sitelink, $siteurl);
342 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
343 $itemlink = $params['link'];
347 if ($params['type'] == NOTIFY_SYSTEM) {
348 switch($params['event']) {
349 case "SYSTEM_REGISTER_REQUEST":
350 $subject = sprintf(t('[Friendica System:Notify] registration request'));
352 $preamble = sprintf(t('You\'ve received a registration request from \'%1$s\' at %2$s'), $params['source_name'], $sitename);
353 $epreamble = sprintf(t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.'),
355 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
357 $body = sprintf(t('Full Name: %1$s\nSite Location: %2$s\nLogin Name: %3$s (%4$s)'),
358 $params['source_name'], $siteurl, $params['source_mail'], $params['source_nick']);
360 $sitelink = t('Please visit %s to approve or reject the request.');
361 $tsitelink = sprintf($sitelink, $params['link']);
362 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
363 $itemlink = $params['link'];
365 case "SYSTEM_DB_UPDATE_FAIL":
370 if ($params['type'] == SYSTEM_EMAIL) {
371 // not part of the notifications.
372 // it just send a mail to the user.
373 // It will be used by the system to send emails to users (like
374 // password reset, invitations and so) using one look (but without
375 // add a notification to the user, with could be inexistent)
376 $subject = $params['subject'];
378 $preamble = $params['preamble'];
380 $body = $params['body'];
386 $show_in_notification_page = false;
389 $subject .= " (".$nickname."@".$hostname.")";
393 'subject' => $subject,
394 'preamble' => $preamble,
395 'epreamble' => $epreamble,
397 'sitelink' => $sitelink,
398 'tsitelink' => $tsitelink,
399 'hsitelink' => $hsitelink,
400 'itemlink' => $itemlink
403 call_hooks('enotify', $h);
405 $subject = $h['subject'];
407 $preamble = $h['preamble'];
408 $epreamble = $h['epreamble'];
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
453 q("INSERT INTO `notify` (`hash`, `name`, `url`, `photo`, `date`, `uid`, `link`, `iid`, `parent`, `type`, `verb`, `otype`, `name_cache`)
454 values('%s', '%s', '%s', '%s', '%s', %d, '%s', %d, %d, %d, '%s', '%s', '%s')",
455 dbesc($datarray['hash']),
456 dbesc($datarray['name']),
457 dbesc($datarray['url']),
458 dbesc($datarray['photo']),
459 dbesc($datarray['date']),
460 intval($datarray['uid']),
461 dbesc($datarray['link']),
462 intval($datarray['iid']),
463 intval($datarray['parent']),
464 intval($datarray['type']),
465 dbesc($datarray['verb']),
466 dbesc($datarray['otype']),
467 dbesc($datarray["name_cache"])
470 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' AND `uid` = %d LIMIT 1",
472 intval($params['uid'])
475 $notify_id = $r[0]['id'];
481 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
482 // After we've stored everything, look again to see if there are any duplicates and if so remove them
483 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
484 intval(NOTIFY_TAGSELF),
485 intval(NOTIFY_COMMENT),
486 dbesc($params['link']),
487 intval($params['uid'])
489 if ($p && (count($p) > 1)) {
490 for ($d = 1; $d < count($p); $d ++) {
491 dba::delete('notify', array('id' => $p[$d]['id']));
494 // only continue on if we stored the first one
495 if ($notify_id != $p[0]['id']) {
501 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
502 $msg = replace_macros($epreamble, array('$itemlink' => $itemlink));
503 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(bbcode($msg)));
504 q("UPDATE `notify` SET `msg` = '%s', `msg_cache` = '%s' WHERE `id` = %d AND `uid` = %d",
508 intval($params['uid'])
512 // send email notification if notification preferences permit
513 if ((intval($params['notify_flags']) & intval($params['type']))
514 || $params['type'] == NOTIFY_SYSTEM
515 || $params['type'] == SYSTEM_EMAIL) {
517 logger('sending notification email');
519 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
520 $id_for_parent = $params['parent']."@".$hostname;
522 // Is this the first email notification for this parent item and user?
524 $r = q("SELECT `id` FROM `notify-threads` WHERE `master-parent-item` = %d AND `receiver-uid` = %d LIMIT 1",
525 intval($params['parent']),
526 intval($params['uid']));
528 // If so, create the record of it and use a message-id smtp header.
531 logger("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), LOGGER_DEBUG);
532 q("INSERT INTO `notify-threads` (`notify-id`, `master-parent-item`, `receiver-uid`, `parent-item`)
533 values(%d, %d, %d, %d)",
535 intval($params['parent']),
536 intval($params['uid']),
539 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
540 $log_msg = "include/enotify: No previous notification found for this parent:\n".
541 " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
542 logger($log_msg, LOGGER_DEBUG);
544 // If not, just "follow" the thread.
545 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
546 logger("There's already a notification for this parent:\n".print_r($r, true), LOGGER_DEBUG);
550 // textversion keeps linebreaks
551 $textversion = strip_tags(str_replace("<br>", "\n", html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n"), "\n",
552 $body))),ENT_QUOTES, 'UTF-8')));
553 $htmlversion = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n\\n", "\\n"),
554 "<br />\n", $body))), ENT_QUOTES, 'UTF-8');
557 $datarray['banner'] = $banner;
558 $datarray['product'] = $product;
559 $datarray['preamble'] = $preamble;
560 $datarray['sitename'] = $sitename;
561 $datarray['siteurl'] = $siteurl;
562 $datarray['type'] = $params['type'];
563 $datarray['parent'] = $params['parent'];
564 $datarray['source_name'] = $params['source_name'];
565 $datarray['source_link'] = $params['source_link'];
566 $datarray['source_photo'] = $params['source_photo'];
567 $datarray['uid'] = $params['uid'];
568 $datarray['username'] = $params['to_name'];
569 $datarray['hsitelink'] = $hsitelink;
570 $datarray['tsitelink'] = $tsitelink;
571 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
572 $datarray['titemlink'] = $itemlink;
573 $datarray['thanks'] = $thanks;
574 $datarray['site_admin'] = $site_admin;
575 $datarray['title'] = stripslashes($title);
576 $datarray['htmlversion'] = $htmlversion;
577 $datarray['textversion'] = $textversion;
578 $datarray['subject'] = $subject;
579 $datarray['headers'] = $additional_mail_header;
581 call_hooks('enotify_mail', $datarray);
583 // check whether sending post content in email notifications is allowed
584 // always true for SYSTEM_EMAIL
585 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
587 // load the template for private message notifications
588 $tpl = get_markup_template('email_notify_html.tpl');
589 $email_html_body = replace_macros($tpl, array(
590 '$banner' => $datarray['banner'],
591 '$product' => $datarray['product'],
592 '$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
593 '$sitename' => $datarray['sitename'],
594 '$siteurl' => $datarray['siteurl'],
595 '$source_name' => $datarray['source_name'],
596 '$source_link' => $datarray['source_link'],
597 '$source_photo' => $datarray['source_photo'],
598 '$username' => $datarray['to_name'],
599 '$hsitelink' => $datarray['hsitelink'],
600 '$hitemlink' => $datarray['hitemlink'],
601 '$thanks' => $datarray['thanks'],
602 '$site_admin' => $datarray['site_admin'],
603 '$title' => $datarray['title'],
604 '$htmlversion' => $datarray['htmlversion'],
605 '$content_allowed' => $content_allowed,
608 // load the template for private message notifications
609 $tpl = get_markup_template('email_notify_text.tpl');
610 $email_text_body = replace_macros($tpl, array(
611 '$banner' => $datarray['banner'],
612 '$product' => $datarray['product'],
613 '$preamble' => $datarray['preamble'],
614 '$sitename' => $datarray['sitename'],
615 '$siteurl' => $datarray['siteurl'],
616 '$source_name' => $datarray['source_name'],
617 '$source_link' => $datarray['source_link'],
618 '$source_photo' => $datarray['source_photo'],
619 '$username' => $datarray['to_name'],
620 '$tsitelink' => $datarray['tsitelink'],
621 '$titemlink' => $datarray['titemlink'],
622 '$thanks' => $datarray['thanks'],
623 '$site_admin' => $datarray['site_admin'],
624 '$title' => $datarray['title'],
625 '$textversion' => $datarray['textversion'],
626 '$content_allowed' => $content_allowed,
629 // use the Emailer class to send the message
630 return Emailer::send(
632 'uid' => $params['uid'],
633 'fromName' => $sender_name,
634 'fromEmail' => $sender_email,
635 'replyTo' => $sender_email,
636 'toEmail' => $params['to_email'],
637 'messageSubject' => $datarray['subject'],
638 'htmlVersion' => $email_html_body,
639 'textVersion' => $email_text_body,
640 'additionalMailHeader' => $datarray['headers'])
648 * @brief Checks for users who should be notified
650 * @param int $itemid ID of the item for which the check should be done
652 function check_user_notification($itemid) {
653 // fetch all users in the thread
654 $users = dba::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
655 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
656 WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
657 while ($user = dba::fetch($users)) {
658 check_item_notification($itemid, $user['uid']);
664 * @brief Checks for item related notifications and sends them
666 * @param int $itemid ID of the item for which the check should be done
667 * @param int $uid User ID
668 * @param str $defaulttype (Optional) Forces a notification with this type.
670 function check_item_notification($itemid, $uid, $defaulttype = "") {
671 $notification_data = array("uid" => $uid, "profiles" => array());
672 call_hooks('check_item_notification', $notification_data);
674 $profiles = $notification_data["profiles"];
676 $fields = ['notify-flags', 'language', 'username', 'email', 'nickname'];
677 $user = dba::select('user', $fields, ['uid' => $uid], ['limit' => 1]);
678 if (!DBM::is_result($user)) {
682 $owner = dba::select('contact', ['url'], ['self' => true, 'uid' => $uid], ['limit' => 1]);
683 if (!DBM::is_result($owner)) {
687 // This is our regular URL format
688 $profiles[] = $owner["url"];
690 // Notifications from Diaspora are often with an URL in the Diaspora format
691 $profiles[] = System::baseUrl()."/u/".$user["nickname"];
693 $profiles2 = array();
695 foreach ($profiles AS $profile) {
696 // Check for invalid profile urls. 13 should be the shortest possible profile length:
698 // Additionally check for invalid urls that would return the normalised value "http:"
699 if ((strlen($profile) >= 13) && (normalise_link($profile) != "http:")) {
700 if (!in_array($profile, $profiles2))
701 $profiles2[] = $profile;
703 $profile = normalise_link($profile);
704 if (!in_array($profile, $profiles2))
705 $profiles2[] = $profile;
707 $profile = str_replace("http://", "https://", $profile);
708 if (!in_array($profile, $profiles2))
709 $profiles2[] = $profile;
713 $profiles = $profiles2;
717 foreach ($profiles AS $profile) {
718 if ($profile_list != "")
719 $profile_list .= "', '";
721 $profile_list .= dbesc($profile);
724 $profile_list = "'".$profile_list."'";
726 // Only act if it is a "real" post
727 // We need the additional check for the "local_profile" because of mixed situations on connector networks
728 $item = q("SELECT `id`, `mention`, `tag`,`parent`, `title`, `body`, `author-name`, `author-link`, `author-avatar`, `guid`,
729 `parent-uri`, `uri`, `contact-id`
730 FROM `item` WHERE `id` = %d AND `verb` IN ('%s', '') AND `type` != 'activity' AND
731 NOT (`author-link` IN ($profile_list)) LIMIT 1",
732 intval($itemid), dbesc(ACTIVITY_POST));
736 // Generate the notification array
738 $params["uid"] = $uid;
739 $params["notify_flags"] = $user["notify-flags"];
740 $params["language"] = $user["language"];
741 $params["to_name"] = $user["username"];
742 $params["to_email"] = $user["email"];
743 $params["item"] = $item[0];
744 $params["parent"] = $item[0]["parent"];
745 $params["link"] = System::baseUrl().'/display/'.urlencode($item[0]["guid"]);
746 $params["otype"] = 'item';
747 $params["source_name"] = $item[0]["author-name"];
748 $params["source_link"] = $item[0]["author-link"];
749 $params["source_photo"] = $item[0]["author-avatar"];
751 if ($item[0]["parent-uri"] === $item[0]["uri"]) {
752 // Send a notification for every new post?
753 $send_notification = dba::exists('contact', ['id' => $item[0]['contact-id'], 'notify_new_posts' => true]);
755 if (!$send_notification) {
756 $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
757 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
759 if (DBM::is_result($tags)) {
760 foreach ($tags AS $tag) {
761 $condition = ['nurl' => normalise_link($tag["url"]), 'uid' => $uid, 'notify_new_posts' => true];
762 $r = dba::exists('contact', $condition);
764 $send_notification = true;
770 if ($send_notification) {
771 $params["type"] = NOTIFY_SHARE;
772 $params["verb"] = ACTIVITY_TAG;
776 // Is the user mentioned in this post?
779 foreach ($profiles AS $profile) {
780 if (strpos($item[0]["tag"], "=".$profile."]") || strpos($item[0]["body"], "=".$profile."]"))
784 if ($item[0]["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
785 $params["type"] = NOTIFY_TAGSELF;
786 $params["verb"] = ACTIVITY_TAG;
789 // Is it a post that the user had started or where he interacted?
790 $parent = q("SELECT `thread`.`iid` FROM `thread` INNER JOIN `item` ON `item`.`parent` = `thread`.`iid`
791 WHERE `thread`.`iid` = %d AND NOT `thread`.`ignored` AND
792 (`thread`.`mention` OR `item`.`author-link` IN ($profile_list))
794 intval($item[0]["parent"]));
796 if ($parent && !isset($params["type"])) {
797 $params["type"] = NOTIFY_COMMENT;
798 $params["verb"] = ACTIVITY_POST;
801 if (isset($params["type"]))
802 notification($params);
806 * @brief Formats a notification message with the notification author
808 * Replace the name with {0} but ensure to make that only once. The {0} is used
809 * later and prints the name in bold.
811 * @param string $name
812 * @param string $message
813 * @return string Formatted message
815 function format_notification_message($name, $message) {
817 $pos = strpos($message, $name);
822 if ($pos !== false) {
823 $message = substr_replace($message, '{0}', $pos, strlen($name));