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