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