]> git.mxchange.org Git - friendica.git/blob - src/Module/Notifications/Ping.php
7dc215826024dd0ccfa6a5b17c631542fec5c9db
[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                         if ($network_count) {
117                                 // Find out how unseen network posts are spread across groups
118                                 $group_counts = Group::countUnseen();
119                                 if (DBA::isResult($group_counts)) {
120                                         foreach ($group_counts as $group_count) {
121                                                 if ($group_count['count'] > 0) {
122                                                         $groups_unseen[] = $group_count;
123                                                 }
124                                         }
125                                 }
126
127                                 $forum_counts = ForumManager::countUnseenItems();
128                                 if (DBA::isResult($forum_counts)) {
129                                         foreach ($forum_counts as $forum_count) {
130                                                 if ($forum_count['count'] > 0) {
131                                                         $forums_unseen[] = $forum_count;
132                                                 }
133                                         }
134                                 }
135                         }
136
137                         $intros = $this->introductionRepo->selectForUser(local_user());
138
139                         $intro_count = $intros->count();
140
141                         $myurl      = DI::baseUrl() . '/profile/' . DI::app()->getLoggedInUserNickname();
142                         $mail_count = DBA::count('mail', ["`uid` = ? AND NOT `seen` AND `from-url` != ?", local_user(), $myurl]);
143
144                         if (intval(DI::config()->get('config', 'register_policy')) === Register::APPROVE && DI::app()->isSiteAdmin()) {
145                                 $regs = \Friendica\Model\Register::getPending();
146
147                                 if (DBA::isResult($regs)) {
148                                         $register_count = count($regs);
149                                 }
150                         }
151
152                         $cachekey = 'ping:events:' . local_user();
153                         $ev       = DI::cache()->get($cachekey);
154                         if (is_null($ev)) {
155                                 $ev = DBA::selectToArray('event', ['type', 'start'],
156                                         ["`uid` = ? AND `start` < ? AND `finish` > ? AND NOT `ignore`",
157                                                 local_user(), DateTimeFormat::utc('now + 7 days'), DateTimeFormat::utcNow()]);
158                                 if (DBA::isResult($ev)) {
159                                         DI::cache()->set($cachekey, $ev, Duration::HOUR);
160                                 }
161                         }
162
163                         if (DBA::isResult($ev)) {
164                                 $all_events = count($ev);
165
166                                 if ($all_events) {
167                                         $str_now = DateTimeFormat::localNow('Y-m-d');
168                                         foreach ($ev as $x) {
169                                                 $bd = false;
170                                                 if ($x['type'] === 'birthday') {
171                                                         $birthday_count++;
172                                                         $bd = true;
173                                                 } else {
174                                                         $event_count++;
175                                                 }
176                                                 if (DateTimeFormat::local($x['start'], 'Y-m-d') === $str_now) {
177                                                         if ($bd) {
178                                                                 $today_birthday_count++;
179                                                         } else {
180                                                                 $today_event_count++;
181                                                         }
182                                                 }
183                                         }
184                                 }
185                         }
186
187                         $owner = User::getOwnerDataById(local_user());
188
189                         $navNotifications = array_map(function (Entity\Notification $notification) use ($owner) {
190                                 if (!DI::notify()->NotifyOnDesktop($notification)) {
191                                         return null;
192                                 }
193                                 if (($notification->type == Post\UserNotification::TYPE_NONE) && in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])) {
194                                         return null;
195                                 }
196                                 try {
197                                         return $this->formattedNavNotification->createFromNotification($notification);
198                                 } catch (NoMessageException $e) {
199                                         return null;
200                                 }
201                         }, $notifications->getArrayCopy());
202                         $navNotifications = array_filter($navNotifications);
203
204                         $sysnotify_count = array_reduce($navNotifications, function (int $carry, ValueObject\FormattedNavNotification $navNotification) {
205                                 return $carry + ($navNotification->seen ? 0 : 1);
206                         }, 0);
207
208                         // merge all notification types in one array
209                         foreach ($intros as $intro) {
210                                 $navNotifications[] = $this->formattedNavNotification->createFromIntro($intro);
211                         }
212
213                         if (DBA::isResult($regs)) {
214                                 if (count($regs) <= 1 || DI::pConfig()->get(local_user(), 'system', 'detailed_notif')) {
215                                         foreach ($regs as $reg) {
216                                                 $navNotifications[] = $this->formattedNavNotification->createFromParams(
217                                                         [
218                                                                 'name' => $reg['name'],
219                                                                 'url'  => $reg['url'],
220                                                         ],
221                                                         DI::l10n()->t('{0} requested registration'),
222                                                         new \DateTime($reg['created'], new \DateTimeZone('UTC')),
223                                                         new Uri(DI::baseUrl()->get(true) . '/admin/users/pending')
224                                                 );
225                                         }
226                                 } else {
227                                         $navNotifications[] = $this->formattedNavNotification->createFromParams(
228                                                 [
229                                                         'name' => $regs[0]['name'],
230                                                         'url'  => $regs[0]['url'],
231                                                 ],
232                                                 DI::l10n()->t('{0} and %d others requested registration', count($regs) - 1),
233                                                 new \DateTime($regs[0]['created'], new \DateTimeZone('UTC')),
234                                                 new Uri(DI::baseUrl()->get(true) . '/admin/users/pending')
235                                         );
236                                 }
237                         }
238
239                         // sort notifications by $[]['date']
240                         $sort_function = function (ValueObject\FormattedNavNotification $a, ValueObject\FormattedNavNotification $b) {
241                                 $a = $a->toArray();
242                                 $b = $b->toArray();
243
244                                 // Unseen messages are kept at the top
245                                 if ($a['seen'] == $b['seen']) {
246                                         if ($a['timestamp'] == $b['timestamp']) {
247                                                 return 0;
248                                         } else {
249                                                 return $a['timestamp'] < $b['timestamp'] ? 1 : -1;
250                                         }
251                                 } else {
252                                         return $a['seen'] ? 1 : -1;
253                                 }
254                         };
255                         usort($navNotifications, $sort_function);
256                 }
257
258                 $sysmsgs      = [];
259                 $sysmsgs_info = [];
260
261                 if (!empty($_SESSION['sysmsg'])) {
262                         $sysmsgs = $_SESSION['sysmsg'];
263                         unset($_SESSION['sysmsg']);
264                 }
265
266                 if (!empty($_SESSION['sysmsg_info'])) {
267                         $sysmsgs_info = $_SESSION['sysmsg_info'];
268                         unset($_SESSION['sysmsg_info']);
269                 }
270
271                 $notification_count = $sysnotify_count + $intro_count + $register_count;
272
273                 $data             = [];
274                 $data['intro']    = $intro_count;
275                 $data['mail']     = $mail_count;
276                 $data['net']      = ($network_count < 1000) ? $network_count : '999+';
277                 $data['home']     = ($home_count < 1000) ? $home_count : '999+';
278                 $data['register'] = $register_count;
279
280                 $data['events']          = $event_count;
281                 $data['events-today']    = $today_event_count;
282                 $data['birthdays']       = $birthday_count;
283                 $data['birthdays-today'] = $today_birthday_count;
284                 $data['groups']          = $groups_unseen;
285                 $data['forums']          = $forums_unseen;
286                 $data['notification']    = ($notification_count < 50) ? $notification_count : '49+';
287
288                 $data['notifications'] = $navNotifications;
289
290                 $data['sysmsgs'] = [
291                         'notice' => $sysmsgs,
292                         'info'   => $sysmsgs_info
293                 ];
294
295                 if (isset($_GET['callback'])) {
296                         // JSONP support
297                         System::httpExit($_GET['callback'] . '(' . json_encode(['result' => $data]) . ')', Response::TYPE_BLANK, 'application/javascript');
298                 } else {
299                         System::jsonExit(['result' => $data]);
300                 }
301         }
302 }