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()) {
205 $regs = Friendica\Model\Register::getPending();
207 if (DBA::isResult($regs)) {
208 $register_count = count($regs);
212 $cachekey = "ping_init:".local_user();
213 $ev = Cache::get($cachekey);
216 "SELECT type, start, adjust FROM `event`
217 WHERE `event`.`uid` = %d AND `start` < '%s' AND `finish` > '%s' and `ignore` = 0
218 ORDER BY `start` ASC ",
219 intval(local_user()),
220 DBA::escape(DateTimeFormat::utc('now + 7 days')),
221 DBA::escape(DateTimeFormat::utcNow())
223 if (DBA::isResult($ev)) {
224 Cache::set($cachekey, $ev, CACHE_HOUR);
228 if (DBA::isResult($ev)) {
229 $all_events = count($ev);
232 $str_now = DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d');
233 foreach ($ev as $x) {
235 if ($x['type'] === 'birthday') {
241 if (DateTimeFormat::convert($x['start'], ((intval($x['adjust'])) ? $a->timezone : 'UTC'), 'UTC', 'Y-m-d') === $str_now) {
242 $all_events_today ++;
253 $data['intro'] = $intro_count;
254 $data['mail'] = $mail_count;
255 $data['net'] = $network_count;
256 $data['home'] = $home_count;
257 $data['register'] = $register_count;
259 $data['all-events'] = $all_events;
260 $data['all-events-today'] = $all_events_today;
261 $data['events'] = $events;
262 $data['events-today'] = $events_today;
263 $data['birthdays'] = $birthdays;
264 $data['birthdays-today'] = $birthdays_today;
266 if (DBA::isResult($notifs)) {
267 foreach ($notifs as $notif) {
268 if ($notif['seen'] == 0) {
274 // merge all notification types in one array
275 if (DBA::isResult($intros)) {
276 foreach ($intros as $intro) {
279 'href' => System::baseUrl() . '/notifications/intros/' . $intro['id'],
280 'name' => $intro['name'],
281 'url' => $intro['url'],
282 'photo' => $intro['photo'],
283 'date' => $intro['datetime'],
285 'message' => L10n::t('{0} wants to be your friend'),
291 if (DBA::isResult($mails)) {
292 foreach ($mails as $mail) {
295 'href' => System::baseUrl() . '/message/' . $mail['id'],
296 'name' => $mail['from-name'],
297 'url' => $mail['from-url'],
298 'photo' => $mail['from-photo'],
299 'date' => $mail['created'],
301 'message' => L10n::t('{0} sent you a message'),
307 if (DBA::isResult($regs)) {
308 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 (DBA::isResult($notifs)) {
345 // Are the nofications called from the regular process or via the friendica app?
346 $regularnotifications = (!empty($_GET['uid']) && !empty($_GET['_']));
348 foreach ($notifs as $notif) {
349 if ($a->isFriendicaApp() || !$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'] = ProxyUtils::proxifyUrl($contact['micro'], false, ProxyUtils::SIZE_MICRO);
357 $notif['photo'] = ProxyUtils::proxifyUrl($notif['photo'], false, ProxyUtils::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 DBA::escape($notification["name"]),
481 DBA::escape($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"]) && !empty($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_count 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
517 * @return array XML-transform ready data array
519 function ping_format_xml_data($data, $sysnotify_count, $notifs, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen)
522 foreach ($notifs as $key => $notif) {
523 $notifications[$key . ':note'] = $notif['message'];
525 $notifications[$key . ':@attributes'] = [
526 'id' => $notif['id'],
527 'href' => $notif['href'],
528 'name' => $notif['name'],
529 'url' => $notif['url'],
530 'photo' => $notif['photo'],
531 'date' => $notif['date'],
532 'seen' => $notif['seen'],
533 'timestamp' => $notif['timestamp']
538 foreach ($sysmsgs as $key => $m) {
539 $sysmsg[$key . ':notice'] = $m;
541 foreach ($sysmsgs_info as $key => $m) {
542 $sysmsg[$key . ':info'] = $m;
545 $data['notif'] = $notifications;
546 $data['@attributes'] = ['count' => $sysnotify_count + $data['intro'] + $data['mail'] + $data['register']];
547 $data['sysmsgs'] = $sysmsg;
549 if ($data['register'] == 0) {
550 unset($data['register']);
554 if (count($groups_unseen)) {
555 foreach ($groups_unseen as $key => $item) {
556 $groups[$key . ':group'] = $item['count'];
557 $groups[$key . ':@attributes'] = ['id' => $item['id']];
559 $data['groups'] = $groups;
563 if (count($forums_unseen)) {
564 foreach ($forums_unseen as $key => $item) {
565 $forums[$key . ':forum'] = $item['count'];
566 $forums[$key . ':@attributes'] = ['id' => $item['id']];
568 $data['forums'] = $forums;