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