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\DBM;
12 use Friendica\Util\DateTimeFormat;
13 use Friendica\Util\Emailer;
14 use Friendica\Model\Item;
17 * @brief Creates a notification entry and possibly sends a mail
19 * @param array $params Array with the elements:
20 * uid, item, parent, type, otype, verb, event,
21 * link, subject, body, to_name, to_email, source_name,
22 * source_link, activity, preamble, notify_flags,
23 * language, show_in_notification_page
25 function notification($params)
29 // from here on everything is in the recipients language
30 L10n::pushLang($params['language']);
32 $banner = L10n::t('Friendica Notification');
33 $product = FRIENDICA_PLATFORM;
34 $siteurl = System::baseUrl(true);
35 $thanks = L10n::t('Thank You,');
36 $sitename = $a->config['sitename'];
37 if (!x($a->config['admin_name'])) {
38 $site_admin = L10n::t('%s Administrator', $sitename);
40 $site_admin = L10n::t('%1$s, %2$s Administrator', $a->config['admin_name'], $sitename);
43 $sender_name = $sitename;
44 $hostname = $a->get_hostname();
45 if (strpos($hostname, ':')) {
46 $hostname = substr($hostname, 0, strpos($hostname, ':'));
49 $sender_email = $a->getSenderEmailAddress();
51 if ($params['type'] != SYSTEM_EMAIL) {
52 $user = dba::selectFirst('user', ['nickname', 'page-flags'],
53 ['uid' => $params['uid']]);
55 // There is no need to create notifications for forum accounts
56 if (!DBM::is_result($user) || in_array($user["page-flags"], [PAGE_COMMUNITY, PAGE_PRVGROUP])) {
60 $nickname = $user["nickname"];
62 // with $params['show_in_notification_page'] == false, the notification isn't inserted into
63 // the database, and an email is sent if applicable.
64 // default, if not specified: true
65 $show_in_notification_page = ((x($params, 'show_in_notification_page')) ? $params['show_in_notification_page']:true);
67 $additional_mail_header = "";
68 $additional_mail_header .= "Precedence: list\n";
69 $additional_mail_header .= "X-Friendica-Host: ".$hostname."\n";
70 $additional_mail_header .= "X-Friendica-Account: <".$nickname."@".$hostname.">\n";
71 $additional_mail_header .= "X-Friendica-Platform: ".FRIENDICA_PLATFORM."\n";
72 $additional_mail_header .= "X-Friendica-Version: ".FRIENDICA_VERSION."\n";
73 $additional_mail_header .= "List-ID: <notification.".$hostname.">\n";
74 $additional_mail_header .= "List-Archive: <".System::baseUrl()."/notifications/system>\n";
76 if (array_key_exists('item', $params)) {
77 $title = $params['item']['title'];
78 $body = $params['item']['body'];
83 if (isset($params['item']['id'])) {
84 $item_id = $params['item']['id'];
89 if (isset($params['parent'])) {
90 $parent_id = $params['parent'];
95 if ($params['type'] == NOTIFY_MAIL) {
96 $subject = L10n::t('[Friendica:Notify] New mail received at %s', $sitename);
98 $preamble = L10n::t('%1$s sent you a new private message at %2$s.', $params['source_name'], $sitename);
99 $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]');
101 $sitelink = L10n::t('Please visit %s to view and/or reply to your private messages.');
102 $tsitelink = sprintf($sitelink, $siteurl.'/message/'.$params['item']['id']);
103 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'/message/'.$params['item']['id'].'">'.$sitename.'</a>');
104 $itemlink = $siteurl.'/message/'.$params['item']['id'];
107 if ($params['type'] == NOTIFY_COMMENT) {
108 $thread = dba::selectFirst('thread', ['ignored'], ['iid' => $parent_id]);
109 if (DBM::is_result($thread) && $thread["ignored"]) {
110 logger("Thread ".$parent_id." will be ignored", LOGGER_DEBUG);
114 // Check to see if there was already a tag notify or comment notify for this post.
115 // If so don't create a second notification
116 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d, %d) AND `link` = '%s' AND `uid` = %d LIMIT 1",
117 intval(NOTIFY_TAGSELF),
118 intval(NOTIFY_COMMENT),
119 intval(NOTIFY_SHARE),
120 dbesc($params['link']),
121 intval($params['uid'])
123 if ($p && count($p)) {
128 // if it's a post figure out who's post it is.
132 if ($params['otype'] === 'item' && $parent_id) {
133 $item = Item::selectFirstForUser($params['uid'], [], ['id' => $parent_id]);
136 $item_post_type = item_post_type($item);
139 $dest_str = L10n::t('%1$s commented on [url=%2$s]a %3$s[/url]',
140 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
145 // "George Bull's post"
147 $dest_str = L10n::t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]',
148 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
150 $item['author-name'],
156 if (DBM::is_result($item) && $item['owner-id'] == $item['author-id'] && $item['wall']) {
157 $dest_str = L10n::t('%1$s commented on [url=%2$s]your %3$s[/url]',
158 '[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 = L10n::t('[Friendica:Notify] Comment to conversation #%1$d by %2$s', $parent_id, $params['source_name']);
171 $preamble = L10n::t('%s commented on an item/conversation you have been following.', $params['source_name']);
172 $epreamble = $dest_str;
174 $sitelink = L10n::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 = L10n::t('[Friendica:Notify] %s posted to your profile wall', $params['source_name']);
183 $preamble = L10n::t('%1$s posted to your profile wall at %2$s', $params['source_name'], $sitename);
184 $epreamble = L10n::t('%1$s posted to [url=%2$s]your wall[/url]',
185 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
189 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
190 $tsitelink = sprintf($sitelink, $siteurl);
191 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
192 $itemlink = $params['link'];
195 if ($params['type'] == NOTIFY_TAGSELF) {
196 $subject = L10n::t('[Friendica:Notify] %s tagged you', $params['source_name']);
198 $preamble = L10n::t('%1$s tagged you at %2$s', $params['source_name'], $sitename);
199 $epreamble = L10n::t('%1$s [url=%2$s]tagged you[/url].',
200 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
204 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
205 $tsitelink = sprintf($sitelink, $siteurl);
206 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
207 $itemlink = $params['link'];
210 if ($params['type'] == NOTIFY_SHARE) {
211 $subject = L10n::t('[Friendica:Notify] %s shared a new post', $params['source_name']);
213 $preamble = L10n::t('%1$s shared a new post at %2$s', $params['source_name'], $sitename);
214 $epreamble = L10n::t('%1$s [url=%2$s]shared a post[/url].',
215 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
219 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
220 $tsitelink = sprintf($sitelink, $siteurl);
221 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
222 $itemlink = $params['link'];
225 if ($params['type'] == NOTIFY_POKE) {
226 $subject = L10n::t('[Friendica:Notify] %1$s poked you', $params['source_name']);
228 $preamble = L10n::t('%1$s poked you at %2$s', $params['source_name'], $sitename);
229 $epreamble = L10n::t('%1$s [url=%2$s]poked you[/url].',
230 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
234 $subject = str_replace('poked', L10n::t($params['activity']), $subject);
235 $preamble = str_replace('poked', L10n::t($params['activity']), $preamble);
236 $epreamble = str_replace('poked', L10n::t($params['activity']), $epreamble);
238 $sitelink = L10n::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_TAGSHARE) {
245 $subject = L10n::t('[Friendica:Notify] %s tagged your post', $params['source_name']);
247 $preamble = L10n::t('%1$s tagged your post at %2$s', $params['source_name'], $sitename);
248 $epreamble = L10n::t('%1$s tagged [url=%2$s]your post[/url]',
249 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
253 $sitelink = L10n::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 = L10n::t('[Friendica:Notify] Introduction received');
262 $preamble = L10n::t('You\'ve received an introduction from \'%1$s\' at %2$s', $params['source_name'], $sitename);
263 $epreamble = L10n::t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.',
265 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
268 $body = L10n::t('You may visit their profile at %s', $params['source_link']);
270 $sitelink = L10n::t('Please visit %s to approve or reject the introduction.');
271 $tsitelink = sprintf($sitelink, $siteurl);
272 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
273 $itemlink = $params['link'];
275 switch ($params['verb']) {
276 case ACTIVITY_FRIEND:
277 // someone started to share with user (mostly OStatus)
278 $subject = L10n::t('[Friendica:Notify] A new person is sharing with you');
280 $preamble = L10n::t('%1$s is sharing with you at %2$s', $params['source_name'], $sitename);
281 $epreamble = L10n::t('%1$s is sharing with you at %2$s',
282 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
286 case ACTIVITY_FOLLOW:
287 // someone started to follow the user (mostly OStatus)
288 $subject = L10n::t('[Friendica:Notify] You have a new follower');
290 $preamble = L10n::t('You have a new follower at %2$s : %1$s', $params['source_name'], $sitename);
291 $epreamble = L10n::t('You have a new follower at %2$s : %1$s',
292 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
297 // ACTIVITY_REQ_FRIEND is default activity for notifications
302 if ($params['type'] == NOTIFY_SUGGEST) {
303 $subject = L10n::t('[Friendica:Notify] Friend suggestion received');
305 $preamble = L10n::t('You\'ve received a friend suggestion from \'%1$s\' at %2$s', $params['source_name'], $sitename);
306 $epreamble = L10n::t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.',
308 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
309 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
312 $body = L10n::t('Name:').' '.$params['item']['name']."\n";
313 $body .= L10n::t('Photo:').' '.$params['item']['photo']."\n";
314 $body .= L10n::t('You may visit their profile at %s', $params['item']['url']);
316 $sitelink = L10n::t('Please visit %s to approve or reject the suggestion.');
317 $tsitelink = sprintf($sitelink, $siteurl);
318 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
319 $itemlink = $params['link'];
322 if ($params['type'] == NOTIFY_CONFIRM) {
323 if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
324 $subject = L10n::t('[Friendica:Notify] Connection accepted');
326 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
327 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
329 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
332 $body = L10n::t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
334 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
335 $tsitelink = sprintf($sitelink, $siteurl);
336 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
337 $itemlink = $params['link'];
338 } else { // ACTIVITY_FOLLOW
339 $subject = L10n::t('[Friendica:Notify] Connection accepted');
341 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
342 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
344 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
347 $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']);
349 $body .= L10n::t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.', $params['source_name']);
351 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
352 $tsitelink = sprintf($sitelink, $siteurl);
353 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
354 $itemlink = $params['link'];
358 if ($params['type'] == NOTIFY_SYSTEM) {
359 switch($params['event']) {
360 case "SYSTEM_REGISTER_REQUEST":
361 $subject = L10n::t('[Friendica System Notify]') . ' ' . L10n::t('registration request');
363 $preamble = L10n::t('You\'ve received a registration request from \'%1$s\' at %2$s', $params['source_name'], $sitename);
364 $epreamble = L10n::t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.',
366 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
369 $body = L10n::t("Full Name: %s\nSite Location: %s\nLogin Name: %s (%s)",
370 $params['source_name'],
371 $siteurl, $params['source_mail'],
372 $params['source_nick']
375 $sitelink = L10n::t('Please visit %s to approve or reject the request.');
376 $tsitelink = sprintf($sitelink, $params['link']);
377 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
378 $itemlink = $params['link'];
380 case "SYSTEM_DB_UPDATE_FAIL":
385 if ($params['type'] == SYSTEM_EMAIL) {
386 // not part of the notifications.
387 // it just send a mail to the user.
388 // It will be used by the system to send emails to users (like
389 // password reset, invitations and so) using one look (but without
390 // add a notification to the user, with could be inexistent)
391 $subject = $params['subject'];
393 $preamble = $params['preamble'];
395 $body = $params['body'];
401 $show_in_notification_page = false;
404 $subject .= " (".$nickname."@".$hostname.")";
408 'subject' => $subject,
409 'preamble' => $preamble,
410 'epreamble' => $epreamble,
412 'sitelink' => $sitelink,
413 'tsitelink' => $tsitelink,
414 'hsitelink' => $hsitelink,
415 'itemlink' => $itemlink
418 Addon::callHooks('enotify', $h);
420 $subject = $h['subject'];
422 $preamble = $h['preamble'];
423 $epreamble = $h['epreamble'];
427 $tsitelink = $h['tsitelink'];
428 $hsitelink = $h['hsitelink'];
429 $itemlink = $h['itemlink'];
431 if ($show_in_notification_page) {
432 logger("adding notification entry", LOGGER_DEBUG);
435 $hash = random_string();
436 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' LIMIT 1",
438 if (DBM::is_result($r)) {
441 } while ($dups == true);
443 /// @TODO One statement is enough
445 $datarray['hash'] = $hash;
446 $datarray['name'] = $params['source_name'];
447 $datarray['name_cache'] = strip_tags(BBCode::convert($params['source_name']));
448 $datarray['url'] = $params['source_link'];
449 $datarray['photo'] = $params['source_photo'];
450 $datarray['date'] = DateTimeFormat::utcNow();
451 $datarray['uid'] = $params['uid'];
452 $datarray['link'] = $itemlink;
453 $datarray['iid'] = $item_id;
454 $datarray['parent'] = $parent_id;
455 $datarray['type'] = $params['type'];
456 $datarray['verb'] = $params['verb'];
457 $datarray['otype'] = $params['otype'];
458 $datarray['abort'] = false;
460 Addon::callHooks('enotify_store', $datarray);
462 if ($datarray['abort']) {
467 // create notification entry in DB
468 q("INSERT INTO `notify` (`hash`, `name`, `url`, `photo`, `date`, `uid`, `link`, `iid`, `parent`, `type`, `verb`, `otype`, `name_cache`)
469 values('%s', '%s', '%s', '%s', '%s', %d, '%s', %d, %d, %d, '%s', '%s', '%s')",
470 dbesc($datarray['hash']),
471 dbesc($datarray['name']),
472 dbesc($datarray['url']),
473 dbesc($datarray['photo']),
474 dbesc($datarray['date']),
475 intval($datarray['uid']),
476 dbesc($datarray['link']),
477 intval($datarray['iid']),
478 intval($datarray['parent']),
479 intval($datarray['type']),
480 dbesc($datarray['verb']),
481 dbesc($datarray['otype']),
482 dbesc($datarray["name_cache"])
485 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' AND `uid` = %d LIMIT 1",
487 intval($params['uid'])
490 $notify_id = $r[0]['id'];
496 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
497 // After we've stored everything, look again to see if there are any duplicates and if so remove them
498 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
499 intval(NOTIFY_TAGSELF),
500 intval(NOTIFY_COMMENT),
501 dbesc($params['link']),
502 intval($params['uid'])
504 if ($p && (count($p) > 1)) {
505 for ($d = 1; $d < count($p); $d ++) {
506 dba::delete('notify', ['id' => $p[$d]['id']]);
509 // only continue on if we stored the first one
510 if ($notify_id != $p[0]['id']) {
516 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
517 $msg = replace_macros($epreamble, ['$itemlink' => $itemlink]);
518 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(BBCode::convert($msg)));
519 q("UPDATE `notify` SET `msg` = '%s', `msg_cache` = '%s' WHERE `id` = %d AND `uid` = %d",
523 intval($params['uid'])
527 // send email notification if notification preferences permit
528 if ((intval($params['notify_flags']) & intval($params['type']))
529 || $params['type'] == NOTIFY_SYSTEM
530 || $params['type'] == SYSTEM_EMAIL) {
532 logger('sending notification email');
534 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
535 $id_for_parent = $params['parent']."@".$hostname;
537 // Is this the first email notification for this parent item and user?
539 $r = q("SELECT `id` FROM `notify-threads` WHERE `master-parent-item` = %d AND `receiver-uid` = %d LIMIT 1",
540 intval($params['parent']),
541 intval($params['uid']));
543 // If so, create the record of it and use a message-id smtp header.
546 logger("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), LOGGER_DEBUG);
547 q("INSERT INTO `notify-threads` (`notify-id`, `master-parent-item`, `receiver-uid`, `parent-item`)
548 values(%d, %d, %d, %d)",
550 intval($params['parent']),
551 intval($params['uid']),
554 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
555 $log_msg = "include/enotify: No previous notification found for this parent:\n".
556 " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
557 logger($log_msg, LOGGER_DEBUG);
559 // If not, just "follow" the thread.
560 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
561 logger("There's already a notification for this parent:\n".print_r($r, true), LOGGER_DEBUG);
565 $textversion = BBCode::toPlaintext($body);
566 $htmlversion = BBCode::convert($body);
569 $datarray['banner'] = $banner;
570 $datarray['product'] = $product;
571 $datarray['preamble'] = $preamble;
572 $datarray['sitename'] = $sitename;
573 $datarray['siteurl'] = $siteurl;
574 $datarray['type'] = $params['type'];
575 $datarray['parent'] = $params['parent'];
576 $datarray['source_name'] = $params['source_name'];
577 $datarray['source_link'] = $params['source_link'];
578 $datarray['source_photo'] = $params['source_photo'];
579 $datarray['uid'] = $params['uid'];
580 $datarray['username'] = $params['to_name'];
581 $datarray['hsitelink'] = $hsitelink;
582 $datarray['tsitelink'] = $tsitelink;
583 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
584 $datarray['titemlink'] = $itemlink;
585 $datarray['thanks'] = $thanks;
586 $datarray['site_admin'] = $site_admin;
587 $datarray['title'] = stripslashes($title);
588 $datarray['htmlversion'] = $htmlversion;
589 $datarray['textversion'] = $textversion;
590 $datarray['subject'] = $subject;
591 $datarray['headers'] = $additional_mail_header;
593 Addon::callHooks('enotify_mail', $datarray);
595 // check whether sending post content in email notifications is allowed
596 // always true for SYSTEM_EMAIL
597 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
599 // load the template for private message notifications
600 $tpl = get_markup_template('email_notify_html.tpl');
601 $email_html_body = replace_macros($tpl, [
602 '$banner' => $datarray['banner'],
603 '$product' => $datarray['product'],
604 '$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
605 '$sitename' => $datarray['sitename'],
606 '$siteurl' => $datarray['siteurl'],
607 '$source_name' => $datarray['source_name'],
608 '$source_link' => $datarray['source_link'],
609 '$source_photo' => $datarray['source_photo'],
610 '$username' => $datarray['to_name'],
611 '$hsitelink' => $datarray['hsitelink'],
612 '$hitemlink' => $datarray['hitemlink'],
613 '$thanks' => $datarray['thanks'],
614 '$site_admin' => $datarray['site_admin'],
615 '$title' => $datarray['title'],
616 '$htmlversion' => $datarray['htmlversion'],
617 '$content_allowed' => $content_allowed,
620 // load the template for private message notifications
621 $tpl = get_markup_template('email_notify_text.tpl');
622 $email_text_body = replace_macros($tpl, [
623 '$banner' => $datarray['banner'],
624 '$product' => $datarray['product'],
625 '$preamble' => $datarray['preamble'],
626 '$sitename' => $datarray['sitename'],
627 '$siteurl' => $datarray['siteurl'],
628 '$source_name' => $datarray['source_name'],
629 '$source_link' => $datarray['source_link'],
630 '$source_photo' => $datarray['source_photo'],
631 '$username' => $datarray['to_name'],
632 '$tsitelink' => $datarray['tsitelink'],
633 '$titemlink' => $datarray['titemlink'],
634 '$thanks' => $datarray['thanks'],
635 '$site_admin' => $datarray['site_admin'],
636 '$title' => $datarray['title'],
637 '$textversion' => $datarray['textversion'],
638 '$content_allowed' => $content_allowed,
641 // 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 users who should be notified
662 * @param int $itemid ID of the item for which the check should be done
664 function check_user_notification($itemid) {
665 // fetch all users in the thread
666 $users = dba::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
667 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
668 WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
669 while ($user = dba::fetch($users)) {
670 check_item_notification($itemid, $user['uid']);
676 * @brief Checks for item related notifications and sends them
678 * @param int $itemid ID of the item for which the check should be done
679 * @param int $uid User ID
680 * @param str $defaulttype (Optional) Forces a notification with this type.
682 function check_item_notification($itemid, $uid, $defaulttype = "") {
683 $notification_data = ["uid" => $uid, "profiles" => []];
684 Addon::callHooks('check_item_notification', $notification_data);
686 $profiles = $notification_data["profiles"];
688 $fields = ['notify-flags', 'language', 'username', 'email', 'nickname'];
689 $user = dba::selectFirst('user', $fields, ['uid' => $uid]);
690 if (!DBM::is_result($user)) {
694 $owner = dba::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
695 if (!DBM::is_result($owner)) {
699 // This is our regular URL format
700 $profiles[] = $owner["url"];
702 // Notifications from Diaspora are often with an URL in the Diaspora format
703 $profiles[] = System::baseUrl()."/u/".$user["nickname"];
707 foreach ($profiles AS $profile) {
708 // Check for invalid profile urls. 13 should be the shortest possible profile length:
710 // Additionally check for invalid urls that would return the normalised value "http:"
711 if ((strlen($profile) >= 13) && (normalise_link($profile) != "http:")) {
712 if (!in_array($profile, $profiles2))
713 $profiles2[] = $profile;
715 $profile = normalise_link($profile);
716 if (!in_array($profile, $profiles2))
717 $profiles2[] = $profile;
719 $profile = str_replace("http://", "https://", $profile);
720 if (!in_array($profile, $profiles2))
721 $profiles2[] = $profile;
725 $profiles = $profiles2;
727 $ret = dba::select('contact', ['id'], ['uid' => 0, 'nurl' => $profiles]);
731 while ($contact = dba::fetch($ret)) {
732 $contacts[] = $contact['id'];
735 $contact_list = implode(',', $contacts);
739 // Only act if it is a "real" post
740 // We need the additional check for the "local_profile" because of mixed situations on connector networks
741 $item = q("SELECT `id`, `mention`, `tag`,`parent`, `title`, `body`, `author-id`, `guid`,
742 `parent-uri`, `uri`, `contact-id`, `network`
743 FROM `item` WHERE `id` = %d AND `verb` IN ('%s', '') AND `type` != 'activity' AND
744 NOT (`author-id` IN ($contact_list)) LIMIT 1",
745 intval($itemid), dbesc(ACTIVITY_POST));
749 if ($item[0]['network'] != NETWORK_FEED) {
750 $author = dba::selectFirst('contact', ['name', 'thumb', 'url'], ['id' => $item[0]['author-id']]);
752 $author = dba::selectFirst('contact', ['name', 'thumb', 'url'], ['id' => $item[0]['contact-id']]);
755 // Generate the notification array
757 $params["uid"] = $uid;
758 $params["notify_flags"] = $user["notify-flags"];
759 $params["language"] = $user["language"];
760 $params["to_name"] = $user["username"];
761 $params["to_email"] = $user["email"];
762 $params["item"] = $item[0];
763 $params["parent"] = $item[0]["parent"];
764 $params["link"] = System::baseUrl().'/display/'.urlencode($item[0]["guid"]);
765 $params["otype"] = 'item';
766 $params["source_name"] = $author["name"];
767 $params["source_link"] = $author["url"];
768 $params["source_photo"] = $author["thumb"];
770 if ($item[0]["parent-uri"] === $item[0]["uri"]) {
771 // Send a notification for every new post?
772 $send_notification = dba::exists('contact', ['id' => $item[0]['contact-id'], 'notify_new_posts' => true]);
774 if (!$send_notification) {
775 $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
776 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
778 if (DBM::is_result($tags)) {
779 foreach ($tags AS $tag) {
780 $condition = ['nurl' => normalise_link($tag["url"]), 'uid' => $uid, 'notify_new_posts' => true];
781 $r = dba::exists('contact', $condition);
783 $send_notification = true;
789 if ($send_notification) {
790 $params["type"] = NOTIFY_SHARE;
791 $params["verb"] = ACTIVITY_TAG;
795 // Is the user mentioned in this post?
798 foreach ($profiles AS $profile) {
799 if (strpos($item[0]["tag"], "=".$profile."]") || strpos($item[0]["body"], "=".$profile."]"))
803 if ($item[0]["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
804 $params["type"] = NOTIFY_TAGSELF;
805 $params["verb"] = ACTIVITY_TAG;
808 // Is it a post that the user had started or where he interacted?
809 $parent = q("SELECT `thread`.`iid` FROM `thread` INNER JOIN `item` ON `item`.`parent` = `thread`.`iid`
810 WHERE `thread`.`iid` = %d AND NOT `thread`.`ignored` AND
811 (`thread`.`mention` OR `item`.`author-id` IN ($contact_list))
813 intval($item[0]["parent"]));
815 if ($parent && !isset($params["type"])) {
816 $params["type"] = NOTIFY_COMMENT;
817 $params["verb"] = ACTIVITY_POST;
820 if (isset($params["type"]))
821 notification($params);
825 * @brief Formats a notification message with the notification author
827 * Replace the name with {0} but ensure to make that only once. The {0} is used
828 * later and prints the name in bold.
830 * @param string $name
831 * @param string $message
832 * @return string Formatted message
834 function format_notification_message($name, $message) {
836 $pos = strpos($message, $name);
841 if ($pos !== false) {
842 $message = substr_replace($message, '{0}', $pos, strlen($name));