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