]> git.mxchange.org Git - friendica.git/blob - src/Module/Notifications/Ping.php
Fixes for the notifications
[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\System;
32 use Friendica\Database\DBA;
33 use Friendica\DI;
34 use Friendica\Model\Group;
35 use Friendica\Model\Post;
36 use Friendica\Model\Verb;
37 use Friendica\Module\Register;
38 use Friendica\Module\Response;
39 use Friendica\Navigation\Notifications\Entity;
40 use Friendica\Navigation\Notifications\Exception\NoMessageException;
41 use Friendica\Navigation\Notifications\Factory;
42 use Friendica\Navigation\Notifications\Repository;
43 use Friendica\Navigation\Notifications\ValueObject;
44 use Friendica\Protocol\Activity;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\Profiler;
47 use GuzzleHttp\Psr7\Uri;
48 use Psr\Log\LoggerInterface;
49
50 class Ping extends BaseModule
51 {
52         /** @var Repository\Notification */
53         private $notificationRepo;
54         /** @var Introduction */
55         private $introductionRepo;
56         /** @var Factory\FormattedNavNotification */
57         private $formattedNavNotification;
58
59         public function __construct(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 = [])
60         {
61                 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
62
63                 $this->notificationRepo         = $notificationRepo;
64                 $this->introductionRepo         = $introductionRepo;
65                 $this->formattedNavNotification = $formattedNavNotification;
66         }
67
68         protected function rawContent(array $request = [])
69         {
70                 $regs             = [];
71                 $navNotifications = [];
72
73                 $intro_count     = 0;
74                 $mail_count      = 0;
75                 $home_count      = 0;
76                 $network_count   = 0;
77                 $register_count  = 0;
78                 $sysnotify_count = 0;
79                 $groups_unseen   = [];
80                 $forums_unseen   = [];
81
82                 $event_count          = 0;
83                 $today_event_count    = 0;
84                 $birthday_count       = 0;
85                 $today_birthday_count = 0;
86
87
88                 if (local_user()) {
89                         if (DI::pConfig()->get(local_user(), 'system', 'detailed_notif')) {
90                                 $notifications = $this->notificationRepo->selectDetailedForUser(local_user());
91                         } else {
92                                 $notifications = $this->notificationRepo->selectDigestForUser(local_user());
93                         }
94
95                         $condition = [
96                                 "`unseen` AND `uid` = ? AND NOT `origin` AND (`vid` != ? OR `vid` IS NULL)",
97                                 local_user(), Verb::getID(Activity::FOLLOW)
98                         ];
99                         $items = Post::selectForUser(local_user(), ['wall', 'uid', 'uri-id'], $condition, ['limit' => 1000]);
100                         if (DBA::isResult($items)) {
101                                 $items_unseen = Post::toArray($items, false);
102                                 $arr          = ['items' => $items_unseen];
103                                 Hook::callAll('network_ping', $arr);
104
105                                 foreach ($items_unseen as $item) {
106                                         if ($item['wall']) {
107                                                 $home_count++;
108                                         } else {
109                                                 $network_count++;
110                                         }
111                                 }
112                         }
113                         DBA::close($items);
114
115                         if ($network_count) {
116                                 // Find out how unseen network posts are spread across groups
117                                 $group_counts = Group::countUnseen();
118                                 if (DBA::isResult($group_counts)) {
119                                         foreach ($group_counts as $group_count) {
120                                                 if ($group_count['count'] > 0) {
121                                                         $groups_unseen[] = $group_count;
122                                                 }
123                                         }
124                                 }
125
126                                 $forum_counts = ForumManager::countUnseenItems();
127                                 if (DBA::isResult($forum_counts)) {
128                                         foreach ($forum_counts as $forum_count) {
129                                                 if ($forum_count['count'] > 0) {
130                                                         $forums_unseen[] = $forum_count;
131                                                 }
132                                         }
133                                 }
134                         }
135
136                         $intros = $this->introductionRepo->selectForUser(local_user());
137
138                         $intro_count = $intros->count();
139
140                         $myurl      = DI::baseUrl() . '/profile/' . DI::app()->getLoggedInUserNickname();
141                         $mail_count = DBA::count('mail', ["`uid` = ? AND NOT `seen` AND `from-url` != ?", local_user(), $myurl]);
142
143                         if (intval(DI::config()->get('config', 'register_policy')) === Register::APPROVE && DI::app()->isSiteAdmin()) {
144                                 $regs = \Friendica\Model\Register::getPending();
145
146                                 if (DBA::isResult($regs)) {
147                                         $register_count = count($regs);
148                                 }
149                         }
150
151                         $cachekey = 'ping:events:' . local_user();
152                         $ev       = DI::cache()->get($cachekey);
153                         if (is_null($ev)) {
154                                 $ev = DBA::selectToArray('event', ['type', 'start'],
155                                         ["`uid` = ? AND `start` < ? AND `finish` > ? AND NOT `ignore`",
156                                                 local_user(), DateTimeFormat::utc('now + 7 days'), DateTimeFormat::utcNow()]);
157                                 if (DBA::isResult($ev)) {
158                                         DI::cache()->set($cachekey, $ev, Duration::HOUR);
159                                 }
160                         }
161
162                         if (DBA::isResult($ev)) {
163                                 $all_events = count($ev);
164
165                                 if ($all_events) {
166                                         $str_now = DateTimeFormat::localNow('Y-m-d');
167                                         foreach ($ev as $x) {
168                                                 $bd = false;
169                                                 if ($x['type'] === 'birthday') {
170                                                         $birthday_count++;
171                                                         $bd = true;
172                                                 } else {
173                                                         $event_count++;
174                                                 }
175                                                 if (DateTimeFormat::local($x['start'], 'Y-m-d') === $str_now) {
176                                                         if ($bd) {
177                                                                 $today_birthday_count++;
178                                                         } else {
179                                                                 $today_event_count++;
180                                                         }
181                                                 }
182                                         }
183                                 }
184                         }
185
186                         $navNotifications = array_map(function (Entity\Notification $notification) {
187                                 try {
188                                         return $this->formattedNavNotification->createFromNotification($notification);
189                                 } catch (NoMessageException $e) {
190                                         return null;
191                                 }
192                         }, $notifications->getArrayCopy());
193                         $navNotifications = array_filter($navNotifications);
194
195                         $sysnotify_count = array_reduce($navNotifications, function (int $carry, ValueObject\FormattedNavNotification $navNotification) {
196                                 return $carry + ($navNotification->seen ? 0 : 1);
197                         }, 0);
198
199                         // merge all notification types in one array
200                         foreach ($intros as $intro) {
201                                 $navNotifications[] = $this->formattedNavNotification->createFromIntro($intro);
202                         }
203
204                         if (DBA::isResult($regs)) {
205                                 if (count($regs) <= 1 || DI::pConfig()->get(local_user(), 'system', 'detailed_notif')) {
206                                         foreach ($regs as $reg) {
207                                                 $navNotifications[] = $this->formattedNavNotification->createFromParams(
208                                                         [
209                                                                 'name' => $reg['name'],
210                                                                 'url'  => $reg['url'],
211                                                         ],
212                                                         DI::l10n()->t('{0} requested registration'),
213                                                         new \DateTime($reg['created'], new \DateTimeZone('UTC')),
214                                                         new Uri(DI::baseUrl()->get(true) . '/admin/users/pending')
215                                                 );
216                                         }
217                                 } else {
218                                         $navNotifications[] = $this->formattedNavNotification->createFromParams(
219                                                 [
220                                                         'name' => $regs[0]['name'],
221                                                         'url'  => $regs[0]['url'],
222                                                 ],
223                                                 DI::l10n()->t('{0} and %d others requested registration', count($regs) - 1),
224                                                 new \DateTime($regs[0]['created'], new \DateTimeZone('UTC')),
225                                                 new Uri(DI::baseUrl()->get(true) . '/admin/users/pending')
226                                         );
227                                 }
228                         }
229
230                         // sort notifications by $[]['date']
231                         $sort_function = function (ValueObject\FormattedNavNotification $a, ValueObject\FormattedNavNotification $b) {
232                                 $a = $a->toArray();
233                                 $b = $b->toArray();
234
235                                 // Unseen messages are kept at the top
236                                 if ($a['seen'] == $b['seen']) {
237                                         if ($a['timestamp'] == $b['timestamp']) {
238                                                 return 0;
239                                         } else {
240                                                 return $a['timestamp'] < $b['timestamp'] ? 1 : -1;
241                                         }
242                                 } else {
243                                         return $a['seen'] ? 1 : -1;
244                                 }
245                         };
246                         usort($navNotifications, $sort_function);
247                 }
248
249                 $sysmsgs      = [];
250                 $sysmsgs_info = [];
251
252                 if (!empty($_SESSION['sysmsg'])) {
253                         $sysmsgs = $_SESSION['sysmsg'];
254                         unset($_SESSION['sysmsg']);
255                 }
256
257                 if (!empty($_SESSION['sysmsg_info'])) {
258                         $sysmsgs_info = $_SESSION['sysmsg_info'];
259                         unset($_SESSION['sysmsg_info']);
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' => $sysmsgs,
283                         'info'   => $sysmsgs_info
284                 ];
285
286                 if (isset($_GET['callback'])) {
287                         // JSONP support
288                         header("Content-type: application/javascript");
289                         echo $_GET['callback'] . '(' . json_encode(['result' => $data]) . ')';
290                         exit;
291                 } else {
292                         System::jsonExit(['result' => $data]);
293                 }
294         }
295 }