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