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