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