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\Hook;
11 use Friendica\Database\DBA;
13 use Friendica\Model\Contact;
14 use Friendica\Model\Group;
15 use Friendica\Model\Item;
16 use Friendica\Model\Notify\Type;
17 use Friendica\Util\DateTimeFormat;
18 use Friendica\Util\Temporal;
19 use Friendica\Util\Proxy as ProxyUtils;
20 use Friendica\Util\XML;
23 * Outputs the counts and the lists of various notifications
25 * The output format can be controlled via the GET parameter 'format'. It can be
26 * - xml (deprecated legacy default)
27 * - json (outputs JSONP with the 'callback' GET parameter)
29 * Expected JSON structure:
38 * "all-events-today": 0,
42 * "birthdays-today": 0,
46 * "notifications": [ ],
54 * @param App $a The Friendica App instance
55 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
57 function ping_init(App $a)
61 if (isset($_GET['format']) && $_GET['format'] == 'json') {
78 $all_events_today = 0;
85 $data['intro'] = $intro_count;
86 $data['mail'] = $mail_count;
87 $data['net'] = $network_count;
88 $data['home'] = $home_count;
89 $data['register'] = $register_count;
91 $data['all-events'] = $all_events;
92 $data['all-events-today'] = $all_events_today;
93 $data['events'] = $events;
94 $data['events-today'] = $events_today;
95 $data['birthdays'] = $birthdays;
96 $data['birthdays-today'] = $birthdays_today;
99 // Different login session than the page that is calling us.
100 if (!empty($_GET['uid']) && intval($_GET['uid']) != local_user()) {
101 $data = ['result' => ['invalid' => 1]];
103 if ($format == 'json') {
104 if (isset($_GET['callback'])) {
106 header("Content-type: application/javascript");
107 echo $_GET['callback'] . '(' . json_encode($data) . ')';
109 header("Content-type: application/json");
110 echo json_encode($data);
113 header("Content-type: text/xml");
114 echo XML::fromArray($data, $xml);
119 $notifs = ping_get_notifications(local_user());
121 $condition = ["`unseen` AND `uid` = ? AND `contact-id` != ?", local_user(), local_user()];
122 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
123 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid', 'wall'];
124 $params = ['order' => ['received' => true]];
125 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
127 if (DBA::isResult($items)) {
128 $items_unseen = Item::inArray($items);
129 $arr = ['items' => $items_unseen];
130 Hook::callAll('network_ping', $arr);
132 foreach ($items_unseen as $item) {
141 if ($network_count) {
142 // Find out how unseen network posts are spread across groups
143 $group_counts = Group::countUnseen();
144 if (DBA::isResult($group_counts)) {
145 foreach ($group_counts as $group_count) {
146 if ($group_count['count'] > 0) {
147 $groups_unseen[] = $group_count;
152 $forum_counts = ForumManager::countUnseenItems();
153 if (DBA::isResult($forum_counts)) {
154 foreach ($forum_counts as $forum_count) {
155 if ($forum_count['count'] > 0) {
156 $forums_unseen[] = $forum_count;
163 "SELECT `intro`.`id`, `intro`.`datetime`,
164 `fcontact`.`name`, `fcontact`.`url`, `fcontact`.`photo`
165 FROM `intro` LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
166 WHERE `intro`.`uid` = %d AND `intro`.`blocked` = 0 AND `intro`.`ignore` = 0 AND `intro`.`fid` != 0",
170 "SELECT `intro`.`id`, `intro`.`datetime`,
171 `contact`.`name`, `contact`.`url`, `contact`.`photo`
172 FROM `intro` LEFT JOIN `contact` ON `intro`.`contact-id` = `contact`.`id`
173 WHERE `intro`.`uid` = %d AND `intro`.`blocked` = 0 AND `intro`.`ignore` = 0 AND `intro`.`contact-id` != 0",
177 $intro_count = count($intros1) + count($intros2);
178 $intros = $intros1 + $intros2;
180 $myurl = DI::baseUrl() . '/profile/' . $a->user['nickname'];
182 "SELECT `id`, `from-name`, `from-url`, `from-photo`, `created` FROM `mail`
183 WHERE `uid` = %d AND `seen` = 0 AND `from-url` != '%s' ",
184 intval(local_user()),
187 $mail_count = count($mails);
189 if (intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::APPROVE && is_site_admin()) {
190 $regs = Friendica\Model\Register::getPending();
192 if (DBA::isResult($regs)) {
193 $register_count = count($regs);
197 $cachekey = "ping_init:".local_user();
198 $ev = DI::cache()->get($cachekey);
201 "SELECT type, start, adjust FROM `event`
202 WHERE `event`.`uid` = %d AND `start` < '%s' AND `finish` > '%s' and `ignore` = 0
203 ORDER BY `start` ASC ",
204 intval(local_user()),
205 DBA::escape(DateTimeFormat::utc('now + 7 days')),
206 DBA::escape(DateTimeFormat::utcNow())
208 if (DBA::isResult($ev)) {
209 DI::cache()->set($cachekey, $ev, Duration::HOUR);
213 if (DBA::isResult($ev)) {
214 $all_events = count($ev);
217 $str_now = DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d');
218 foreach ($ev as $x) {
220 if ($x['type'] === 'birthday') {
226 if (DateTimeFormat::convert($x['start'], ((intval($x['adjust'])) ? $a->timezone : 'UTC'), 'UTC', 'Y-m-d') === $str_now) {
227 $all_events_today ++;
238 $data['intro'] = $intro_count;
239 $data['mail'] = $mail_count;
240 $data['net'] = $network_count;
241 $data['home'] = $home_count;
242 $data['register'] = $register_count;
244 $data['all-events'] = $all_events;
245 $data['all-events-today'] = $all_events_today;
246 $data['events'] = $events;
247 $data['events-today'] = $events_today;
248 $data['birthdays'] = $birthdays;
249 $data['birthdays-today'] = $birthdays_today;
251 if (DBA::isResult($notifs)) {
252 foreach ($notifs as $notif) {
253 if ($notif['seen'] == 0) {
259 // merge all notification types in one array
260 if (DBA::isResult($intros)) {
261 foreach ($intros as $intro) {
264 'href' => DI::baseUrl() . '/notifications/intros/' . $intro['id'],
265 'name' => $intro['name'],
266 'url' => $intro['url'],
267 'photo' => $intro['photo'],
268 'date' => $intro['datetime'],
270 'message' => DI::l10n()->t('{0} wants to be your friend'),
276 if (DBA::isResult($regs)) {
277 foreach ($regs as $reg) {
280 'href' => DI::baseUrl() . '/admin/users/',
281 'name' => $reg['name'],
282 'url' => $reg['url'],
283 'photo' => $reg['micro'],
284 'date' => $reg['created'],
286 'message' => DI::l10n()->t('{0} requested registration'),
292 // sort notifications by $[]['date']
293 $sort_function = function ($a, $b) {
294 $adate = strtotime($a['date']);
295 $bdate = strtotime($b['date']);
297 // Unseen messages are kept at the top
298 // The value 31536000 means one year. This should be enough :-)
306 if ($adate == $bdate) {
309 return ($adate < $bdate) ? 1 : -1;
311 usort($notifs, $sort_function);
313 if (DBA::isResult($notifs)) {
314 foreach ($notifs as $notif) {
315 $contact = Contact::getDetailsByURL($notif['url']);
316 if (isset($contact['micro'])) {
317 $notif['photo'] = ProxyUtils::proxifyUrl($contact['micro'], false, ProxyUtils::SIZE_MICRO);
319 $notif['photo'] = ProxyUtils::proxifyUrl($notif['photo'], false, ProxyUtils::SIZE_MICRO);
322 $local_time = DateTimeFormat::local($notif['date']);
325 'id' => $notif['id'],
326 'href' => $notif['href'],
327 'name' => $notif['name'],
328 'url' => $notif['url'],
329 'photo' => $notif['photo'],
330 'date' => Temporal::getRelativeDate($notif['date']),
331 'message' => $notif['message'],
332 'seen' => $notif['seen'],
333 'timestamp' => strtotime($local_time)
342 if (!empty($_SESSION['sysmsg'])) {
343 $sysmsgs = $_SESSION['sysmsg'];
344 unset($_SESSION['sysmsg']);
347 if (!empty($_SESSION['sysmsg_info'])) {
348 $sysmsgs_info = $_SESSION['sysmsg_info'];
349 unset($_SESSION['sysmsg_info']);
352 if ($format == 'json') {
353 $data['groups'] = $groups_unseen;
354 $data['forums'] = $forums_unseen;
355 $data['notification'] = $sysnotify_count + $intro_count + $register_count;
356 $data['notifications'] = $notifications;
358 'notice' => $sysmsgs,
359 'info' => $sysmsgs_info
362 $json_payload = json_encode(["result" => $data]);
364 if (isset($_GET['callback'])) {
366 header("Content-type: application/javascript");
367 echo $_GET['callback'] . '(' . $json_payload . ')';
369 header("Content-type: application/json");
373 // Legacy slower XML format output
374 $data = ping_format_xml_data($data, $sysnotify_count, $notifications, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen);
376 header("Content-type: text/xml");
377 echo XML::fromArray(["result" => $data], $xml);
384 * Retrieves the notifications array for the given user ID
386 * @param int $uid User id
387 * @return array Associative array of notifications
388 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
390 function ping_get_notifications($uid)
401 "SELECT `notify`.*, `item`.`visible`, `item`.`deleted`
402 FROM `notify` LEFT JOIN `item` ON `item`.`id` = `notify`.`iid`
403 WHERE `notify`.`uid` = %d AND `notify`.`msg` != ''
404 AND NOT (`notify`.`type` IN (%d, %d))
405 AND $seensql `notify`.`seen` ORDER BY `notify`.`date` $order LIMIT %d, 50",
423 foreach ($r as $notification) {
424 if (is_null($notification["visible"])) {
425 $notification["visible"] = true;
428 if (is_null($notification["deleted"])) {
429 $notification["deleted"] = 0;
432 if ($notification["msg_cache"]) {
433 $notification["name"] = $notification["name_cache"];
434 $notification["message"] = $notification["msg_cache"];
436 $notification["name"] = strip_tags(BBCode::convert($notification["name"]));
437 $notification["message"] = Friendica\Model\Notify::formatMessage($notification["name"], strip_tags(BBCode::convert($notification["msg"])));
440 "UPDATE `notify` SET `name_cache` = '%s', `msg_cache` = '%s' WHERE `id` = %d",
441 DBA::escape($notification["name"]),
442 DBA::escape($notification["message"]),
443 intval($notification["id"])
447 $notification["href"] = DI::baseUrl() . "/notification/" . $notification["id"];
449 if ($notification["visible"]
450 && !$notification["deleted"]
451 && empty($result[$notification["parent"]])
453 // Should we condense the notifications or show them all?
454 if (DI::pConfig()->get(local_user(), 'system', 'detailed_notif')) {
455 $result[$notification["id"]] = $notification;
457 $result[$notification["parent"]] = $notification;
461 } while ((count($result) < 50) && !$quit);
467 * Backward-compatible XML formatting for ping.php output
470 * @param array $data The initial ping data array
471 * @param int $sysnotify_count Number of unseen system notifications
472 * @param array $notifs Complete list of notification
473 * @param array $sysmsgs List of system notice messages
474 * @param array $sysmsgs_info List of system info messages
475 * @param array $groups_unseen List of unseen group items
476 * @param array $forums_unseen List of unseen forum items
478 * @return array XML-transform ready data array
480 function ping_format_xml_data($data, $sysnotify_count, $notifs, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen)
483 foreach ($notifs as $key => $notif) {
484 $notifications[$key . ':note'] = $notif['message'];
486 $notifications[$key . ':@attributes'] = [
487 'id' => $notif['id'],
488 'href' => $notif['href'],
489 'name' => $notif['name'],
490 'url' => $notif['url'],
491 'photo' => $notif['photo'],
492 'date' => $notif['date'],
493 'seen' => $notif['seen'],
494 'timestamp' => $notif['timestamp']
499 foreach ($sysmsgs as $key => $m) {
500 $sysmsg[$key . ':notice'] = $m;
502 foreach ($sysmsgs_info as $key => $m) {
503 $sysmsg[$key . ':info'] = $m;
506 $data['notif'] = $notifications;
507 $data['@attributes'] = ['count' => $sysnotify_count + $data['intro'] + $data['mail'] + $data['register']];
508 $data['sysmsgs'] = $sysmsg;
510 if ($data['register'] == 0) {
511 unset($data['register']);
515 if (count($groups_unseen)) {
516 foreach ($groups_unseen as $key => $item) {
517 $groups[$key . ':group'] = $item['count'];
518 $groups[$key . ':@attributes'] = ['id' => $item['id']];
520 $data['groups'] = $groups;
524 if (count($forums_unseen)) {
525 foreach ($forums_unseen as $key => $item) {
526 $forums[$key . ':forum'] = $item['count'];
527 $forums[$key . ':@attributes'] = ['id' => $item['id']];
529 $data['forums'] = $forums;