3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Module\Notifications;
25 use Friendica\BaseModule;
26 use Friendica\Contact\Introduction\Repository\Introduction;
27 use Friendica\Content\ForumManager;
28 use Friendica\Core\Cache\Enum\Duration;
29 use Friendica\Core\Hook;
30 use Friendica\Core\L10n;
31 use Friendica\Core\Session;
32 use Friendica\Core\System;
33 use Friendica\Database\DBA;
35 use Friendica\Model\Group;
36 use Friendica\Model\Post;
37 use Friendica\Model\User;
38 use Friendica\Model\Verb;
39 use Friendica\Module\Register;
40 use Friendica\Module\Response;
41 use Friendica\Navigation\Notifications\Entity;
42 use Friendica\Navigation\Notifications\Exception\NoMessageException;
43 use Friendica\Navigation\Notifications\Factory;
44 use Friendica\Navigation\Notifications\Repository;
45 use Friendica\Navigation\Notifications\ValueObject;
46 use Friendica\Navigation\SystemMessages;
47 use Friendica\Protocol\Activity;
48 use Friendica\Util\DateTimeFormat;
49 use Friendica\Util\Profiler;
50 use GuzzleHttp\Psr7\Uri;
51 use Psr\Log\LoggerInterface;
53 class Ping extends BaseModule
55 /** @var SystemMessages */
56 private $systemMessages;
57 /** @var Repository\Notification */
58 private $notificationRepo;
59 /** @var Introduction */
60 private $introductionRepo;
61 /** @var Factory\FormattedNavNotification */
62 private $formattedNavNotification;
64 public function __construct(SystemMessages $systemMessages, Repository\Notification $notificationRepo, Introduction $introductionRepo, Factory\FormattedNavNotification $formattedNavNotification, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, array $server, array $parameters = [])
66 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
68 $this->systemMessages = $systemMessages;
69 $this->notificationRepo = $notificationRepo;
70 $this->introductionRepo = $introductionRepo;
71 $this->formattedNavNotification = $formattedNavNotification;
74 protected function rawContent(array $request = [])
77 $navNotifications = [];
89 $today_event_count = 0;
91 $today_birthday_count = 0;
94 if (Session::getLocalUser()) {
95 if (DI::pConfig()->get(Session::getLocalUser(), 'system', 'detailed_notif')) {
96 $notifications = $this->notificationRepo->selectDetailedForUser(Session::getLocalUser());
98 $notifications = $this->notificationRepo->selectDigestForUser(Session::getLocalUser());
102 "`unseen` AND `uid` = ? AND NOT `origin` AND (`vid` != ? OR `vid` IS NULL)",
103 Session::getLocalUser(), Verb::getID(Activity::FOLLOW)
105 $items = Post::selectForUser(Session::getLocalUser(), ['wall', 'uid', 'uri-id'], $condition, ['limit' => 1000]);
106 if (DBA::isResult($items)) {
107 $items_unseen = Post::toArray($items, false);
108 $arr = ['items' => $items_unseen];
109 Hook::callAll('network_ping', $arr);
111 foreach ($items_unseen as $item) {
121 $compute_group_counts = DI::config()->get('system','compute_group_counts');
122 if ($network_count && $compute_group_counts) {
123 // Find out how unseen network posts are spread across groups
124 $group_counts = Group::countUnseen();
125 if (DBA::isResult($group_counts)) {
126 foreach ($group_counts as $group_count) {
127 if ($group_count['count'] > 0) {
128 $groups_unseen[] = $group_count;
133 $forum_counts = ForumManager::countUnseenItems();
134 if (DBA::isResult($forum_counts)) {
135 foreach ($forum_counts as $forum_count) {
136 if ($forum_count['count'] > 0) {
137 $forums_unseen[] = $forum_count;
143 $intros = $this->introductionRepo->selectForUser(Session::getLocalUser());
145 $intro_count = $intros->count();
147 $myurl = DI::baseUrl() . '/profile/' . DI::app()->getLoggedInUserNickname();
148 $mail_count = DBA::count('mail', ["`uid` = ? AND NOT `seen` AND `from-url` != ?", Session::getLocalUser(), $myurl]);
150 if (intval(DI::config()->get('config', 'register_policy')) === Register::APPROVE && DI::app()->isSiteAdmin()) {
151 $regs = \Friendica\Model\Register::getPending();
153 if (DBA::isResult($regs)) {
154 $register_count = count($regs);
158 $cachekey = 'ping:events:' . Session::getLocalUser();
159 $ev = DI::cache()->get($cachekey);
161 $ev = DBA::selectToArray('event', ['type', 'start'],
162 ["`uid` = ? AND `start` < ? AND `finish` > ? AND NOT `ignore`",
163 Session::getLocalUser(), DateTimeFormat::utc('now + 7 days'), DateTimeFormat::utcNow()]);
164 DI::cache()->set($cachekey, $ev, Duration::HOUR);
167 if (DBA::isResult($ev)) {
168 $all_events = count($ev);
171 $str_now = DateTimeFormat::localNow('Y-m-d');
172 foreach ($ev as $x) {
174 if ($x['type'] === 'birthday') {
180 if (DateTimeFormat::local($x['start'], 'Y-m-d') === $str_now) {
182 $today_birthday_count++;
184 $today_event_count++;
191 $owner = User::getOwnerDataById(Session::getLocalUser());
193 $navNotifications = array_map(function (Entity\Notification $notification) use ($owner) {
194 if (!DI::notify()->NotifyOnDesktop($notification)) {
197 if (($notification->type == Post\UserNotification::TYPE_NONE) && in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])) {
201 return $this->formattedNavNotification->createFromNotification($notification);
202 } catch (NoMessageException $e) {
205 }, $notifications->getArrayCopy());
206 $navNotifications = array_filter($navNotifications);
208 $sysnotify_count = array_reduce($navNotifications, function (int $carry, ValueObject\FormattedNavNotification $navNotification) {
209 return $carry + ($navNotification->seen ? 0 : 1);
212 // merge all notification types in one array
213 foreach ($intros as $intro) {
214 $navNotifications[] = $this->formattedNavNotification->createFromIntro($intro);
217 if (DBA::isResult($regs)) {
218 if (count($regs) <= 1 || DI::pConfig()->get(Session::getLocalUser(), 'system', 'detailed_notif')) {
219 foreach ($regs as $reg) {
220 $navNotifications[] = $this->formattedNavNotification->createFromParams(
222 'name' => $reg['name'],
223 'url' => $reg['url'],
225 DI::l10n()->t('{0} requested registration'),
226 new \DateTime($reg['created'], new \DateTimeZone('UTC')),
227 new Uri(DI::baseUrl()->get(true) . '/admin/users/pending')
231 $navNotifications[] = $this->formattedNavNotification->createFromParams(
233 'name' => $regs[0]['name'],
234 'url' => $regs[0]['url'],
236 DI::l10n()->t('{0} and %d others requested registration', count($regs) - 1),
237 new \DateTime($regs[0]['created'], new \DateTimeZone('UTC')),
238 new Uri(DI::baseUrl()->get(true) . '/admin/users/pending')
243 // sort notifications by $[]['date']
244 $sort_function = function (ValueObject\FormattedNavNotification $a, ValueObject\FormattedNavNotification $b) {
248 // Unseen messages are kept at the top
249 if ($a['seen'] == $b['seen']) {
250 if ($a['timestamp'] == $b['timestamp']) {
253 return $a['timestamp'] < $b['timestamp'] ? 1 : -1;
256 return $a['seen'] ? 1 : -1;
259 usort($navNotifications, $sort_function);
262 $notification_count = $sysnotify_count + $intro_count + $register_count;
265 $data['intro'] = $intro_count;
266 $data['mail'] = $mail_count;
267 $data['net'] = ($network_count < 1000) ? $network_count : '999+';
268 $data['home'] = ($home_count < 1000) ? $home_count : '999+';
269 $data['register'] = $register_count;
271 $data['events'] = $event_count;
272 $data['events-today'] = $today_event_count;
273 $data['birthdays'] = $birthday_count;
274 $data['birthdays-today'] = $today_birthday_count;
275 $data['groups'] = $groups_unseen;
276 $data['forums'] = $forums_unseen;
277 $data['notification'] = ($notification_count < 50) ? $notification_count : '49+';
279 $data['notifications'] = $navNotifications;
282 'notice' => $this->systemMessages->flushNotices(),
283 'info' => $this->systemMessages->flushInfos(),
286 if (isset($_GET['callback'])) {
288 System::httpExit($_GET['callback'] . '(' . json_encode(['result' => $data]) . ')', Response::TYPE_BLANK, 'application/javascript');
290 System::jsonExit(['result' => $data]);