]> git.mxchange.org Git - friendica.git/blob - src/Module/Notifications/Ping.php
0a2d02390fe1c6e28f3c5c7884dbf3a052039713
[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                                 DI::cache()->set($cachekey, $ev, Duration::HOUR);
165                         }
166
167                         if (DBA::isResult($ev)) {
168                                 $all_events = count($ev);
169
170                                 if ($all_events) {
171                                         $str_now = DateTimeFormat::localNow('Y-m-d');
172                                         foreach ($ev as $x) {
173                                                 $bd = false;
174                                                 if ($x['type'] === 'birthday') {
175                                                         $birthday_count++;
176                                                         $bd = true;
177                                                 } else {
178                                                         $event_count++;
179                                                 }
180                                                 if (DateTimeFormat::local($x['start'], 'Y-m-d') === $str_now) {
181                                                         if ($bd) {
182                                                                 $today_birthday_count++;
183                                                         } else {
184                                                                 $today_event_count++;
185                                                         }
186                                                 }
187                                         }
188                                 }
189                         }
190
191                         $owner = User::getOwnerDataById(Session::getLocalUser());
192
193                         $navNotifications = array_map(function (Entity\Notification $notification) use ($owner) {
194                                 if (!DI::notify()->NotifyOnDesktop($notification)) {
195                                         return null;
196                                 }
197                                 if (($notification->type == Post\UserNotification::TYPE_NONE) && in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])) {
198                                         return null;
199                                 }
200                                 try {
201                                         return $this->formattedNavNotification->createFromNotification($notification);
202                                 } catch (NoMessageException $e) {
203                                         return null;
204                                 }
205                         }, $notifications->getArrayCopy());
206                         $navNotifications = array_filter($navNotifications);
207
208                         $sysnotify_count = array_reduce($navNotifications, function (int $carry, ValueObject\FormattedNavNotification $navNotification) {
209                                 return $carry + ($navNotification->seen ? 0 : 1);
210                         }, 0);
211
212                         // merge all notification types in one array
213                         foreach ($intros as $intro) {
214                                 $navNotifications[] = $this->formattedNavNotification->createFromIntro($intro);
215                         }
216
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(
221                                                         [
222                                                                 'name' => $reg['name'],
223                                                                 'url'  => $reg['url'],
224                                                         ],
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')
228                                                 );
229                                         }
230                                 } else {
231                                         $navNotifications[] = $this->formattedNavNotification->createFromParams(
232                                                 [
233                                                         'name' => $regs[0]['name'],
234                                                         'url'  => $regs[0]['url'],
235                                                 ],
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')
239                                         );
240                                 }
241                         }
242
243                         // sort notifications by $[]['date']
244                         $sort_function = function (ValueObject\FormattedNavNotification $a, ValueObject\FormattedNavNotification $b) {
245                                 $a = $a->toArray();
246                                 $b = $b->toArray();
247
248                                 // Unseen messages are kept at the top
249                                 if ($a['seen'] == $b['seen']) {
250                                         if ($a['timestamp'] == $b['timestamp']) {
251                                                 return 0;
252                                         } else {
253                                                 return $a['timestamp'] < $b['timestamp'] ? 1 : -1;
254                                         }
255                                 } else {
256                                         return $a['seen'] ? 1 : -1;
257                                 }
258                         };
259                         usort($navNotifications, $sort_function);
260                 }
261
262                 $notification_count = $sysnotify_count + $intro_count + $register_count;
263
264                 $data             = [];
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;
270
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+';
278
279                 $data['notifications'] = $navNotifications;
280
281                 $data['sysmsgs'] = [
282                         'notice' => $this->systemMessages->flushNotices(),
283                         'info'   => $this->systemMessages->flushInfos(),
284                 ];
285
286                 if (isset($_GET['callback'])) {
287                         // JSONP support
288                         System::httpExit($_GET['callback'] . '(' . json_encode(['result' => $data]) . ')', Response::TYPE_BLANK, 'application/javascript');
289                 } else {
290                         System::jsonExit(['result' => $data]);
291                 }
292         }
293 }