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