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