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