]> git.mxchange.org Git - friendica.git/blob - mod/ping.php
c6e32a9314c4544f701ecf89c4ac081bd4cda609
[friendica.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\Item;
32 use Friendica\Model\Notify\Type;
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                 $notifs = 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 = Item::selectForUser(local_user(), ['wall', 'uid', 'uri-id'], $condition);
141                 if (DBA::isResult($items)) {
142                         $items_unseen = Item::inArray($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` LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
181                         WHERE `intro`.`uid` = %d  AND `intro`.`blocked` = 0 AND `intro`.`ignore` = 0 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` LEFT JOIN `contact` ON `intro`.`contact-id` = `contact`.`id`
188                         WHERE `intro`.`uid` = %d  AND `intro`.`blocked` = 0 AND `intro`.`ignore` = 0 AND `intro`.`contact-id` != 0",
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($notifs)) {
267                         foreach ($notifs 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'    => $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                                 $notifs[] = $notif;
288                         }
289                 }
290
291                 if (DBA::isResult($regs)) {
292                         foreach ($regs as $reg) {
293                                 $notif = [
294                                         'id'      => 0,
295                                         'href'    => DI::baseUrl() . '/admin/users/',
296                                         'name'    => $reg['name'],
297                                         'url'     => $reg['url'],
298                                         'photo'   => $reg['micro'],
299                                         'date'    => $reg['created'],
300                                         'seen'    => false,
301                                         'message' => DI::l10n()->t('{0} requested registration'),
302                                 ];
303                                 $notifs[] = $notif;
304                         }
305                 }
306
307                 // sort notifications by $[]['date']
308                 $sort_function = function ($a, $b) {
309                         $adate = strtotime($a['date']);
310                         $bdate = strtotime($b['date']);
311
312                         // Unseen messages are kept at the top
313                         // The value 31536000 means one year. This should be enough :-)
314                         if (!$a['seen']) {
315                                 $adate += 31536000;
316                         }
317                         if (!$b['seen']) {
318                                 $bdate += 31536000;
319                         }
320
321                         if ($adate == $bdate) {
322                                 return 0;
323                         }
324                         return ($adate < $bdate) ? 1 : -1;
325                 };
326                 usort($notifs, $sort_function);
327
328                 if (DBA::isResult($notifs)) {
329                         foreach ($notifs as $notif) {
330                                 $contact = Contact::getByURL($notif['url'], false, ['micro']);
331                                 $notif['photo'] = Contact::getMicro($contact, $notif['photo']);
332
333                                 $local_time = DateTimeFormat::local($notif['date']);
334
335                                 $notifications[] = [
336                                         'id'        => $notif['id'],
337                                         'href'      => $notif['href'],
338                                         'name'      => $notif['name'],
339                                         'url'       => $notif['url'],
340                                         'photo'     => $notif['photo'],
341                                         'date'      => Temporal::getRelativeDate($notif['date']),
342                                         'message'   => $notif['message'],
343                                         'seen'      => $notif['seen'],
344                                         'timestamp' => strtotime($local_time)
345                                 ];
346                         }
347                 }
348         }
349
350         $sysmsgs = [];
351         $sysmsgs_info = [];
352
353         if (!empty($_SESSION['sysmsg'])) {
354                 $sysmsgs = $_SESSION['sysmsg'];
355                 unset($_SESSION['sysmsg']);
356         }
357
358         if (!empty($_SESSION['sysmsg_info'])) {
359                 $sysmsgs_info = $_SESSION['sysmsg_info'];
360                 unset($_SESSION['sysmsg_info']);
361         }
362
363         if ($format == 'json') {
364                 $data['groups'] = $groups_unseen;
365                 $data['forums'] = $forums_unseen;
366                 $data['notification'] = $sysnotify_count + $intro_count + $register_count;
367                 $data['notifications'] = $notifications;
368                 $data['sysmsgs'] = [
369                         'notice' => $sysmsgs,
370                         'info' => $sysmsgs_info
371                 ];
372
373                 $json_payload = json_encode(["result" => $data]);
374
375                 if (isset($_GET['callback'])) {
376                         // JSONP support
377                         header("Content-type: application/javascript");
378                         echo $_GET['callback'] . '(' . $json_payload . ')';
379                 } else {
380                         header("Content-type: application/json");
381                         echo $json_payload;
382                 }
383         } else {
384                 // Legacy slower XML format output
385                 $data = ping_format_xml_data($data, $sysnotify_count, $notifications, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen);
386
387                 header("Content-type: text/xml");
388                 echo XML::fromArray(["result" => $data], $xml);
389         }
390
391         exit();
392 }
393
394 /**
395  * Retrieves the notifications array for the given user ID
396  *
397  * @param int $uid User id
398  * @return array Associative array of notifications
399  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
400  */
401 function ping_get_notifications($uid)
402 {
403         $result  = [];
404         $offset  = 0;
405         $seen    = false;
406         $seensql = "NOT";
407         $order   = "DESC";
408         $quit    = false;
409
410         do {
411                 $r = q(
412                         "SELECT `notify`.*, `item`.`visible`, `item`.`deleted`
413                         FROM `notify` LEFT JOIN `item` ON `item`.`id` = `notify`.`iid`
414                         WHERE `notify`.`uid` = %d AND `notify`.`msg` != ''
415                         AND NOT (`notify`.`type` IN (%d, %d))
416                         AND $seensql `notify`.`seen` ORDER BY `notify`.`date` $order LIMIT %d, 50",
417                         intval($uid),
418                         intval(Type::INTRO),
419                         intval(Type::MAIL),
420                         intval($offset)
421                 );
422
423                 if (!$r && !$seen) {
424                         $seen = true;
425                         $seensql = "";
426                         $order = "DESC";
427                         $offset = 0;
428                 } elseif (!$r) {
429                         $quit = true;
430                 } else {
431                         $offset += 50;
432                 }
433
434                 foreach ($r as $notification) {
435                         if (is_null($notification["visible"])) {
436                                 $notification["visible"] = true;
437                         }
438
439                         if (is_null($notification["deleted"])) {
440                                 $notification["deleted"] = 0;
441                         }
442
443                         if ($notification["msg_cache"]) {
444                                 $notification["name"] = $notification["name_cache"];
445                                 $notification["message"] = $notification["msg_cache"];
446                         } else {
447                                 $notification["name"] = strip_tags(BBCode::convert($notification["name"]));
448                                 $notification["message"] = Friendica\Model\Notify::formatMessage($notification["name"], strip_tags(BBCode::convert($notification["msg"])));
449
450                                 q(
451                                         "UPDATE `notify` SET `name_cache` = '%s', `msg_cache` = '%s' WHERE `id` = %d",
452                                         DBA::escape($notification["name"]),
453                                         DBA::escape($notification["message"]),
454                                         intval($notification["id"])
455                                 );
456                         }
457
458                         $notification["href"] = DI::baseUrl() . "/notification/" . $notification["id"];
459
460                         if ($notification["visible"]
461                                 && !$notification["deleted"]
462                                 && empty($result[$notification['parent']])
463                         ) {
464                                 // Should we condense the notifications or show them all?
465                                 if (DI::pConfig()->get(local_user(), 'system', 'detailed_notif')) {
466                                         $result[$notification["id"]] = $notification;
467                                 } else {
468                                         $result[$notification['parent']] = $notification;
469                                 }
470                         }
471                 }
472         } while ((count($result) < 50) && !$quit);
473
474         return($result);
475 }
476
477 /**
478  * Backward-compatible XML formatting for ping.php output
479  * @deprecated
480  *
481  * @param array $data            The initial ping data array
482  * @param int   $sysnotify_count Number of unseen system notifications
483  * @param array $notifs          Complete list of notification
484  * @param array $sysmsgs         List of system notice messages
485  * @param array $sysmsgs_info    List of system info messages
486  * @param array $groups_unseen   List of unseen group items
487  * @param array $forums_unseen   List of unseen forum items
488  *
489  * @return array XML-transform ready data array
490  */
491 function ping_format_xml_data($data, $sysnotify_count, $notifs, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen)
492 {
493         $notifications = [];
494         foreach ($notifs as $key => $notif) {
495                 $notifications[$key . ':note'] = $notif['message'];
496
497                 $notifications[$key . ':@attributes'] = [
498                         'id'        => $notif['id'],
499                         'href'      => $notif['href'],
500                         'name'      => $notif['name'],
501                         'url'       => $notif['url'],
502                         'photo'     => $notif['photo'],
503                         'date'      => $notif['date'],
504                         'seen'      => $notif['seen'],
505                         'timestamp' => $notif['timestamp']
506                 ];
507         }
508
509         $sysmsg = [];
510         foreach ($sysmsgs as $key => $m) {
511                 $sysmsg[$key . ':notice'] = $m;
512         }
513         foreach ($sysmsgs_info as $key => $m) {
514                 $sysmsg[$key . ':info'] = $m;
515         }
516
517         $data['notif'] = $notifications;
518         $data['@attributes'] = ['count' => $sysnotify_count + $data['intro'] + $data['mail'] + $data['register']];
519         $data['sysmsgs'] = $sysmsg;
520
521         if ($data['register'] == 0) {
522                 unset($data['register']);
523         }
524
525         $groups = [];
526         if (count($groups_unseen)) {
527                 foreach ($groups_unseen as $key => $item) {
528                         $groups[$key . ':group'] = $item['count'];
529                         $groups[$key . ':@attributes'] = ['id' => $item['id']];
530                 }
531                 $data['groups'] = $groups;
532         }
533
534         $forums = [];
535         if (count($forums_unseen)) {
536                 foreach ($forums_unseen as $key => $item) {
537                         $forums[$key . ':forum'] = $item['count'];
538                         $forums[$key . ':@attributes'] = ['id' => $item['id']];
539                 }
540                 $data['forums'] = $forums;
541         }
542
543         return $data;
544 }