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\Model\Item;
13 use Friendica\Util\DateTimeFormat;
14 use Friendica\Util\Emailer;
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 = Config::get('config', 'sitename');
37 if (Config::get('config', 'admin_name')) {
38 $site_admin = L10n::t('%1$s, %2$s Administrator', Config::get('config', 'admin_name'), $sitename);
40 $site_admin = L10n::t('%s Administrator', $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 (!DBA::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 $itemlink = $siteurl.'/message/'.$params['item']['id'];
98 $subject = L10n::t('[Friendica:Notify] New mail received at %s', $sitename);
100 $preamble = L10n::t('%1$s sent you a new private message at %2$s.', $params['source_name'], $sitename);
101 $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]');
103 $sitelink = L10n::t('Please visit %s to view and/or reply to your private messages.');
104 $tsitelink = sprintf($sitelink, $siteurl.'/message/'.$params['item']['id']);
105 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'/message/'.$params['item']['id'].'">'.$sitename.'</a>');
108 if ($params['type'] == NOTIFY_COMMENT) {
109 $thread = DBA::selectFirst('thread', ['ignored'], ['iid' => $parent_id]);
110 if (DBA::is_result($thread) && $thread["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 $item = Item::selectFirstForUser($params['uid'], Item::ITEM_FIELDLIST, ['id' => $parent_id]);
137 $item_post_type = item_post_type($item);
138 $itemlink = $item['plink'];
141 $dest_str = L10n::t('%1$s commented on [url=%2$s]a %3$s[/url]',
142 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
147 // "George Bull's post"
149 $dest_str = L10n::t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]',
150 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
152 $item['author-name'],
158 if (DBA::is_result($item) && $item['owner-id'] == $item['author-id'] && $item['wall']) {
159 $dest_str = L10n::t('%1$s commented on [url=%2$s]your %3$s[/url]',
160 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
166 // Some mail softwares relies on subject field for threading.
167 // So, we cannot have different subjects for notifications of the same thread.
168 // Before this we have the name of the replier on the subject rendering
169 // differents subjects for messages on the same thread.
171 $subject = L10n::t('[Friendica:Notify] Comment to conversation #%1$d by %2$s', $parent_id, $params['source_name']);
173 $preamble = L10n::t('%s commented on an item/conversation you have been following.', $params['source_name']);
174 $epreamble = $dest_str;
176 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
177 $tsitelink = sprintf($sitelink, $siteurl);
178 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
179 $itemlink = $params['link'];
182 if ($params['type'] == NOTIFY_WALL) {
183 $subject = L10n::t('[Friendica:Notify] %s posted to your profile wall', $params['source_name']);
185 $preamble = L10n::t('%1$s posted to your profile wall at %2$s', $params['source_name'], $sitename);
186 $epreamble = L10n::t('%1$s posted to [url=%2$s]your wall[/url]',
187 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
191 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
192 $tsitelink = sprintf($sitelink, $siteurl);
193 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
194 $itemlink = $params['link'];
197 if ($params['type'] == NOTIFY_TAGSELF) {
198 $subject = L10n::t('[Friendica:Notify] %s tagged you', $params['source_name']);
200 $preamble = L10n::t('%1$s tagged you at %2$s', $params['source_name'], $sitename);
201 $epreamble = L10n::t('%1$s [url=%2$s]tagged you[/url].',
202 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
206 $sitelink = L10n::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_SHARE) {
213 $subject = L10n::t('[Friendica:Notify] %s shared a new post', $params['source_name']);
215 $preamble = L10n::t('%1$s shared a new post at %2$s', $params['source_name'], $sitename);
216 $epreamble = L10n::t('%1$s [url=%2$s]shared a post[/url].',
217 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
221 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
222 $tsitelink = sprintf($sitelink, $siteurl);
223 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
224 $itemlink = $params['link'];
227 if ($params['type'] == NOTIFY_POKE) {
228 $subject = L10n::t('[Friendica:Notify] %1$s poked you', $params['source_name']);
230 $preamble = L10n::t('%1$s poked you at %2$s', $params['source_name'], $sitename);
231 $epreamble = L10n::t('%1$s [url=%2$s]poked you[/url].',
232 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
236 $subject = str_replace('poked', L10n::t($params['activity']), $subject);
237 $preamble = str_replace('poked', L10n::t($params['activity']), $preamble);
238 $epreamble = str_replace('poked', L10n::t($params['activity']), $epreamble);
240 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
241 $tsitelink = sprintf($sitelink, $siteurl);
242 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
243 $itemlink = $params['link'];
246 if ($params['type'] == NOTIFY_TAGSHARE) {
247 $itemlink = $params['link'];
248 $subject = L10n::t('[Friendica:Notify] %s tagged your post', $params['source_name']);
250 $preamble = L10n::t('%1$s tagged your post at %2$s', $params['source_name'], $sitename);
251 $epreamble = L10n::t('%1$s tagged [url=%2$s]your post[/url]',
252 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
256 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
257 $tsitelink = sprintf($sitelink, $siteurl);
258 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
261 if ($params['type'] == NOTIFY_INTRO) {
262 $itemlink = $params['link'];
263 $subject = L10n::t('[Friendica:Notify] Introduction received');
265 $preamble = L10n::t('You\'ve received an introduction from \'%1$s\' at %2$s', $params['source_name'], $sitename);
266 $epreamble = L10n::t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.',
268 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
271 $body = L10n::t('You may visit their profile at %s', $params['source_link']);
273 $sitelink = L10n::t('Please visit %s to approve or reject the introduction.');
274 $tsitelink = sprintf($sitelink, $siteurl);
275 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
277 switch ($params['verb']) {
278 case ACTIVITY_FRIEND:
279 // someone started to share with user (mostly OStatus)
280 $subject = L10n::t('[Friendica:Notify] A new person is sharing with you');
282 $preamble = L10n::t('%1$s is sharing with you at %2$s', $params['source_name'], $sitename);
283 $epreamble = L10n::t('%1$s is sharing with you at %2$s',
284 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
288 case ACTIVITY_FOLLOW:
289 // someone started to follow the user (mostly OStatus)
290 $subject = L10n::t('[Friendica:Notify] You have a new follower');
292 $preamble = L10n::t('You have a new follower at %2$s : %1$s', $params['source_name'], $sitename);
293 $epreamble = L10n::t('You have a new follower at %2$s : %1$s',
294 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
299 // ACTIVITY_REQ_FRIEND is default activity for notifications
304 if ($params['type'] == NOTIFY_SUGGEST) {
305 $itemlink = $params['link'];
306 $subject = L10n::t('[Friendica:Notify] Friend suggestion received');
308 $preamble = L10n::t('You\'ve received a friend suggestion from \'%1$s\' at %2$s', $params['source_name'], $sitename);
309 $epreamble = L10n::t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.',
311 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
312 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
315 $body = L10n::t('Name:').' '.$params['item']['name']."\n";
316 $body .= L10n::t('Photo:').' '.$params['item']['photo']."\n";
317 $body .= L10n::t('You may visit their profile at %s', $params['item']['url']);
319 $sitelink = L10n::t('Please visit %s to approve or reject the suggestion.');
320 $tsitelink = sprintf($sitelink, $siteurl);
321 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
324 if ($params['type'] == NOTIFY_CONFIRM) {
325 if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
326 $itemlink = $params['link'];
327 $subject = L10n::t('[Friendica:Notify] Connection accepted');
329 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
330 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
332 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
335 $body = L10n::t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
337 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
338 $tsitelink = sprintf($sitelink, $siteurl);
339 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
340 } else { // ACTIVITY_FOLLOW
341 $itemlink = $params['link'];
342 $subject = L10n::t('[Friendica:Notify] Connection accepted');
344 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
345 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
347 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
350 $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']);
352 $body .= L10n::t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.', $params['source_name']);
354 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
355 $tsitelink = sprintf($sitelink, $siteurl);
356 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
360 if ($params['type'] == NOTIFY_SYSTEM) {
361 switch($params['event']) {
362 case "SYSTEM_REGISTER_REQUEST":
363 $itemlink = $params['link'];
364 $subject = L10n::t('[Friendica System Notify]') . ' ' . L10n::t('registration request');
366 $preamble = L10n::t('You\'ve received a registration request from \'%1$s\' at %2$s', $params['source_name'], $sitename);
367 $epreamble = L10n::t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.',
369 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
372 $body = L10n::t("Full Name: %s\nSite Location: %s\nLogin Name: %s (%s)",
373 $params['source_name'],
374 $siteurl, $params['source_mail'],
375 $params['source_nick']
378 $sitelink = L10n::t('Please visit %s to approve or reject the request.');
379 $tsitelink = sprintf($sitelink, $params['link']);
380 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
382 case "SYSTEM_DB_UPDATE_FAIL":
387 if ($params['type'] == SYSTEM_EMAIL) {
388 // not part of the notifications.
389 // it just send a mail to the user.
390 // It will be used by the system to send emails to users (like
391 // password reset, invitations and so) using one look (but without
392 // add a notification to the user, with could be inexistent)
393 $subject = $params['subject'];
395 $preamble = $params['preamble'];
397 $body = $params['body'];
403 $show_in_notification_page = false;
406 $subject .= " (".$nickname."@".$hostname.")";
410 'subject' => $subject,
411 'preamble' => $preamble,
412 'epreamble' => $epreamble,
414 'sitelink' => $sitelink,
415 'tsitelink' => $tsitelink,
416 'hsitelink' => $hsitelink,
417 'itemlink' => $itemlink
420 Addon::callHooks('enotify', $h);
422 $subject = $h['subject'];
424 $preamble = $h['preamble'];
425 $epreamble = $h['epreamble'];
429 $tsitelink = $h['tsitelink'];
430 $hsitelink = $h['hsitelink'];
431 $itemlink = $h['itemlink'];
433 if ($show_in_notification_page) {
434 logger("adding notification entry", LOGGER_DEBUG);
437 $hash = random_string();
438 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' LIMIT 1",
440 if (DBA::is_result($r)) {
443 } while ($dups == true);
445 /// @TODO One statement is enough
447 $datarray['hash'] = $hash;
448 $datarray['name'] = $params['source_name'];
449 $datarray['name_cache'] = strip_tags(BBCode::convert($params['source_name']));
450 $datarray['url'] = $params['source_link'];
451 $datarray['photo'] = $params['source_photo'];
452 $datarray['date'] = DateTimeFormat::utcNow();
453 $datarray['uid'] = $params['uid'];
454 $datarray['link'] = $itemlink;
455 $datarray['iid'] = $item_id;
456 $datarray['parent'] = $parent_id;
457 $datarray['type'] = $params['type'];
458 $datarray['verb'] = $params['verb'];
459 $datarray['otype'] = $params['otype'];
460 $datarray['abort'] = false;
462 Addon::callHooks('enotify_store', $datarray);
464 if ($datarray['abort']) {
469 // create notification entry in DB
470 q("INSERT INTO `notify` (`hash`, `name`, `url`, `photo`, `date`, `uid`, `link`, `iid`, `parent`, `type`, `verb`, `otype`, `name_cache`)
471 values('%s', '%s', '%s', '%s', '%s', %d, '%s', %d, %d, %d, '%s', '%s', '%s')",
472 dbesc($datarray['hash']),
473 dbesc($datarray['name']),
474 dbesc($datarray['url']),
475 dbesc($datarray['photo']),
476 dbesc($datarray['date']),
477 intval($datarray['uid']),
478 dbesc($datarray['link']),
479 intval($datarray['iid']),
480 intval($datarray['parent']),
481 intval($datarray['type']),
482 dbesc($datarray['verb']),
483 dbesc($datarray['otype']),
484 dbesc($datarray["name_cache"])
487 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' AND `uid` = %d LIMIT 1",
489 intval($params['uid'])
492 $notify_id = $r[0]['id'];
498 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
499 // After we've stored everything, look again to see if there are any duplicates and if so remove them
500 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
501 intval(NOTIFY_TAGSELF),
502 intval(NOTIFY_COMMENT),
503 dbesc($params['link']),
504 intval($params['uid'])
506 if ($p && (count($p) > 1)) {
507 for ($d = 1; $d < count($p); $d ++) {
508 DBA::delete('notify', ['id' => $p[$d]['id']]);
511 // only continue on if we stored the first one
512 if ($notify_id != $p[0]['id']) {
518 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
519 $msg = replace_macros($epreamble, ['$itemlink' => $itemlink]);
520 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(BBCode::convert($msg)));
521 q("UPDATE `notify` SET `msg` = '%s', `msg_cache` = '%s' WHERE `id` = %d AND `uid` = %d",
525 intval($params['uid'])
529 // send email notification if notification preferences permit
530 if ((intval($params['notify_flags']) & intval($params['type']))
531 || $params['type'] == NOTIFY_SYSTEM
532 || $params['type'] == SYSTEM_EMAIL) {
534 logger('sending notification email');
536 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
537 $id_for_parent = $params['parent']."@".$hostname;
539 // Is this the first email notification for this parent item and user?
541 $r = q("SELECT `id` FROM `notify-threads` WHERE `master-parent-item` = %d AND `receiver-uid` = %d LIMIT 1",
542 intval($params['parent']),
543 intval($params['uid']));
545 // If so, create the record of it and use a message-id smtp header.
548 logger("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), LOGGER_DEBUG);
549 q("INSERT INTO `notify-threads` (`notify-id`, `master-parent-item`, `receiver-uid`, `parent-item`)
550 values(%d, %d, %d, %d)",
552 intval($params['parent']),
553 intval($params['uid']),
556 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
557 $log_msg = "include/enotify: No previous notification found for this parent:\n".
558 " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
559 logger($log_msg, LOGGER_DEBUG);
561 // If not, just "follow" the thread.
562 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
563 logger("There's already a notification for this parent:\n".print_r($r, true), LOGGER_DEBUG);
567 $textversion = BBCode::toPlaintext($body);
568 $htmlversion = BBCode::convert($body);
571 $datarray['banner'] = $banner;
572 $datarray['product'] = $product;
573 $datarray['preamble'] = $preamble;
574 $datarray['sitename'] = $sitename;
575 $datarray['siteurl'] = $siteurl;
576 $datarray['type'] = $params['type'];
577 $datarray['parent'] = $parent_id;
578 $datarray['source_name'] = $params['source_name'];
579 $datarray['source_link'] = $params['source_link'];
580 $datarray['source_photo'] = $params['source_photo'];
581 $datarray['uid'] = $params['uid'];
582 $datarray['username'] = $params['to_name'];
583 $datarray['hsitelink'] = $hsitelink;
584 $datarray['tsitelink'] = $tsitelink;
585 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
586 $datarray['titemlink'] = $itemlink;
587 $datarray['thanks'] = $thanks;
588 $datarray['site_admin'] = $site_admin;
589 $datarray['title'] = stripslashes($title);
590 $datarray['htmlversion'] = $htmlversion;
591 $datarray['textversion'] = $textversion;
592 $datarray['subject'] = $subject;
593 $datarray['headers'] = $additional_mail_header;
595 Addon::callHooks('enotify_mail', $datarray);
597 // check whether sending post content in email notifications is allowed
598 // always true for SYSTEM_EMAIL
599 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
601 // load the template for private message notifications
602 $tpl = get_markup_template('email_notify_html.tpl');
603 $email_html_body = replace_macros($tpl, [
604 '$banner' => $datarray['banner'],
605 '$product' => $datarray['product'],
606 '$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
607 '$sitename' => $datarray['sitename'],
608 '$siteurl' => $datarray['siteurl'],
609 '$source_name' => $datarray['source_name'],
610 '$source_link' => $datarray['source_link'],
611 '$source_photo' => $datarray['source_photo'],
612 '$username' => $datarray['username'],
613 '$hsitelink' => $datarray['hsitelink'],
614 '$hitemlink' => $datarray['hitemlink'],
615 '$thanks' => $datarray['thanks'],
616 '$site_admin' => $datarray['site_admin'],
617 '$title' => $datarray['title'],
618 '$htmlversion' => $datarray['htmlversion'],
619 '$content_allowed' => $content_allowed,
622 // load the template for private message notifications
623 $tpl = get_markup_template('email_notify_text.tpl');
624 $email_text_body = replace_macros($tpl, [
625 '$banner' => $datarray['banner'],
626 '$product' => $datarray['product'],
627 '$preamble' => $datarray['preamble'],
628 '$sitename' => $datarray['sitename'],
629 '$siteurl' => $datarray['siteurl'],
630 '$source_name' => $datarray['source_name'],
631 '$source_link' => $datarray['source_link'],
632 '$source_photo' => $datarray['source_photo'],
633 '$username' => $datarray['username'],
634 '$tsitelink' => $datarray['tsitelink'],
635 '$titemlink' => $datarray['titemlink'],
636 '$thanks' => $datarray['thanks'],
637 '$site_admin' => $datarray['site_admin'],
638 '$title' => $datarray['title'],
639 '$textversion' => $datarray['textversion'],
640 '$content_allowed' => $content_allowed,
643 // use the Emailer class to send the message
644 return Emailer::send(
646 'uid' => $params['uid'],
647 'fromName' => $sender_name,
648 'fromEmail' => $sender_email,
649 'replyTo' => $sender_email,
650 'toEmail' => $params['to_email'],
651 'messageSubject' => $datarray['subject'],
652 'htmlVersion' => $email_html_body,
653 'textVersion' => $email_text_body,
654 'additionalMailHeader' => $datarray['headers']]
662 * @brief Checks for users who should be notified
664 * @param int $itemid ID of the item for which the check should be done
666 function check_user_notification($itemid) {
667 // fetch all users in the thread
668 $users = DBA::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
669 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
670 WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
671 while ($user = DBA::fetch($users)) {
672 check_item_notification($itemid, $user['uid']);
678 * @brief Checks for item related notifications and sends them
680 * @param int $itemid ID of the item for which the check should be done
681 * @param int $uid User ID
682 * @param string $defaulttype (Optional) Forces a notification with this type.
684 function check_item_notification($itemid, $uid, $defaulttype = "") {
685 $notification_data = ["uid" => $uid, "profiles" => []];
686 Addon::callHooks('check_item_notification', $notification_data);
688 $profiles = $notification_data["profiles"];
690 $fields = ['notify-flags', 'language', 'username', 'email', 'nickname'];
691 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
692 if (!DBA::is_result($user)) {
696 $owner = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
697 if (!DBA::is_result($owner)) {
701 // This is our regular URL format
702 $profiles[] = $owner["url"];
704 // Notifications from Diaspora are often with an URL in the Diaspora format
705 $profiles[] = System::baseUrl()."/u/".$user["nickname"];
709 foreach ($profiles AS $profile) {
710 // Check for invalid profile urls. 13 should be the shortest possible profile length:
712 // Additionally check for invalid urls that would return the normalised value "http:"
713 if ((strlen($profile) >= 13) && (normalise_link($profile) != "http:")) {
714 if (!in_array($profile, $profiles2))
715 $profiles2[] = $profile;
717 $profile = normalise_link($profile);
718 if (!in_array($profile, $profiles2))
719 $profiles2[] = $profile;
721 $profile = str_replace("http://", "https://", $profile);
722 if (!in_array($profile, $profiles2))
723 $profiles2[] = $profile;
727 $profiles = $profiles2;
729 $ret = DBA::select('contact', ['id'], ['uid' => 0, 'nurl' => $profiles]);
733 while ($contact = DBA::fetch($ret)) {
734 $contacts[] = $contact['id'];
737 $contact_list = implode(',', $contacts);
741 // Only act if it is a "real" post
742 // We need the additional check for the "local_profile" because of mixed situations on connector networks
743 $fields = ['id', 'mention', 'tag', 'parent', 'title', 'body',
744 'author-link', 'author-name', 'author-avatar', 'author-id',
745 'guid', 'parent-uri', 'uri', 'contact-id', 'network'];
746 $condition = ['id' => $itemid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
747 $item = Item::selectFirst($fields, $condition);
748 if (!DBA::is_result($item) || in_array($item['author-id'], $contacts)) {
752 // Generate the notification array
754 $params["uid"] = $uid;
755 $params["notify_flags"] = $user["notify-flags"];
756 $params["language"] = $user["language"];
757 $params["to_name"] = $user["username"];
758 $params["to_email"] = $user["email"];
759 $params["item"] = $item;
760 $params["parent"] = $item["parent"];
761 $params["link"] = System::baseUrl().'/display/'.urlencode($item["guid"]);
762 $params["otype"] = 'item';
763 $params["source_name"] = $item["author-name"];
764 $params["source_link"] = $item["author-link"];
765 $params["source_photo"] = $item["author-avatar"];
767 if ($item["parent-uri"] === $item["uri"]) {
768 // Send a notification for every new post?
769 $send_notification = DBA::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true]);
771 if (!$send_notification) {
772 $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
773 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
775 if (DBA::is_result($tags)) {
776 foreach ($tags AS $tag) {
777 $condition = ['nurl' => normalise_link($tag["url"]), 'uid' => $uid, 'notify_new_posts' => true];
778 $r = DBA::exists('contact', $condition);
780 $send_notification = true;
786 if ($send_notification) {
787 $params["type"] = NOTIFY_SHARE;
788 $params["verb"] = ACTIVITY_TAG;
792 // Is the user mentioned in this post?
795 foreach ($profiles AS $profile) {
796 if (strpos($item["tag"], "=".$profile."]") || strpos($item["body"], "=".$profile."]"))
800 if ($item["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
801 $params["type"] = NOTIFY_TAGSELF;
802 $params["verb"] = ACTIVITY_TAG;
805 // Is it a post that the user had started or where he interacted?
806 $parent = q("SELECT `thread`.`iid` FROM `thread` INNER JOIN `item` ON `item`.`parent` = `thread`.`iid`
807 WHERE `thread`.`iid` = %d AND NOT `thread`.`ignored` AND
808 (`thread`.`mention` OR `item`.`author-id` IN ($contact_list))
810 intval($item["parent"]));
812 if ($parent && !isset($params["type"])) {
813 $params["type"] = NOTIFY_COMMENT;
814 $params["verb"] = ACTIVITY_POST;
817 if (isset($params["type"]))
818 notification($params);
822 * @brief Formats a notification message with the notification author
824 * Replace the name with {0} but ensure to make that only once. The {0} is used
825 * later and prints the name in bold.
827 * @param string $name
828 * @param string $message
829 * @return string Formatted message
831 function format_notification_message($name, $message) {
833 $pos = strpos($message, $name);
838 if ($pos !== false) {
839 $message = substr_replace($message, '{0}', $pos, strlen($name));