]> git.mxchange.org Git - friendica.git/blob - mod/ping.php
Merge remote-tracking branch 'upstream/develop' into develop
[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 (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 = qu("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_count++;
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 = qu("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 = qu("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 = count($intros1) + count($intros2);
178                 $intros = $intros1 + $intros2;
179
180                 $myurl = $a->get_baseurl() . '/profile/' . $a->user['nickname'] ;
181                 $mails = qu("SELECT `id`, `from-name`, `from-url`, `from-photo`, `created` 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 = qu("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
193                         $register_count = 0;
194
195                         if (dbm::is_result($regs)) {
196                                 $register_count = $regs[0]['total'];
197                         }
198                 }
199
200                 $ev = qu("SELECT count(`event`.`id`) AS total, type, start, adjust FROM `event`
201                         WHERE `event`.`uid` = %d AND `start` < '%s' AND `finish` > '%s' and `ignore` = 0
202                         ORDER BY `start` ASC ",
203                         intval(local_user()),
204                         dbesc(datetime_convert('UTC', 'UTC', 'now + 7 days')),
205                         dbesc(datetime_convert('UTC', 'UTC', 'now'))
206                 );
207
208                 if (dbm::is_result($ev)) {
209                         $all_events = intval($ev[0]['total']);
210
211                         if ($all_events) {
212                                 $str_now = datetime_convert('UTC', $a->timezone, 'now', 'Y-m-d');
213                                 foreach($ev as $x) {
214                                         $bd = false;
215                                         if ($x['type'] === 'birthday') {
216                                                 $birthdays ++;
217                                                 $bd = true;
218                                         }
219                                         else {
220                                                 $events ++;
221                                         }
222                                         if (datetime_convert('UTC', ((intval($x['adjust'])) ? $a->timezone : 'UTC'), $x['start'], 'Y-m-d') === $str_now) {
223                                                 $all_events_today ++;
224                                                 if ($bd)
225                                                         $birthdays_today ++;
226                                                 else
227                                                         $events_today ++;
228                                         }
229                                 }
230                         }
231                 }
232
233                 $data['intro']    = $intro_count;
234                 $data['mail']     = $mail_count;
235                 $data['net']      = $network_count;
236                 $data['home']     = $home_count;
237                 $data['register'] = $register_count;
238
239                 $data['all-events']       = $all_events;
240                 $data['all-events-today'] = $all_events_today;
241                 $data['events']           = $events;
242                 $data['events-today']     = $events_today;
243                 $data['birthdays']        = $birthdays;
244                 $data['birthdays-today']  = $birthdays_today;
245
246                 if (dbm::is_result($notifs)) {
247                         foreach ($notifs as $notif) {
248                                 if ($notif['seen'] == 0) {
249                                         $sysnotify_count ++;
250                                 }
251                         }
252                 }
253
254                 // merge all notification types in one array
255                 if (dbm::is_result($intros)) {
256                         foreach ($intros as $intro) {
257                                 $notif = array(
258                                         'href'    => $a->get_baseurl() . '/notifications/intros/' . $intro['id'],
259                                         'name'    => $intro['name'],
260                                         'url'     => $intro['url'],
261                                         'photo'   => $intro['photo'],
262                                         'date'    => $intro['datetime'],
263                                         'seen'    => false,
264                                         'message' => t('{0} wants to be your friend'),
265                                 );
266                                 $notifs[] = $notif;
267                         }
268                 }
269
270                 if (dbm::is_result($mails)) {
271                         foreach ($mails as $mail) {
272                                 $notif = array(
273                                         'href'    => $a->get_baseurl() . '/message/' . $mail['id'],
274                                         'name'    => $mail['from-name'],
275                                         'url'     => $mail['from-url'],
276                                         'photo'   => $mail['from-photo'],
277                                         'date'    => $mail['created'],
278                                         'seen'    => false,
279                                         'message' => t('{0} sent you a message'),
280                                 );
281                                 $notifs[] = $notif;
282                         }
283                 }
284
285                 if (dbm::is_result($regs)) {
286                         foreach ($regs as $reg) {
287                                 $notif = array(
288                                         'href'    => $a->get_baseurl() . '/admin/users/',
289                                         'name'    => $reg['name'],
290                                         'url'     => $reg['url'],
291                                         'photo'   => $reg['micro'],
292                                         'date'    => $reg['created'],
293                                         'seen'    => false,
294                                         'message' => t('{0} requested registration'),
295                                 );
296                                 $notifs[] = $notif;
297                         }
298                 }
299
300                 // sort notifications by $[]['date']
301                 $sort_function = function($a, $b) {
302                         $adate = date($a['date']);
303                         $bdate = date($b['date']);
304                         if ($adate == $bdate) {
305                                 return 0;
306                         }
307                         return ($adate < $bdate) ? 1 : -1;
308                 };
309                 usort($notifs, $sort_function);
310
311                 if (dbm::is_result($notifs)) {
312                         // Are the nofications called from the regular process or via the friendica app?
313                         $regularnotifications = (intval($_GET['uid']) AND intval($_GET['_']));
314
315                         foreach ($notifs as $notif) {
316                                 if ($a->is_friendica_app() OR !$regularnotifications) {
317                                         $notif['message'] = str_replace("{0}", $notif['name'], $notif['message']);
318                                 }
319
320                                 $contact = get_contact_details_by_url($notif['url']);
321                                 if (isset($contact['micro'])) {
322                                         $notif['photo'] = proxy_url($contact['micro'], false, PROXY_SIZE_MICRO);
323                                 } else {
324                                         $notif['photo'] = proxy_url($notif['photo'], false, PROXY_SIZE_MICRO);
325                                 }
326
327                                 $local_time = datetime_convert('UTC', date_default_timezone_get(), $notif['date']);
328
329                                 $notifications[] = array(
330                                         'id'        => $notif['id'],
331                                         'href'      => $notif['href'],
332                                         'name'      => $notif['name'],
333                                         'url'       => $notif['url'],
334                                         'photo'     => $notif['photo'],
335                                         'date'      => relative_date($notif['date']),
336                                         'message'   => $notif['message'],
337                                         'seen'      => $notif['seen'],
338                                         'timestamp' => strtotime($local_time)
339                                 );
340                         }
341                 }
342         }
343
344         $sysmsgs = array();
345         $sysmsgs_info = array();
346
347         if (x($_SESSION, 'sysmsg')) {
348                 $sysmsgs = $_SESSION['sysmsg'];
349                 unset($_SESSION['sysmsg']);
350         }
351
352         if (x($_SESSION, 'sysmsg_info')) {
353                 $sysmsgs_info = $_SESSION['sysmsg_info'];
354                 unset($_SESSION['sysmsg_info']);
355         }
356
357         if ($format == 'json') {
358                 $data['groups'] = $groups_unseen;
359                 $data['forums'] = $forums_unseen;
360                 $data['notify'] = $sysnotify_count + $intro_count + $mail_count + $register_count;
361                 $data['notifications'] = $notifications;
362                 $data['sysmsgs'] = array(
363                         'notice' => $sysmsgs,
364                         'info' => $sysmsgs_info
365                 );
366
367                 $json_payload = json_encode(array("result" => $data));
368
369                 if (isset($_GET['callback'])) {
370                         // JSONP support
371                         header("Content-type: application/javascript");
372                         echo $_GET['callback'] . '(' . $json_payload . ')';
373                 } else {
374                         header("Content-type: application/json");
375                         echo $json_payload;
376                 }
377         } else {
378                 // Legacy slower XML format output
379                 $data = ping_format_xml_data($data, $sysnotify_count, $notifications, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen);
380
381                 header("Content-type: text/xml");
382                 echo xml::from_array(array("result" => $data), $xml);
383         }
384
385         killme();
386 }
387
388 /**
389  * @brief Retrieves the notifications array for the given user ID
390  *
391  * @param int $uid User id
392  * @return array Associative array of notifications
393  */
394 function ping_get_notifications($uid)
395 {
396         $result  = array();
397         $offset  = 0;
398         $seen    = false;
399         $seensql = "NOT";
400         $order   = "DESC";
401         $quit    = false;
402
403         $a = get_app();
404
405         do {
406                 $r = qu("SELECT `notify`.*, `item`.`visible`, `item`.`spam`, `item`.`deleted`
407                         FROM `notify` LEFT JOIN `item` ON `item`.`id` = `notify`.`iid`
408                         WHERE `notify`.`uid` = %d AND `notify`.`msg` != ''
409                         AND NOT (`notify`.`type` IN (%d, %d))
410                         AND $seensql `notify`.`seen` ORDER BY `notify`.`date` $order LIMIT %d, 50",
411                         intval($uid),
412                         intval(NOTIFY_INTRO),
413                         intval(NOTIFY_MAIL),
414                         intval($offset)
415                 );
416
417                 if (!$r AND !$seen) {
418                         $seen = true;
419                         $seensql = "";
420                         $order = "DESC";
421                         $offset = 0;
422                 } elseif (!$r) {
423                         $quit = true;
424                 } else {
425                         $offset += 50;
426                 }
427
428                 foreach ($r AS $notification) {
429                         if (is_null($notification["visible"])) {
430                                 $notification["visible"] = true;
431                         }
432
433                         if (is_null($notification["spam"])) {
434                                 $notification["spam"] = 0;
435                         }
436
437                         if (is_null($notification["deleted"])) {
438                                 $notification["deleted"] = 0;
439                         }
440
441                         if ($notification["msg_cache"]) {
442                                 $notification["name"] = $notification["name_cache"];
443                                 $notification["message"] = $notification["msg_cache"];
444                         } else {
445                                 $notification["name"] = strip_tags(bbcode($notification["name"]));
446                                 $notification["message"] = format_notification_message($notification["name"], strip_tags(bbcode($notification["msg"])));
447
448                                 q("UPDATE `notify` SET `name_cache` = '%s', `msg_cache` = '%s' WHERE `id` = %d",
449                                         dbesc($notification["name"]),
450                                         dbesc($notification["message"]),
451                                         intval($notification["id"])
452                                 );
453                         }
454
455                         $notification["href"] = $a->get_baseurl() . "/notify/view/" . $notification["id"];
456
457                         if ($notification["visible"] AND !$notification["spam"] AND
458                                 !$notification["deleted"] AND !is_array($result[$notification["parent"]])) {
459                                 $result[$notification["parent"]] = $notification;
460                         }
461                 }
462         } while ((count($result) < 50) AND !$quit);
463
464         return($result);
465 }
466
467 /**
468  * @brief Backward-compatible XML formatting for ping.php output
469  * @deprecated
470  *
471  * @param array $data The initial ping data array
472  * @param int $sysnotify_count Number of unseen system notifications
473  * @param array $notifs Complete list of notification
474  * @param array $sysmsgs List of system notice messages
475  * @param array $sysmsgs_info List of system info messages
476  * @param int $groups_unseen Number of unseen group items
477  * @param int $forums_unseen Number of unseen forum items
478  * @return array XML-transform ready data array
479  */
480 function ping_format_xml_data($data, $sysnotify, $notifs, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen)
481 {
482         $notifications = array();
483         foreach($notifs as $key => $notif) {
484                 $notifications[$key . ':note'] = $notif['message'];
485
486                 $notifications[$key . ':@attributes'] = array(
487                         'id'        => $notif['id'],
488                         'href'      => $notif['href'],
489                         'name'      => $notif['name'],
490                         'url'       => $notif['url'],
491                         'photo'     => $notif['photo'],
492                         'date'      => $notif['date'],
493                         'seen'      => $notif['seen'],
494                         'timestamp' => $notif['timestamp']
495                 );
496         }
497
498         $sysmsg = array();
499         foreach ($sysmsgs as $key => $m){
500                 $sysmsg[$key . ':notice'] = $m;
501         }
502         foreach ($sysmsgs_info as $key => $m){
503                 $sysmsg[$key . ':info'] = $m;
504         }
505
506         $data['notif'] = $notifications;
507         $data['@attributes'] = array('count' => $sysnotify_count + $data['intro'] + $data['mail'] + $data['register']);
508         $data['sysmsgs'] = $sysmsg;
509
510         if ($data['register'] == 0) {
511                 unset($data['register']);
512         }
513
514         $groups = array();
515         if (count($groups_unseen)) {
516                 foreach ($groups_unseen as $key => $item) {
517                         $groups[$key . ':group'] = $item['count'];
518                         $groups[$key . ':@attributes'] = array('id' => $item['id']);
519                 }
520                 $data['groups'] = $groups;
521         }
522
523         $forums = array();
524         if (count($forums_unseen)) {
525                 foreach ($forums_unseen as $key => $item) {
526                         $forums[$count . ':forum'] = $item['count'];
527                         $forums[$count . ':@attributes'] = array('id' => $item['id']);
528                 }
529                 $data['forums'] = $forums;
530         }
531
532         return $data;
533 }