]> git.mxchange.org Git - friendica.git/blob - src/Module/Notifications/Ping.php
Remove dependency on DI in Notifications\Ping module
[friendica.git] / src / Module / Notifications / Ping.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Module\Notifications;
23
24 use Friendica\App;
25 use Friendica\BaseModule;
26 use Friendica\Contact\Introduction\Repository\Introduction;
27 use Friendica\Content\ForumManager;
28 use Friendica\Core\Cache\Capability\ICanCache;
29 use Friendica\Core\Cache\Enum\Duration;
30 use Friendica\Core\Config\Capability\IManageConfigValues;
31 use Friendica\Core\Hook;
32 use Friendica\Core\L10n;
33 use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
34 use Friendica\Core\Session\Capability\IHandleUserSessions;
35 use Friendica\Core\System;
36 use Friendica\Database\Database;
37 use Friendica\Database\DBA;
38 use Friendica\Model\Group;
39 use Friendica\Model\Post;
40 use Friendica\Model\User;
41 use Friendica\Model\Verb;
42 use Friendica\Module\Conversation\Network;
43 use Friendica\Module\Register;
44 use Friendica\Module\Response;
45 use Friendica\Navigation\Notifications\Entity;
46 use Friendica\Navigation\Notifications\Exception\NoMessageException;
47 use Friendica\Navigation\Notifications\Factory;
48 use Friendica\Navigation\Notifications\Repository;
49 use Friendica\Navigation\Notifications\ValueObject;
50 use Friendica\Navigation\SystemMessages;
51 use Friendica\Protocol\Activity;
52 use Friendica\Util\DateTimeFormat;
53 use Friendica\Util\Profiler;
54 use GuzzleHttp\Psr7\Uri;
55 use Psr\Log\LoggerInterface;
56
57 class Ping extends BaseModule
58 {
59         /** @var SystemMessages */
60         private $systemMessages;
61         /** @var Repository\Notification */
62         private $notificationRepo;
63         /** @var Introduction */
64         private $introductionRepo;
65         /** @var Factory\FormattedNavNotification */
66         private $formattedNavNotification;
67         /** @var IHandleUserSessions */
68         private $session;
69         /** @var IManageConfigValues */
70         private $config;
71         /** @var IManagePersonalConfigValues */
72         private $pconfig;
73         /** @var Database */
74         private $database;
75         /** @var ICanCache */
76         private $cache;
77         /** @var Repository\Notify */
78         private $notify;
79         /** @var App */
80         private $app;
81
82         public function __construct(App $app, Repository\Notify $notify, ICanCache $cache, Database $database, IManagePersonalConfigValues $pconfig, IManageConfigValues $config, IHandleUserSessions $session, 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 = [])
83         {
84                 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
85
86                 $this->systemMessages           = $systemMessages;
87                 $this->notificationRepo         = $notificationRepo;
88                 $this->introductionRepo         = $introductionRepo;
89                 $this->formattedNavNotification = $formattedNavNotification;
90                 $this->session                  = $session;
91                 $this->config                   = $config;
92                 $this->pconfig                  = $pconfig;
93                 $this->database                 = $database;
94                 $this->cache                    = $cache;
95                 $this->notify                   = $notify;
96                 $this->app                      = $app;
97         }
98
99         protected function rawContent(array $request = [])
100         {
101                 $registrations    = [];
102                 $navNotifications = [];
103
104                 $intro_count     = 0;
105                 $mail_count      = 0;
106                 $home_count      = 0;
107                 $network_count   = 0;
108                 $register_count  = 0;
109                 $sysnotify_count = 0;
110                 $groups_unseen   = [];
111                 $forums_unseen   = [];
112
113                 $event_count          = 0;
114                 $today_event_count    = 0;
115                 $birthday_count       = 0;
116                 $today_birthday_count = 0;
117
118
119                 if ($this->session->getLocalUserId()) {
120                         if ($this->pconfig->get($this->session->getLocalUserId(), 'system', 'detailed_notif')) {
121                                 $notifications = $this->notificationRepo->selectDetailedForUser($this->session->getLocalUserId());
122                         } else {
123                                 $notifications = $this->notificationRepo->selectDigestForUser($this->session->getLocalUserId());
124                         }
125
126                         $condition = [
127                                 "`unseen` AND `uid` = ? AND NOT `origin` AND (`vid` != ? OR `vid` IS NULL)",
128                                 $this->session->getLocalUserId(), Verb::getID(Activity::FOLLOW)
129                         ];
130
131                         $items_unseen = $this->database->toArray(Post::selectForUser(
132                                 $this->session->getLocalUserId(),
133                                 ['wall', 'uid', 'uri-id'],
134                                 $condition,
135                                 ['limit' => 1000],
136                         ));
137                         $arr = ['items' => $items_unseen];
138                         Hook::callAll('network_ping', $arr);
139
140                         foreach ($items_unseen as $item) {
141                                 if ($item['wall']) {
142                                         $home_count++;
143                                 } else {
144                                         $network_count++;
145                                 }
146                         }
147
148                         $compute_group_counts = $this->config->get('system','compute_group_counts');
149                         if ($network_count && $compute_group_counts) {
150                                 // Find out how unseen network posts are spread across groups
151                                 foreach (Group::countUnseen() as $group_count) {
152                                         if ($group_count['count'] > 0) {
153                                                 $groups_unseen[] = $group_count;
154                                         }
155                                 }
156
157                                 foreach (ForumManager::countUnseenItems() as $forum_count) {
158                                         if ($forum_count['count'] > 0) {
159                                                 $forums_unseen[] = $forum_count;
160                                         }
161                                 }
162                         }
163
164                         $intros = $this->introductionRepo->selectForUser($this->session->getLocalUserId());
165
166                         $intro_count = $intros->count();
167
168                         $myurl      = $this->session->getMyUrl();
169                         $mail_count = $this->database->count('mail', ["`uid` = ? AND NOT `seen` AND `from-url` != ?", $this->session->getLocalUserId(), $myurl]);
170
171                         if (intval($this->config->get('config', 'register_policy')) === Register::APPROVE && $this->app->isSiteAdmin()) {
172                                 $registrations = \Friendica\Model\Register::getPending();
173                                 $register_count = count($registrations);
174                         }
175
176                         $cachekey = 'ping:events:' . $this->session->getLocalUserId();
177                         $events   = $this->cache->get($cachekey);
178                         if (is_null($events)) {
179                                 $events = $this->database->selectToArray('event', ['type', 'start'],
180                                         ["`uid` = ? AND `start` < ? AND `finish` > ? AND NOT `ignore`",
181                                                 $this->session->getLocalUserId(), DateTimeFormat::utc('now + 7 days'), DateTimeFormat::utcNow()]);
182                                 $this->cache->set($cachekey, $events, Duration::HOUR);
183                         }
184
185                         $now_date = DateTimeFormat::localNow('Y-m-d');
186                         foreach ($events as $event) {
187                                 $is_birthday = false;
188                                 if ($event['type'] === 'birthday') {
189                                         $birthday_count++;
190                                         $is_birthday = true;
191                                 } else {
192                                         $event_count++;
193                                 }
194
195                                 if (DateTimeFormat::local($event['start'], 'Y-m-d') === $now_date) {
196                                         if ($is_birthday) {
197                                                 $today_birthday_count++;
198                                         } else {
199                                                 $today_event_count++;
200                                         }
201                                 }
202                         }
203
204                         $owner = User::getOwnerDataById($this->session->getLocalUserId());
205
206                         $navNotifications = array_map(function (Entity\Notification $notification) use ($owner) {
207                                 if (!$this->notify->shouldShowOnDesktop($notification)) {
208                                         return null;
209                                 }
210                                 if (($notification->type == Post\UserNotification::TYPE_NONE) && in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])) {
211                                         return null;
212                                 }
213                                 try {
214                                         return $this->formattedNavNotification->createFromNotification($notification);
215                                 } catch (NoMessageException $e) {
216                                         return null;
217                                 }
218                         }, $notifications->getArrayCopy());
219                         $navNotifications = array_filter($navNotifications);
220
221                         $sysnotify_count = array_reduce($navNotifications, function (int $carry, ValueObject\FormattedNavNotification $navNotification) {
222                                 return $carry + ($navNotification->seen ? 0 : 1);
223                         }, 0);
224
225                         // merge all notification types in one array
226                         foreach ($intros as $intro) {
227                                 $navNotifications[] = $this->formattedNavNotification->createFromIntro($intro);
228                         }
229
230                         if (count($registrations) <= 1 || $this->pconfig->get($this->session->getLocalUserId(), 'system', 'detailed_notif')) {
231                                 foreach ($registrations as $reg) {
232                                         $navNotifications[] = $this->formattedNavNotification->createFromParams(
233                                                 [
234                                                         'name' => $reg['name'],
235                                                         'url'  => $reg['url'],
236                                                 ],
237                                                 $this->l10n->t('{0} requested registration'),
238                                                 new \DateTime($reg['created'], new \DateTimeZone('UTC')),
239                                                 new Uri($this->baseUrl->get(true) . '/admin/users/pending')
240                                         );
241                                 }
242                         } elseif (count($registrations) > 1) {
243                                 $navNotifications[] = $this->formattedNavNotification->createFromParams(
244                                         [
245                                                 'name' => $registrations[0]['name'],
246                                                 'url'  => $registrations[0]['url'],
247                                         ],
248                                         $this->l10n->t('{0} and %d others requested registration', count($registrations) - 1),
249                                         new \DateTime($registrations[0]['created'], new \DateTimeZone('UTC')),
250                                         new Uri($this->baseUrl->get(true) . '/admin/users/pending')
251                                 );
252                         }
253
254                         // sort notifications by $[]['date']
255                         $sort_function = function (ValueObject\FormattedNavNotification $a, ValueObject\FormattedNavNotification $b) {
256                                 $a = $a->toArray();
257                                 $b = $b->toArray();
258
259                                 // Unseen messages are kept at the top
260                                 if ($a['seen'] == $b['seen']) {
261                                         if ($a['timestamp'] == $b['timestamp']) {
262                                                 return 0;
263                                         } else {
264                                                 return $a['timestamp'] < $b['timestamp'] ? 1 : -1;
265                                         }
266                                 } else {
267                                         return $a['seen'] ? 1 : -1;
268                                 }
269                         };
270                         usort($navNotifications, $sort_function);
271                 }
272
273                 $notification_count = $sysnotify_count + $intro_count + $register_count;
274
275                 $data             = [];
276                 $data['intro']    = $intro_count;
277                 $data['mail']     = $mail_count;
278                 $data['net']      = ($network_count < 1000) ? $network_count : '999+';
279                 $data['home']     = ($home_count < 1000) ? $home_count : '999+';
280                 $data['register'] = $register_count;
281
282                 $data['events']          = $event_count;
283                 $data['events-today']    = $today_event_count;
284                 $data['birthdays']       = $birthday_count;
285                 $data['birthdays-today'] = $today_birthday_count;
286                 $data['groups']          = $groups_unseen;
287                 $data['forums']          = $forums_unseen;
288                 $data['notification']    = ($notification_count < 50) ? $notification_count : '49+';
289
290                 $data['notifications'] = $navNotifications;
291
292                 $data['sysmsgs'] = [
293                         'notice' => $this->systemMessages->flushNotices(),
294                         'info'   => $this->systemMessages->flushInfos(),
295                 ];
296
297                 if (isset($_GET['callback'])) {
298                         // JSONP support
299                         System::httpExit($_GET['callback'] . '(' . json_encode(['result' => $data]) . ')', Response::TYPE_BLANK, 'application/javascript');
300                 } else {
301                         System::jsonExit(['result' => $data]);
302                 }
303         }
304 }