]> git.mxchange.org Git - friendica.git/blob - src/Module/Notifications/Ping.php
e8dd0ce2d8a7ec8d67670ac7e1fe792e6c3cf24f
[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\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;
34 use Friendica\DI;
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;
52
53 class Ping extends BaseModule
54 {
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;
63
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 = [])
65         {
66                 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
67
68                 $this->systemMessages           = $systemMessages;
69                 $this->notificationRepo         = $notificationRepo;
70                 $this->introductionRepo         = $introductionRepo;
71                 $this->formattedNavNotification = $formattedNavNotification;
72         }
73
74         protected function rawContent(array $request = [])
75         {
76                 $regs             = [];
77                 $navNotifications = [];
78
79                 $intro_count     = 0;
80                 $mail_count      = 0;
81                 $home_count      = 0;
82                 $network_count   = 0;
83                 $register_count  = 0;
84                 $sysnotify_count = 0;
85                 $groups_unseen   = [];
86                 $forums_unseen   = [];
87
88                 $event_count          = 0;
89                 $today_event_count    = 0;
90                 $birthday_count       = 0;
91                 $today_birthday_count = 0;
92
93
94                 if (Session::getLocalUser()) {
95                         if (DI::pConfig()->get(Session::getLocalUser(), 'system', 'detailed_notif')) {
96                                 $notifications = $this->notificationRepo->selectDetailedForUser(Session::getLocalUser());
97                         } else {
98                                 $notifications = $this->notificationRepo->selectDigestForUser(Session::getLocalUser());
99                         }
100
101                         $condition = [
102                                 "`unseen` AND `uid` = ? AND NOT `origin` AND (`vid` != ? OR `vid` IS NULL)",
103                                 Session::getLocalUser(), Verb::getID(Activity::FOLLOW)
104                         ];
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);
110
111                                 foreach ($items_unseen as $item) {
112                                         if ($item['wall']) {
113                                                 $home_count++;
114                                         } else {
115                                                 $network_count++;
116                                         }
117                                 }
118                         }
119                         DBA::close($items);
120
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;
129                                                 }
130                                         }
131                                 }
132
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;
138                                                 }
139                                         }
140                                 }
141                         }
142
143                         $intros = $this->introductionRepo->selectForUser(Session::getLocalUser());
144
145                         $intro_count = $intros->count();
146
147                         $myurl      = DI::baseUrl() . '/profile/' . DI::app()->getLoggedInUserNickname();
148                         $mail_count = DBA::count('mail', ["`uid` = ? AND NOT `seen` AND `from-url` != ?", Session::getLocalUser(), $myurl]);
149
150                         if (intval(DI::config()->get('config', 'register_policy')) === Register::APPROVE && DI::app()->isSiteAdmin()) {
151                                 $regs = \Friendica\Model\Register::getPending();
152
153                                 if (DBA::isResult($regs)) {
154                                         $register_count = count($regs);
155                                 }
156                         }
157
158                         $cachekey = 'ping:events:' . Session::getLocalUser();
159                         $ev       = DI::cache()->get($cachekey);
160                         if (is_null($ev)) {
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                                 if (DBA::isResult($ev)) {
165                                         DI::cache()->set($cachekey, $ev, Duration::HOUR);
166                                 }
167                         }
168
169                         if (DBA::isResult($ev)) {
170                                 $all_events = count($ev);
171
172                                 if ($all_events) {
173                                         $str_now = DateTimeFormat::localNow('Y-m-d');
174                                         foreach ($ev as $x) {
175                                                 $bd = false;
176                                                 if ($x['type'] === 'birthday') {
177                                                         $birthday_count++;
178                                                         $bd = true;
179                                                 } else {
180                                                         $event_count++;
181                                                 }
182                                                 if (DateTimeFormat::local($x['start'], 'Y-m-d') === $str_now) {
183                                                         if ($bd) {
184                                                                 $today_birthday_count++;
185                                                         } else {
186                                                                 $today_event_count++;
187                                                         }
188                                                 }
189                                         }
190                                 }
191                         }
192
193                         $owner = User::getOwnerDataById(Session::getLocalUser());
194
195                         $navNotifications = array_map(function (Entity\Notification $notification) use ($owner) {
196                                 if (!DI::notify()->NotifyOnDesktop($notification)) {
197                                         return null;
198                                 }
199                                 if (($notification->type == Post\UserNotification::TYPE_NONE) && in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])) {
200                                         return null;
201                                 }
202                                 try {
203                                         return $this->formattedNavNotification->createFromNotification($notification);
204                                 } catch (NoMessageException $e) {
205                                         return null;
206                                 }
207                         }, $notifications->getArrayCopy());
208                         $navNotifications = array_filter($navNotifications);
209
210                         $sysnotify_count = array_reduce($navNotifications, function (int $carry, ValueObject\FormattedNavNotification $navNotification) {
211                                 return $carry + ($navNotification->seen ? 0 : 1);
212                         }, 0);
213
214                         // merge all notification types in one array
215                         foreach ($intros as $intro) {
216                                 $navNotifications[] = $this->formattedNavNotification->createFromIntro($intro);
217                         }
218
219                         if (DBA::isResult($regs)) {
220                                 if (count($regs) <= 1 || DI::pConfig()->get(Session::getLocalUser(), 'system', 'detailed_notif')) {
221                                         foreach ($regs as $reg) {
222                                                 $navNotifications[] = $this->formattedNavNotification->createFromParams(
223                                                         [
224                                                                 'name' => $reg['name'],
225                                                                 'url'  => $reg['url'],
226                                                         ],
227                                                         DI::l10n()->t('{0} requested registration'),
228                                                         new \DateTime($reg['created'], new \DateTimeZone('UTC')),
229                                                         new Uri(DI::baseUrl()->get(true) . '/admin/users/pending')
230                                                 );
231                                         }
232                                 } else {
233                                         $navNotifications[] = $this->formattedNavNotification->createFromParams(
234                                                 [
235                                                         'name' => $regs[0]['name'],
236                                                         'url'  => $regs[0]['url'],
237                                                 ],
238                                                 DI::l10n()->t('{0} and %d others requested registration', count($regs) - 1),
239                                                 new \DateTime($regs[0]['created'], new \DateTimeZone('UTC')),
240                                                 new Uri(DI::baseUrl()->get(true) . '/admin/users/pending')
241                                         );
242                                 }
243                         }
244
245                         // sort notifications by $[]['date']
246                         $sort_function = function (ValueObject\FormattedNavNotification $a, ValueObject\FormattedNavNotification $b) {
247                                 $a = $a->toArray();
248                                 $b = $b->toArray();
249
250                                 // Unseen messages are kept at the top
251                                 if ($a['seen'] == $b['seen']) {
252                                         if ($a['timestamp'] == $b['timestamp']) {
253                                                 return 0;
254                                         } else {
255                                                 return $a['timestamp'] < $b['timestamp'] ? 1 : -1;
256                                         }
257                                 } else {
258                                         return $a['seen'] ? 1 : -1;
259                                 }
260                         };
261                         usort($navNotifications, $sort_function);
262                 }
263
264                 $notification_count = $sysnotify_count + $intro_count + $register_count;
265
266                 $data             = [];
267                 $data['intro']    = $intro_count;
268                 $data['mail']     = $mail_count;
269                 $data['net']      = ($network_count < 1000) ? $network_count : '999+';
270                 $data['home']     = ($home_count < 1000) ? $home_count : '999+';
271                 $data['register'] = $register_count;
272
273                 $data['events']          = $event_count;
274                 $data['events-today']    = $today_event_count;
275                 $data['birthdays']       = $birthday_count;
276                 $data['birthdays-today'] = $today_birthday_count;
277                 $data['groups']          = $groups_unseen;
278                 $data['forums']          = $forums_unseen;
279                 $data['notification']    = ($notification_count < 50) ? $notification_count : '49+';
280
281                 $data['notifications'] = $navNotifications;
282
283                 $data['sysmsgs'] = [
284                         'notice' => $this->systemMessages->flushNotices(),
285                         'info'   => $this->systemMessages->flushInfos(),
286                 ];
287
288                 if (isset($_GET['callback'])) {
289                         // JSONP support
290                         System::httpExit($_GET['callback'] . '(' . json_encode(['result' => $data]) . ')', Response::TYPE_BLANK, 'application/javascript');
291                 } else {
292                         System::jsonExit(['result' => $data]);
293                 }
294         }
295 }