3 * @file include/ping.php
7 use Friendica\Content\ForumManager;
8 use Friendica\Content\Text\BBCode;
9 use Friendica\Core\Cache;
10 use Friendica\Core\Config;
11 use Friendica\Core\Hook;
12 use Friendica\Core\L10n;
13 use Friendica\Core\PConfig;
14 use Friendica\Core\System;
15 use Friendica\Database\DBA;
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\Proxy as ProxyUtils;
22 use Friendica\Util\XML;
25 * @brief Outputs the counts and the lists of various notifications
27 * The output format can be controlled via the GET parameter 'format'. It can be
28 * - xml (deprecated legacy default)
29 * - json (outputs JSONP with the 'callback' GET parameter)
31 * Expected JSON structure:
40 * "all-events-today": 0,
44 * "birthdays-today": 0,
48 * "notifications": [ ],
56 * @param App $a The Friendica App instance
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' => ['created' => 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 = System::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')) === 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 = 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 Cache::set($cachekey, $ev, Cache::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' => System::baseUrl() . '/notifications/intros/' . $intro['id'],
266 'name' => $intro['name'],
267 'url' => $intro['url'],
268 'photo' => $intro['photo'],
269 'date' => $intro['datetime'],
271 'message' => L10n::t('{0} wants to be your friend'),
277 if (DBA::isResult($regs)) {
278 foreach ($regs as $reg) {
281 'href' => System::baseUrl() . '/admin/users/',
282 'name' => $reg['name'],
283 'url' => $reg['url'],
284 'photo' => $reg['micro'],
285 'date' => $reg['created'],
287 'message' => 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 // Are the nofications called from the regular process or via the friendica app?
316 $regularnotifications = (!empty($_GET['uid']) && !empty($_GET['_']));
318 foreach ($notifs as $notif) {
319 if ($a->isFriendicaApp() || !$regularnotifications) {
320 $notif['message'] = str_replace("{0}", $notif['name'], $notif['message']);
323 $contact = Contact::getDetailsByURL($notif['url']);
324 if (isset($contact['micro'])) {
325 $notif['photo'] = ProxyUtils::proxifyUrl($contact['micro'], false, ProxyUtils::SIZE_MICRO);
327 $notif['photo'] = ProxyUtils::proxifyUrl($notif['photo'], false, ProxyUtils::SIZE_MICRO);
330 $local_time = DateTimeFormat::local($notif['date']);
333 'id' => $notif['id'],
334 'href' => $notif['href'],
335 'name' => $notif['name'],
336 'url' => $notif['url'],
337 'photo' => $notif['photo'],
338 'date' => Temporal::getRelativeDate($notif['date']),
339 'message' => $notif['message'],
340 'seen' => $notif['seen'],
341 'timestamp' => strtotime($local_time)
350 if (!empty($_SESSION['sysmsg'])) {
351 $sysmsgs = $_SESSION['sysmsg'];
352 unset($_SESSION['sysmsg']);
355 if (!empty($_SESSION['sysmsg_info'])) {
356 $sysmsgs_info = $_SESSION['sysmsg_info'];
357 unset($_SESSION['sysmsg_info']);
360 if ($format == 'json') {
361 $data['groups'] = $groups_unseen;
362 $data['forums'] = $forums_unseen;
363 $data['notify'] = $sysnotify_count + $intro_count + $register_count;
364 $data['notifications'] = $notifications;
366 'notice' => $sysmsgs,
367 'info' => $sysmsgs_info
370 $json_payload = json_encode(["result" => $data]);
372 if (isset($_GET['callback'])) {
374 header("Content-type: application/javascript");
375 echo $_GET['callback'] . '(' . $json_payload . ')';
377 header("Content-type: application/json");
381 // Legacy slower XML format output
382 $data = ping_format_xml_data($data, $sysnotify_count, $notifications, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen);
384 header("Content-type: text/xml");
385 echo XML::fromArray(["result" => $data], $xml);
392 * @brief Retrieves the notifications array for the given user ID
394 * @param int $uid User id
395 * @return array Associative array of notifications
397 function ping_get_notifications($uid)
408 "SELECT `notify`.*, `item`.`visible`, `item`.`deleted`
409 FROM `notify` LEFT JOIN `item` ON `item`.`id` = `notify`.`iid`
410 WHERE `notify`.`uid` = %d AND `notify`.`msg` != ''
411 AND NOT (`notify`.`type` IN (%d, %d))
412 AND $seensql `notify`.`seen` ORDER BY `notify`.`date` $order LIMIT %d, 50",
414 intval(NOTIFY_INTRO),
430 foreach ($r as $notification) {
431 if (is_null($notification["visible"])) {
432 $notification["visible"] = true;
435 if (is_null($notification["deleted"])) {
436 $notification["deleted"] = 0;
439 if ($notification["msg_cache"]) {
440 $notification["name"] = $notification["name_cache"];
441 $notification["message"] = $notification["msg_cache"];
443 $notification["name"] = strip_tags(BBCode::convert($notification["name"]));
444 $notification["message"] = format_notification_message($notification["name"], strip_tags(BBCode::convert($notification["msg"])));
447 "UPDATE `notify` SET `name_cache` = '%s', `msg_cache` = '%s' WHERE `id` = %d",
448 DBA::escape($notification["name"]),
449 DBA::escape($notification["message"]),
450 intval($notification["id"])
454 $notification["href"] = System::baseUrl() . "/notify/view/" . $notification["id"];
456 if ($notification["visible"]
457 && !$notification["deleted"]
458 && empty($result[$notification["parent"]])
460 // Should we condense the notifications or show them all?
461 if (PConfig::get(local_user(), 'system', 'detailed_notif')) {
462 $result[$notification["id"]] = $notification;
464 $result[$notification["parent"]] = $notification;
468 } while ((count($result) < 50) && !$quit);
474 * @brief Backward-compatible XML formatting for ping.php output
477 * @param array $data The initial ping data array
478 * @param int $sysnotify_count Number of unseen system notifications
479 * @param array $notifs Complete list of notification
480 * @param array $sysmsgs List of system notice messages
481 * @param array $sysmsgs_info List of system info messages
482 * @param array $groups_unseen List of unseen group messages
483 * @param array $forums_unseen List of unseen forum messages
485 * @return array XML-transform ready data array
487 function ping_format_xml_data($data, $sysnotify_count, $notifs, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen)
490 foreach ($notifs as $key => $notif) {
491 $notifications[$key . ':note'] = $notif['message'];
493 $notifications[$key . ':@attributes'] = [
494 'id' => $notif['id'],
495 'href' => $notif['href'],
496 'name' => $notif['name'],
497 'url' => $notif['url'],
498 'photo' => $notif['photo'],
499 'date' => $notif['date'],
500 'seen' => $notif['seen'],
501 'timestamp' => $notif['timestamp']
506 foreach ($sysmsgs as $key => $m) {
507 $sysmsg[$key . ':notice'] = $m;
509 foreach ($sysmsgs_info as $key => $m) {
510 $sysmsg[$key . ':info'] = $m;
513 $data['notif'] = $notifications;
514 $data['@attributes'] = ['count' => $sysnotify_count + $data['intro'] + $data['mail'] + $data['register']];
515 $data['sysmsgs'] = $sysmsg;
517 if ($data['register'] == 0) {
518 unset($data['register']);
522 if (count($groups_unseen)) {
523 foreach ($groups_unseen as $key => $item) {
524 $groups[$key . ':group'] = $item['count'];
525 $groups[$key . ':@attributes'] = ['id' => $item['id']];
527 $data['groups'] = $groups;
531 if (count($forums_unseen)) {
532 foreach ($forums_unseen as $key => $item) {
533 $forums[$key . ':forum'] = $item['count'];
534 $forums[$key . ':@attributes'] = ['id' => $item['id']];
536 $data['forums'] = $forums;