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