]> git.mxchange.org Git - friendica.git/blob - mod/ping.php
Fix wrong mode for App since local conf file wasn't present
[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 (Config::get('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                                         'id'      => 0,
282                                         'href'    => System::baseUrl() . '/notifications/intros/' . $intro['id'],
283                                         'name'    => $intro['name'],
284                                         'url'     => $intro['url'],
285                                         'photo'   => $intro['photo'],
286                                         'date'    => $intro['datetime'],
287                                         'seen'    => false,
288                                         'message' => L10n::t('{0} wants to be your friend'),
289                                 ];
290                                 $notifs[] = $notif;
291                         }
292                 }
293
294                 if (DBM::is_result($mails)) {
295                         foreach ($mails as $mail) {
296                                 $notif = [
297                                         'id'      => 0,
298                                         'href'    => System::baseUrl() . '/message/' . $mail['id'],
299                                         'name'    => $mail['from-name'],
300                                         'url'     => $mail['from-url'],
301                                         'photo'   => $mail['from-photo'],
302                                         'date'    => $mail['created'],
303                                         'seen'    => false,
304                                         'message' => L10n::t('{0} sent you a message'),
305                                 ];
306                                 $notifs[] = $notif;
307                         }
308                 }
309
310                 if (DBM::is_result($regs)) {
311                         foreach ($regs as $reg) {
312                                 $notif = [
313                                         'id'      => 0,
314                                         'href'    => System::baseUrl() . '/admin/users/',
315                                         'name'    => $reg['name'],
316                                         'url'     => $reg['url'],
317                                         'photo'   => $reg['micro'],
318                                         'date'    => $reg['created'],
319                                         'seen'    => false,
320                                         'message' => L10n::t('{0} requested registration'),
321                                 ];
322                                 $notifs[] = $notif;
323                         }
324                 }
325
326                 // sort notifications by $[]['date']
327                 $sort_function = function ($a, $b) {
328                         $adate = strtotime($a['date']);
329                         $bdate = strtotime($b['date']);
330
331                         // Unseen messages are kept at the top
332                         // The value 31536000 means one year. This should be enough :-)
333                         if (!$a['seen']) {
334                                 $adate += 31536000;
335                         }
336                         if (!$b['seen']) {
337                                 $bdate += 31536000;
338                         }
339
340                         if ($adate == $bdate) {
341                                 return 0;
342                         }
343                         return ($adate < $bdate) ? 1 : -1;
344                 };
345                 usort($notifs, $sort_function);
346
347                 if (DBM::is_result($notifs)) {
348                         // Are the nofications called from the regular process or via the friendica app?
349                         $regularnotifications = (intval($_GET['uid']) && intval($_GET['_']));
350
351                         foreach ($notifs as $notif) {
352                                 if ($a->is_friendica_app() || !$regularnotifications) {
353                                         $notif['message'] = str_replace("{0}", $notif['name'], $notif['message']);
354                                 }
355
356                                 $contact = Contact::getDetailsByURL($notif['url']);
357                                 if (isset($contact['micro'])) {
358                                         $notif['photo'] = proxy_url($contact['micro'], false, PROXY_SIZE_MICRO);
359                                 } else {
360                                         $notif['photo'] = proxy_url($notif['photo'], false, PROXY_SIZE_MICRO);
361                                 }
362
363                                 $local_time = DateTimeFormat::local($notif['date']);
364
365                                 $notifications[] = [
366                                         'id'        => $notif['id'],
367                                         'href'      => $notif['href'],
368                                         'name'      => $notif['name'],
369                                         'url'       => $notif['url'],
370                                         'photo'     => $notif['photo'],
371                                         'date'      => Temporal::getRelativeDate($notif['date']),
372                                         'message'   => $notif['message'],
373                                         'seen'      => $notif['seen'],
374                                         'timestamp' => strtotime($local_time)
375                                 ];
376                         }
377                 }
378         }
379
380         $sysmsgs = [];
381         $sysmsgs_info = [];
382
383         if (x($_SESSION, 'sysmsg')) {
384                 $sysmsgs = $_SESSION['sysmsg'];
385                 unset($_SESSION['sysmsg']);
386         }
387
388         if (x($_SESSION, 'sysmsg_info')) {
389                 $sysmsgs_info = $_SESSION['sysmsg_info'];
390                 unset($_SESSION['sysmsg_info']);
391         }
392
393         if ($format == 'json') {
394                 $data['groups'] = $groups_unseen;
395                 $data['forums'] = $forums_unseen;
396                 $data['notify'] = $sysnotify_count + $intro_count + $mail_count + $register_count;
397                 $data['notifications'] = $notifications;
398                 $data['sysmsgs'] = [
399                         'notice' => $sysmsgs,
400                         'info' => $sysmsgs_info
401                 ];
402
403                 $json_payload = json_encode(["result" => $data]);
404
405                 if (isset($_GET['callback'])) {
406                         // JSONP support
407                         header("Content-type: application/javascript");
408                         echo $_GET['callback'] . '(' . $json_payload . ')';
409                 } else {
410                         header("Content-type: application/json");
411                         echo $json_payload;
412                 }
413         } else {
414                 // Legacy slower XML format output
415                 $data = ping_format_xml_data($data, $sysnotify_count, $notifications, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen);
416
417                 header("Content-type: text/xml");
418                 echo XML::fromArray(["result" => $data], $xml);
419         }
420
421         killme();
422 }
423
424 /**
425  * @brief Retrieves the notifications array for the given user ID
426  *
427  * @param int $uid User id
428  * @return array Associative array of notifications
429  */
430 function ping_get_notifications($uid)
431 {
432         $result  = [];
433         $offset  = 0;
434         $seen    = false;
435         $seensql = "NOT";
436         $order   = "DESC";
437         $quit    = false;
438
439         $a = get_app();
440
441         do {
442                 $r = q(
443                         "SELECT `notify`.*, `item`.`visible`, `item`.`deleted`
444                         FROM `notify` LEFT JOIN `item` ON `item`.`id` = `notify`.`iid`
445                         WHERE `notify`.`uid` = %d AND `notify`.`msg` != ''
446                         AND NOT (`notify`.`type` IN (%d, %d))
447                         AND $seensql `notify`.`seen` ORDER BY `notify`.`date` $order LIMIT %d, 50",
448                         intval($uid),
449                         intval(NOTIFY_INTRO),
450                         intval(NOTIFY_MAIL),
451                         intval($offset)
452                 );
453
454                 if (!$r && !$seen) {
455                         $seen = true;
456                         $seensql = "";
457                         $order = "DESC";
458                         $offset = 0;
459                 } elseif (!$r) {
460                         $quit = true;
461                 } else {
462                         $offset += 50;
463                 }
464
465                 foreach ($r as $notification) {
466                         if (is_null($notification["visible"])) {
467                                 $notification["visible"] = true;
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::convert($notification["name"]));
479                                 $notification["message"] = format_notification_message($notification["name"], strip_tags(BBCode::convert($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"]
492                                 && !$notification["deleted"]
493                                 && !(x($result, $notification["parent"]) && !empty($result[$notification["parent"]]))
494                         ) {
495                                 // Should we condense the notifications or show them all?
496                                 if (PConfig::get(local_user(), 'system', 'detailed_notif')) {
497                                         $result[$notification["id"]] = $notification;
498                                 } else {
499                                         $result[$notification["parent"]] = $notification;
500                                 }
501                         }
502                 }
503         } while ((count($result) < 50) && !$quit);
504
505         return($result);
506 }
507
508 /**
509  * @brief Backward-compatible XML formatting for ping.php output
510  * @deprecated
511  *
512  * @param array $data          The initial ping data array
513  * @param int   $sysnotify     Number of unseen system notifications
514  * @param array $notifs        Complete list of notification
515  * @param array $sysmsgs       List of system notice messages
516  * @param array $sysmsgs_info  List of system info messages
517  * @param int   $groups_unseen Number of unseen group items
518  * @param int   $forums_unseen Number of unseen forum items
519  * @return array XML-transform ready data array
520  */
521 function ping_format_xml_data($data, $sysnotify, $notifs, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen)
522 {
523         $notifications = [];
524         foreach ($notifs as $key => $notif) {
525                 $notifications[$key . ':note'] = $notif['message'];
526
527                 $notifications[$key . ':@attributes'] = [
528                         'id'        => $notif['id'],
529                         'href'      => $notif['href'],
530                         'name'      => $notif['name'],
531                         'url'       => $notif['url'],
532                         'photo'     => $notif['photo'],
533                         'date'      => $notif['date'],
534                         'seen'      => $notif['seen'],
535                         'timestamp' => $notif['timestamp']
536                 ];
537         }
538
539         $sysmsg = [];
540         foreach ($sysmsgs as $key => $m) {
541                 $sysmsg[$key . ':notice'] = $m;
542         }
543         foreach ($sysmsgs_info as $key => $m) {
544                 $sysmsg[$key . ':info'] = $m;
545         }
546
547         $data['notif'] = $notifications;
548         $data['@attributes'] = ['count' => $sysnotify_count + $data['intro'] + $data['mail'] + $data['register']];
549         $data['sysmsgs'] = $sysmsg;
550
551         if ($data['register'] == 0) {
552                 unset($data['register']);
553         }
554
555         $groups = [];
556         if (count($groups_unseen)) {
557                 foreach ($groups_unseen as $key => $item) {
558                         $groups[$key . ':group'] = $item['count'];
559                         $groups[$key . ':@attributes'] = ['id' => $item['id']];
560                 }
561                 $data['groups'] = $groups;
562         }
563
564         $forums = [];
565         if (count($forums_unseen)) {
566                 foreach ($forums_unseen as $key => $item) {
567                         $forums[$key . ':forum'] = $item['count'];
568                         $forums[$key . ':@attributes'] = ['id' => $item['id']];
569                 }
570                 $data['forums'] = $forums;
571         }
572
573         return $data;
574 }