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\L10n;
13 use Friendica\Core\PConfig;
14 use Friendica\Core\System;
15 use Friendica\Database\DBM;
16 use Friendica\Model\Contact;
17 use Friendica\Model\Group;
18 use Friendica\Model\Item;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\Temporal;
21 use Friendica\Util\XML;
23 require_once 'mod/proxy.php';
24 require_once 'include/enotify.php';
27 * @brief Outputs the counts and the lists of various notifications
29 * The output format can be controlled via the GET parameter 'format'. It can be
30 * - xml (deprecated legacy default)
31 * - json (outputs JSONP with the 'callback' GET parameter)
33 * Expected JSON structure:
42 * "all-events-today": 0,
46 * "birthdays-today": 0,
50 * "notifications": [ ],
58 * @param App $a The Friendica App instance
60 function ping_init(App $a)
64 if (isset($_GET['format']) && $_GET['format'] == 'json') {
88 $all_events_today = 0;
95 $data['intro'] = $intro_count;
96 $data['mail'] = $mail_count;
97 $data['net'] = $network_count;
98 $data['home'] = $home_count;
99 $data['register'] = $register_count;
101 $data['all-events'] = $all_events;
102 $data['all-events-today'] = $all_events_today;
103 $data['events'] = $events;
104 $data['events-today'] = $events_today;
105 $data['birthdays'] = $birthdays;
106 $data['birthdays-today'] = $birthdays_today;
109 // Different login session than the page that is calling us.
110 if (intval($_GET['uid']) && intval($_GET['uid']) != local_user()) {
111 $data = ['result' => ['invalid' => 1]];
113 if ($format == 'json') {
114 if (isset($_GET['callback'])) {
116 header("Content-type: application/javascript");
117 echo $_GET['callback'] . '(' . json_encode($data) . ')';
119 header("Content-type: application/json");
120 echo json_encode($data);
123 header("Content-type: text/xml");
124 echo XML::fromArray($data, $xml);
129 $notifs = ping_get_notifications(local_user());
131 $condition = ["`unseen` AND `uid` = ? AND `contact-id` != ?", local_user(), local_user()];
132 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
133 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
134 $params = ['order' => ['created' => true]];
135 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
137 if (DBM::is_result($items)) {
138 $items_unseen = Item::inArray($items);
139 $arr = ['items' => $items_unseen];
140 Addon::callHooks('network_ping', $arr);
142 foreach ($items_unseen as $item) {
151 if ($network_count) {
152 if (intval(Feature::isEnabled(local_user(), 'groups'))) {
153 // Find out how unseen network posts are spread across groups
154 $group_counts = Group::countUnseen();
155 if (DBM::is_result($group_counts)) {
156 foreach ($group_counts as $group_count) {
157 if ($group_count['count'] > 0) {
158 $groups_unseen[] = $group_count;
164 if (intval(Feature::isEnabled(local_user(), 'forumlist_widget'))) {
165 $forum_counts = ForumManager::countUnseenItems();
166 if (DBM::is_result($forum_counts)) {
167 foreach ($forum_counts as $forum_count) {
168 if ($forum_count['count'] > 0) {
169 $forums_unseen[] = $forum_count;
177 "SELECT `intro`.`id`, `intro`.`datetime`,
178 `fcontact`.`name`, `fcontact`.`url`, `fcontact`.`photo`
179 FROM `intro` LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
180 WHERE `intro`.`uid` = %d AND `intro`.`blocked` = 0 AND `intro`.`ignore` = 0 AND `intro`.`fid` != 0",
184 "SELECT `intro`.`id`, `intro`.`datetime`,
185 `contact`.`name`, `contact`.`url`, `contact`.`photo`
186 FROM `intro` LEFT JOIN `contact` ON `intro`.`contact-id` = `contact`.`id`
187 WHERE `intro`.`uid` = %d AND `intro`.`blocked` = 0 AND `intro`.`ignore` = 0 AND `intro`.`contact-id` != 0",
191 $intro_count = count($intros1) + count($intros2);
192 $intros = $intros1 + $intros2;
194 $myurl = System::baseUrl() . '/profile/' . $a->user['nickname'] ;
196 "SELECT `id`, `from-name`, `from-url`, `from-photo`, `created` FROM `mail`
197 WHERE `uid` = %d AND `seen` = 0 AND `from-url` != '%s' ",
198 intval(local_user()),
201 $mail_count = count($mails);
203 if ($a->config['register_policy'] == REGISTER_APPROVE && is_site_admin()) {
205 "SELECT `contact`.`name`, `contact`.`url`, `contact`.`micro`, `register`.`created`
206 FROM `contact` RIGHT JOIN `register` ON `register`.`uid` = `contact`.`uid`
207 WHERE `contact`.`self` = 1"
210 if (DBM::is_result($regs)) {
211 $register_count = count($regs);
215 $cachekey = "ping_init:".local_user();
216 $ev = Cache::get($cachekey);
219 "SELECT type, start, adjust FROM `event`
220 WHERE `event`.`uid` = %d AND `start` < '%s' AND `finish` > '%s' and `ignore` = 0
221 ORDER BY `start` ASC ",
222 intval(local_user()),
223 dbesc(DateTimeFormat::utc('now + 7 days')),
224 dbesc(DateTimeFormat::utcNow())
226 if (DBM::is_result($ev)) {
227 Cache::set($cachekey, $ev, CACHE_HOUR);
231 if (DBM::is_result($ev)) {
232 $all_events = count($ev);
235 $str_now = DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d');
236 foreach ($ev as $x) {
238 if ($x['type'] === 'birthday') {
244 if (DateTimeFormat::convert($x['start'], ((intval($x['adjust'])) ? $a->timezone : 'UTC'), 'UTC', 'Y-m-d') === $str_now) {
245 $all_events_today ++;
256 $data['intro'] = $intro_count;
257 $data['mail'] = $mail_count;
258 $data['net'] = $network_count;
259 $data['home'] = $home_count;
260 $data['register'] = $register_count;
262 $data['all-events'] = $all_events;
263 $data['all-events-today'] = $all_events_today;
264 $data['events'] = $events;
265 $data['events-today'] = $events_today;
266 $data['birthdays'] = $birthdays;
267 $data['birthdays-today'] = $birthdays_today;
269 if (DBM::is_result($notifs)) {
270 foreach ($notifs as $notif) {
271 if ($notif['seen'] == 0) {
277 // merge all notification types in one array
278 if (DBM::is_result($intros)) {
279 foreach ($intros as $intro) {
281 'href' => System::baseUrl() . '/notifications/intros/' . $intro['id'],
282 'name' => $intro['name'],
283 'url' => $intro['url'],
284 'photo' => $intro['photo'],
285 'date' => $intro['datetime'],
287 'message' => L10n::t('{0} wants to be your friend'),
293 if (DBM::is_result($mails)) {
294 foreach ($mails as $mail) {
296 'href' => System::baseUrl() . '/message/' . $mail['id'],
297 'name' => $mail['from-name'],
298 'url' => $mail['from-url'],
299 'photo' => $mail['from-photo'],
300 'date' => $mail['created'],
302 'message' => L10n::t('{0} sent you a message'),
308 if (DBM::is_result($regs)) {
309 foreach ($regs as $reg) {
311 'href' => System::baseUrl() . '/admin/users/',
312 'name' => $reg['name'],
313 'url' => $reg['url'],
314 'photo' => $reg['micro'],
315 'date' => $reg['created'],
317 'message' => L10n::t('{0} requested registration'),
323 // sort notifications by $[]['date']
324 $sort_function = function ($a, $b) {
325 $adate = strtotime($a['date']);
326 $bdate = strtotime($b['date']);
328 // Unseen messages are kept at the top
329 // The value 31536000 means one year. This should be enough :-)
337 if ($adate == $bdate) {
340 return ($adate < $bdate) ? 1 : -1;
342 usort($notifs, $sort_function);
344 if (DBM::is_result($notifs)) {
345 // Are the nofications called from the regular process or via the friendica app?
346 $regularnotifications = (intval($_GET['uid']) && intval($_GET['_']));
348 foreach ($notifs as $notif) {
349 if ($a->is_friendica_app() || !$regularnotifications) {
350 $notif['message'] = str_replace("{0}", $notif['name'], $notif['message']);
353 $contact = Contact::getDetailsByURL($notif['url']);
354 if (isset($contact['micro'])) {
355 $notif['photo'] = proxy_url($contact['micro'], false, PROXY_SIZE_MICRO);
357 $notif['photo'] = proxy_url($notif['photo'], false, PROXY_SIZE_MICRO);
360 $local_time = DateTimeFormat::local($notif['date']);
363 'id' => $notif['id'],
364 'href' => $notif['href'],
365 'name' => $notif['name'],
366 'url' => $notif['url'],
367 'photo' => $notif['photo'],
368 'date' => Temporal::getRelativeDate($notif['date']),
369 'message' => $notif['message'],
370 'seen' => $notif['seen'],
371 'timestamp' => strtotime($local_time)
380 if (x($_SESSION, 'sysmsg')) {
381 $sysmsgs = $_SESSION['sysmsg'];
382 unset($_SESSION['sysmsg']);
385 if (x($_SESSION, 'sysmsg_info')) {
386 $sysmsgs_info = $_SESSION['sysmsg_info'];
387 unset($_SESSION['sysmsg_info']);
390 if ($format == 'json') {
391 $data['groups'] = $groups_unseen;
392 $data['forums'] = $forums_unseen;
393 $data['notify'] = $sysnotify_count + $intro_count + $mail_count + $register_count;
394 $data['notifications'] = $notifications;
396 'notice' => $sysmsgs,
397 'info' => $sysmsgs_info
400 $json_payload = json_encode(["result" => $data]);
402 if (isset($_GET['callback'])) {
404 header("Content-type: application/javascript");
405 echo $_GET['callback'] . '(' . $json_payload . ')';
407 header("Content-type: application/json");
411 // Legacy slower XML format output
412 $data = ping_format_xml_data($data, $sysnotify_count, $notifications, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen);
414 header("Content-type: text/xml");
415 echo XML::fromArray(["result" => $data], $xml);
422 * @brief Retrieves the notifications array for the given user ID
424 * @param int $uid User id
425 * @return array Associative array of notifications
427 function ping_get_notifications($uid)
440 "SELECT `notify`.*, `item`.`visible`, `item`.`deleted`
441 FROM `notify` LEFT JOIN `item` ON `item`.`id` = `notify`.`iid`
442 WHERE `notify`.`uid` = %d AND `notify`.`msg` != ''
443 AND NOT (`notify`.`type` IN (%d, %d))
444 AND $seensql `notify`.`seen` ORDER BY `notify`.`date` $order LIMIT %d, 50",
446 intval(NOTIFY_INTRO),
462 foreach ($r as $notification) {
463 if (is_null($notification["visible"])) {
464 $notification["visible"] = true;
467 if (is_null($notification["deleted"])) {
468 $notification["deleted"] = 0;
471 if ($notification["msg_cache"]) {
472 $notification["name"] = $notification["name_cache"];
473 $notification["message"] = $notification["msg_cache"];
475 $notification["name"] = strip_tags(BBCode::convert($notification["name"]));
476 $notification["message"] = format_notification_message($notification["name"], strip_tags(BBCode::convert($notification["msg"])));
479 "UPDATE `notify` SET `name_cache` = '%s', `msg_cache` = '%s' WHERE `id` = %d",
480 dbesc($notification["name"]),
481 dbesc($notification["message"]),
482 intval($notification["id"])
486 $notification["href"] = System::baseUrl() . "/notify/view/" . $notification["id"];
488 if ($notification["visible"]
489 && !$notification["deleted"]
490 && !(x($result, $notification["parent"]) && is_array($result[$notification["parent"]]))
492 // Should we condense the notifications or show them all?
493 if (PConfig::get(local_user(), 'system', 'detailed_notif')) {
494 $result[$notification["id"]] = $notification;
496 $result[$notification["parent"]] = $notification;
500 } while ((count($result) < 50) && !$quit);
506 * @brief Backward-compatible XML formatting for ping.php output
509 * @param array $data The initial ping data array
510 * @param int $sysnotify Number of unseen system notifications
511 * @param array $notifs Complete list of notification
512 * @param array $sysmsgs List of system notice messages
513 * @param array $sysmsgs_info List of system info messages
514 * @param int $groups_unseen Number of unseen group items
515 * @param int $forums_unseen Number of unseen forum items
516 * @return array XML-transform ready data array
518 function ping_format_xml_data($data, $sysnotify, $notifs, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen)
521 foreach ($notifs as $key => $notif) {
522 $notifications[$key . ':note'] = $notif['message'];
524 $notifications[$key . ':@attributes'] = [
525 'id' => $notif['id'],
526 'href' => $notif['href'],
527 'name' => $notif['name'],
528 'url' => $notif['url'],
529 'photo' => $notif['photo'],
530 'date' => $notif['date'],
531 'seen' => $notif['seen'],
532 'timestamp' => $notif['timestamp']
537 foreach ($sysmsgs as $key => $m) {
538 $sysmsg[$key . ':notice'] = $m;
540 foreach ($sysmsgs_info as $key => $m) {
541 $sysmsg[$key . ':info'] = $m;
544 $data['notif'] = $notifications;
545 $data['@attributes'] = ['count' => $sysnotify_count + $data['intro'] + $data['mail'] + $data['register']];
546 $data['sysmsgs'] = $sysmsg;
548 if ($data['register'] == 0) {
549 unset($data['register']);
553 if (count($groups_unseen)) {
554 foreach ($groups_unseen as $key => $item) {
555 $groups[$key . ':group'] = $item['count'];
556 $groups[$key . ':@attributes'] = ['id' => $item['id']];
558 $data['groups'] = $groups;
562 if (count($forums_unseen)) {
563 foreach ($forums_unseen as $key => $item) {
564 $forums[$key . ':forum'] = $item['count'];
565 $forums[$key . ':@attributes'] = ['id' => $item['id']];
567 $data['forums'] = $forums;