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