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