]> git.mxchange.org Git - friendica.git/blob - mod/ping.php
Update "storage" console command
[friendica.git] / mod / ping.php
1 <?php
2 /**
3  * @file include/ping.php
4  */
5
6 use Friendica\App;
7 use Friendica\Content\ForumManager;
8 use Friendica\Content\Text\BBCode;
9 use Friendica\Core\Cache;
10 use Friendica\Core\Config;
11 use Friendica\Core\Hook;
12 use Friendica\Core\L10n;
13 use Friendica\Core\PConfig;
14 use Friendica\Core\System;
15 use Friendica\Database\DBA;
16 use Friendica\Model\Contact;
17 use Friendica\Model\Group;
18 use Friendica\Model\Item;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\Temporal;
21 use Friendica\Util\Proxy as ProxyUtils;
22 use Friendica\Util\XML;
23
24 /**
25  * @brief Outputs the counts and the lists of various notifications
26  *
27  * The output format can be controlled via the GET parameter 'format'. It can be
28  * - xml (deprecated legacy default)
29  * - json (outputs JSONP with the 'callback' GET parameter)
30  *
31  * Expected JSON structure:
32  * {
33  *              "result": {
34  *                      "intro": 0,
35  *                      "mail": 0,
36  *                      "net": 0,
37  *                      "home": 0,
38  *                      "register": 0,
39  *                      "all-events": 0,
40  *                      "all-events-today": 0,
41  *                      "events": 0,
42  *                      "events-today": 0,
43  *                      "birthdays": 0,
44  *                      "birthdays-today": 0,
45  *                      "groups": [ ],
46  *                      "forums": [ ],
47  *                      "notify": 0,
48  *                      "notifications": [ ],
49  *                      "sysmsgs": {
50  *                              "notice": [ ],
51  *                              "info": [ ]
52  *                      }
53  *              }
54  *      }
55  *
56  * @param App $a The Friendica App instance
57  */
58 function ping_init(App $a)
59 {
60         $format = 'xml';
61
62         if (isset($_GET['format']) && $_GET['format'] == 'json') {
63                 $format = 'json';
64         }
65
66         $regs          = [];
67         $notifications = [];
68
69         $intro_count    = 0;
70         $mail_count     = 0;
71         $home_count     = 0;
72         $network_count  = 0;
73         $register_count = 0;
74         $sysnotify_count = 0;
75         $groups_unseen  = [];
76         $forums_unseen  = [];
77
78         $all_events       = 0;
79         $all_events_today = 0;
80         $events           = 0;
81         $events_today     = 0;
82         $birthdays        = 0;
83         $birthdays_today  = 0;
84
85         $data = [];
86         $data['intro']    = $intro_count;
87         $data['mail']     = $mail_count;
88         $data['net']      = $network_count;
89         $data['home']     = $home_count;
90         $data['register'] = $register_count;
91
92         $data['all-events']       = $all_events;
93         $data['all-events-today'] = $all_events_today;
94         $data['events']           = $events;
95         $data['events-today']     = $events_today;
96         $data['birthdays']        = $birthdays;
97         $data['birthdays-today']  = $birthdays_today;
98
99         if (local_user()) {
100                 // Different login session than the page that is calling us.
101                 if (!empty($_GET['uid']) && intval($_GET['uid']) != local_user()) {
102                         $data = ['result' => ['invalid' => 1]];
103
104                         if ($format == 'json') {
105                                 if (isset($_GET['callback'])) {
106                                         // JSONP support
107                                         header("Content-type: application/javascript");
108                                         echo $_GET['callback'] . '(' . json_encode($data) . ')';
109                                 } else {
110                                         header("Content-type: application/json");
111                                         echo json_encode($data);
112                                 }
113                         } else {
114                                 header("Content-type: text/xml");
115                                 echo XML::fromArray($data, $xml);
116                         }
117                         exit();
118                 }
119
120                 $notifs = ping_get_notifications(local_user());
121
122                 $condition = ["`unseen` AND `uid` = ? AND `contact-id` != ?", local_user(), local_user()];
123                 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
124                         'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid', 'wall'];
125                 $params = ['order' => ['created' => true]];
126                 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
127
128                 if (DBA::isResult($items)) {
129                         $items_unseen = Item::inArray($items);
130                         $arr = ['items' => $items_unseen];
131                         Hook::callAll('network_ping', $arr);
132
133                         foreach ($items_unseen as $item) {
134                                 if ($item['wall']) {
135                                         $home_count++;
136                                 } else {
137                                         $network_count++;
138                                 }
139                         }
140                 }
141
142                 if ($network_count) {
143                         // Find out how unseen network posts are spread across groups
144                         $group_counts = Group::countUnseen();
145                         if (DBA::isResult($group_counts)) {
146                                 foreach ($group_counts as $group_count) {
147                                         if ($group_count['count'] > 0) {
148                                                 $groups_unseen[] = $group_count;
149                                         }
150                                 }
151                         }
152
153                         $forum_counts = ForumManager::countUnseenItems();
154                         if (DBA::isResult($forum_counts)) {
155                                 foreach ($forum_counts as $forum_count) {
156                                         if ($forum_count['count'] > 0) {
157                                                 $forums_unseen[] = $forum_count;
158                                         }
159                                 }
160                         }
161                 }
162
163                 $intros1 = q(
164                         "SELECT  `intro`.`id`, `intro`.`datetime`,
165                         `fcontact`.`name`, `fcontact`.`url`, `fcontact`.`photo`
166                         FROM `intro` LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
167                         WHERE `intro`.`uid` = %d  AND `intro`.`blocked` = 0 AND `intro`.`ignore` = 0 AND `intro`.`fid` != 0",
168                         intval(local_user())
169                 );
170                 $intros2 = q(
171                         "SELECT `intro`.`id`, `intro`.`datetime`,
172                         `contact`.`name`, `contact`.`url`, `contact`.`photo`
173                         FROM `intro` LEFT JOIN `contact` ON `intro`.`contact-id` = `contact`.`id`
174                         WHERE `intro`.`uid` = %d  AND `intro`.`blocked` = 0 AND `intro`.`ignore` = 0 AND `intro`.`contact-id` != 0",
175                         intval(local_user())
176                 );
177
178                 $intro_count = count($intros1) + count($intros2);
179                 $intros = $intros1 + $intros2;
180
181                 $myurl = System::baseUrl() . '/profile/' . $a->user['nickname'];
182                 $mails = q(
183                         "SELECT `id`, `from-name`, `from-url`, `from-photo`, `created` FROM `mail`
184                         WHERE `uid` = %d AND `seen` = 0 AND `from-url` != '%s' ",
185                         intval(local_user()),
186                         DBA::escape($myurl)
187                 );
188                 $mail_count = count($mails);
189
190                 if (intval(Config::get('config', 'register_policy')) === REGISTER_APPROVE && is_site_admin()) {
191                         $regs = Friendica\Model\Register::getPending();
192
193                         if (DBA::isResult($regs)) {
194                                 $register_count = count($regs);
195                         }
196                 }
197
198                 $cachekey = "ping_init:".local_user();
199                 $ev = Cache::get($cachekey);
200                 if (is_null($ev)) {
201                         $ev = q(
202                                 "SELECT type, start, adjust FROM `event`
203                                 WHERE `event`.`uid` = %d AND `start` < '%s' AND `finish` > '%s' and `ignore` = 0
204                                 ORDER BY `start` ASC ",
205                                 intval(local_user()),
206                                 DBA::escape(DateTimeFormat::utc('now + 7 days')),
207                                 DBA::escape(DateTimeFormat::utcNow())
208                         );
209                         if (DBA::isResult($ev)) {
210                                 Cache::set($cachekey, $ev, Cache::HOUR);
211                         }
212                 }
213
214                 if (DBA::isResult($ev)) {
215                         $all_events = count($ev);
216
217                         if ($all_events) {
218                                 $str_now = DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d');
219                                 foreach ($ev as $x) {
220                                         $bd = false;
221                                         if ($x['type'] === 'birthday') {
222                                                 $birthdays ++;
223                                                 $bd = true;
224                                         } else {
225                                                 $events ++;
226                                         }
227                                         if (DateTimeFormat::convert($x['start'], ((intval($x['adjust'])) ? $a->timezone : 'UTC'), 'UTC', 'Y-m-d') === $str_now) {
228                                                 $all_events_today ++;
229                                                 if ($bd) {
230                                                         $birthdays_today ++;
231                                                 } else {
232                                                         $events_today ++;
233                                                 }
234                                         }
235                                 }
236                         }
237                 }
238
239                 $data['intro']    = $intro_count;
240                 $data['mail']     = $mail_count;
241                 $data['net']      = $network_count;
242                 $data['home']     = $home_count;
243                 $data['register'] = $register_count;
244
245                 $data['all-events']       = $all_events;
246                 $data['all-events-today'] = $all_events_today;
247                 $data['events']           = $events;
248                 $data['events-today']     = $events_today;
249                 $data['birthdays']        = $birthdays;
250                 $data['birthdays-today']  = $birthdays_today;
251
252                 if (DBA::isResult($notifs)) {
253                         foreach ($notifs as $notif) {
254                                 if ($notif['seen'] == 0) {
255                                         $sysnotify_count ++;
256                                 }
257                         }
258                 }
259
260                 // merge all notification types in one array
261                 if (DBA::isResult($intros)) {
262                         foreach ($intros as $intro) {
263                                 $notif = [
264                                         'id'      => 0,
265                                         'href'    => System::baseUrl() . '/notifications/intros/' . $intro['id'],
266                                         'name'    => $intro['name'],
267                                         'url'     => $intro['url'],
268                                         'photo'   => $intro['photo'],
269                                         'date'    => $intro['datetime'],
270                                         'seen'    => false,
271                                         'message' => L10n::t('{0} wants to be your friend'),
272                                 ];
273                                 $notifs[] = $notif;
274                         }
275                 }
276
277                 if (DBA::isResult($regs)) {
278                         foreach ($regs as $reg) {
279                                 $notif = [
280                                         'id'      => 0,
281                                         'href'    => System::baseUrl() . '/admin/users/',
282                                         'name'    => $reg['name'],
283                                         'url'     => $reg['url'],
284                                         'photo'   => $reg['micro'],
285                                         'date'    => $reg['created'],
286                                         'seen'    => false,
287                                         'message' => L10n::t('{0} requested registration'),
288                                 ];
289                                 $notifs[] = $notif;
290                         }
291                 }
292
293                 // sort notifications by $[]['date']
294                 $sort_function = function ($a, $b) {
295                         $adate = strtotime($a['date']);
296                         $bdate = strtotime($b['date']);
297
298                         // Unseen messages are kept at the top
299                         // The value 31536000 means one year. This should be enough :-)
300                         if (!$a['seen']) {
301                                 $adate += 31536000;
302                         }
303                         if (!$b['seen']) {
304                                 $bdate += 31536000;
305                         }
306
307                         if ($adate == $bdate) {
308                                 return 0;
309                         }
310                         return ($adate < $bdate) ? 1 : -1;
311                 };
312                 usort($notifs, $sort_function);
313
314                 if (DBA::isResult($notifs)) {
315                         // Are the nofications called from the regular process or via the friendica app?
316                         $regularnotifications = (!empty($_GET['uid']) && !empty($_GET['_']));
317
318                         foreach ($notifs as $notif) {
319                                 if ($a->isFriendicaApp() || !$regularnotifications) {
320                                         $notif['message'] = str_replace("{0}", $notif['name'], $notif['message']);
321                                 }
322
323                                 $contact = Contact::getDetailsByURL($notif['url']);
324                                 if (isset($contact['micro'])) {
325                                         $notif['photo'] = ProxyUtils::proxifyUrl($contact['micro'], false, ProxyUtils::SIZE_MICRO);
326                                 } else {
327                                         $notif['photo'] = ProxyUtils::proxifyUrl($notif['photo'], false, ProxyUtils::SIZE_MICRO);
328                                 }
329
330                                 $local_time = DateTimeFormat::local($notif['date']);
331
332                                 $notifications[] = [
333                                         'id'        => $notif['id'],
334                                         'href'      => $notif['href'],
335                                         'name'      => $notif['name'],
336                                         'url'       => $notif['url'],
337                                         'photo'     => $notif['photo'],
338                                         'date'      => Temporal::getRelativeDate($notif['date']),
339                                         'message'   => $notif['message'],
340                                         'seen'      => $notif['seen'],
341                                         'timestamp' => strtotime($local_time)
342                                 ];
343                         }
344                 }
345         }
346
347         $sysmsgs = [];
348         $sysmsgs_info = [];
349
350         if (!empty($_SESSION['sysmsg'])) {
351                 $sysmsgs = $_SESSION['sysmsg'];
352                 unset($_SESSION['sysmsg']);
353         }
354
355         if (!empty($_SESSION['sysmsg_info'])) {
356                 $sysmsgs_info = $_SESSION['sysmsg_info'];
357                 unset($_SESSION['sysmsg_info']);
358         }
359
360         if ($format == 'json') {
361                 $data['groups'] = $groups_unseen;
362                 $data['forums'] = $forums_unseen;
363                 $data['notify'] = $sysnotify_count + $intro_count + $register_count;
364                 $data['notifications'] = $notifications;
365                 $data['sysmsgs'] = [
366                         'notice' => $sysmsgs,
367                         'info' => $sysmsgs_info
368                 ];
369
370                 $json_payload = json_encode(["result" => $data]);
371
372                 if (isset($_GET['callback'])) {
373                         // JSONP support
374                         header("Content-type: application/javascript");
375                         echo $_GET['callback'] . '(' . $json_payload . ')';
376                 } else {
377                         header("Content-type: application/json");
378                         echo $json_payload;
379                 }
380         } else {
381                 // Legacy slower XML format output
382                 $data = ping_format_xml_data($data, $sysnotify_count, $notifications, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen);
383
384                 header("Content-type: text/xml");
385                 echo XML::fromArray(["result" => $data], $xml);
386         }
387
388         exit();
389 }
390
391 /**
392  * @brief Retrieves the notifications array for the given user ID
393  *
394  * @param int $uid User id
395  * @return array Associative array of notifications
396  */
397 function ping_get_notifications($uid)
398 {
399         $result  = [];
400         $offset  = 0;
401         $seen    = false;
402         $seensql = "NOT";
403         $order   = "DESC";
404         $quit    = false;
405
406         do {
407                 $r = q(
408                         "SELECT `notify`.*, `item`.`visible`, `item`.`deleted`
409                         FROM `notify` LEFT JOIN `item` ON `item`.`id` = `notify`.`iid`
410                         WHERE `notify`.`uid` = %d AND `notify`.`msg` != ''
411                         AND NOT (`notify`.`type` IN (%d, %d))
412                         AND $seensql `notify`.`seen` ORDER BY `notify`.`date` $order LIMIT %d, 50",
413                         intval($uid),
414                         intval(NOTIFY_INTRO),
415                         intval(NOTIFY_MAIL),
416                         intval($offset)
417                 );
418
419                 if (!$r && !$seen) {
420                         $seen = true;
421                         $seensql = "";
422                         $order = "DESC";
423                         $offset = 0;
424                 } elseif (!$r) {
425                         $quit = true;
426                 } else {
427                         $offset += 50;
428                 }
429
430                 foreach ($r as $notification) {
431                         if (is_null($notification["visible"])) {
432                                 $notification["visible"] = true;
433                         }
434
435                         if (is_null($notification["deleted"])) {
436                                 $notification["deleted"] = 0;
437                         }
438
439                         if ($notification["msg_cache"]) {
440                                 $notification["name"] = $notification["name_cache"];
441                                 $notification["message"] = $notification["msg_cache"];
442                         } else {
443                                 $notification["name"] = strip_tags(BBCode::convert($notification["name"]));
444                                 $notification["message"] = format_notification_message($notification["name"], strip_tags(BBCode::convert($notification["msg"])));
445
446                                 q(
447                                         "UPDATE `notify` SET `name_cache` = '%s', `msg_cache` = '%s' WHERE `id` = %d",
448                                         DBA::escape($notification["name"]),
449                                         DBA::escape($notification["message"]),
450                                         intval($notification["id"])
451                                 );
452                         }
453
454                         $notification["href"] = System::baseUrl() . "/notify/view/" . $notification["id"];
455
456                         if ($notification["visible"]
457                                 && !$notification["deleted"]
458                                 && empty($result[$notification["parent"]])
459                         ) {
460                                 // Should we condense the notifications or show them all?
461                                 if (PConfig::get(local_user(), 'system', 'detailed_notif')) {
462                                         $result[$notification["id"]] = $notification;
463                                 } else {
464                                         $result[$notification["parent"]] = $notification;
465                                 }
466                         }
467                 }
468         } while ((count($result) < 50) && !$quit);
469
470         return($result);
471 }
472
473 /**
474  * @brief Backward-compatible XML formatting for ping.php output
475  * @deprecated
476  *
477  * @param array $data            The initial ping data array
478  * @param int   $sysnotify_count Number of unseen system notifications
479  * @param array $notifs          Complete list of notification
480  * @param array $sysmsgs         List of system notice messages
481  * @param array $sysmsgs_info    List of system info messages
482  * @param array $groups_unseen   List of unseen group messages
483  * @param array $forums_unseen   List of unseen forum messages
484  *
485  * @return array XML-transform ready data array
486  */
487 function ping_format_xml_data($data, $sysnotify_count, $notifs, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen)
488 {
489         $notifications = [];
490         foreach ($notifs as $key => $notif) {
491                 $notifications[$key . ':note'] = $notif['message'];
492
493                 $notifications[$key . ':@attributes'] = [
494                         'id'        => $notif['id'],
495                         'href'      => $notif['href'],
496                         'name'      => $notif['name'],
497                         'url'       => $notif['url'],
498                         'photo'     => $notif['photo'],
499                         'date'      => $notif['date'],
500                         'seen'      => $notif['seen'],
501                         'timestamp' => $notif['timestamp']
502                 ];
503         }
504
505         $sysmsg = [];
506         foreach ($sysmsgs as $key => $m) {
507                 $sysmsg[$key . ':notice'] = $m;
508         }
509         foreach ($sysmsgs_info as $key => $m) {
510                 $sysmsg[$key . ':info'] = $m;
511         }
512
513         $data['notif'] = $notifications;
514         $data['@attributes'] = ['count' => $sysnotify_count + $data['intro'] + $data['mail'] + $data['register']];
515         $data['sysmsgs'] = $sysmsg;
516
517         if ($data['register'] == 0) {
518                 unset($data['register']);
519         }
520
521         $groups = [];
522         if (count($groups_unseen)) {
523                 foreach ($groups_unseen as $key => $item) {
524                         $groups[$key . ':group'] = $item['count'];
525                         $groups[$key . ':@attributes'] = ['id' => $item['id']];
526                 }
527                 $data['groups'] = $groups;
528         }
529
530         $forums = [];
531         if (count($forums_unseen)) {
532                 foreach ($forums_unseen as $key => $item) {
533                         $forums[$key . ':forum'] = $item['count'];
534                         $forums[$key . ':@attributes'] = ['id' => $item['id']];
535                 }
536                 $data['forums'] = $forums;
537         }
538
539         return $data;
540 }