]> git.mxchange.org Git - friendica.git/blob - mod/ping.php
Merge pull request #8883 from annando/replace-getdetails
[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 `contact-id` != ? AND (`vid` != ? OR `vid` IS NULL)",
140                         local_user(), local_user(), Verb::getID(Activity::FOLLOW)];
141                 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
142                         'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid', 'wall', 'activity'];
143                 $params = ['order' => ['received' => true]];
144                 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
145
146                 if (DBA::isResult($items)) {
147                         $items_unseen = Item::inArray($items);
148                         $arr = ['items' => $items_unseen];
149                         Hook::callAll('network_ping', $arr);
150
151                         foreach ($items_unseen as $item) {
152                                 if ($item['wall']) {
153                                         $home_count++;
154                                 } else {
155                                         $network_count++;
156                                 }
157                         }
158                 }
159
160                 if ($network_count) {
161                         // Find out how unseen network posts are spread across groups
162                         $group_counts = Group::countUnseen();
163                         if (DBA::isResult($group_counts)) {
164                                 foreach ($group_counts as $group_count) {
165                                         if ($group_count['count'] > 0) {
166                                                 $groups_unseen[] = $group_count;
167                                         }
168                                 }
169                         }
170
171                         $forum_counts = ForumManager::countUnseenItems();
172                         if (DBA::isResult($forum_counts)) {
173                                 foreach ($forum_counts as $forum_count) {
174                                         if ($forum_count['count'] > 0) {
175                                                 $forums_unseen[] = $forum_count;
176                                         }
177                                 }
178                         }
179                 }
180
181                 $intros1 = q(
182                         "SELECT  `intro`.`id`, `intro`.`datetime`,
183                         `fcontact`.`name`, `fcontact`.`url`, `fcontact`.`photo`
184                         FROM `intro` LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
185                         WHERE `intro`.`uid` = %d  AND `intro`.`blocked` = 0 AND `intro`.`ignore` = 0 AND `intro`.`fid` != 0",
186                         intval(local_user())
187                 );
188                 $intros2 = q(
189                         "SELECT `intro`.`id`, `intro`.`datetime`,
190                         `contact`.`name`, `contact`.`url`, `contact`.`photo`
191                         FROM `intro` LEFT JOIN `contact` ON `intro`.`contact-id` = `contact`.`id`
192                         WHERE `intro`.`uid` = %d  AND `intro`.`blocked` = 0 AND `intro`.`ignore` = 0 AND `intro`.`contact-id` != 0",
193                         intval(local_user())
194                 );
195
196                 $intro_count = count($intros1) + count($intros2);
197                 $intros = $intros1 + $intros2;
198
199                 $myurl = DI::baseUrl() . '/profile/' . $a->user['nickname'];
200                 $mails = q(
201                         "SELECT `id`, `from-name`, `from-url`, `from-photo`, `created` FROM `mail`
202                         WHERE `uid` = %d AND `seen` = 0 AND `from-url` != '%s' ",
203                         intval(local_user()),
204                         DBA::escape($myurl)
205                 );
206                 $mail_count = count($mails);
207
208                 if (intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::APPROVE && is_site_admin()) {
209                         $regs = Friendica\Model\Register::getPending();
210
211                         if (DBA::isResult($regs)) {
212                                 $register_count = count($regs);
213                         }
214                 }
215
216                 $cachekey = "ping_init:".local_user();
217                 $ev = DI::cache()->get($cachekey);
218                 if (is_null($ev)) {
219                         $ev = q(
220                                 "SELECT type, start, adjust FROM `event`
221                                 WHERE `event`.`uid` = %d AND `start` < '%s' AND `finish` > '%s' and `ignore` = 0
222                                 ORDER BY `start` ASC ",
223                                 intval(local_user()),
224                                 DBA::escape(DateTimeFormat::utc('now + 7 days')),
225                                 DBA::escape(DateTimeFormat::utcNow())
226                         );
227                         if (DBA::isResult($ev)) {
228                                 DI::cache()->set($cachekey, $ev, Duration::HOUR);
229                         }
230                 }
231
232                 if (DBA::isResult($ev)) {
233                         $all_events = count($ev);
234
235                         if ($all_events) {
236                                 $str_now = DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d');
237                                 foreach ($ev as $x) {
238                                         $bd = false;
239                                         if ($x['type'] === 'birthday') {
240                                                 $birthdays ++;
241                                                 $bd = true;
242                                         } else {
243                                                 $events ++;
244                                         }
245                                         if (DateTimeFormat::convert($x['start'], ((intval($x['adjust'])) ? $a->timezone : 'UTC'), 'UTC', 'Y-m-d') === $str_now) {
246                                                 $all_events_today ++;
247                                                 if ($bd) {
248                                                         $birthdays_today ++;
249                                                 } else {
250                                                         $events_today ++;
251                                                 }
252                                         }
253                                 }
254                         }
255                 }
256
257                 $data['intro']    = $intro_count;
258                 $data['mail']     = $mail_count;
259                 $data['net']      = $network_count;
260                 $data['home']     = $home_count;
261                 $data['register'] = $register_count;
262
263                 $data['all-events']       = $all_events;
264                 $data['all-events-today'] = $all_events_today;
265                 $data['events']           = $events;
266                 $data['events-today']     = $events_today;
267                 $data['birthdays']        = $birthdays;
268                 $data['birthdays-today']  = $birthdays_today;
269
270                 if (DBA::isResult($notifs)) {
271                         foreach ($notifs as $notif) {
272                                 if ($notif['seen'] == 0) {
273                                         $sysnotify_count ++;
274                                 }
275                         }
276                 }
277
278                 // merge all notification types in one array
279                 if (DBA::isResult($intros)) {
280                         foreach ($intros as $intro) {
281                                 $notif = [
282                                         'id'      => 0,
283                                         'href'    => DI::baseUrl() . '/notifications/intros/' . $intro['id'],
284                                         'name'    => $intro['name'],
285                                         'url'     => $intro['url'],
286                                         'photo'   => $intro['photo'],
287                                         'date'    => $intro['datetime'],
288                                         'seen'    => false,
289                                         'message' => DI::l10n()->t('{0} wants to be your friend'),
290                                 ];
291                                 $notifs[] = $notif;
292                         }
293                 }
294
295                 if (DBA::isResult($regs)) {
296                         foreach ($regs as $reg) {
297                                 $notif = [
298                                         'id'      => 0,
299                                         'href'    => DI::baseUrl() . '/admin/users/',
300                                         'name'    => $reg['name'],
301                                         'url'     => $reg['url'],
302                                         'photo'   => $reg['micro'],
303                                         'date'    => $reg['created'],
304                                         'seen'    => false,
305                                         'message' => DI::l10n()->t('{0} requested registration'),
306                                 ];
307                                 $notifs[] = $notif;
308                         }
309                 }
310
311                 // sort notifications by $[]['date']
312                 $sort_function = function ($a, $b) {
313                         $adate = strtotime($a['date']);
314                         $bdate = strtotime($b['date']);
315
316                         // Unseen messages are kept at the top
317                         // The value 31536000 means one year. This should be enough :-)
318                         if (!$a['seen']) {
319                                 $adate += 31536000;
320                         }
321                         if (!$b['seen']) {
322                                 $bdate += 31536000;
323                         }
324
325                         if ($adate == $bdate) {
326                                 return 0;
327                         }
328                         return ($adate < $bdate) ? 1 : -1;
329                 };
330                 usort($notifs, $sort_function);
331
332                 if (DBA::isResult($notifs)) {
333                         foreach ($notifs as $notif) {
334                                 $contact = Contact::getByURL($notif['url'], false, ['micro']);
335                                 if (isset($contact['micro'])) {
336                                         $notif['photo'] = ProxyUtils::proxifyUrl($contact['micro'], false, ProxyUtils::SIZE_MICRO);
337                                 } else {
338                                         $notif['photo'] = ProxyUtils::proxifyUrl($notif['photo'], false, ProxyUtils::SIZE_MICRO);
339                                 }
340
341                                 $local_time = DateTimeFormat::local($notif['date']);
342
343                                 $notifications[] = [
344                                         'id'        => $notif['id'],
345                                         'href'      => $notif['href'],
346                                         'name'      => $notif['name'],
347                                         'url'       => $notif['url'],
348                                         'photo'     => $notif['photo'],
349                                         'date'      => Temporal::getRelativeDate($notif['date']),
350                                         'message'   => $notif['message'],
351                                         'seen'      => $notif['seen'],
352                                         'timestamp' => strtotime($local_time)
353                                 ];
354                         }
355                 }
356         }
357
358         $sysmsgs = [];
359         $sysmsgs_info = [];
360
361         if (!empty($_SESSION['sysmsg'])) {
362                 $sysmsgs = $_SESSION['sysmsg'];
363                 unset($_SESSION['sysmsg']);
364         }
365
366         if (!empty($_SESSION['sysmsg_info'])) {
367                 $sysmsgs_info = $_SESSION['sysmsg_info'];
368                 unset($_SESSION['sysmsg_info']);
369         }
370
371         if ($format == 'json') {
372                 $data['groups'] = $groups_unseen;
373                 $data['forums'] = $forums_unseen;
374                 $data['notification'] = $sysnotify_count + $intro_count + $register_count;
375                 $data['notifications'] = $notifications;
376                 $data['sysmsgs'] = [
377                         'notice' => $sysmsgs,
378                         'info' => $sysmsgs_info
379                 ];
380
381                 $json_payload = json_encode(["result" => $data]);
382
383                 if (isset($_GET['callback'])) {
384                         // JSONP support
385                         header("Content-type: application/javascript");
386                         echo $_GET['callback'] . '(' . $json_payload . ')';
387                 } else {
388                         header("Content-type: application/json");
389                         echo $json_payload;
390                 }
391         } else {
392                 // Legacy slower XML format output
393                 $data = ping_format_xml_data($data, $sysnotify_count, $notifications, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen);
394
395                 header("Content-type: text/xml");
396                 echo XML::fromArray(["result" => $data], $xml);
397         }
398
399         exit();
400 }
401
402 /**
403  * Retrieves the notifications array for the given user ID
404  *
405  * @param int $uid User id
406  * @return array Associative array of notifications
407  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
408  */
409 function ping_get_notifications($uid)
410 {
411         $result  = [];
412         $offset  = 0;
413         $seen    = false;
414         $seensql = "NOT";
415         $order   = "DESC";
416         $quit    = false;
417
418         do {
419                 $r = q(
420                         "SELECT `notify`.*, `item`.`visible`, `item`.`deleted`
421                         FROM `notify` LEFT JOIN `item` ON `item`.`id` = `notify`.`iid`
422                         WHERE `notify`.`uid` = %d AND `notify`.`msg` != ''
423                         AND NOT (`notify`.`type` IN (%d, %d))
424                         AND $seensql `notify`.`seen` ORDER BY `notify`.`date` $order LIMIT %d, 50",
425                         intval($uid),
426                         intval(Type::INTRO),
427                         intval(Type::MAIL),
428                         intval($offset)
429                 );
430
431                 if (!$r && !$seen) {
432                         $seen = true;
433                         $seensql = "";
434                         $order = "DESC";
435                         $offset = 0;
436                 } elseif (!$r) {
437                         $quit = true;
438                 } else {
439                         $offset += 50;
440                 }
441
442                 foreach ($r as $notification) {
443                         if (is_null($notification["visible"])) {
444                                 $notification["visible"] = true;
445                         }
446
447                         if (is_null($notification["deleted"])) {
448                                 $notification["deleted"] = 0;
449                         }
450
451                         if ($notification["msg_cache"]) {
452                                 $notification["name"] = $notification["name_cache"];
453                                 $notification["message"] = $notification["msg_cache"];
454                         } else {
455                                 $notification["name"] = strip_tags(BBCode::convert($notification["name"]));
456                                 $notification["message"] = Friendica\Model\Notify::formatMessage($notification["name"], strip_tags(BBCode::convert($notification["msg"])));
457
458                                 q(
459                                         "UPDATE `notify` SET `name_cache` = '%s', `msg_cache` = '%s' WHERE `id` = %d",
460                                         DBA::escape($notification["name"]),
461                                         DBA::escape($notification["message"]),
462                                         intval($notification["id"])
463                                 );
464                         }
465
466                         $notification["href"] = DI::baseUrl() . "/notification/" . $notification["id"];
467
468                         if ($notification["visible"]
469                                 && !$notification["deleted"]
470                                 && empty($result[$notification['parent']])
471                         ) {
472                                 // Should we condense the notifications or show them all?
473                                 if (DI::pConfig()->get(local_user(), 'system', 'detailed_notif')) {
474                                         $result[$notification["id"]] = $notification;
475                                 } else {
476                                         $result[$notification['parent']] = $notification;
477                                 }
478                         }
479                 }
480         } while ((count($result) < 50) && !$quit);
481
482         return($result);
483 }
484
485 /**
486  * Backward-compatible XML formatting for ping.php output
487  * @deprecated
488  *
489  * @param array $data            The initial ping data array
490  * @param int   $sysnotify_count Number of unseen system notifications
491  * @param array $notifs          Complete list of notification
492  * @param array $sysmsgs         List of system notice messages
493  * @param array $sysmsgs_info    List of system info messages
494  * @param array $groups_unseen   List of unseen group items
495  * @param array $forums_unseen   List of unseen forum items
496  *
497  * @return array XML-transform ready data array
498  */
499 function ping_format_xml_data($data, $sysnotify_count, $notifs, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen)
500 {
501         $notifications = [];
502         foreach ($notifs as $key => $notif) {
503                 $notifications[$key . ':note'] = $notif['message'];
504
505                 $notifications[$key . ':@attributes'] = [
506                         'id'        => $notif['id'],
507                         'href'      => $notif['href'],
508                         'name'      => $notif['name'],
509                         'url'       => $notif['url'],
510                         'photo'     => $notif['photo'],
511                         'date'      => $notif['date'],
512                         'seen'      => $notif['seen'],
513                         'timestamp' => $notif['timestamp']
514                 ];
515         }
516
517         $sysmsg = [];
518         foreach ($sysmsgs as $key => $m) {
519                 $sysmsg[$key . ':notice'] = $m;
520         }
521         foreach ($sysmsgs_info as $key => $m) {
522                 $sysmsg[$key . ':info'] = $m;
523         }
524
525         $data['notif'] = $notifications;
526         $data['@attributes'] = ['count' => $sysnotify_count + $data['intro'] + $data['mail'] + $data['register']];
527         $data['sysmsgs'] = $sysmsg;
528
529         if ($data['register'] == 0) {
530                 unset($data['register']);
531         }
532
533         $groups = [];
534         if (count($groups_unseen)) {
535                 foreach ($groups_unseen as $key => $item) {
536                         $groups[$key . ':group'] = $item['count'];
537                         $groups[$key . ':@attributes'] = ['id' => $item['id']];
538                 }
539                 $data['groups'] = $groups;
540         }
541
542         $forums = [];
543         if (count($forums_unseen)) {
544                 foreach ($forums_unseen as $key => $item) {
545                         $forums[$key . ':forum'] = $item['count'];
546                         $forums[$key . ':@attributes'] = ['id' => $item['id']];
547                 }
548                 $data['forums'] = $forums;
549         }
550
551         return $data;
552 }