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