3 * @file include/enotify.php
6 use Friendica\Content\Text\BBCode;
7 use Friendica\Core\Config;
8 use Friendica\Core\Hook;
9 use Friendica\Core\L10n;
10 use Friendica\Core\Logger;
11 use Friendica\Core\Renderer;
12 use Friendica\Core\System;
13 use Friendica\Database\DBA;
14 use Friendica\Model\Contact;
15 use Friendica\Model\Item;
16 use Friendica\Util\DateTimeFormat;
17 use Friendica\Util\Emailer;
18 use Friendica\Util\Strings;
21 * @brief Creates a notification entry and possibly sends a mail
23 * @param array $params Array with the elements:
24 * uid, item, parent, type, otype, verb, event,
25 * link, subject, body, to_name, to_email, source_name,
26 * source_link, activity, preamble, notify_flags,
27 * language, show_in_notification_page
29 function notification($params)
33 // Temporary logging for finding the origin
34 if (!isset($params['language']) || !isset($params['uid'])) {
35 Logger::log('Missing parameters.' . System::callstack());
38 // Ensure that the important fields are set at any time
39 $fields = ['notify-flags', 'language', 'username', 'email'];
40 $user = DBA::selectFirst('user', $fields, ['uid' => $params['uid']]);
42 if (!DBA::isResult($user)) {
43 Logger::log('Unknown user ' . $params['uid']);
47 $params['notify_flags'] = defaults($params, 'notify_flags', $user['notify-flags']);
48 $params['language'] = defaults($params, 'language' , $user['language']);
49 $params['to_name'] = defaults($params, 'to_name' , $user['username']);
50 $params['to_email'] = defaults($params, 'to_email' , $user['email']);
52 // from here on everything is in the recipients language
53 L10n::pushLang($params['language']);
55 $banner = L10n::t('Friendica Notification');
56 $product = FRIENDICA_PLATFORM;
57 $siteurl = System::baseUrl(true);
58 $thanks = L10n::t('Thank You,');
59 $sitename = Config::get('config', 'sitename');
60 if (Config::get('config', 'admin_name')) {
61 $site_admin = L10n::t('%1$s, %2$s Administrator', Config::get('config', 'admin_name'), $sitename);
63 $site_admin = L10n::t('%s Administrator', $sitename);
66 $sender_name = $sitename;
67 $hostname = $a->getHostName();
68 if (strpos($hostname, ':')) {
69 $hostname = substr($hostname, 0, strpos($hostname, ':'));
72 $sender_email = $a->getSenderEmailAddress();
74 if ($params['type'] != SYSTEM_EMAIL) {
75 $user = DBA::selectFirst('user', ['nickname', 'page-flags'],
76 ['uid' => $params['uid']]);
78 // There is no need to create notifications for forum accounts
79 if (!DBA::isResult($user) || in_array($user["page-flags"], [Contact::PAGE_COMMUNITY, Contact::PAGE_PRVGROUP])) {
82 $nickname = $user["nickname"];
87 // with $params['show_in_notification_page'] == false, the notification isn't inserted into
88 // the database, and an email is sent if applicable.
89 // default, if not specified: true
90 $show_in_notification_page = isset($params['show_in_notification_page']) ? $params['show_in_notification_page'] : true;
92 $additional_mail_header = "";
93 $additional_mail_header .= "Precedence: list\n";
94 $additional_mail_header .= "X-Friendica-Host: ".$hostname."\n";
95 $additional_mail_header .= "X-Friendica-Account: <".$nickname."@".$hostname.">\n";
96 $additional_mail_header .= "X-Friendica-Platform: ".FRIENDICA_PLATFORM."\n";
97 $additional_mail_header .= "X-Friendica-Version: ".FRIENDICA_VERSION."\n";
98 $additional_mail_header .= "List-ID: <notification.".$hostname.">\n";
99 $additional_mail_header .= "List-Archive: <".System::baseUrl()."/notifications/system>\n";
101 if (array_key_exists('item', $params)) {
102 $title = $params['item']['title'];
103 $body = $params['item']['body'];
108 if (isset($params['item']['id'])) {
109 $item_id = $params['item']['id'];
114 if (isset($params['parent'])) {
115 $parent_id = $params['parent'];
122 if ($params['type'] == NOTIFY_MAIL) {
123 $itemlink = $siteurl.'/message/'.$params['item']['id'];
124 $params["link"] = $itemlink;
126 $subject = L10n::t('[Friendica:Notify] New mail received at %s', $sitename);
128 $preamble = L10n::t('%1$s sent you a new private message at %2$s.', $params['source_name'], $sitename);
129 $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]');
131 $sitelink = L10n::t('Please visit %s to view and/or reply to your private messages.');
132 $tsitelink = sprintf($sitelink, $siteurl.'/message/'.$params['item']['id']);
133 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'/message/'.$params['item']['id'].'">'.$sitename.'</a>');
136 if ($params['type'] == NOTIFY_COMMENT || $params['type'] == NOTIFY_TAGSELF) {
137 $thread = Item::selectFirstThreadForUser($params['uid'], ['ignored'], ['iid' => $parent_id]);
138 if (DBA::isResult($thread) && $thread['ignored']) {
139 Logger::log('Thread ' . $parent_id . ' will be ignored', Logger::DEBUG);
144 // Check to see if there was already a tag notify or comment notify for this post.
145 // If so don't create a second notification
146 $condition = ['type' => [NOTIFY_TAGSELF, NOTIFY_COMMENT, NOTIFY_SHARE],
147 'link' => $params['link'], 'uid' => $params['uid']];
148 if (DBA::exists('notify', $condition)) {
153 // if it's a post figure out who's post it is.
155 if ($params['otype'] === 'item' && $parent_id) {
156 $item = Item::selectFirstForUser($params['uid'], Item::ITEM_FIELDLIST, ['id' => $parent_id]);
159 $item_post_type = Item::postType($item);
160 $itemlink = $item['plink'];
163 if ($params['type'] == NOTIFY_TAGSELF) {
164 $dest_str = L10n::t('%1$s tagged you on [url=%2$s]a %3$s[/url]',
165 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
170 $dest_str = L10n::t('%1$s commented on [url=%2$s]a %3$s[/url]',
171 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
177 // "George Bull's post"
178 if (DBA::isResult($item)) {
179 if ($params['type'] == NOTIFY_TAGSELF) {
180 $dest_str = L10n::t('%1$s tagged you on [url=%2$s]%3$s\'s %4$s[/url]',
181 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
183 $item['author-name'],
187 $dest_str = L10n::t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]',
188 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
190 $item['author-name'],
197 if (DBA::isResult($item) && $item['owner-id'] == $item['author-id'] && $item['wall']) {
198 if ($params['type'] == NOTIFY_TAGSELF) {
199 $dest_str = L10n::t('%1$s tagged you on [url=%2$s]your %3$s[/url]',
200 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
205 $dest_str = L10n::t('%1$s commented on [url=%2$s]your %3$s[/url]',
206 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
214 if (DBA::isResult($item) && $item['author-link'] == $params['source_link']) {
215 if ($params['type'] == NOTIFY_TAGSELF) {
216 $dest_str = L10n::t('%1$s tagged you on [url=%2$s]their %3$s[/url]',
217 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
222 $dest_str = L10n::t('%1$s commented on [url=%2$s]their %3$s[/url]',
223 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
230 // Some mail software relies on subject field for threading.
231 // So, we cannot have different subjects for notifications of the same thread.
232 // Before this we have the name of the replier on the subject rendering
233 // different subjects for messages on the same thread.
234 if ($params['type'] == NOTIFY_TAGSELF) {
235 $subject = L10n::t('[Friendica:Notify] %s tagged you', $params['source_name']);
237 $preamble = L10n::t('%1$s tagged you at %2$s', $params['source_name'], $sitename);
239 $subject = L10n::t('[Friendica:Notify] Comment to conversation #%1$d by %2$s', $parent_id, $params['source_name']);
241 $preamble = L10n::t('%s commented on an item/conversation you have been following.', $params['source_name']);
244 $epreamble = $dest_str;
246 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
247 $tsitelink = sprintf($sitelink, $siteurl);
248 $hsitelink = sprintf($sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
249 $itemlink = $params['link'];
252 if ($params['type'] == NOTIFY_WALL) {
253 $subject = L10n::t('[Friendica:Notify] %s posted to your profile wall', $params['source_name']);
255 $preamble = L10n::t('%1$s posted to your profile wall at %2$s', $params['source_name'], $sitename);
256 $epreamble = L10n::t('%1$s posted to [url=%2$s]your wall[/url]',
257 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
261 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
262 $tsitelink = sprintf($sitelink, $siteurl);
263 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
264 $itemlink = $params['link'];
267 if ($params['type'] == NOTIFY_SHARE) {
268 $subject = L10n::t('[Friendica:Notify] %s shared a new post', $params['source_name']);
270 $preamble = L10n::t('%1$s shared a new post at %2$s', $params['source_name'], $sitename);
271 $epreamble = L10n::t('%1$s [url=%2$s]shared a post[/url].',
272 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
276 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
277 $tsitelink = sprintf($sitelink, $siteurl);
278 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
279 $itemlink = $params['link'];
282 if ($params['type'] == NOTIFY_POKE) {
283 $subject = L10n::t('[Friendica:Notify] %1$s poked you', $params['source_name']);
285 $preamble = L10n::t('%1$s poked you at %2$s', $params['source_name'], $sitename);
286 $epreamble = L10n::t('%1$s [url=%2$s]poked you[/url].',
287 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
291 $subject = str_replace('poked', L10n::t($params['activity']), $subject);
292 $preamble = str_replace('poked', L10n::t($params['activity']), $preamble);
293 $epreamble = str_replace('poked', L10n::t($params['activity']), $epreamble);
295 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
296 $tsitelink = sprintf($sitelink, $siteurl);
297 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
298 $itemlink = $params['link'];
301 if ($params['type'] == NOTIFY_TAGSHARE) {
302 $itemlink = $params['link'];
303 $subject = L10n::t('[Friendica:Notify] %s tagged your post', $params['source_name']);
305 $preamble = L10n::t('%1$s tagged your post at %2$s', $params['source_name'], $sitename);
306 $epreamble = L10n::t('%1$s tagged [url=%2$s]your post[/url]',
307 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
311 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
312 $tsitelink = sprintf($sitelink, $siteurl);
313 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
316 if ($params['type'] == NOTIFY_INTRO) {
317 $itemlink = $params['link'];
318 $subject = L10n::t('[Friendica:Notify] Introduction received');
320 $preamble = L10n::t('You\'ve received an introduction from \'%1$s\' at %2$s', $params['source_name'], $sitename);
321 $epreamble = L10n::t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.',
323 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
326 $body = L10n::t('You may visit their profile at %s', $params['source_link']);
328 $sitelink = L10n::t('Please visit %s to approve or reject the introduction.');
329 $tsitelink = sprintf($sitelink, $siteurl);
330 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
332 switch ($params['verb']) {
333 case ACTIVITY_FRIEND:
334 // someone started to share with user (mostly OStatus)
335 $subject = L10n::t('[Friendica:Notify] A new person is sharing with you');
337 $preamble = L10n::t('%1$s is sharing with you at %2$s', $params['source_name'], $sitename);
338 $epreamble = L10n::t('%1$s is sharing with you at %2$s',
339 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
343 case ACTIVITY_FOLLOW:
344 // someone started to follow the user (mostly OStatus)
345 $subject = L10n::t('[Friendica:Notify] You have a new follower');
347 $preamble = L10n::t('You have a new follower at %2$s : %1$s', $params['source_name'], $sitename);
348 $epreamble = L10n::t('You have a new follower at %2$s : %1$s',
349 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
354 // ACTIVITY_REQ_FRIEND is default activity for notifications
359 if ($params['type'] == NOTIFY_SUGGEST) {
360 $itemlink = $params['link'];
361 $subject = L10n::t('[Friendica:Notify] Friend suggestion received');
363 $preamble = L10n::t('You\'ve received a friend suggestion from \'%1$s\' at %2$s', $params['source_name'], $sitename);
364 $epreamble = L10n::t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.',
366 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
367 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
370 $body = L10n::t('Name:').' '.$params['item']['name']."\n";
371 $body .= L10n::t('Photo:').' '.$params['item']['photo']."\n";
372 $body .= L10n::t('You may visit their profile at %s', $params['item']['url']);
374 $sitelink = L10n::t('Please visit %s to approve or reject the suggestion.');
375 $tsitelink = sprintf($sitelink, $siteurl);
376 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
379 if ($params['type'] == NOTIFY_CONFIRM) {
380 if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
381 $itemlink = $params['link'];
382 $subject = L10n::t('[Friendica:Notify] Connection accepted');
384 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
385 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
387 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
390 $body = L10n::t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
392 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
393 $tsitelink = sprintf($sitelink, $siteurl);
394 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
395 } else { // ACTIVITY_FOLLOW
396 $itemlink = $params['link'];
397 $subject = L10n::t('[Friendica:Notify] Connection accepted');
399 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
400 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
402 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
405 $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']);
407 $body .= L10n::t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.', $params['source_name']);
409 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
410 $tsitelink = sprintf($sitelink, $siteurl);
411 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
415 if ($params['type'] == NOTIFY_SYSTEM) {
416 switch($params['event']) {
417 case "SYSTEM_REGISTER_REQUEST":
418 $itemlink = $params['link'];
419 $subject = L10n::t('[Friendica System Notify]') . ' ' . L10n::t('registration request');
421 $preamble = L10n::t('You\'ve received a registration request from \'%1$s\' at %2$s', $params['source_name'], $sitename);
422 $epreamble = L10n::t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.',
424 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
427 $body = L10n::t("Full Name: %s\nSite Location: %s\nLogin Name: %s (%s)",
428 $params['source_name'],
429 $siteurl, $params['source_mail'],
430 $params['source_nick']
433 $sitelink = L10n::t('Please visit %s to approve or reject the request.');
434 $tsitelink = sprintf($sitelink, $params['link']);
435 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
437 case "SYSTEM_DB_UPDATE_FAIL":
442 if ($params['type'] == SYSTEM_EMAIL) {
443 // not part of the notifications.
444 // it just send a mail to the user.
445 // It will be used by the system to send emails to users (like
446 // password reset, invitations and so) using one look (but without
447 // add a notification to the user, with could be inexistent)
448 $subject = $params['subject'];
450 $preamble = $params['preamble'];
452 $body = $params['body'];
458 $show_in_notification_page = false;
461 $subject .= " (".$nickname."@".$hostname.")";
465 'subject' => $subject,
466 'preamble' => $preamble,
467 'epreamble' => $epreamble,
469 'sitelink' => $sitelink,
470 'tsitelink' => $tsitelink,
471 'hsitelink' => $hsitelink,
472 'itemlink' => $itemlink
475 Hook::callAll('enotify', $h);
477 $subject = $h['subject'];
479 $preamble = $h['preamble'];
480 $epreamble = $h['epreamble'];
484 $tsitelink = $h['tsitelink'];
485 $hsitelink = $h['hsitelink'];
486 $itemlink = $h['itemlink'];
488 if ($show_in_notification_page) {
489 Logger::log("adding notification entry", Logger::DEBUG);
492 $hash = Strings::getRandomHex();
493 if (DBA::exists('notify', ['hash' => $hash])) {
496 } while ($dups == true);
498 /// @TODO One statement is enough
500 $datarray['hash'] = $hash;
501 $datarray['name'] = $params['source_name'];
502 $datarray['name_cache'] = strip_tags(BBCode::convert($params['source_name']));
503 $datarray['url'] = $params['source_link'];
504 $datarray['photo'] = $params['source_photo'];
505 $datarray['date'] = DateTimeFormat::utcNow();
506 $datarray['uid'] = $params['uid'];
507 $datarray['link'] = $itemlink;
508 $datarray['iid'] = $item_id;
509 $datarray['parent'] = $parent_id;
510 $datarray['type'] = $params['type'];
511 $datarray['verb'] = $params['verb'];
512 $datarray['otype'] = $params['otype'];
513 $datarray['abort'] = false;
515 Hook::callAll('enotify_store', $datarray);
517 if ($datarray['abort']) {
522 // create notification entry in DB
523 $fields = ['hash' => $datarray['hash'], 'name' => $datarray['name'], 'url' => $datarray['url'],
524 'photo' => $datarray['photo'], 'date' => $datarray['date'], 'uid' => $datarray['uid'],
525 'link' => $datarray['link'], 'iid' => $datarray['iid'], 'parent' => $datarray['parent'],
526 'type' => $datarray['type'], 'verb' => $datarray['verb'], 'otype' => $datarray['otype'],
527 'name_cache' => $datarray["name_cache"]];
528 DBA::insert('notify', $fields);
530 $notify_id = DBA::lastInsertId();
532 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
533 // After we've stored everything, look again to see if there are any duplicates and if so remove them
534 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
535 intval(NOTIFY_TAGSELF),
536 intval(NOTIFY_COMMENT),
537 DBA::escape($params['link']),
538 intval($params['uid'])
540 if ($p && (count($p) > 1)) {
541 for ($d = 1; $d < count($p); $d ++) {
542 DBA::delete('notify', ['id' => $p[$d]['id']]);
545 // only continue on if we stored the first one
546 if ($notify_id != $p[0]['id']) {
552 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
553 $msg = Renderer::replaceMacros($epreamble, ['$itemlink' => $itemlink]);
554 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(BBCode::convert($msg)));
556 $fields = ['msg' => $msg, 'msg_cache' => $msg_cache];
557 $condition = ['id' => $notify_id, 'uid' => $params['uid']];
558 DBA::update('notify', $fields, $condition);
561 // send email notification if notification preferences permit
562 if ((intval($params['notify_flags']) & intval($params['type']))
563 || $params['type'] == NOTIFY_SYSTEM
564 || $params['type'] == SYSTEM_EMAIL) {
566 Logger::log('sending notification email');
568 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
569 $id_for_parent = $params['parent']."@".$hostname;
571 // Is this the first email notification for this parent item and user?
572 if (!DBA::exists('notify-threads', ['master-parent-item' => $params['parent'], 'receiver-uid' => $params['uid']])) {
573 Logger::log("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), Logger::DEBUG);
575 $fields = ['notify-id' => $notify_id, 'master-parent-item' => $params['parent'],
576 'receiver-uid' => $params['uid'], 'parent-item' => 0];
577 DBA::insert('notify-threads', $fields);
579 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
580 $log_msg = "include/enotify: No previous notification found for this parent:\n".
581 " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
582 Logger::log($log_msg, Logger::DEBUG);
584 // If not, just "follow" the thread.
585 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
586 Logger::log("There's already a notification for this parent.", Logger::DEBUG);
590 $textversion = BBCode::toPlaintext($body);
591 $htmlversion = BBCode::convert($body);
594 $datarray['banner'] = $banner;
595 $datarray['product'] = $product;
596 $datarray['preamble'] = $preamble;
597 $datarray['sitename'] = $sitename;
598 $datarray['siteurl'] = $siteurl;
599 $datarray['type'] = $params['type'];
600 $datarray['parent'] = $parent_id;
601 $datarray['source_name'] = defaults($params, 'source_name', '');
602 $datarray['source_link'] = defaults($params, 'source_link', '');
603 $datarray['source_photo'] = defaults($params, 'source_photo', '');
604 $datarray['uid'] = $params['uid'];
605 $datarray['username'] = defaults($params, 'to_name', '');
606 $datarray['hsitelink'] = $hsitelink;
607 $datarray['tsitelink'] = $tsitelink;
608 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
609 $datarray['titemlink'] = $itemlink;
610 $datarray['thanks'] = $thanks;
611 $datarray['site_admin'] = $site_admin;
612 $datarray['title'] = stripslashes($title);
613 $datarray['htmlversion'] = $htmlversion;
614 $datarray['textversion'] = $textversion;
615 $datarray['subject'] = $subject;
616 $datarray['headers'] = $additional_mail_header;
618 Hook::callAll('enotify_mail', $datarray);
620 // check whether sending post content in email notifications is allowed
621 // always true for SYSTEM_EMAIL
622 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
624 // load the template for private message notifications
625 $tpl = Renderer::getMarkupTemplate('email_notify_html.tpl');
626 $email_html_body = Renderer::replaceMacros($tpl, [
627 '$banner' => $datarray['banner'],
628 '$product' => $datarray['product'],
629 '$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
630 '$sitename' => $datarray['sitename'],
631 '$siteurl' => $datarray['siteurl'],
632 '$source_name' => $datarray['source_name'],
633 '$source_link' => $datarray['source_link'],
634 '$source_photo' => $datarray['source_photo'],
635 '$username' => $datarray['username'],
636 '$hsitelink' => $datarray['hsitelink'],
637 '$hitemlink' => $datarray['hitemlink'],
638 '$thanks' => $datarray['thanks'],
639 '$site_admin' => $datarray['site_admin'],
640 '$title' => $datarray['title'],
641 '$htmlversion' => $datarray['htmlversion'],
642 '$content_allowed' => $content_allowed,
645 // load the template for private message notifications
646 $tpl = Renderer::getMarkupTemplate('email_notify_text.tpl');
647 $email_text_body = Renderer::replaceMacros($tpl, [
648 '$banner' => $datarray['banner'],
649 '$product' => $datarray['product'],
650 '$preamble' => $datarray['preamble'],
651 '$sitename' => $datarray['sitename'],
652 '$siteurl' => $datarray['siteurl'],
653 '$source_name' => $datarray['source_name'],
654 '$source_link' => $datarray['source_link'],
655 '$source_photo' => $datarray['source_photo'],
656 '$username' => $datarray['username'],
657 '$tsitelink' => $datarray['tsitelink'],
658 '$titemlink' => $datarray['titemlink'],
659 '$thanks' => $datarray['thanks'],
660 '$site_admin' => $datarray['site_admin'],
661 '$title' => $datarray['title'],
662 '$textversion' => $datarray['textversion'],
663 '$content_allowed' => $content_allowed,
667 // use the Emailer class to send the message
668 return Emailer::send(
670 'uid' => $params['uid'],
671 'fromName' => $sender_name,
672 'fromEmail' => $sender_email,
673 'replyTo' => $sender_email,
674 'toEmail' => $params['to_email'],
675 'messageSubject' => $datarray['subject'],
676 'htmlVersion' => $email_html_body,
677 'textVersion' => $email_text_body,
678 'additionalMailHeader' => $datarray['headers']]
687 * @brief Checks for users who should be notified
689 * @param int $itemid ID of the item for which the check should be done
691 function check_user_notification($itemid) {
692 // fetch all users in the thread
693 $users = DBA::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
694 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
695 WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
696 while ($user = DBA::fetch($users)) {
697 check_item_notification($itemid, $user['uid']);
703 * @brief Checks for item related notifications and sends them
705 * @param int $itemid ID of the item for which the check should be done
706 * @param int $uid User ID
707 * @param string $defaulttype (Optional) Forces a notification with this type.
709 function check_item_notification($itemid, $uid, $defaulttype = "") {
710 $notification_data = ["uid" => $uid, "profiles" => []];
711 Hook::callAll('check_item_notification', $notification_data);
713 $profiles = $notification_data["profiles"];
715 $fields = ['nickname'];
716 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
717 if (!DBA::isResult($user)) {
721 $owner = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
722 if (!DBA::isResult($owner)) {
726 // This is our regular URL format
727 $profiles[] = $owner["url"];
729 // Notifications from Diaspora are often with an URL in the Diaspora format
730 $profiles[] = System::baseUrl()."/u/".$user["nickname"];
734 foreach ($profiles AS $profile) {
735 // Check for invalid profile urls. 13 should be the shortest possible profile length:
737 // Additionally check for invalid urls that would return the normalised value "http:"
738 if ((strlen($profile) >= 13) && (Strings::normaliseLink($profile) != "http:")) {
739 if (!in_array($profile, $profiles2))
740 $profiles2[] = $profile;
742 $profile = Strings::normaliseLink($profile);
743 if (!in_array($profile, $profiles2))
744 $profiles2[] = $profile;
746 $profile = str_replace("http://", "https://", $profile);
747 if (!in_array($profile, $profiles2))
748 $profiles2[] = $profile;
752 $profiles = $profiles2;
754 $ret = DBA::select('contact', ['id'], ['uid' => 0, 'nurl' => $profiles]);
758 while ($contact = DBA::fetch($ret)) {
759 $contacts[] = $contact['id'];
764 // Only act if it is a "real" post
765 // We need the additional check for the "local_profile" because of mixed situations on connector networks
766 $fields = ['id', 'mention', 'tag', 'parent', 'title', 'body',
767 'author-link', 'author-name', 'author-avatar', 'author-id',
768 'guid', 'parent-uri', 'uri', 'contact-id', 'network'];
769 $condition = ['id' => $itemid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
770 $item = Item::selectFirst($fields, $condition);
771 if (!DBA::isResult($item) || in_array($item['author-id'], $contacts)) {
775 // Generate the notification array
777 $params["uid"] = $uid;
778 $params["item"] = $item;
779 $params["parent"] = $item["parent"];
780 $params["link"] = System::baseUrl().'/display/'.urlencode($item["guid"]);
781 $params["otype"] = 'item';
782 $params["source_name"] = $item["author-name"];
783 $params["source_link"] = $item["author-link"];
784 $params["source_photo"] = $item["author-avatar"];
786 if ($item["parent-uri"] === $item["uri"]) {
787 // Send a notification for every new post?
788 $send_notification = DBA::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true]);
790 if (!$send_notification) {
791 $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
792 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
794 if (DBA::isResult($tags)) {
795 foreach ($tags AS $tag) {
796 $condition = ['nurl' => Strings::normaliseLink($tag["url"]), 'uid' => $uid, 'notify_new_posts' => true];
797 $r = DBA::exists('contact', $condition);
799 $send_notification = true;
805 if ($send_notification) {
806 $params["type"] = NOTIFY_SHARE;
807 $params["verb"] = ACTIVITY_TAG;
811 // Is the user mentioned in this post?
814 foreach ($profiles AS $profile) {
815 if (strpos($item["tag"], "=".$profile."]") || strpos($item["body"], "=".$profile."]"))
819 if ($item["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
820 $params["type"] = NOTIFY_TAGSELF;
821 $params["verb"] = ACTIVITY_TAG;
824 // Is it a post that the user had started?
825 $fields = ['ignored', 'mention'];
826 $thread = Item::selectFirstThreadForUser($params['uid'], $fields, ['iid' => $item["parent"]]);
828 if ($thread['mention'] && !$thread['ignored'] && !isset($params["type"])) {
829 $params["type"] = NOTIFY_COMMENT;
830 $params["verb"] = ACTIVITY_POST;
833 // And now we check for participation of one of our contacts in the thread
834 $condition = ['parent' => $item["parent"], 'author-id' => $contacts];
836 if (!$thread['ignored'] && !isset($params["type"]) && Item::exists($condition)) {
837 $params["type"] = NOTIFY_COMMENT;
838 $params["verb"] = ACTIVITY_POST;
841 if (isset($params["type"])) {
842 notification($params);
847 * @brief Formats a notification message with the notification author
849 * Replace the name with {0} but ensure to make that only once. The {0} is used
850 * later and prints the name in bold.
852 * @param string $name
853 * @param string $message
854 * @return string Formatted message
856 function format_notification_message($name, $message) {
858 $pos = strpos($message, $name);
863 if ($pos !== false) {
864 $message = substr_replace($message, '{0}', $pos, strlen($name));