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