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