]> git.mxchange.org Git - friendica.git/blob - mod/ping.php
Merge pull request #10362 from tobiasd/2021.06-CHANGELOG
[friendica.git] / mod / ping.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, 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 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\Notification;
32 use Friendica\Model\Post;
33 use Friendica\Model\Verb;
34 use Friendica\Protocol\Activity;
35 use Friendica\Util\DateTimeFormat;
36 use Friendica\Util\Proxy;
37 use Friendica\Util\Temporal;
38 use Friendica\Util\XML;
39
40 /**
41  * Outputs the counts and the lists of various notifications
42  *
43  * The output format can be controlled via the GET parameter 'format'. It can be
44  * - xml (deprecated legacy default)
45  * - json (outputs JSONP with the 'callback' GET parameter)
46  *
47  * Expected JSON structure:
48  * {
49  *        "result": {
50  *            "intro": 0,
51  *            "mail": 0,
52  *            "net": 0,
53  *            "home": 0,
54  *            "register": 0,
55  *            "all-events": 0,
56  *            "all-events-today": 0,
57  *            "events": 0,
58  *            "events-today": 0,
59  *            "birthdays": 0,
60  *            "birthdays-today": 0,
61  *            "groups": [ ],
62  *            "forums": [ ],
63  *            "notification": 0,
64  *            "notifications": [ ],
65  *            "sysmsgs": {
66  *                "notice": [ ],
67  *                "info": [ ]
68  *            }
69  *        }
70  *    }
71  *
72  * @param App $a The Friendica App instance
73  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
74  */
75 function ping_init(App $a)
76 {
77         $format = 'xml';
78
79         if (isset($_GET['format']) && $_GET['format'] == 'json') {
80                 $format = 'json';
81         }
82
83         $regs          = [];
84         $notifications = [];
85
86         $intro_count    = 0;
87         $mail_count     = 0;
88         $home_count     = 0;
89         $network_count  = 0;
90         $register_count = 0;
91         $sysnotify_count = 0;
92         $groups_unseen  = [];
93         $forums_unseen  = [];
94
95         $all_events       = 0;
96         $all_events_today = 0;
97         $events           = 0;
98         $events_today     = 0;
99         $birthdays        = 0;
100         $birthdays_today  = 0;
101
102         $data = [];
103         $data['intro']    = $intro_count;
104         $data['mail']     = $mail_count;
105         $data['net']      = $network_count;
106         $data['home']     = $home_count;
107         $data['register'] = $register_count;
108
109         $data['all-events']       = $all_events;
110         $data['all-events-today'] = $all_events_today;
111         $data['events']           = $events;
112         $data['events-today']     = $events_today;
113         $data['birthdays']        = $birthdays;
114         $data['birthdays-today']  = $birthdays_today;
115
116         if (local_user()) {
117                 // Different login session than the page that is calling us.
118                 if (!empty($_GET['uid']) && intval($_GET['uid']) != local_user()) {
119                         $data = ['result' => ['invalid' => 1]];
120
121                         if ($format == 'json') {
122                                 if (isset($_GET['callback'])) {
123                                         // JSONP support
124                                         header("Content-type: application/javascript");
125                                         echo $_GET['callback'] . '(' . json_encode($data) . ')';
126                                 } else {
127                                         header("Content-type: application/json");
128                                         echo json_encode($data);
129                                 }
130                         } else {
131                                 header("Content-type: text/xml");
132                                 echo XML::fromArray($data, $xml);
133                         }
134                         exit();
135                 }
136
137                 $notifications = ping_get_notifications(local_user());
138
139                 $condition = ["`unseen` AND `uid` = ? AND NOT `origin` AND (`vid` != ? OR `vid` IS NULL)",
140                         local_user(), Verb::getID(Activity::FOLLOW)];
141                 $items = Post::selectForUser(local_user(), ['wall', 'uid', 'uri-id'], $condition);
142                 if (DBA::isResult($items)) {
143                         $items_unseen = Post::toArray($items, false);
144                         $arr = ['items' => $items_unseen];
145                         Hook::callAll('network_ping', $arr);
146
147                         foreach ($items_unseen as $item) {
148                                 if ($item['wall']) {
149                                         $home_count++;
150                                 } else {
151                                         $network_count++;
152                                 }
153                         }
154                 }
155                 DBA::close($items);
156
157                 if ($network_count) {
158                         // Find out how unseen network posts are spread across groups
159                         $group_counts = Group::countUnseen();
160                         if (DBA::isResult($group_counts)) {
161                                 foreach ($group_counts as $group_count) {
162                                         if ($group_count['count'] > 0) {
163                                                 $groups_unseen[] = $group_count;
164                                         }
165                                 }
166                         }
167
168                         $forum_counts = ForumManager::countUnseenItems();
169                         if (DBA::isResult($forum_counts)) {
170                                 foreach ($forum_counts as $forum_count) {
171                                         if ($forum_count['count'] > 0) {
172                                                 $forums_unseen[] = $forum_count;
173                                         }
174                                 }
175                         }
176                 }
177
178                 $intros1 = q(
179                         "SELECT  `intro`.`id`, `intro`.`datetime`,
180                         `fcontact`.`name`, `fcontact`.`url`, `fcontact`.`photo`
181                         FROM `intro` INNER JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
182                         WHERE `intro`.`uid` = %d AND NOT `intro`.`blocked` AND NOT `intro`.`ignore` AND `intro`.`fid` != 0",
183                         intval(local_user())
184                 );
185                 $intros2 = q(
186                         "SELECT `intro`.`id`, `intro`.`datetime`,
187                         `contact`.`name`, `contact`.`url`, `contact`.`photo`
188                         FROM `intro` INNER JOIN `contact` ON `intro`.`contact-id` = `contact`.`id`
189                         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)",
190                         intval(local_user())
191                 );
192
193                 $intro_count = count($intros1) + count($intros2);
194                 $intros = $intros1 + $intros2;
195
196                 $myurl = DI::baseUrl() . '/profile/' . $a->user['nickname'];
197                 $mails = q(
198                         "SELECT `id`, `from-name`, `from-url`, `from-photo`, `created` FROM `mail`
199                         WHERE `uid` = %d AND `seen` = 0 AND `from-url` != '%s' ",
200                         intval(local_user()),
201                         DBA::escape($myurl)
202                 );
203                 $mail_count = count($mails);
204
205                 if (intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::APPROVE && is_site_admin()) {
206                         $regs = Friendica\Model\Register::getPending();
207
208                         if (DBA::isResult($regs)) {
209                                 $register_count = count($regs);
210                         }
211                 }
212
213                 $cachekey = "ping_init:".local_user();
214                 $ev = DI::cache()->get($cachekey);
215                 if (is_null($ev)) {
216                         $ev = q(
217                                 "SELECT type, start, adjust FROM `event`
218                                 WHERE `event`.`uid` = %d AND `start` < '%s' AND `finish` > '%s' and `ignore` = 0
219                                 ORDER BY `start` ASC ",
220                                 intval(local_user()),
221                                 DBA::escape(DateTimeFormat::utc('now + 7 days')),
222                                 DBA::escape(DateTimeFormat::utcNow())
223                         );
224                         if (DBA::isResult($ev)) {
225                                 DI::cache()->set($cachekey, $ev, Duration::HOUR);
226                         }
227                 }
228
229                 if (DBA::isResult($ev)) {
230                         $all_events = count($ev);
231
232                         if ($all_events) {
233                                 $str_now = DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d');
234                                 foreach ($ev as $x) {
235                                         $bd = false;
236                                         if ($x['type'] === 'birthday') {
237                                                 $birthdays ++;
238                                                 $bd = true;
239                                         } else {
240                                                 $events ++;
241                                         }
242                                         if (DateTimeFormat::convert($x['start'], ((intval($x['adjust'])) ? $a->timezone : 'UTC'), 'UTC', 'Y-m-d') === $str_now) {
243                                                 $all_events_today ++;
244                                                 if ($bd) {
245                                                         $birthdays_today ++;
246                                                 } else {
247                                                         $events_today ++;
248                                                 }
249                                         }
250                                 }
251                         }
252                 }
253
254                 $data['intro']    = $intro_count;
255                 $data['mail']     = $mail_count;
256                 $data['net']      = $network_count;
257                 $data['home']     = $home_count;
258                 $data['register'] = $register_count;
259
260                 $data['all-events']       = $all_events;
261                 $data['all-events-today'] = $all_events_today;
262                 $data['events']           = $events;
263                 $data['events-today']     = $events_today;
264                 $data['birthdays']        = $birthdays;
265                 $data['birthdays-today']  = $birthdays_today;
266
267                 if (DBA::isResult($notifications)) {
268                         foreach ($notifications as $notif) {
269                                 if ($notif['seen'] == 0) {
270                                         $sysnotify_count ++;
271                                 }
272                         }
273                 }
274
275                 // merge all notification types in one array
276                 if (DBA::isResult($intros)) {
277                         foreach ($intros as $intro) {
278                                 $notif = [
279                                         'id'      => 0,
280                                         'href'    => DI::baseUrl() . '/notifications/intros/' . $intro['id'],
281                                         'name'    => BBCode::convert($intro['name']),
282                                         'url'     => $intro['url'],
283                                         'photo'   => $intro['photo'],
284                                         'date'    => $intro['datetime'],
285                                         'seen'    => false,
286                                         'message' => DI::l10n()->t('{0} wants to be your friend'),
287                                 ];
288                                 $notifications[] = $notif;
289                         }
290                 }
291
292                 if (DBA::isResult($regs)) {
293                         if (count($regs) <= 1 || DI::pConfig()->get(local_user(), 'system', 'detailed_notif')) {
294                                 foreach ($regs as $reg) {
295                                         $notif = [
296                                                 'id'      => 0,
297                                                 'href'    => DI::baseUrl() . '/admin/users/pending',
298                                                 'name'    => $reg['name'],
299                                                 'url'     => $reg['url'],
300                                                 'photo'   => $reg['micro'],
301                                                 'date'    => $reg['created'],
302                                                 'seen'    => false,
303                                                 'message' => DI::l10n()->t('{0} requested registration'),
304                                         ];
305                                         $notifications[] = $notif;
306                                 }
307                         } else {
308                                 $notif = [
309                                         'id'      => 0,
310                                         'href'    => DI::baseUrl() . '/admin/users/pending',
311                                         'name'    => $regs[0]['name'],
312                                         'url'     => $regs[0]['url'],
313                                         'photo'   => $regs[0]['micro'],
314                                         'date'    => $regs[0]['created'],
315                                         'seen'    => false,
316                                         'message' => DI::l10n()->t('{0} and %d others requested registration', count($regs) - 1),
317                                 ];
318                                 $notifications[] = $notif;
319                         }
320                 }
321
322                 // sort notifications by $[]['date']
323                 $sort_function = function ($a, $b) {
324                         $adate = strtotime($a['date']);
325                         $bdate = strtotime($b['date']);
326
327                         // Unseen messages are kept at the top
328                         // The value 31536000 means one year. This should be enough :-)
329                         if (!$a['seen']) {
330                                 $adate += 31536000;
331                         }
332                         if (!$b['seen']) {
333                                 $bdate += 31536000;
334                         }
335
336                         if ($adate == $bdate) {
337                                 return 0;
338                         }
339                         return ($adate < $bdate) ? 1 : -1;
340                 };
341                 usort($notifications, $sort_function);
342
343                 array_walk($notifications, function (&$notification) {
344                         $notification['photo']     = Contact::getAvatarUrlForUrl($notification['url'], local_user(), Proxy::SIZE_MICRO);
345                         $notification['timestamp'] = DateTimeFormat::local($notification['date']);
346                         $notification['date']      = Temporal::getRelativeDate($notification['date']);
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`.*, `post`.`visible`, `post`.`deleted`
413                         FROM `notify` LEFT JOIN `post` ON `post`.`uri-id` = `notify`.`uri-id`
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(Notification\Type::INTRO),
419                         intval(Notification\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"] = Notification::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 }