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