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