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