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