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