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;
25 require_once 'include/enotify.php';
28 * @brief Outputs the counts and the lists of various notifications
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)
34 * Expected JSON structure:
43 * "all-events-today": 0,
47 * "birthdays-today": 0,
51 * "notifications": [ ],
59 * @param App $a The Friendica App instance
61 function ping_init(App $a)
65 if (isset($_GET['format']) && $_GET['format'] == 'json') {
89 $all_events_today = 0;
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;
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;
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]];
114 if ($format == 'json') {
115 if (isset($_GET['callback'])) {
117 header("Content-type: application/javascript");
118 echo $_GET['callback'] . '(' . json_encode($data) . ')';
120 header("Content-type: application/json");
121 echo json_encode($data);
124 header("Content-type: text/xml");
125 echo XML::fromArray($data, $xml);
130 $notifs = ping_get_notifications(local_user());
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);
138 if (DBA::isResult($items)) {
139 $items_unseen = Item::inArray($items);
140 $arr = ['items' => $items_unseen];
141 Addon::callHooks('network_ping', $arr);
143 foreach ($items_unseen as $item) {
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;
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;
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",
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",
192 $intro_count = count($intros1) + count($intros2);
193 $intros = $intros1 + $intros2;
195 $myurl = System::baseUrl() . '/profile/' . $a->user['nickname'] ;
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()),
202 $mail_count = count($mails);
204 if (intval(Config::get('config', 'register_policy')) === REGISTER_APPROVE && is_site_admin()) {
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"
211 if (DBA::isResult($regs)) {
212 $register_count = count($regs);
216 $cachekey = "ping_init:".local_user();
217 $ev = Cache::get($cachekey);
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())
227 if (DBA::isResult($ev)) {
228 Cache::set($cachekey, $ev, CACHE_HOUR);
232 if (DBA::isResult($ev)) {
233 $all_events = count($ev);
236 $str_now = DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d');
237 foreach ($ev as $x) {
239 if ($x['type'] === 'birthday') {
245 if (DateTimeFormat::convert($x['start'], ((intval($x['adjust'])) ? $a->timezone : 'UTC'), 'UTC', 'Y-m-d') === $str_now) {
246 $all_events_today ++;
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;
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;
270 if (DBA::isResult($notifs)) {
271 foreach ($notifs as $notif) {
272 if ($notif['seen'] == 0) {
278 // merge all notification types in one array
279 if (DBA::isResult($intros)) {
280 foreach ($intros as $intro) {
283 'href' => System::baseUrl() . '/notifications/intros/' . $intro['id'],
284 'name' => $intro['name'],
285 'url' => $intro['url'],
286 'photo' => $intro['photo'],
287 'date' => $intro['datetime'],
289 'message' => L10n::t('{0} wants to be your friend'),
295 if (DBA::isResult($mails)) {
296 foreach ($mails as $mail) {
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'],
305 'message' => L10n::t('{0} sent you a message'),
311 if (DBA::isResult($regs)) {
312 foreach ($regs as $reg) {
315 'href' => System::baseUrl() . '/admin/users/',
316 'name' => $reg['name'],
317 'url' => $reg['url'],
318 'photo' => $reg['micro'],
319 'date' => $reg['created'],
321 'message' => L10n::t('{0} requested registration'),
327 // sort notifications by $[]['date']
328 $sort_function = function ($a, $b) {
329 $adate = strtotime($a['date']);
330 $bdate = strtotime($b['date']);
332 // Unseen messages are kept at the top
333 // The value 31536000 means one year. This should be enough :-)
341 if ($adate == $bdate) {
344 return ($adate < $bdate) ? 1 : -1;
346 usort($notifs, $sort_function);
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['_']));
352 foreach ($notifs as $notif) {
353 if ($a->is_friendica_app() || !$regularnotifications) {
354 $notif['message'] = str_replace("{0}", $notif['name'], $notif['message']);
357 $contact = Contact::getDetailsByURL($notif['url']);
358 if (isset($contact['micro'])) {
359 $notif['photo'] = ProxyUtils::proxifyUrl($contact['micro'], false, ProxyUtils::SIZE_MICRO);
361 $notif['photo'] = ProxyUtils::proxifyUrl($notif['photo'], false, ProxyUtils::SIZE_MICRO);
364 $local_time = DateTimeFormat::local($notif['date']);
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)
384 if (x($_SESSION, 'sysmsg')) {
385 $sysmsgs = $_SESSION['sysmsg'];
386 unset($_SESSION['sysmsg']);
389 if (x($_SESSION, 'sysmsg_info')) {
390 $sysmsgs_info = $_SESSION['sysmsg_info'];
391 unset($_SESSION['sysmsg_info']);
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;
400 'notice' => $sysmsgs,
401 'info' => $sysmsgs_info
404 $json_payload = json_encode(["result" => $data]);
406 if (isset($_GET['callback'])) {
408 header("Content-type: application/javascript");
409 echo $_GET['callback'] . '(' . $json_payload . ')';
411 header("Content-type: application/json");
415 // Legacy slower XML format output
416 $data = ping_format_xml_data($data, $sysnotify_count, $notifications, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen);
418 header("Content-type: text/xml");
419 echo XML::fromArray(["result" => $data], $xml);
426 * @brief Retrieves the notifications array for the given user ID
428 * @param int $uid User id
429 * @return array Associative array of notifications
431 function ping_get_notifications($uid)
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",
450 intval(NOTIFY_INTRO),
466 foreach ($r as $notification) {
467 if (is_null($notification["visible"])) {
468 $notification["visible"] = true;
471 if (is_null($notification["deleted"])) {
472 $notification["deleted"] = 0;
475 if ($notification["msg_cache"]) {
476 $notification["name"] = $notification["name_cache"];
477 $notification["message"] = $notification["msg_cache"];
479 $notification["name"] = strip_tags(BBCode::convert($notification["name"]));
480 $notification["message"] = format_notification_message($notification["name"], strip_tags(BBCode::convert($notification["msg"])));
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"])
490 $notification["href"] = System::baseUrl() . "/notify/view/" . $notification["id"];
492 if ($notification["visible"]
493 && !$notification["deleted"]
494 && !(x($result, $notification["parent"]) && !empty($result[$notification["parent"]]))
496 // Should we condense the notifications or show them all?
497 if (PConfig::get(local_user(), 'system', 'detailed_notif')) {
498 $result[$notification["id"]] = $notification;
500 $result[$notification["parent"]] = $notification;
504 } while ((count($result) < 50) && !$quit);
510 * @brief Backward-compatible XML formatting for ping.php output
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
521 * @return array XML-transform ready data array
523 function ping_format_xml_data($data, $sysnotify_count, $notifs, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen)
526 foreach ($notifs as $key => $notif) {
527 $notifications[$key . ':note'] = $notif['message'];
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']
542 foreach ($sysmsgs as $key => $m) {
543 $sysmsg[$key . ':notice'] = $m;
545 foreach ($sysmsgs_info as $key => $m) {
546 $sysmsg[$key . ':info'] = $m;
549 $data['notif'] = $notifications;
550 $data['@attributes'] = ['count' => $sysnotify_count + $data['intro'] + $data['mail'] + $data['register']];
551 $data['sysmsgs'] = $sysmsg;
553 if ($data['register'] == 0) {
554 unset($data['register']);
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']];
563 $data['groups'] = $groups;
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']];
572 $data['forums'] = $forums;