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\Contact;
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 // Temporary logging for finding the origin
31 if (!isset($params['language']) || !isset($params['uid'])) {
32 logger('Missing parameters.' . System::callstack());
35 // from here on everything is in the recipients language
36 L10n::pushLang($params['language']);
38 $banner = L10n::t('Friendica Notification');
39 $product = FRIENDICA_PLATFORM;
40 $siteurl = System::baseUrl(true);
41 $thanks = L10n::t('Thank You,');
42 $sitename = Config::get('config', 'sitename');
43 if (Config::get('config', 'admin_name')) {
44 $site_admin = L10n::t('%1$s, %2$s Administrator', Config::get('config', 'admin_name'), $sitename);
46 $site_admin = L10n::t('%s Administrator', $sitename);
49 $sender_name = $sitename;
50 $hostname = $a->get_hostname();
51 if (strpos($hostname, ':')) {
52 $hostname = substr($hostname, 0, strpos($hostname, ':'));
55 $sender_email = $a->getSenderEmailAddress();
57 if ($params['type'] != SYSTEM_EMAIL) {
58 $user = DBA::selectFirst('user', ['nickname', 'page-flags'],
59 ['uid' => $params['uid']]);
61 // There is no need to create notifications for forum accounts
62 if (!DBA::isResult($user) || in_array($user["page-flags"], [Contact::PAGE_COMMUNITY, Contact::PAGE_PRVGROUP])) {
65 $nickname = $user["nickname"];
70 // with $params['show_in_notification_page'] == false, the notification isn't inserted into
71 // the database, and an email is sent if applicable.
72 // default, if not specified: true
73 $show_in_notification_page = ((x($params, 'show_in_notification_page')) ? $params['show_in_notification_page']:true);
75 $additional_mail_header = "";
76 $additional_mail_header .= "Precedence: list\n";
77 $additional_mail_header .= "X-Friendica-Host: ".$hostname."\n";
78 $additional_mail_header .= "X-Friendica-Account: <".$nickname."@".$hostname.">\n";
79 $additional_mail_header .= "X-Friendica-Platform: ".FRIENDICA_PLATFORM."\n";
80 $additional_mail_header .= "X-Friendica-Version: ".FRIENDICA_VERSION."\n";
81 $additional_mail_header .= "List-ID: <notification.".$hostname.">\n";
82 $additional_mail_header .= "List-Archive: <".System::baseUrl()."/notifications/system>\n";
84 if (array_key_exists('item', $params)) {
85 $title = $params['item']['title'];
86 $body = $params['item']['body'];
91 if (isset($params['item']['id'])) {
92 $item_id = $params['item']['id'];
97 if (isset($params['parent'])) {
98 $parent_id = $params['parent'];
105 if ($params['type'] == NOTIFY_MAIL) {
106 $itemlink = $siteurl.'/message/'.$params['item']['id'];
107 $params["link"] = $itemlink;
109 $subject = L10n::t('[Friendica:Notify] New mail received at %s', $sitename);
111 $preamble = L10n::t('%1$s sent you a new private message at %2$s.', $params['source_name'], $sitename);
112 $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]');
114 $sitelink = L10n::t('Please visit %s to view and/or reply to your private messages.');
115 $tsitelink = sprintf($sitelink, $siteurl.'/message/'.$params['item']['id']);
116 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'/message/'.$params['item']['id'].'">'.$sitename.'</a>');
119 if ($params['type'] == NOTIFY_COMMENT) {
120 $thread = DBA::selectFirst('thread', ['ignored'], ['iid' => $parent_id]);
121 if (DBA::isResult($thread) && $thread["ignored"]) {
122 logger("Thread ".$parent_id." will be ignored", LOGGER_DEBUG);
126 // Check to see if there was already a tag notify or comment notify for this post.
127 // If so don't create a second notification
128 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d, %d) AND `link` = '%s' AND `uid` = %d LIMIT 1",
129 intval(NOTIFY_TAGSELF),
130 intval(NOTIFY_COMMENT),
131 intval(NOTIFY_SHARE),
132 DBA::escape($params['link']),
133 intval($params['uid'])
135 if ($p && count($p)) {
140 // if it's a post figure out who's post it is.
144 if ($params['otype'] === 'item' && $parent_id) {
145 $item = Item::selectFirstForUser($params['uid'], Item::ITEM_FIELDLIST, ['id' => $parent_id]);
148 $item_post_type = item_post_type($item);
149 $itemlink = $item['plink'];
152 $dest_str = L10n::t('%1$s commented on [url=%2$s]a %3$s[/url]',
153 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
158 // "George Bull's post"
160 $dest_str = L10n::t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]',
161 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
163 $item['author-name'],
169 if (DBA::isResult($item) && $item['owner-id'] == $item['author-id'] && $item['wall']) {
170 $dest_str = L10n::t('%1$s commented on [url=%2$s]your %3$s[/url]',
171 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
177 // Some mail softwares relies on subject field for threading.
178 // So, we cannot have different subjects for notifications of the same thread.
179 // Before this we have the name of the replier on the subject rendering
180 // differents subjects for messages on the same thread.
182 $subject = L10n::t('[Friendica:Notify] Comment to conversation #%1$d by %2$s', $parent_id, $params['source_name']);
184 $preamble = L10n::t('%s commented on an item/conversation you have been following.', $params['source_name']);
185 $epreamble = $dest_str;
187 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
188 $tsitelink = sprintf($sitelink, $siteurl);
189 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
190 $itemlink = $params['link'];
193 if ($params['type'] == NOTIFY_WALL) {
194 $subject = L10n::t('[Friendica:Notify] %s posted to your profile wall', $params['source_name']);
196 $preamble = L10n::t('%1$s posted to your profile wall at %2$s', $params['source_name'], $sitename);
197 $epreamble = L10n::t('%1$s posted to [url=%2$s]your wall[/url]',
198 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
202 $sitelink = L10n::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_TAGSELF) {
209 $subject = L10n::t('[Friendica:Notify] %s tagged you', $params['source_name']);
211 $preamble = L10n::t('%1$s tagged you at %2$s', $params['source_name'], $sitename);
212 $epreamble = L10n::t('%1$s [url=%2$s]tagged you[/url].',
213 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
217 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
218 $tsitelink = sprintf($sitelink, $siteurl);
219 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
220 $itemlink = $params['link'];
223 if ($params['type'] == NOTIFY_SHARE) {
224 $subject = L10n::t('[Friendica:Notify] %s shared a new post', $params['source_name']);
226 $preamble = L10n::t('%1$s shared a new post at %2$s', $params['source_name'], $sitename);
227 $epreamble = L10n::t('%1$s [url=%2$s]shared a post[/url].',
228 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
232 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
233 $tsitelink = sprintf($sitelink, $siteurl);
234 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
235 $itemlink = $params['link'];
238 if ($params['type'] == NOTIFY_POKE) {
239 $subject = L10n::t('[Friendica:Notify] %1$s poked you', $params['source_name']);
241 $preamble = L10n::t('%1$s poked you at %2$s', $params['source_name'], $sitename);
242 $epreamble = L10n::t('%1$s [url=%2$s]poked you[/url].',
243 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
247 $subject = str_replace('poked', L10n::t($params['activity']), $subject);
248 $preamble = str_replace('poked', L10n::t($params['activity']), $preamble);
249 $epreamble = str_replace('poked', L10n::t($params['activity']), $epreamble);
251 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
252 $tsitelink = sprintf($sitelink, $siteurl);
253 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
254 $itemlink = $params['link'];
257 if ($params['type'] == NOTIFY_TAGSHARE) {
258 $itemlink = $params['link'];
259 $subject = L10n::t('[Friendica:Notify] %s tagged your post', $params['source_name']);
261 $preamble = L10n::t('%1$s tagged your post at %2$s', $params['source_name'], $sitename);
262 $epreamble = L10n::t('%1$s tagged [url=%2$s]your post[/url]',
263 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
267 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
268 $tsitelink = sprintf($sitelink, $siteurl);
269 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
272 if ($params['type'] == NOTIFY_INTRO) {
273 $itemlink = $params['link'];
274 $subject = L10n::t('[Friendica:Notify] Introduction received');
276 $preamble = L10n::t('You\'ve received an introduction from \'%1$s\' at %2$s', $params['source_name'], $sitename);
277 $epreamble = L10n::t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.',
279 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
282 $body = L10n::t('You may visit their profile at %s', $params['source_link']);
284 $sitelink = L10n::t('Please visit %s to approve or reject the introduction.');
285 $tsitelink = sprintf($sitelink, $siteurl);
286 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
288 switch ($params['verb']) {
289 case ACTIVITY_FRIEND:
290 // someone started to share with user (mostly OStatus)
291 $subject = L10n::t('[Friendica:Notify] A new person is sharing with you');
293 $preamble = L10n::t('%1$s is sharing with you at %2$s', $params['source_name'], $sitename);
294 $epreamble = L10n::t('%1$s is sharing with you at %2$s',
295 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
299 case ACTIVITY_FOLLOW:
300 // someone started to follow the user (mostly OStatus)
301 $subject = L10n::t('[Friendica:Notify] You have a new follower');
303 $preamble = L10n::t('You have a new follower at %2$s : %1$s', $params['source_name'], $sitename);
304 $epreamble = L10n::t('You have a new follower at %2$s : %1$s',
305 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
310 // ACTIVITY_REQ_FRIEND is default activity for notifications
315 if ($params['type'] == NOTIFY_SUGGEST) {
316 $itemlink = $params['link'];
317 $subject = L10n::t('[Friendica:Notify] Friend suggestion received');
319 $preamble = L10n::t('You\'ve received a friend suggestion from \'%1$s\' at %2$s', $params['source_name'], $sitename);
320 $epreamble = L10n::t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.',
322 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
323 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
326 $body = L10n::t('Name:').' '.$params['item']['name']."\n";
327 $body .= L10n::t('Photo:').' '.$params['item']['photo']."\n";
328 $body .= L10n::t('You may visit their profile at %s', $params['item']['url']);
330 $sitelink = L10n::t('Please visit %s to approve or reject the suggestion.');
331 $tsitelink = sprintf($sitelink, $siteurl);
332 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
335 if ($params['type'] == NOTIFY_CONFIRM) {
336 if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
337 $itemlink = $params['link'];
338 $subject = L10n::t('[Friendica:Notify] Connection accepted');
340 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
341 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
343 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
346 $body = L10n::t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
348 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
349 $tsitelink = sprintf($sitelink, $siteurl);
350 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
351 } else { // ACTIVITY_FOLLOW
352 $itemlink = $params['link'];
353 $subject = L10n::t('[Friendica:Notify] Connection accepted');
355 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
356 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
358 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
361 $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']);
363 $body .= L10n::t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.', $params['source_name']);
365 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
366 $tsitelink = sprintf($sitelink, $siteurl);
367 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
371 if ($params['type'] == NOTIFY_SYSTEM) {
372 switch($params['event']) {
373 case "SYSTEM_REGISTER_REQUEST":
374 $itemlink = $params['link'];
375 $subject = L10n::t('[Friendica System Notify]') . ' ' . L10n::t('registration request');
377 $preamble = L10n::t('You\'ve received a registration request from \'%1$s\' at %2$s', $params['source_name'], $sitename);
378 $epreamble = L10n::t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.',
380 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
383 $body = L10n::t("Full Name: %s\nSite Location: %s\nLogin Name: %s (%s)",
384 $params['source_name'],
385 $siteurl, $params['source_mail'],
386 $params['source_nick']
389 $sitelink = L10n::t('Please visit %s to approve or reject the request.');
390 $tsitelink = sprintf($sitelink, $params['link']);
391 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
393 case "SYSTEM_DB_UPDATE_FAIL":
398 if ($params['type'] == SYSTEM_EMAIL) {
399 // not part of the notifications.
400 // it just send a mail to the user.
401 // It will be used by the system to send emails to users (like
402 // password reset, invitations and so) using one look (but without
403 // add a notification to the user, with could be inexistent)
404 $subject = $params['subject'];
406 $preamble = $params['preamble'];
408 $body = $params['body'];
414 $show_in_notification_page = false;
417 $subject .= " (".$nickname."@".$hostname.")";
421 'subject' => $subject,
422 'preamble' => $preamble,
423 'epreamble' => $epreamble,
425 'sitelink' => $sitelink,
426 'tsitelink' => $tsitelink,
427 'hsitelink' => $hsitelink,
428 'itemlink' => $itemlink
431 Addon::callHooks('enotify', $h);
433 $subject = $h['subject'];
435 $preamble = $h['preamble'];
436 $epreamble = $h['epreamble'];
440 $tsitelink = $h['tsitelink'];
441 $hsitelink = $h['hsitelink'];
442 $itemlink = $h['itemlink'];
444 if ($show_in_notification_page) {
445 logger("adding notification entry", LOGGER_DEBUG);
448 $hash = random_string();
449 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' LIMIT 1",
451 if (DBA::isResult($r)) {
454 } while ($dups == true);
456 /// @TODO One statement is enough
458 $datarray['hash'] = $hash;
459 $datarray['name'] = $params['source_name'];
460 $datarray['name_cache'] = strip_tags(BBCode::convert($params['source_name']));
461 $datarray['url'] = $params['source_link'];
462 $datarray['photo'] = $params['source_photo'];
463 $datarray['date'] = DateTimeFormat::utcNow();
464 $datarray['uid'] = $params['uid'];
465 $datarray['link'] = $itemlink;
466 $datarray['iid'] = $item_id;
467 $datarray['parent'] = $parent_id;
468 $datarray['type'] = $params['type'];
469 $datarray['verb'] = $params['verb'];
470 $datarray['otype'] = $params['otype'];
471 $datarray['abort'] = false;
473 Addon::callHooks('enotify_store', $datarray);
475 if ($datarray['abort']) {
480 // create notification entry in DB
481 q("INSERT INTO `notify` (`hash`, `name`, `url`, `photo`, `date`, `uid`, `link`, `iid`, `parent`, `type`, `verb`, `otype`, `name_cache`)
482 values('%s', '%s', '%s', '%s', '%s', %d, '%s', %d, %d, %d, '%s', '%s', '%s')",
483 DBA::escape($datarray['hash']),
484 DBA::escape($datarray['name']),
485 DBA::escape($datarray['url']),
486 DBA::escape($datarray['photo']),
487 DBA::escape($datarray['date']),
488 intval($datarray['uid']),
489 DBA::escape($datarray['link']),
490 intval($datarray['iid']),
491 intval($datarray['parent']),
492 intval($datarray['type']),
493 DBA::escape($datarray['verb']),
494 DBA::escape($datarray['otype']),
495 DBA::escape($datarray["name_cache"])
498 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' AND `uid` = %d LIMIT 1",
500 intval($params['uid'])
503 $notify_id = $r[0]['id'];
509 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
510 // After we've stored everything, look again to see if there are any duplicates and if so remove them
511 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
512 intval(NOTIFY_TAGSELF),
513 intval(NOTIFY_COMMENT),
514 DBA::escape($params['link']),
515 intval($params['uid'])
517 if ($p && (count($p) > 1)) {
518 for ($d = 1; $d < count($p); $d ++) {
519 DBA::delete('notify', ['id' => $p[$d]['id']]);
522 // only continue on if we stored the first one
523 if ($notify_id != $p[0]['id']) {
529 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
530 $msg = replace_macros($epreamble, ['$itemlink' => $itemlink]);
531 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(BBCode::convert($msg)));
532 q("UPDATE `notify` SET `msg` = '%s', `msg_cache` = '%s' WHERE `id` = %d AND `uid` = %d",
534 DBA::escape($msg_cache),
536 intval($params['uid'])
540 // send email notification if notification preferences permit
541 if ((!empty($params['notify_flags']) & intval($params['type']))
542 || $params['type'] == NOTIFY_SYSTEM
543 || $params['type'] == SYSTEM_EMAIL) {
545 logger('sending notification email');
547 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
548 $id_for_parent = $params['parent']."@".$hostname;
550 // Is this the first email notification for this parent item and user?
552 $r = q("SELECT `id` FROM `notify-threads` WHERE `master-parent-item` = %d AND `receiver-uid` = %d LIMIT 1",
553 intval($params['parent']),
554 intval($params['uid']));
556 // If so, create the record of it and use a message-id smtp header.
559 logger("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), LOGGER_DEBUG);
560 q("INSERT INTO `notify-threads` (`notify-id`, `master-parent-item`, `receiver-uid`, `parent-item`)
561 values(%d, %d, %d, %d)",
563 intval($params['parent']),
564 intval($params['uid']),
567 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
568 $log_msg = "include/enotify: No previous notification found for this parent:\n".
569 " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
570 logger($log_msg, LOGGER_DEBUG);
572 // If not, just "follow" the thread.
573 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
574 logger("There's already a notification for this parent:\n".print_r($r, true), LOGGER_DEBUG);
578 $textversion = BBCode::toPlaintext($body);
579 $htmlversion = BBCode::convert($body);
582 $datarray['banner'] = $banner;
583 $datarray['product'] = $product;
584 $datarray['preamble'] = $preamble;
585 $datarray['sitename'] = $sitename;
586 $datarray['siteurl'] = $siteurl;
587 $datarray['type'] = $params['type'];
588 $datarray['parent'] = $parent_id;
589 $datarray['source_name'] = defaults($params, 'source_name', '');
590 $datarray['source_link'] = defaults($params, 'source_link', '');
591 $datarray['source_photo'] = defaults($params, 'source_photo', '');
592 $datarray['uid'] = $params['uid'];
593 $datarray['username'] = defaults($params, 'to_name', '');
594 $datarray['hsitelink'] = $hsitelink;
595 $datarray['tsitelink'] = $tsitelink;
596 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
597 $datarray['titemlink'] = $itemlink;
598 $datarray['thanks'] = $thanks;
599 $datarray['site_admin'] = $site_admin;
600 $datarray['title'] = stripslashes($title);
601 $datarray['htmlversion'] = $htmlversion;
602 $datarray['textversion'] = $textversion;
603 $datarray['subject'] = $subject;
604 $datarray['headers'] = $additional_mail_header;
606 Addon::callHooks('enotify_mail', $datarray);
608 // check whether sending post content in email notifications is allowed
609 // always true for SYSTEM_EMAIL
610 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
612 // load the template for private message notifications
613 $tpl = get_markup_template('email_notify_html.tpl');
614 $email_html_body = replace_macros($tpl, [
615 '$banner' => $datarray['banner'],
616 '$product' => $datarray['product'],
617 '$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
618 '$sitename' => $datarray['sitename'],
619 '$siteurl' => $datarray['siteurl'],
620 '$source_name' => $datarray['source_name'],
621 '$source_link' => $datarray['source_link'],
622 '$source_photo' => $datarray['source_photo'],
623 '$username' => $datarray['username'],
624 '$hsitelink' => $datarray['hsitelink'],
625 '$hitemlink' => $datarray['hitemlink'],
626 '$thanks' => $datarray['thanks'],
627 '$site_admin' => $datarray['site_admin'],
628 '$title' => $datarray['title'],
629 '$htmlversion' => $datarray['htmlversion'],
630 '$content_allowed' => $content_allowed,
633 // load the template for private message notifications
634 $tpl = get_markup_template('email_notify_text.tpl');
635 $email_text_body = replace_macros($tpl, [
636 '$banner' => $datarray['banner'],
637 '$product' => $datarray['product'],
638 '$preamble' => $datarray['preamble'],
639 '$sitename' => $datarray['sitename'],
640 '$siteurl' => $datarray['siteurl'],
641 '$source_name' => $datarray['source_name'],
642 '$source_link' => $datarray['source_link'],
643 '$source_photo' => $datarray['source_photo'],
644 '$username' => $datarray['username'],
645 '$tsitelink' => $datarray['tsitelink'],
646 '$titemlink' => $datarray['titemlink'],
647 '$thanks' => $datarray['thanks'],
648 '$site_admin' => $datarray['site_admin'],
649 '$title' => $datarray['title'],
650 '$textversion' => $datarray['textversion'],
651 '$content_allowed' => $content_allowed,
654 // use the Emailer class to send the message
655 return Emailer::send(
657 'uid' => $params['uid'],
658 'fromName' => $sender_name,
659 'fromEmail' => $sender_email,
660 'replyTo' => $sender_email,
661 'toEmail' => $params['to_email'],
662 'messageSubject' => $datarray['subject'],
663 'htmlVersion' => $email_html_body,
664 'textVersion' => $email_text_body,
665 'additionalMailHeader' => $datarray['headers']]
673 * @brief Checks for users who should be notified
675 * @param int $itemid ID of the item for which the check should be done
677 function check_user_notification($itemid) {
678 // fetch all users in the thread
679 $users = DBA::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
680 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
681 WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
682 while ($user = DBA::fetch($users)) {
683 check_item_notification($itemid, $user['uid']);
689 * @brief Checks for item related notifications and sends them
691 * @param int $itemid ID of the item for which the check should be done
692 * @param int $uid User ID
693 * @param string $defaulttype (Optional) Forces a notification with this type.
695 function check_item_notification($itemid, $uid, $defaulttype = "") {
696 $notification_data = ["uid" => $uid, "profiles" => []];
697 Addon::callHooks('check_item_notification', $notification_data);
699 $profiles = $notification_data["profiles"];
701 $fields = ['notify-flags', 'language', 'username', 'email', 'nickname'];
702 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
703 if (!DBA::isResult($user)) {
707 $owner = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
708 if (!DBA::isResult($owner)) {
712 // This is our regular URL format
713 $profiles[] = $owner["url"];
715 // Notifications from Diaspora are often with an URL in the Diaspora format
716 $profiles[] = System::baseUrl()."/u/".$user["nickname"];
720 foreach ($profiles AS $profile) {
721 // Check for invalid profile urls. 13 should be the shortest possible profile length:
723 // Additionally check for invalid urls that would return the normalised value "http:"
724 if ((strlen($profile) >= 13) && (normalise_link($profile) != "http:")) {
725 if (!in_array($profile, $profiles2))
726 $profiles2[] = $profile;
728 $profile = normalise_link($profile);
729 if (!in_array($profile, $profiles2))
730 $profiles2[] = $profile;
732 $profile = str_replace("http://", "https://", $profile);
733 if (!in_array($profile, $profiles2))
734 $profiles2[] = $profile;
738 $profiles = $profiles2;
740 $ret = DBA::select('contact', ['id'], ['uid' => 0, 'nurl' => $profiles]);
744 while ($contact = DBA::fetch($ret)) {
745 $contacts[] = $contact['id'];
748 $contact_list = implode(',', $contacts);
752 // Only act if it is a "real" post
753 // We need the additional check for the "local_profile" because of mixed situations on connector networks
754 $fields = ['id', 'mention', 'tag', 'parent', 'title', 'body',
755 'author-link', 'author-name', 'author-avatar', 'author-id',
756 'guid', 'parent-uri', 'uri', 'contact-id', 'network'];
757 $condition = ['id' => $itemid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
758 $item = Item::selectFirst($fields, $condition);
759 if (!DBA::isResult($item) || in_array($item['author-id'], $contacts)) {
763 // Generate the notification array
765 $params["uid"] = $uid;
766 $params["notify_flags"] = $user["notify-flags"];
767 $params["language"] = $user["language"];
768 $params["to_name"] = $user["username"];
769 $params["to_email"] = $user["email"];
770 $params["item"] = $item;
771 $params["parent"] = $item["parent"];
772 $params["link"] = System::baseUrl().'/display/'.urlencode($item["guid"]);
773 $params["otype"] = 'item';
774 $params["source_name"] = $item["author-name"];
775 $params["source_link"] = $item["author-link"];
776 $params["source_photo"] = $item["author-avatar"];
778 if ($item["parent-uri"] === $item["uri"]) {
779 // Send a notification for every new post?
780 $send_notification = DBA::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true]);
782 if (!$send_notification) {
783 $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
784 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
786 if (DBA::isResult($tags)) {
787 foreach ($tags AS $tag) {
788 $condition = ['nurl' => normalise_link($tag["url"]), 'uid' => $uid, 'notify_new_posts' => true];
789 $r = DBA::exists('contact', $condition);
791 $send_notification = true;
797 if ($send_notification) {
798 $params["type"] = NOTIFY_SHARE;
799 $params["verb"] = ACTIVITY_TAG;
803 // Is the user mentioned in this post?
806 foreach ($profiles AS $profile) {
807 if (strpos($item["tag"], "=".$profile."]") || strpos($item["body"], "=".$profile."]"))
811 if ($item["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
812 $params["type"] = NOTIFY_TAGSELF;
813 $params["verb"] = ACTIVITY_TAG;
816 // Is it a post that the user had started or where he interacted?
817 $parent = q("SELECT `thread`.`iid` FROM `thread` INNER JOIN `item` ON `item`.`parent` = `thread`.`iid`
818 WHERE `thread`.`iid` = %d AND NOT `thread`.`ignored` AND
819 (`thread`.`mention` OR `item`.`author-id` IN ($contact_list))
821 intval($item["parent"]));
823 if ($parent && !isset($params["type"])) {
824 $params["type"] = NOTIFY_COMMENT;
825 $params["verb"] = ACTIVITY_POST;
828 if (isset($params["type"]))
829 notification($params);
833 * @brief Formats a notification message with the notification author
835 * Replace the name with {0} but ensure to make that only once. The {0} is used
836 * later and prints the name in bold.
838 * @param string $name
839 * @param string $message
840 * @return string Formatted message
842 function format_notification_message($name, $message) {
844 $pos = strpos($message, $name);
849 if ($pos !== false) {
850 $message = substr_replace($message, '{0}', $pos, strlen($name));