3 * @file include/ping.php
7 use Friendica\Content\ForumManager;
8 use Friendica\Content\Text\BBCode;
9 use Friendica\Core\Cache\Duration;
10 use Friendica\Core\Config;
11 use Friendica\Core\Hook;
12 use Friendica\Core\L10n;
13 use Friendica\Database\DBA;
15 use Friendica\Model\Contact;
16 use Friendica\Model\Group;
17 use Friendica\Model\Item;
18 use Friendica\Util\DateTimeFormat;
19 use Friendica\Util\Temporal;
20 use Friendica\Util\Proxy as ProxyUtils;
21 use Friendica\Util\XML;
24 * Outputs the counts and the lists of various notifications
26 * The output format can be controlled via the GET parameter 'format'. It can be
27 * - xml (deprecated legacy default)
28 * - json (outputs JSONP with the 'callback' GET parameter)
30 * Expected JSON structure:
39 * "all-events-today": 0,
43 * "birthdays-today": 0,
47 * "notifications": [ ],
55 * @param App $a The Friendica App instance
56 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
58 function ping_init(App $a)
62 if (isset($_GET['format']) && $_GET['format'] == 'json') {
79 $all_events_today = 0;
86 $data['intro'] = $intro_count;
87 $data['mail'] = $mail_count;
88 $data['net'] = $network_count;
89 $data['home'] = $home_count;
90 $data['register'] = $register_count;
92 $data['all-events'] = $all_events;
93 $data['all-events-today'] = $all_events_today;
94 $data['events'] = $events;
95 $data['events-today'] = $events_today;
96 $data['birthdays'] = $birthdays;
97 $data['birthdays-today'] = $birthdays_today;
100 // Different login session than the page that is calling us.
101 if (!empty($_GET['uid']) && intval($_GET['uid']) != local_user()) {
102 $data = ['result' => ['invalid' => 1]];
104 if ($format == 'json') {
105 if (isset($_GET['callback'])) {
107 header("Content-type: application/javascript");
108 echo $_GET['callback'] . '(' . json_encode($data) . ')';
110 header("Content-type: application/json");
111 echo json_encode($data);
114 header("Content-type: text/xml");
115 echo XML::fromArray($data, $xml);
120 $notifs = ping_get_notifications(local_user());
122 $condition = ["`unseen` AND `uid` = ? AND `contact-id` != ?", local_user(), local_user()];
123 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
124 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid', 'wall'];
125 $params = ['order' => ['received' => true]];
126 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
128 if (DBA::isResult($items)) {
129 $items_unseen = Item::inArray($items);
130 $arr = ['items' => $items_unseen];
131 Hook::callAll('network_ping', $arr);
133 foreach ($items_unseen as $item) {
142 if ($network_count) {
143 // Find out how unseen network posts are spread across groups
144 $group_counts = Group::countUnseen();
145 if (DBA::isResult($group_counts)) {
146 foreach ($group_counts as $group_count) {
147 if ($group_count['count'] > 0) {
148 $groups_unseen[] = $group_count;
153 $forum_counts = ForumManager::countUnseenItems();
154 if (DBA::isResult($forum_counts)) {
155 foreach ($forum_counts as $forum_count) {
156 if ($forum_count['count'] > 0) {
157 $forums_unseen[] = $forum_count;
164 "SELECT `intro`.`id`, `intro`.`datetime`,
165 `fcontact`.`name`, `fcontact`.`url`, `fcontact`.`photo`
166 FROM `intro` LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
167 WHERE `intro`.`uid` = %d AND `intro`.`blocked` = 0 AND `intro`.`ignore` = 0 AND `intro`.`fid` != 0",
171 "SELECT `intro`.`id`, `intro`.`datetime`,
172 `contact`.`name`, `contact`.`url`, `contact`.`photo`
173 FROM `intro` LEFT JOIN `contact` ON `intro`.`contact-id` = `contact`.`id`
174 WHERE `intro`.`uid` = %d AND `intro`.`blocked` = 0 AND `intro`.`ignore` = 0 AND `intro`.`contact-id` != 0",
178 $intro_count = count($intros1) + count($intros2);
179 $intros = $intros1 + $intros2;
181 $myurl = DI::baseUrl() . '/profile/' . $a->user['nickname'];
183 "SELECT `id`, `from-name`, `from-url`, `from-photo`, `created` FROM `mail`
184 WHERE `uid` = %d AND `seen` = 0 AND `from-url` != '%s' ",
185 intval(local_user()),
188 $mail_count = count($mails);
190 if (intval(Config::get('config', 'register_policy')) === \Friendica\Module\Register::APPROVE && is_site_admin()) {
191 $regs = Friendica\Model\Register::getPending();
193 if (DBA::isResult($regs)) {
194 $register_count = count($regs);
198 $cachekey = "ping_init:".local_user();
199 $ev = DI::cache()->get($cachekey);
202 "SELECT type, start, adjust FROM `event`
203 WHERE `event`.`uid` = %d AND `start` < '%s' AND `finish` > '%s' and `ignore` = 0
204 ORDER BY `start` ASC ",
205 intval(local_user()),
206 DBA::escape(DateTimeFormat::utc('now + 7 days')),
207 DBA::escape(DateTimeFormat::utcNow())
209 if (DBA::isResult($ev)) {
210 DI::cache()->set($cachekey, $ev, Duration::HOUR);
214 if (DBA::isResult($ev)) {
215 $all_events = count($ev);
218 $str_now = DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d');
219 foreach ($ev as $x) {
221 if ($x['type'] === 'birthday') {
227 if (DateTimeFormat::convert($x['start'], ((intval($x['adjust'])) ? $a->timezone : 'UTC'), 'UTC', 'Y-m-d') === $str_now) {
228 $all_events_today ++;
239 $data['intro'] = $intro_count;
240 $data['mail'] = $mail_count;
241 $data['net'] = $network_count;
242 $data['home'] = $home_count;
243 $data['register'] = $register_count;
245 $data['all-events'] = $all_events;
246 $data['all-events-today'] = $all_events_today;
247 $data['events'] = $events;
248 $data['events-today'] = $events_today;
249 $data['birthdays'] = $birthdays;
250 $data['birthdays-today'] = $birthdays_today;
252 if (DBA::isResult($notifs)) {
253 foreach ($notifs as $notif) {
254 if ($notif['seen'] == 0) {
260 // merge all notification types in one array
261 if (DBA::isResult($intros)) {
262 foreach ($intros as $intro) {
265 'href' => DI::baseUrl() . '/notifications/intros/' . $intro['id'],
266 'name' => $intro['name'],
267 'url' => $intro['url'],
268 'photo' => $intro['photo'],
269 'date' => $intro['datetime'],
271 'message' => DI::l10n()->t('{0} wants to be your friend'),
277 if (DBA::isResult($regs)) {
278 foreach ($regs as $reg) {
281 'href' => DI::baseUrl() . '/admin/users/',
282 'name' => $reg['name'],
283 'url' => $reg['url'],
284 'photo' => $reg['micro'],
285 'date' => $reg['created'],
287 'message' => DI::l10n()->t('{0} requested registration'),
293 // sort notifications by $[]['date']
294 $sort_function = function ($a, $b) {
295 $adate = strtotime($a['date']);
296 $bdate = strtotime($b['date']);
298 // Unseen messages are kept at the top
299 // The value 31536000 means one year. This should be enough :-)
307 if ($adate == $bdate) {
310 return ($adate < $bdate) ? 1 : -1;
312 usort($notifs, $sort_function);
314 if (DBA::isResult($notifs)) {
315 foreach ($notifs as $notif) {
316 $contact = Contact::getDetailsByURL($notif['url']);
317 if (isset($contact['micro'])) {
318 $notif['photo'] = ProxyUtils::proxifyUrl($contact['micro'], false, ProxyUtils::SIZE_MICRO);
320 $notif['photo'] = ProxyUtils::proxifyUrl($notif['photo'], false, ProxyUtils::SIZE_MICRO);
323 $local_time = DateTimeFormat::local($notif['date']);
326 'id' => $notif['id'],
327 'href' => $notif['href'],
328 'name' => $notif['name'],
329 'url' => $notif['url'],
330 'photo' => $notif['photo'],
331 'date' => Temporal::getRelativeDate($notif['date']),
332 'message' => $notif['message'],
333 'seen' => $notif['seen'],
334 'timestamp' => strtotime($local_time)
343 if (!empty($_SESSION['sysmsg'])) {
344 $sysmsgs = $_SESSION['sysmsg'];
345 unset($_SESSION['sysmsg']);
348 if (!empty($_SESSION['sysmsg_info'])) {
349 $sysmsgs_info = $_SESSION['sysmsg_info'];
350 unset($_SESSION['sysmsg_info']);
353 if ($format == 'json') {
354 $data['groups'] = $groups_unseen;
355 $data['forums'] = $forums_unseen;
356 $data['notify'] = $sysnotify_count + $intro_count + $register_count;
357 $data['notifications'] = $notifications;
359 'notice' => $sysmsgs,
360 'info' => $sysmsgs_info
363 $json_payload = json_encode(["result" => $data]);
365 if (isset($_GET['callback'])) {
367 header("Content-type: application/javascript");
368 echo $_GET['callback'] . '(' . $json_payload . ')';
370 header("Content-type: application/json");
374 // Legacy slower XML format output
375 $data = ping_format_xml_data($data, $sysnotify_count, $notifications, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen);
377 header("Content-type: text/xml");
378 echo XML::fromArray(["result" => $data], $xml);
385 * Retrieves the notifications array for the given user ID
387 * @param int $uid User id
388 * @return array Associative array of notifications
389 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
391 function ping_get_notifications($uid)
402 "SELECT `notify`.*, `item`.`visible`, `item`.`deleted`
403 FROM `notify` LEFT JOIN `item` ON `item`.`id` = `notify`.`iid`
404 WHERE `notify`.`uid` = %d AND `notify`.`msg` != ''
405 AND NOT (`notify`.`type` IN (%d, %d))
406 AND $seensql `notify`.`seen` ORDER BY `notify`.`date` $order LIMIT %d, 50",
408 intval(NOTIFY_INTRO),
424 foreach ($r as $notification) {
425 if (is_null($notification["visible"])) {
426 $notification["visible"] = true;
429 if (is_null($notification["deleted"])) {
430 $notification["deleted"] = 0;
433 if ($notification["msg_cache"]) {
434 $notification["name"] = $notification["name_cache"];
435 $notification["message"] = $notification["msg_cache"];
437 $notification["name"] = strip_tags(BBCode::convert($notification["name"]));
438 $notification["message"] = format_notification_message($notification["name"], strip_tags(BBCode::convert($notification["msg"])));
441 "UPDATE `notify` SET `name_cache` = '%s', `msg_cache` = '%s' WHERE `id` = %d",
442 DBA::escape($notification["name"]),
443 DBA::escape($notification["message"]),
444 intval($notification["id"])
448 $notification["href"] = DI::baseUrl() . "/notify/view/" . $notification["id"];
450 if ($notification["visible"]
451 && !$notification["deleted"]
452 && empty($result[$notification["parent"]])
454 // Should we condense the notifications or show them all?
455 if (DI::pConfig()->get(local_user(), 'system', 'detailed_notif')) {
456 $result[$notification["id"]] = $notification;
458 $result[$notification["parent"]] = $notification;
462 } while ((count($result) < 50) && !$quit);
468 * Backward-compatible XML formatting for ping.php output
471 * @param array $data The initial ping data array
472 * @param int $sysnotify_count Number of unseen system notifications
473 * @param array $notifs Complete list of notification
474 * @param array $sysmsgs List of system notice messages
475 * @param array $sysmsgs_info List of system info messages
476 * @param array $groups_unseen List of unseen group items
477 * @param array $forums_unseen List of unseen forum items
479 * @return array XML-transform ready data array
481 function ping_format_xml_data($data, $sysnotify_count, $notifs, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen)
484 foreach ($notifs as $key => $notif) {
485 $notifications[$key . ':note'] = $notif['message'];
487 $notifications[$key . ':@attributes'] = [
488 'id' => $notif['id'],
489 'href' => $notif['href'],
490 'name' => $notif['name'],
491 'url' => $notif['url'],
492 'photo' => $notif['photo'],
493 'date' => $notif['date'],
494 'seen' => $notif['seen'],
495 'timestamp' => $notif['timestamp']
500 foreach ($sysmsgs as $key => $m) {
501 $sysmsg[$key . ':notice'] = $m;
503 foreach ($sysmsgs_info as $key => $m) {
504 $sysmsg[$key . ':info'] = $m;
507 $data['notif'] = $notifications;
508 $data['@attributes'] = ['count' => $sysnotify_count + $data['intro'] + $data['mail'] + $data['register']];
509 $data['sysmsgs'] = $sysmsg;
511 if ($data['register'] == 0) {
512 unset($data['register']);
516 if (count($groups_unseen)) {
517 foreach ($groups_unseen as $key => $item) {
518 $groups[$key . ':group'] = $item['count'];
519 $groups[$key . ':@attributes'] = ['id' => $item['id']];
521 $data['groups'] = $groups;
525 if (count($forums_unseen)) {
526 foreach ($forums_unseen as $key => $item) {
527 $forums[$key . ':forum'] = $item['count'];
528 $forums[$key . ':@attributes'] = ['id' => $item['id']];
530 $data['forums'] = $forums;