Merge pull request #9845 from Extarys/frio-eslint-prettier
[friendica.git/.git] / mod / ping.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
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 use Friendica\App;
23 use Friendica\Content\ForumManager;
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Core\Cache\Duration;
26 use Friendica\Core\Hook;
27 use Friendica\Database\DBA;
28 use Friendica\DI;
29 use Friendica\Model\Contact;
30 use Friendica\Model\Group;
31 use Friendica\Model\Notify\Type;
32 use Friendica\Model\Post;
33 use Friendica\Model\Verb;
34 use Friendica\Protocol\Activity;
35 use Friendica\Util\DateTimeFormat;
36 use Friendica\Util\Temporal;
37 use Friendica\Util\XML;
38
39 /**
40  * Outputs the counts and the lists of various notifications
41  *
42  * The output format can be controlled via the GET parameter 'format'. It can be
43  * - xml (deprecated legacy default)
44  * - json (outputs JSONP with the 'callback' GET parameter)
45  *
46  * Expected JSON structure:
47  * {
48  *        "result": {
49  *            "intro": 0,
50  *            "mail": 0,
51  *            "net": 0,
52  *            "home": 0,
53  *            "register": 0,
54  *            "all-events": 0,
55  *            "all-events-today": 0,
56  *            "events": 0,
57  *            "events-today": 0,
58  *            "birthdays": 0,
59  *            "birthdays-today": 0,
60  *            "groups": [ ],
61  *            "forums": [ ],
62  *            "notification": 0,
63  *            "notifications": [ ],
64  *            "sysmsgs": {
65  *                "notice": [ ],
66  *                "info": [ ]
67  *            }
68  *        }
69  *    }
70  *
71  * @param App $a The Friendica App instance
72  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
73  */
74 function ping_init(App $a)
75 {
76         $format = 'xml';
77
78         if (isset($_GET['format']) && $_GET['format'] == 'json') {
79                 $format = 'json';
80         }
81
82         $regs          = [];
83         $notifications = [];
84
85         $intro_count    = 0;
86         $mail_count     = 0;
87         $home_count     = 0;
88         $network_count  = 0;
89         $register_count = 0;
90         $sysnotify_count = 0;
91         $groups_unseen  = [];
92         $forums_unseen  = [];
93
94         $all_events       = 0;
95         $all_events_today = 0;
96         $events           = 0;
97         $events_today     = 0;
98         $birthdays        = 0;
99         $birthdays_today  = 0;
100
101         $data = [];
102         $data['intro']    = $intro_count;
103         $data['mail']     = $mail_count;
104         $data['net']      = $network_count;
105         $data['home']     = $home_count;
106         $data['register'] = $register_count;
107
108         $data['all-events']       = $all_events;
109         $data['all-events-today'] = $all_events_today;
110         $data['events']           = $events;
111         $data['events-today']     = $events_today;
112         $data['birthdays']        = $birthdays;
113         $data['birthdays-today']  = $birthdays_today;
114
115         if (local_user()) {
116                 // Different login session than the page that is calling us.
117                 if (!empty($_GET['uid']) && intval($_GET['uid']) != local_user()) {
118                         $data = ['result' => ['invalid' => 1]];
119
120                         if ($format == 'json') {
121                                 if (isset($_GET['callback'])) {
122                                         // JSONP support
123                                         header("Content-type: application/javascript");
124                                         echo $_GET['callback'] . '(' . json_encode($data) . ')';
125                                 } else {
126                                         header("Content-type: application/json");
127                                         echo json_encode($data);
128                                 }
129                         } else {
130                                 header("Content-type: text/xml");
131                                 echo XML::fromArray($data, $xml);
132                         }
133                         exit();
134                 }
135
136                 $notifications = ping_get_notifications(local_user());
137
138                 $condition = ["`unseen` AND `uid` = ? AND NOT `origin` AND (`vid` != ? OR `vid` IS NULL)",
139                         local_user(), Verb::getID(Activity::FOLLOW)];
140                 $items = Post::selectForUser(local_user(), ['wall', 'uid', 'uri-id'], $condition);
141                 if (DBA::isResult($items)) {
142                         $items_unseen = Post::toArray($items);
143                         $arr = ['items' => $items_unseen];
144                         Hook::callAll('network_ping', $arr);
145
146                         foreach ($items_unseen as $item) {
147                                 if ($item['wall']) {
148                                         $home_count++;
149                                 } else {
150                                         $network_count++;
151                                 }
152                         }
153                 }
154                 DBA::close($items);
155
156                 if ($network_count) {
157                         // Find out how unseen network posts are spread across groups
158                         $group_counts = Group::countUnseen();
159                         if (DBA::isResult($group_counts)) {
160                                 foreach ($group_counts as $group_count) {
161                                         if ($group_count['count'] > 0) {
162                                                 $groups_unseen[] = $group_count;
163                                         }
164                                 }
165                         }
166
167                         $forum_counts = ForumManager::countUnseenItems();
168                         if (DBA::isResult($forum_counts)) {
169                                 foreach ($forum_counts as $forum_count) {
170                                         if ($forum_count['count'] > 0) {
171                                                 $forums_unseen[] = $forum_count;
172                                         }
173                                 }
174                         }
175                 }
176
177                 $intros1 = q(
178                         "SELECT  `intro`.`id`, `intro`.`datetime`,
179                         `fcontact`.`name`, `fcontact`.`url`, `fcontact`.`photo`
180                         FROM `intro` INNER JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
181                         WHERE `intro`.`uid` = %d AND NOT `intro`.`blocked` AND NOT `intro`.`ignore` AND `intro`.`fid` != 0",
182                         intval(local_user())
183                 );
184                 $intros2 = q(
185                         "SELECT `intro`.`id`, `intro`.`datetime`,
186                         `contact`.`name`, `contact`.`url`, `contact`.`photo`
187                         FROM `intro` INNER JOIN `contact` ON `intro`.`contact-id` = `contact`.`id`
188                         WHERE `intro`.`uid` = %d AND NOT `intro`.`blocked` AND NOT `intro`.`ignore` AND `intro`.`contact-id` != 0 AND (`intro`.`fid` = 0 OR `intro`.`fid` IS NULL)",
189                         intval(local_user())
190                 );
191
192                 $intro_count = count($intros1) + count($intros2);
193                 $intros = $intros1 + $intros2;
194
195                 $myurl = DI::baseUrl() . '/profile/' . $a->user['nickname'];
196                 $mails = q(
197                         "SELECT `id`, `from-name`, `from-url`, `from-photo`, `created` FROM `mail`
198                         WHERE `uid` = %d AND `seen` = 0 AND `from-url` != '%s' ",
199                         intval(local_user()),
200                         DBA::escape($myurl)
201                 );
202                 $mail_count = count($mails);
203
204                 if (intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::APPROVE && is_site_admin()) {
205                         $regs = Friendica\Model\Register::getPending();
206
207                         if (DBA::isResult($regs)) {
208                                 $register_count = count($regs);
209                         }
210                 }
211
212                 $cachekey = "ping_init:".local_user();
213                 $ev = DI::cache()->get($cachekey);
214                 if (is_null($ev)) {
215                         $ev = q(
216                                 "SELECT type, start, adjust FROM `event`
217                                 WHERE `event`.`uid` = %d AND `start` < '%s' AND `finish` > '%s' and `ignore` = 0
218                                 ORDER BY `start` ASC ",
219                                 intval(local_user()),
220                                 DBA::escape(DateTimeFormat::utc('now + 7 days')),
221                                 DBA::escape(DateTimeFormat::utcNow())
222                         );
223                         if (DBA::isResult($ev)) {
224                                 DI::cache()->set($cachekey, $ev, Duration::HOUR);
225                         }
226                 }
227
228                 if (DBA::isResult($ev)) {
229                         $all_events = count($ev);
230
231                         if ($all_events) {
232                                 $str_now = DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d');
233                                 foreach ($ev as $x) {
234                                         $bd = false;
235                                         if ($x['type'] === 'birthday') {
236                                                 $birthdays ++;
237                                                 $bd = true;
238                                         } else {
239                                                 $events ++;
240                                         }
241                                         if (DateTimeFormat::convert($x['start'], ((intval($x['adjust'])) ? $a->timezone : 'UTC'), 'UTC', 'Y-m-d') === $str_now) {
242                                                 $all_events_today ++;
243                                                 if ($bd) {
244                                                         $birthdays_today ++;
245                                                 } else {
246                                                         $events_today ++;
247                                                 }
248                                         }
249                                 }
250                         }
251                 }
252
253                 $data['intro']    = $intro_count;
254                 $data['mail']     = $mail_count;
255                 $data['net']      = $network_count;
256                 $data['home']     = $home_count;
257                 $data['register'] = $register_count;
258
259                 $data['all-events']       = $all_events;
260                 $data['all-events-today'] = $all_events_today;
261                 $data['events']           = $events;
262                 $data['events-today']     = $events_today;
263                 $data['birthdays']        = $birthdays;
264                 $data['birthdays-today']  = $birthdays_today;
265
266                 if (DBA::isResult($notifications)) {
267                         foreach ($notifications as $notif) {
268                                 if ($notif['seen'] == 0) {
269                                         $sysnotify_count ++;
270                                 }
271                         }
272                 }
273
274                 // merge all notification types in one array
275                 if (DBA::isResult($intros)) {
276                         foreach ($intros as $intro) {
277                                 $notif = [
278                                         'id'      => 0,
279                                         'href'    => DI::baseUrl() . '/notifications/intros/' . $intro['id'],
280                                         'name'    => BBCode::convert($intro['name']),
281                                         'url'     => $intro['url'],
282                                         'photo'   => $intro['photo'],
283                                         'date'    => $intro['datetime'],
284                                         'seen'    => false,
285                                         'message' => DI::l10n()->t('{0} wants to be your friend'),
286                                 ];
287                                 $notifications[] = $notif;
288                         }
289                 }
290
291                 if (DBA::isResult($regs)) {
292                         if (count($regs) <= 1 || DI::pConfig()->get(local_user(), 'system', 'detailed_notif')) {
293                                 foreach ($regs as $reg) {
294                                         $notif = [
295                                                 'id'      => 0,
296                                                 'href'    => DI::baseUrl() . '/admin/users/pending',
297                                                 'name'    => $reg['name'],
298                                                 'url'     => $reg['url'],
299                                                 'photo'   => $reg['micro'],
300                                                 'date'    => $reg['created'],
301                                                 'seen'    => false,
302                                                 'message' => DI::l10n()->t('{0} requested registration'),
303                                         ];
304                                         $notifications[] = $notif;
305                                 }
306                         } else {
307                                 $notif = [
308                                         'id'      => 0,
309                                         'href'    => DI::baseUrl() . '/admin/users/pending',
310                                         'name'    => $regs[0]['name'],
311                                         'url'     => $regs[0]['url'],
312                                         'photo'   => $regs[0]['micro'],
313                                         'date'    => $regs[0]['created'],
314                                         'seen'    => false,
315                                         'message' => DI::l10n()->t('{0} and %d others requested registration', count($regs) - 1),
316                                 ];
317                                 $notifications[] = $notif;
318                         }
319                 }
320
321                 // sort notifications by $[]['date']
322                 $sort_function = function ($a, $b) {
323                         $adate = strtotime($a['date']);
324                         $bdate = strtotime($b['date']);
325
326                         // Unseen messages are kept at the top
327                         // The value 31536000 means one year. This should be enough :-)
328                         if (!$a['seen']) {
329                                 $adate += 31536000;
330                         }
331                         if (!$b['seen']) {
332                                 $bdate += 31536000;
333                         }
334
335                         if ($adate == $bdate) {
336                                 return 0;
337                         }
338                         return ($adate < $bdate) ? 1 : -1;
339                 };
340                 usort($notifications, $sort_function);
341
342                 array_walk($notifications, function (&$notification) {
343                         if (empty($notification['photo'])) {
344                                 $contact = Contact::getByURL($notification['url'], false, ['micro', 'id', 'avatar']);
345                                 $notification['photo'] = Contact::getMicro($contact, $notification['photo']);
346                         }
347
348                         $notification['timestamp'] = DateTimeFormat::local($notification['date']);
349                         $notification['date'] = Temporal::getRelativeDate($notification['date']);
350                 });
351         }
352
353         $sysmsgs = [];
354         $sysmsgs_info = [];
355
356         if (!empty($_SESSION['sysmsg'])) {
357                 $sysmsgs = $_SESSION['sysmsg'];
358                 unset($_SESSION['sysmsg']);
359         }
360
361         if (!empty($_SESSION['sysmsg_info'])) {
362                 $sysmsgs_info = $_SESSION['sysmsg_info'];
363                 unset($_SESSION['sysmsg_info']);
364         }
365
366         if ($format == 'json') {
367                 $data['groups'] = $groups_unseen;
368                 $data['forums'] = $forums_unseen;
369                 $data['notification'] = $sysnotify_count + $intro_count + $register_count;
370                 $data['notifications'] = $notifications;
371                 $data['sysmsgs'] = [
372                         'notice' => $sysmsgs,
373                         'info' => $sysmsgs_info
374                 ];
375
376                 $json_payload = json_encode(["result" => $data]);
377
378                 if (isset($_GET['callback'])) {
379                         // JSONP support
380                         header("Content-type: application/javascript");
381                         echo $_GET['callback'] . '(' . $json_payload . ')';
382                 } else {
383                         header("Content-type: application/json");
384                         echo $json_payload;
385                 }
386         } else {
387                 // Legacy slower XML format output
388                 $data = ping_format_xml_data($data, $sysnotify_count, $notifications, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen);
389
390                 header("Content-type: text/xml");
391                 echo XML::fromArray(["result" => $data], $xml);
392         }
393
394         exit();
395 }
396
397 /**
398  * Retrieves the notifications array for the given user ID
399  *
400  * @param int $uid User id
401  * @return array Associative array of notifications
402  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
403  */
404 function ping_get_notifications($uid)
405 {
406         $result  = [];
407         $offset  = 0;
408         $seen    = false;
409         $seensql = "NOT";
410         $order   = "DESC";
411         $quit    = false;
412
413         do {
414                 $r = q(
415                         "SELECT `notify`.*, `post-view`.`visible`, `post-view`.`deleted`
416                         FROM `notify` LEFT JOIN `post-view` ON `post-view`.`id` = `notify`.`iid`
417                         WHERE `notify`.`uid` = %d AND `notify`.`msg` != ''
418                         AND NOT (`notify`.`type` IN (%d, %d))
419                         AND $seensql `notify`.`seen` ORDER BY `notify`.`date` $order LIMIT %d, 50",
420                         intval($uid),
421                         intval(Type::INTRO),
422                         intval(Type::MAIL),
423                         intval($offset)
424                 );
425
426                 if (!$r && !$seen) {
427                         $seen = true;
428                         $seensql = "";
429                         $order = "DESC";
430                         $offset = 0;
431                 } elseif (!$r) {
432                         $quit = true;
433                 } else {
434                         $offset += 50;
435                 }
436
437                 foreach ($r as $notification) {
438                         if (is_null($notification["visible"])) {
439                                 $notification["visible"] = true;
440                         }
441
442                         if (is_null($notification["deleted"])) {
443                                 $notification["deleted"] = 0;
444                         }
445
446                         if ($notification["msg_cache"]) {
447                                 $notification["name"] = $notification["name_cache"];
448                                 $notification["message"] = $notification["msg_cache"];
449                         } else {
450                                 $notification["name"] = strip_tags(BBCode::convert($notification["name"]));
451                                 $notification["message"] = Friendica\Model\Notify::formatMessage($notification["name"], strip_tags(BBCode::convert($notification["msg"])));
452
453                                 q(
454                                         "UPDATE `notify` SET `name_cache` = '%s', `msg_cache` = '%s' WHERE `id` = %d",
455                                         DBA::escape($notification["name"]),
456                                         DBA::escape($notification["message"]),
457                                         intval($notification["id"])
458                                 );
459                         }
460
461                         $notification["href"] = DI::baseUrl() . "/notification/" . $notification["id"];
462
463                         if ($notification["visible"]
464                                 && !$notification["deleted"]
465                                 && empty($result[$notification['parent']])
466                         ) {
467                                 // Should we condense the notifications or show them all?
468                                 if (DI::pConfig()->get(local_user(), 'system', 'detailed_notif')) {
469                                         $result[$notification["id"]] = $notification;
470                                 } else {
471                                         $result[$notification['parent']] = $notification;
472                                 }
473                         }
474                 }
475         } while ((count($result) < 50) && !$quit);
476
477         return($result);
478 }
479
480 /**
481  * Backward-compatible XML formatting for ping.php output
482  * @deprecated
483  *
484  * @param array $data            The initial ping data array
485  * @param int   $sysnotify_count Number of unseen system notifications
486  * @param array $notifs          Complete list of notification
487  * @param array $sysmsgs         List of system notice messages
488  * @param array $sysmsgs_info    List of system info messages
489  * @param array $groups_unseen   List of unseen group items
490  * @param array $forums_unseen   List of unseen forum items
491  *
492  * @return array XML-transform ready data array
493  */
494 function ping_format_xml_data($data, $sysnotify_count, $notifs, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen)
495 {
496         $notifications = [];
497         foreach ($notifs as $key => $notif) {
498                 $notifications[$key . ':note'] = $notif['message'];
499
500                 $notifications[$key . ':@attributes'] = [
501                         'id'        => $notif['id'],
502                         'href'      => $notif['href'],
503                         'name'      => $notif['name'],
504                         'url'       => $notif['url'],
505                         'photo'     => $notif['photo'],
506                         'date'      => $notif['date'],
507                         'seen'      => $notif['seen'],
508                         'timestamp' => $notif['timestamp']
509                 ];
510         }
511
512         $sysmsg = [];
513         foreach ($sysmsgs as $key => $m) {
514                 $sysmsg[$key . ':notice'] = $m;
515         }
516         foreach ($sysmsgs_info as $key => $m) {
517                 $sysmsg[$key . ':info'] = $m;
518         }
519
520         $data['notif'] = $notifications;
521         $data['@attributes'] = ['count' => $sysnotify_count + $data['intro'] + $data['mail'] + $data['register']];
522         $data['sysmsgs'] = $sysmsg;
523
524         if ($data['register'] == 0) {
525                 unset($data['register']);
526         }
527
528         $groups = [];
529         if (count($groups_unseen)) {
530                 foreach ($groups_unseen as $key => $item) {
531                         $groups[$key . ':group'] = $item['count'];
532                         $groups[$key . ':@attributes'] = ['id' => $item['id']];
533                 }
534                 $data['groups'] = $groups;
535         }
536
537         $forums = [];
538         if (count($forums_unseen)) {
539                 foreach ($forums_unseen as $key => $item) {
540                         $forums[$key . ':forum'] = $item['count'];
541                         $forums[$key . ':@attributes'] = ['id' => $item['id']];
542                 }
543                 $data['forums'] = $forums;
544         }
545
546         return $data;
547 }