3 * @file include/ping.php
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;
26 * @brief Outputs the counts and the lists of various notifications
28 * The output format can be controlled via the GET parameter 'format'. It can be
29 * - xml (deprecated legacy default)
30 * - json (outputs JSONP with the 'callback' GET parameter)
32 * Expected JSON structure:
41 * "all-events-today": 0,
45 * "birthdays-today": 0,
49 * "notifications": [ ],
57 * @param App $a The Friendica App instance
59 function ping_init(App $a)
63 if (isset($_GET['format']) && $_GET['format'] == 'json') {
87 $all_events_today = 0;
94 $data['intro'] = $intro_count;
95 $data['mail'] = $mail_count;
96 $data['net'] = $network_count;
97 $data['home'] = $home_count;
98 $data['register'] = $register_count;
100 $data['all-events'] = $all_events;
101 $data['all-events-today'] = $all_events_today;
102 $data['events'] = $events;
103 $data['events-today'] = $events_today;
104 $data['birthdays'] = $birthdays;
105 $data['birthdays-today'] = $birthdays_today;
108 // Different login session than the page that is calling us.
109 if (!empty($_GET['uid']) && intval($_GET['uid']) != local_user()) {
110 $data = ['result' => ['invalid' => 1]];
112 if ($format == 'json') {
113 if (isset($_GET['callback'])) {
115 header("Content-type: application/javascript");
116 echo $_GET['callback'] . '(' . json_encode($data) . ')';
118 header("Content-type: application/json");
119 echo json_encode($data);
122 header("Content-type: text/xml");
123 echo XML::fromArray($data, $xml);
128 $notifs = ping_get_notifications(local_user());
130 $condition = ["`unseen` AND `uid` = ? AND `contact-id` != ?", local_user(), local_user()];
131 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
132 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid', 'wall'];
133 $params = ['order' => ['created' => true]];
134 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
136 if (DBA::isResult($items)) {
137 $items_unseen = Item::inArray($items);
138 $arr = ['items' => $items_unseen];
139 Addon::callHooks('network_ping', $arr);
141 foreach ($items_unseen as $item) {
150 if ($network_count) {
151 // Find out how unseen network posts are spread across groups
152 $group_counts = Group::countUnseen();
153 if (DBA::isResult($group_counts)) {
154 foreach ($group_counts as $group_count) {
155 if ($group_count['count'] > 0) {
156 $groups_unseen[] = $group_count;
161 $forum_counts = ForumManager::countUnseenItems();
162 if (DBA::isResult($forum_counts)) {
163 foreach ($forum_counts as $forum_count) {
164 if ($forum_count['count'] > 0) {
165 $forums_unseen[] = $forum_count;
172 "SELECT `intro`.`id`, `intro`.`datetime`,
173 `fcontact`.`name`, `fcontact`.`url`, `fcontact`.`photo`
174 FROM `intro` LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
175 WHERE `intro`.`uid` = %d AND `intro`.`blocked` = 0 AND `intro`.`ignore` = 0 AND `intro`.`fid` != 0",
179 "SELECT `intro`.`id`, `intro`.`datetime`,
180 `contact`.`name`, `contact`.`url`, `contact`.`photo`
181 FROM `intro` LEFT JOIN `contact` ON `intro`.`contact-id` = `contact`.`id`
182 WHERE `intro`.`uid` = %d AND `intro`.`blocked` = 0 AND `intro`.`ignore` = 0 AND `intro`.`contact-id` != 0",
186 $intro_count = count($intros1) + count($intros2);
187 $intros = $intros1 + $intros2;
189 $myurl = System::baseUrl() . '/profile/' . $a->user['nickname'];
191 "SELECT `id`, `from-name`, `from-url`, `from-photo`, `created` FROM `mail`
192 WHERE `uid` = %d AND `seen` = 0 AND `from-url` != '%s' ",
193 intval(local_user()),
196 $mail_count = count($mails);
198 if (intval(Config::get('config', 'register_policy')) === REGISTER_APPROVE && is_site_admin()) {
199 $regs = Friendica\Model\Register::getPending();
201 if (DBA::isResult($regs)) {
202 $register_count = count($regs);
206 $cachekey = "ping_init:".local_user();
207 $ev = Cache::get($cachekey);
210 "SELECT type, start, adjust FROM `event`
211 WHERE `event`.`uid` = %d AND `start` < '%s' AND `finish` > '%s' and `ignore` = 0
212 ORDER BY `start` ASC ",
213 intval(local_user()),
214 DBA::escape(DateTimeFormat::utc('now + 7 days')),
215 DBA::escape(DateTimeFormat::utcNow())
217 if (DBA::isResult($ev)) {
218 Cache::set($cachekey, $ev, Cache::HOUR);
222 if (DBA::isResult($ev)) {
223 $all_events = count($ev);
226 $str_now = DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d');
227 foreach ($ev as $x) {
229 if ($x['type'] === 'birthday') {
235 if (DateTimeFormat::convert($x['start'], ((intval($x['adjust'])) ? $a->timezone : 'UTC'), 'UTC', 'Y-m-d') === $str_now) {
236 $all_events_today ++;
247 $data['intro'] = $intro_count;
248 $data['mail'] = $mail_count;
249 $data['net'] = $network_count;
250 $data['home'] = $home_count;
251 $data['register'] = $register_count;
253 $data['all-events'] = $all_events;
254 $data['all-events-today'] = $all_events_today;
255 $data['events'] = $events;
256 $data['events-today'] = $events_today;
257 $data['birthdays'] = $birthdays;
258 $data['birthdays-today'] = $birthdays_today;
260 if (DBA::isResult($notifs)) {
261 foreach ($notifs as $notif) {
262 if ($notif['seen'] == 0) {
268 // merge all notification types in one array
269 if (DBA::isResult($intros)) {
270 foreach ($intros as $intro) {
273 'href' => System::baseUrl() . '/notifications/intros/' . $intro['id'],
274 'name' => $intro['name'],
275 'url' => $intro['url'],
276 'photo' => $intro['photo'],
277 'date' => $intro['datetime'],
279 'message' => L10n::t('{0} wants to be your friend'),
285 if (DBA::isResult($mails)) {
286 foreach ($mails as $mail) {
289 'href' => System::baseUrl() . '/message/' . $mail['id'],
290 'name' => $mail['from-name'],
291 'url' => $mail['from-url'],
292 'photo' => $mail['from-photo'],
293 'date' => $mail['created'],
295 'message' => L10n::t('{0} sent you a message'),
301 if (DBA::isResult($regs)) {
302 foreach ($regs as $reg) {
305 'href' => System::baseUrl() . '/admin/users/',
306 'name' => $reg['name'],
307 'url' => $reg['url'],
308 'photo' => $reg['micro'],
309 'date' => $reg['created'],
311 'message' => L10n::t('{0} requested registration'),
317 // sort notifications by $[]['date']
318 $sort_function = function ($a, $b) {
319 $adate = strtotime($a['date']);
320 $bdate = strtotime($b['date']);
322 // Unseen messages are kept at the top
323 // The value 31536000 means one year. This should be enough :-)
331 if ($adate == $bdate) {
334 return ($adate < $bdate) ? 1 : -1;
336 usort($notifs, $sort_function);
338 if (DBA::isResult($notifs)) {
339 // Are the nofications called from the regular process or via the friendica app?
340 $regularnotifications = (!empty($_GET['uid']) && !empty($_GET['_']));
342 foreach ($notifs as $notif) {
343 if ($a->isFriendicaApp() || !$regularnotifications) {
344 $notif['message'] = str_replace("{0}", $notif['name'], $notif['message']);
347 $contact = Contact::getDetailsByURL($notif['url']);
348 if (isset($contact['micro'])) {
349 $notif['photo'] = ProxyUtils::proxifyUrl($contact['micro'], false, ProxyUtils::SIZE_MICRO);
351 $notif['photo'] = ProxyUtils::proxifyUrl($notif['photo'], false, ProxyUtils::SIZE_MICRO);
354 $local_time = DateTimeFormat::local($notif['date']);
357 'id' => $notif['id'],
358 'href' => $notif['href'],
359 'name' => $notif['name'],
360 'url' => $notif['url'],
361 'photo' => $notif['photo'],
362 'date' => Temporal::getRelativeDate($notif['date']),
363 'message' => $notif['message'],
364 'seen' => $notif['seen'],
365 'timestamp' => strtotime($local_time)
374 if (!empty($_SESSION['sysmsg'])) {
375 $sysmsgs = $_SESSION['sysmsg'];
376 unset($_SESSION['sysmsg']);
379 if (!empty($_SESSION['sysmsg_info'])) {
380 $sysmsgs_info = $_SESSION['sysmsg_info'];
381 unset($_SESSION['sysmsg_info']);
384 if ($format == 'json') {
385 $data['groups'] = $groups_unseen;
386 $data['forums'] = $forums_unseen;
387 $data['notify'] = $sysnotify_count + $intro_count + $mail_count + $register_count;
388 $data['notifications'] = $notifications;
390 'notice' => $sysmsgs,
391 'info' => $sysmsgs_info
394 $json_payload = json_encode(["result" => $data]);
396 if (isset($_GET['callback'])) {
398 header("Content-type: application/javascript");
399 echo $_GET['callback'] . '(' . $json_payload . ')';
401 header("Content-type: application/json");
405 // Legacy slower XML format output
406 $data = ping_format_xml_data($data, $sysnotify_count, $notifications, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen);
408 header("Content-type: text/xml");
409 echo XML::fromArray(["result" => $data], $xml);
416 * @brief Retrieves the notifications array for the given user ID
418 * @param int $uid User id
419 * @return array Associative array of notifications
421 function ping_get_notifications($uid)
434 "SELECT `notify`.*, `item`.`visible`, `item`.`deleted`
435 FROM `notify` LEFT JOIN `item` ON `item`.`id` = `notify`.`iid`
436 WHERE `notify`.`uid` = %d AND `notify`.`msg` != ''
437 AND NOT (`notify`.`type` IN (%d, %d))
438 AND $seensql `notify`.`seen` ORDER BY `notify`.`date` $order LIMIT %d, 50",
440 intval(NOTIFY_INTRO),
456 foreach ($r as $notification) {
457 if (is_null($notification["visible"])) {
458 $notification["visible"] = true;
461 if (is_null($notification["deleted"])) {
462 $notification["deleted"] = 0;
465 if ($notification["msg_cache"]) {
466 $notification["name"] = $notification["name_cache"];
467 $notification["message"] = $notification["msg_cache"];
469 $notification["name"] = strip_tags(BBCode::convert($notification["name"]));
470 $notification["message"] = format_notification_message($notification["name"], strip_tags(BBCode::convert($notification["msg"])));
473 "UPDATE `notify` SET `name_cache` = '%s', `msg_cache` = '%s' WHERE `id` = %d",
474 DBA::escape($notification["name"]),
475 DBA::escape($notification["message"]),
476 intval($notification["id"])
480 $notification["href"] = System::baseUrl() . "/notify/view/" . $notification["id"];
482 if ($notification["visible"]
483 && !$notification["deleted"]
484 && empty($result[$notification["parent"]])
486 // Should we condense the notifications or show them all?
487 if (PConfig::get(local_user(), 'system', 'detailed_notif')) {
488 $result[$notification["id"]] = $notification;
490 $result[$notification["parent"]] = $notification;
494 } while ((count($result) < 50) && !$quit);
500 * @brief Backward-compatible XML formatting for ping.php output
503 * @param array $data The initial ping data array
504 * @param int $sysnotify_count Number of unseen system notifications
505 * @param array $notifs Complete list of notification
506 * @param array $sysmsgs List of system notice messages
507 * @param array $sysmsgs_info List of system info messages
508 * @param int $groups_unseen Number of unseen group items
509 * @param int $forums_unseen Number of unseen forum items
511 * @return array XML-transform ready data array
513 function ping_format_xml_data($data, $sysnotify_count, $notifs, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen)
516 foreach ($notifs as $key => $notif) {
517 $notifications[$key . ':note'] = $notif['message'];
519 $notifications[$key . ':@attributes'] = [
520 'id' => $notif['id'],
521 'href' => $notif['href'],
522 'name' => $notif['name'],
523 'url' => $notif['url'],
524 'photo' => $notif['photo'],
525 'date' => $notif['date'],
526 'seen' => $notif['seen'],
527 'timestamp' => $notif['timestamp']
532 foreach ($sysmsgs as $key => $m) {
533 $sysmsg[$key . ':notice'] = $m;
535 foreach ($sysmsgs_info as $key => $m) {
536 $sysmsg[$key . ':info'] = $m;
539 $data['notif'] = $notifications;
540 $data['@attributes'] = ['count' => $sysnotify_count + $data['intro'] + $data['mail'] + $data['register']];
541 $data['sysmsgs'] = $sysmsg;
543 if ($data['register'] == 0) {
544 unset($data['register']);
548 if (count($groups_unseen)) {
549 foreach ($groups_unseen as $key => $item) {
550 $groups[$key . ':group'] = $item['count'];
551 $groups[$key . ':@attributes'] = ['id' => $item['id']];
553 $data['groups'] = $groups;
557 if (count($forums_unseen)) {
558 foreach ($forums_unseen as $key => $item) {
559 $forums[$key . ':forum'] = $item['count'];
560 $forums[$key . ':@attributes'] = ['id' => $item['id']];
562 $data['forums'] = $forums;