3 * @file include/enotify.php
6 use Friendica\Content\Text\BBCode;
7 use Friendica\Core\Addon;
8 use Friendica\Core\Config;
9 use Friendica\Core\L10n;
10 use Friendica\Core\System;
11 use Friendica\Database\dba;
12 use Friendica\Database\DBM;
13 use Friendica\Model\Item;
14 use Friendica\Util\DateTimeFormat;
15 use Friendica\Util\Emailer;
18 * @brief Creates a notification entry and possibly sends a mail
20 * @param array $params Array with the elements:
21 * uid, item, parent, type, otype, verb, event,
22 * link, subject, body, to_name, to_email, source_name,
23 * source_link, activity, preamble, notify_flags,
24 * language, show_in_notification_page
26 function notification($params)
30 // from here on everything is in the recipients language
31 L10n::pushLang($params['language']);
33 $banner = L10n::t('Friendica Notification');
34 $product = FRIENDICA_PLATFORM;
35 $siteurl = System::baseUrl(true);
36 $thanks = L10n::t('Thank You,');
37 $sitename = Config::get('config', 'sitename');
38 if (Config::get('config', 'admin_name')) {
39 $site_admin = L10n::t('%1$s, %2$s Administrator', Config::get('config', 'admin_name'), $sitename);
41 $site_admin = L10n::t('%s Administrator', $sitename);
44 $sender_name = $sitename;
45 $hostname = $a->get_hostname();
46 if (strpos($hostname, ':')) {
47 $hostname = substr($hostname, 0, strpos($hostname, ':'));
50 $sender_email = $a->getSenderEmailAddress();
52 if ($params['type'] != SYSTEM_EMAIL) {
53 $user = dba::selectFirst('user', ['nickname', 'page-flags'],
54 ['uid' => $params['uid']]);
56 // There is no need to create notifications for forum accounts
57 if (!DBM::is_result($user) || in_array($user["page-flags"], [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 $itemlink = $siteurl.'/message/'.$params['item']['id'];
99 $subject = L10n::t('[Friendica:Notify] New mail received at %s', $sitename);
101 $preamble = L10n::t('%1$s sent you a new private message at %2$s.', $params['source_name'], $sitename);
102 $epreamble = L10n::t('%1$s sent you %2$s.', '[url='.$params['source_link'].']'.$params['source_name'].'[/url]', '[url=$itemlink]'.L10n::t('a private message').'[/url]');
104 $sitelink = L10n::t('Please visit %s to view and/or reply to your private messages.');
105 $tsitelink = sprintf($sitelink, $siteurl.'/message/'.$params['item']['id']);
106 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'/message/'.$params['item']['id'].'">'.$sitename.'</a>');
109 if ($params['type'] == NOTIFY_COMMENT) {
110 $thread = dba::selectFirst('thread', ['ignored'], ['iid' => $parent_id]);
111 if (DBM::is_result($thread) && $thread["ignored"]) {
112 logger("Thread ".$parent_id." will be ignored", LOGGER_DEBUG);
116 // Check to see if there was already a tag notify or comment notify for this post.
117 // If so don't create a second notification
118 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d, %d) AND `link` = '%s' AND `uid` = %d LIMIT 1",
119 intval(NOTIFY_TAGSELF),
120 intval(NOTIFY_COMMENT),
121 intval(NOTIFY_SHARE),
122 dbesc($params['link']),
123 intval($params['uid'])
125 if ($p && count($p)) {
130 // if it's a post figure out who's post it is.
134 if ($params['otype'] === 'item' && $parent_id) {
135 $item = Item::selectFirstForUser($params['uid'], Item::ITEM_FIELDLIST, ['id' => $parent_id]);
138 $item_post_type = item_post_type($item);
139 $itemlink = $item['plink'];
142 $dest_str = L10n::t('%1$s commented on [url=%2$s]a %3$s[/url]',
143 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
148 // "George Bull's post"
150 $dest_str = L10n::t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]',
151 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
153 $item['author-name'],
159 if (DBM::is_result($item) && $item['owner-id'] == $item['author-id'] && $item['wall']) {
160 $dest_str = L10n::t('%1$s commented on [url=%2$s]your %3$s[/url]',
161 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
167 // Some mail softwares relies on subject field for threading.
168 // So, we cannot have different subjects for notifications of the same thread.
169 // Before this we have the name of the replier on the subject rendering
170 // differents subjects for messages on the same thread.
172 $subject = L10n::t('[Friendica:Notify] Comment to conversation #%1$d by %2$s', $parent_id, $params['source_name']);
174 $preamble = L10n::t('%s commented on an item/conversation you have been following.', $params['source_name']);
175 $epreamble = $dest_str;
177 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
178 $tsitelink = sprintf($sitelink, $siteurl);
179 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
180 $itemlink = $params['link'];
183 if ($params['type'] == NOTIFY_WALL) {
184 $subject = L10n::t('[Friendica:Notify] %s posted to your profile wall', $params['source_name']);
186 $preamble = L10n::t('%1$s posted to your profile wall at %2$s', $params['source_name'], $sitename);
187 $epreamble = L10n::t('%1$s posted to [url=%2$s]your wall[/url]',
188 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
192 $sitelink = L10n::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_TAGSELF) {
199 $subject = L10n::t('[Friendica:Notify] %s tagged you', $params['source_name']);
201 $preamble = L10n::t('%1$s tagged you at %2$s', $params['source_name'], $sitename);
202 $epreamble = L10n::t('%1$s [url=%2$s]tagged you[/url].',
203 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
207 $sitelink = L10n::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 = L10n::t('[Friendica:Notify] %s shared a new post', $params['source_name']);
216 $preamble = L10n::t('%1$s shared a new post at %2$s', $params['source_name'], $sitename);
217 $epreamble = L10n::t('%1$s [url=%2$s]shared a post[/url].',
218 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
222 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
223 $tsitelink = sprintf($sitelink, $siteurl);
224 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
225 $itemlink = $params['link'];
228 if ($params['type'] == NOTIFY_POKE) {
229 $subject = L10n::t('[Friendica:Notify] %1$s poked you', $params['source_name']);
231 $preamble = L10n::t('%1$s poked you at %2$s', $params['source_name'], $sitename);
232 $epreamble = L10n::t('%1$s [url=%2$s]poked you[/url].',
233 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
237 $subject = str_replace('poked', L10n::t($params['activity']), $subject);
238 $preamble = str_replace('poked', L10n::t($params['activity']), $preamble);
239 $epreamble = str_replace('poked', L10n::t($params['activity']), $epreamble);
241 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
242 $tsitelink = sprintf($sitelink, $siteurl);
243 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
244 $itemlink = $params['link'];
247 if ($params['type'] == NOTIFY_TAGSHARE) {
248 $itemlink = $params['link'];
249 $subject = L10n::t('[Friendica:Notify] %s tagged your post', $params['source_name']);
251 $preamble = L10n::t('%1$s tagged your post at %2$s', $params['source_name'], $sitename);
252 $epreamble = L10n::t('%1$s tagged [url=%2$s]your post[/url]',
253 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
257 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
258 $tsitelink = sprintf($sitelink, $siteurl);
259 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
262 if ($params['type'] == NOTIFY_INTRO) {
263 $itemlink = $params['link'];
264 $subject = L10n::t('[Friendica:Notify] Introduction received');
266 $preamble = L10n::t('You\'ve received an introduction from \'%1$s\' at %2$s', $params['source_name'], $sitename);
267 $epreamble = L10n::t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.',
269 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
272 $body = L10n::t('You may visit their profile at %s', $params['source_link']);
274 $sitelink = L10n::t('Please visit %s to approve or reject the introduction.');
275 $tsitelink = sprintf($sitelink, $siteurl);
276 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
278 switch ($params['verb']) {
279 case ACTIVITY_FRIEND:
280 // someone started to share with user (mostly OStatus)
281 $subject = L10n::t('[Friendica:Notify] A new person is sharing with you');
283 $preamble = L10n::t('%1$s is sharing with you at %2$s', $params['source_name'], $sitename);
284 $epreamble = L10n::t('%1$s is sharing with you at %2$s',
285 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
289 case ACTIVITY_FOLLOW:
290 // someone started to follow the user (mostly OStatus)
291 $subject = L10n::t('[Friendica:Notify] You have a new follower');
293 $preamble = L10n::t('You have a new follower at %2$s : %1$s', $params['source_name'], $sitename);
294 $epreamble = L10n::t('You have a new follower at %2$s : %1$s',
295 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
300 // ACTIVITY_REQ_FRIEND is default activity for notifications
305 if ($params['type'] == NOTIFY_SUGGEST) {
306 $itemlink = $params['link'];
307 $subject = L10n::t('[Friendica:Notify] Friend suggestion received');
309 $preamble = L10n::t('You\'ve received a friend suggestion from \'%1$s\' at %2$s', $params['source_name'], $sitename);
310 $epreamble = L10n::t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.',
312 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
313 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
316 $body = L10n::t('Name:').' '.$params['item']['name']."\n";
317 $body .= L10n::t('Photo:').' '.$params['item']['photo']."\n";
318 $body .= L10n::t('You may visit their profile at %s', $params['item']['url']);
320 $sitelink = L10n::t('Please visit %s to approve or reject the suggestion.');
321 $tsitelink = sprintf($sitelink, $siteurl);
322 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
325 if ($params['type'] == NOTIFY_CONFIRM) {
326 if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
327 $itemlink = $params['link'];
328 $subject = L10n::t('[Friendica:Notify] Connection accepted');
330 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
331 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
333 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
336 $body = L10n::t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
338 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
339 $tsitelink = sprintf($sitelink, $siteurl);
340 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
341 } else { // ACTIVITY_FOLLOW
342 $itemlink = $params['link'];
343 $subject = L10n::t('[Friendica:Notify] Connection accepted');
345 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
346 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
348 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
351 $body = L10n::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']);
353 $body .= L10n::t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.', $params['source_name']);
355 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
356 $tsitelink = sprintf($sitelink, $siteurl);
357 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
361 if ($params['type'] == NOTIFY_SYSTEM) {
362 switch($params['event']) {
363 case "SYSTEM_REGISTER_REQUEST":
364 $itemlink = $params['link'];
365 $subject = L10n::t('[Friendica System Notify]') . ' ' . L10n::t('registration request');
367 $preamble = L10n::t('You\'ve received a registration request from \'%1$s\' at %2$s', $params['source_name'], $sitename);
368 $epreamble = L10n::t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.',
370 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
373 $body = L10n::t("Full Name: %s\nSite Location: %s\nLogin Name: %s (%s)",
374 $params['source_name'],
375 $siteurl, $params['source_mail'],
376 $params['source_nick']
379 $sitelink = L10n::t('Please visit %s to approve or reject the request.');
380 $tsitelink = sprintf($sitelink, $params['link']);
381 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
383 case "SYSTEM_DB_UPDATE_FAIL":
388 if ($params['type'] == SYSTEM_EMAIL) {
389 // not part of the notifications.
390 // it just send a mail to the user.
391 // It will be used by the system to send emails to users (like
392 // password reset, invitations and so) using one look (but without
393 // add a notification to the user, with could be inexistent)
394 $subject = $params['subject'];
396 $preamble = $params['preamble'];
398 $body = $params['body'];
404 $show_in_notification_page = false;
407 $subject .= " (".$nickname."@".$hostname.")";
411 'subject' => $subject,
412 'preamble' => $preamble,
413 'epreamble' => $epreamble,
415 'sitelink' => $sitelink,
416 'tsitelink' => $tsitelink,
417 'hsitelink' => $hsitelink,
418 'itemlink' => $itemlink
421 Addon::callHooks('enotify', $h);
423 $subject = $h['subject'];
425 $preamble = $h['preamble'];
426 $epreamble = $h['epreamble'];
430 $tsitelink = $h['tsitelink'];
431 $hsitelink = $h['hsitelink'];
432 $itemlink = $h['itemlink'];
434 if ($show_in_notification_page) {
435 logger("adding notification entry", LOGGER_DEBUG);
438 $hash = random_string();
439 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' LIMIT 1",
441 if (DBM::is_result($r)) {
444 } while ($dups == true);
446 /// @TODO One statement is enough
448 $datarray['hash'] = $hash;
449 $datarray['name'] = $params['source_name'];
450 $datarray['name_cache'] = strip_tags(BBCode::convert($params['source_name']));
451 $datarray['url'] = $params['source_link'];
452 $datarray['photo'] = $params['source_photo'];
453 $datarray['date'] = DateTimeFormat::utcNow();
454 $datarray['uid'] = $params['uid'];
455 $datarray['link'] = $itemlink;
456 $datarray['iid'] = $item_id;
457 $datarray['parent'] = $parent_id;
458 $datarray['type'] = $params['type'];
459 $datarray['verb'] = $params['verb'];
460 $datarray['otype'] = $params['otype'];
461 $datarray['abort'] = false;
463 Addon::callHooks('enotify_store', $datarray);
465 if ($datarray['abort']) {
470 // create notification entry in DB
471 q("INSERT INTO `notify` (`hash`, `name`, `url`, `photo`, `date`, `uid`, `link`, `iid`, `parent`, `type`, `verb`, `otype`, `name_cache`)
472 values('%s', '%s', '%s', '%s', '%s', %d, '%s', %d, %d, %d, '%s', '%s', '%s')",
473 dbesc($datarray['hash']),
474 dbesc($datarray['name']),
475 dbesc($datarray['url']),
476 dbesc($datarray['photo']),
477 dbesc($datarray['date']),
478 intval($datarray['uid']),
479 dbesc($datarray['link']),
480 intval($datarray['iid']),
481 intval($datarray['parent']),
482 intval($datarray['type']),
483 dbesc($datarray['verb']),
484 dbesc($datarray['otype']),
485 dbesc($datarray["name_cache"])
488 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' AND `uid` = %d LIMIT 1",
490 intval($params['uid'])
493 $notify_id = $r[0]['id'];
499 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
500 // After we've stored everything, look again to see if there are any duplicates and if so remove them
501 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
502 intval(NOTIFY_TAGSELF),
503 intval(NOTIFY_COMMENT),
504 dbesc($params['link']),
505 intval($params['uid'])
507 if ($p && (count($p) > 1)) {
508 for ($d = 1; $d < count($p); $d ++) {
509 dba::delete('notify', ['id' => $p[$d]['id']]);
512 // only continue on if we stored the first one
513 if ($notify_id != $p[0]['id']) {
519 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
520 $msg = replace_macros($epreamble, ['$itemlink' => $itemlink]);
521 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(BBCode::convert($msg)));
522 q("UPDATE `notify` SET `msg` = '%s', `msg_cache` = '%s' WHERE `id` = %d AND `uid` = %d",
526 intval($params['uid'])
530 // send email notification if notification preferences permit
531 if ((intval($params['notify_flags']) & intval($params['type']))
532 || $params['type'] == NOTIFY_SYSTEM
533 || $params['type'] == SYSTEM_EMAIL) {
535 logger('sending notification email');
537 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
538 $id_for_parent = $params['parent']."@".$hostname;
540 // Is this the first email notification for this parent item and user?
542 $r = q("SELECT `id` FROM `notify-threads` WHERE `master-parent-item` = %d AND `receiver-uid` = %d LIMIT 1",
543 intval($params['parent']),
544 intval($params['uid']));
546 // If so, create the record of it and use a message-id smtp header.
549 logger("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), LOGGER_DEBUG);
550 q("INSERT INTO `notify-threads` (`notify-id`, `master-parent-item`, `receiver-uid`, `parent-item`)
551 values(%d, %d, %d, %d)",
553 intval($params['parent']),
554 intval($params['uid']),
557 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
558 $log_msg = "include/enotify: No previous notification found for this parent:\n".
559 " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
560 logger($log_msg, LOGGER_DEBUG);
562 // If not, just "follow" the thread.
563 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
564 logger("There's already a notification for this parent:\n".print_r($r, true), LOGGER_DEBUG);
568 $textversion = BBCode::toPlaintext($body);
569 $htmlversion = BBCode::convert($body);
572 $datarray['banner'] = $banner;
573 $datarray['product'] = $product;
574 $datarray['preamble'] = $preamble;
575 $datarray['sitename'] = $sitename;
576 $datarray['siteurl'] = $siteurl;
577 $datarray['type'] = $params['type'];
578 $datarray['parent'] = $parent_id;
579 $datarray['source_name'] = $params['source_name'];
580 $datarray['source_link'] = $params['source_link'];
581 $datarray['source_photo'] = $params['source_photo'];
582 $datarray['uid'] = $params['uid'];
583 $datarray['username'] = $params['to_name'];
584 $datarray['hsitelink'] = $hsitelink;
585 $datarray['tsitelink'] = $tsitelink;
586 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
587 $datarray['titemlink'] = $itemlink;
588 $datarray['thanks'] = $thanks;
589 $datarray['site_admin'] = $site_admin;
590 $datarray['title'] = stripslashes($title);
591 $datarray['htmlversion'] = $htmlversion;
592 $datarray['textversion'] = $textversion;
593 $datarray['subject'] = $subject;
594 $datarray['headers'] = $additional_mail_header;
596 Addon::callHooks('enotify_mail', $datarray);
598 // check whether sending post content in email notifications is allowed
599 // always true for SYSTEM_EMAIL
600 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
602 // load the template for private message notifications
603 $tpl = get_markup_template('email_notify_html.tpl');
604 $email_html_body = replace_macros($tpl, [
605 '$banner' => $datarray['banner'],
606 '$product' => $datarray['product'],
607 '$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
608 '$sitename' => $datarray['sitename'],
609 '$siteurl' => $datarray['siteurl'],
610 '$source_name' => $datarray['source_name'],
611 '$source_link' => $datarray['source_link'],
612 '$source_photo' => $datarray['source_photo'],
613 '$username' => $datarray['username'],
614 '$hsitelink' => $datarray['hsitelink'],
615 '$hitemlink' => $datarray['hitemlink'],
616 '$thanks' => $datarray['thanks'],
617 '$site_admin' => $datarray['site_admin'],
618 '$title' => $datarray['title'],
619 '$htmlversion' => $datarray['htmlversion'],
620 '$content_allowed' => $content_allowed,
623 // load the template for private message notifications
624 $tpl = get_markup_template('email_notify_text.tpl');
625 $email_text_body = replace_macros($tpl, [
626 '$banner' => $datarray['banner'],
627 '$product' => $datarray['product'],
628 '$preamble' => $datarray['preamble'],
629 '$sitename' => $datarray['sitename'],
630 '$siteurl' => $datarray['siteurl'],
631 '$source_name' => $datarray['source_name'],
632 '$source_link' => $datarray['source_link'],
633 '$source_photo' => $datarray['source_photo'],
634 '$username' => $datarray['username'],
635 '$tsitelink' => $datarray['tsitelink'],
636 '$titemlink' => $datarray['titemlink'],
637 '$thanks' => $datarray['thanks'],
638 '$site_admin' => $datarray['site_admin'],
639 '$title' => $datarray['title'],
640 '$textversion' => $datarray['textversion'],
641 '$content_allowed' => $content_allowed,
644 // use the Emailer class to send the message
645 return Emailer::send(
647 'uid' => $params['uid'],
648 'fromName' => $sender_name,
649 'fromEmail' => $sender_email,
650 'replyTo' => $sender_email,
651 'toEmail' => $params['to_email'],
652 'messageSubject' => $datarray['subject'],
653 'htmlVersion' => $email_html_body,
654 'textVersion' => $email_text_body,
655 'additionalMailHeader' => $datarray['headers']]
663 * @brief Checks for users who should be notified
665 * @param int $itemid ID of the item for which the check should be done
667 function check_user_notification($itemid) {
668 // fetch all users in the thread
669 $users = dba::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
670 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
671 WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
672 while ($user = dba::fetch($users)) {
673 check_item_notification($itemid, $user['uid']);
679 * @brief Checks for item related notifications and sends them
681 * @param int $itemid ID of the item for which the check should be done
682 * @param int $uid User ID
683 * @param string $defaulttype (Optional) Forces a notification with this type.
685 function check_item_notification($itemid, $uid, $defaulttype = "") {
686 $notification_data = ["uid" => $uid, "profiles" => []];
687 Addon::callHooks('check_item_notification', $notification_data);
689 $profiles = $notification_data["profiles"];
691 $fields = ['notify-flags', 'language', 'username', 'email', 'nickname'];
692 $user = dba::selectFirst('user', $fields, ['uid' => $uid]);
693 if (!DBM::is_result($user)) {
697 $owner = dba::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
698 if (!DBM::is_result($owner)) {
702 // This is our regular URL format
703 $profiles[] = $owner["url"];
705 // Notifications from Diaspora are often with an URL in the Diaspora format
706 $profiles[] = System::baseUrl()."/u/".$user["nickname"];
710 foreach ($profiles AS $profile) {
711 // Check for invalid profile urls. 13 should be the shortest possible profile length:
713 // Additionally check for invalid urls that would return the normalised value "http:"
714 if ((strlen($profile) >= 13) && (normalise_link($profile) != "http:")) {
715 if (!in_array($profile, $profiles2))
716 $profiles2[] = $profile;
718 $profile = normalise_link($profile);
719 if (!in_array($profile, $profiles2))
720 $profiles2[] = $profile;
722 $profile = str_replace("http://", "https://", $profile);
723 if (!in_array($profile, $profiles2))
724 $profiles2[] = $profile;
728 $profiles = $profiles2;
730 $ret = dba::select('contact', ['id'], ['uid' => 0, 'nurl' => $profiles]);
734 while ($contact = dba::fetch($ret)) {
735 $contacts[] = $contact['id'];
738 $contact_list = implode(',', $contacts);
742 // Only act if it is a "real" post
743 // We need the additional check for the "local_profile" because of mixed situations on connector networks
744 $fields = ['id', 'mention', 'tag', 'parent', 'title', 'body',
745 'author-link', 'author-name', 'author-avatar', 'author-id',
746 'guid', 'parent-uri', 'uri', 'contact-id', 'network'];
747 $condition = ['id' => $itemid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
748 $item = Item::selectFirst($fields, $condition);
749 if (!DBM::is_result($item) || in_array($item['author-id'], $contacts)) {
753 // Generate the notification array
755 $params["uid"] = $uid;
756 $params["notify_flags"] = $user["notify-flags"];
757 $params["language"] = $user["language"];
758 $params["to_name"] = $user["username"];
759 $params["to_email"] = $user["email"];
760 $params["item"] = $item;
761 $params["parent"] = $item["parent"];
762 $params["link"] = System::baseUrl().'/display/'.urlencode($item["guid"]);
763 $params["otype"] = 'item';
764 $params["source_name"] = $item["author-name"];
765 $params["source_link"] = $item["author-link"];
766 $params["source_photo"] = $item["author-avatar"];
768 if ($item["parent-uri"] === $item["uri"]) {
769 // Send a notification for every new post?
770 $send_notification = dba::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true]);
772 if (!$send_notification) {
773 $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
774 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
776 if (DBM::is_result($tags)) {
777 foreach ($tags AS $tag) {
778 $condition = ['nurl' => normalise_link($tag["url"]), 'uid' => $uid, 'notify_new_posts' => true];
779 $r = dba::exists('contact', $condition);
781 $send_notification = true;
787 if ($send_notification) {
788 $params["type"] = NOTIFY_SHARE;
789 $params["verb"] = ACTIVITY_TAG;
793 // Is the user mentioned in this post?
796 foreach ($profiles AS $profile) {
797 if (strpos($item["tag"], "=".$profile."]") || strpos($item["body"], "=".$profile."]"))
801 if ($item["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
802 $params["type"] = NOTIFY_TAGSELF;
803 $params["verb"] = ACTIVITY_TAG;
806 // Is it a post that the user had started or where he interacted?
807 $parent = q("SELECT `thread`.`iid` FROM `thread` INNER JOIN `item` ON `item`.`parent` = `thread`.`iid`
808 WHERE `thread`.`iid` = %d AND NOT `thread`.`ignored` AND
809 (`thread`.`mention` OR `item`.`author-id` IN ($contact_list))
811 intval($item["parent"]));
813 if ($parent && !isset($params["type"])) {
814 $params["type"] = NOTIFY_COMMENT;
815 $params["verb"] = ACTIVITY_POST;
818 if (isset($params["type"]))
819 notification($params);
823 * @brief Formats a notification message with the notification author
825 * Replace the name with {0} but ensure to make that only once. The {0} is used
826 * later and prints the name in bold.
828 * @param string $name
829 * @param string $message
830 * @return string Formatted message
832 function format_notification_message($name, $message) {
834 $pos = strpos($message, $name);
839 if ($pos !== false) {
840 $message = substr_replace($message, '{0}', $pos, strlen($name));