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', 'wall'];
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) {
282 'href' => System::baseUrl() . '/notifications/intros/' . $intro['id'],
283 'name' => $intro['name'],
284 'url' => $intro['url'],
285 'photo' => $intro['photo'],
286 'date' => $intro['datetime'],
288 'message' => L10n::t('{0} wants to be your friend'),
294 if (DBM::is_result($mails)) {
295 foreach ($mails as $mail) {
298 'href' => System::baseUrl() . '/message/' . $mail['id'],
299 'name' => $mail['from-name'],
300 'url' => $mail['from-url'],
301 'photo' => $mail['from-photo'],
302 'date' => $mail['created'],
304 'message' => L10n::t('{0} sent you a message'),
310 if (DBM::is_result($regs)) {
311 foreach ($regs as $reg) {
314 'href' => System::baseUrl() . '/admin/users/',
315 'name' => $reg['name'],
316 'url' => $reg['url'],
317 'photo' => $reg['micro'],
318 'date' => $reg['created'],
320 'message' => L10n::t('{0} requested registration'),
326 // sort notifications by $[]['date']
327 $sort_function = function ($a, $b) {
328 $adate = strtotime($a['date']);
329 $bdate = strtotime($b['date']);
331 // Unseen messages are kept at the top
332 // The value 31536000 means one year. This should be enough :-)
340 if ($adate == $bdate) {
343 return ($adate < $bdate) ? 1 : -1;
345 usort($notifs, $sort_function);
347 if (DBM::is_result($notifs)) {
348 // Are the nofications called from the regular process or via the friendica app?
349 $regularnotifications = (intval($_GET['uid']) && intval($_GET['_']));
351 foreach ($notifs as $notif) {
352 if ($a->is_friendica_app() || !$regularnotifications) {
353 $notif['message'] = str_replace("{0}", $notif['name'], $notif['message']);
356 $contact = Contact::getDetailsByURL($notif['url']);
357 if (isset($contact['micro'])) {
358 $notif['photo'] = proxy_url($contact['micro'], false, PROXY_SIZE_MICRO);
360 $notif['photo'] = proxy_url($notif['photo'], false, PROXY_SIZE_MICRO);
363 $local_time = DateTimeFormat::local($notif['date']);
366 'id' => $notif['id'],
367 'href' => $notif['href'],
368 'name' => $notif['name'],
369 'url' => $notif['url'],
370 'photo' => $notif['photo'],
371 'date' => Temporal::getRelativeDate($notif['date']),
372 'message' => $notif['message'],
373 'seen' => $notif['seen'],
374 'timestamp' => strtotime($local_time)
383 if (x($_SESSION, 'sysmsg')) {
384 $sysmsgs = $_SESSION['sysmsg'];
385 unset($_SESSION['sysmsg']);
388 if (x($_SESSION, 'sysmsg_info')) {
389 $sysmsgs_info = $_SESSION['sysmsg_info'];
390 unset($_SESSION['sysmsg_info']);
393 if ($format == 'json') {
394 $data['groups'] = $groups_unseen;
395 $data['forums'] = $forums_unseen;
396 $data['notify'] = $sysnotify_count + $intro_count + $mail_count + $register_count;
397 $data['notifications'] = $notifications;
399 'notice' => $sysmsgs,
400 'info' => $sysmsgs_info
403 $json_payload = json_encode(["result" => $data]);
405 if (isset($_GET['callback'])) {
407 header("Content-type: application/javascript");
408 echo $_GET['callback'] . '(' . $json_payload . ')';
410 header("Content-type: application/json");
414 // Legacy slower XML format output
415 $data = ping_format_xml_data($data, $sysnotify_count, $notifications, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen);
417 header("Content-type: text/xml");
418 echo XML::fromArray(["result" => $data], $xml);
425 * @brief Retrieves the notifications array for the given user ID
427 * @param int $uid User id
428 * @return array Associative array of notifications
430 function ping_get_notifications($uid)
443 "SELECT `notify`.*, `item`.`visible`, `item`.`deleted`
444 FROM `notify` LEFT JOIN `item` ON `item`.`id` = `notify`.`iid`
445 WHERE `notify`.`uid` = %d AND `notify`.`msg` != ''
446 AND NOT (`notify`.`type` IN (%d, %d))
447 AND $seensql `notify`.`seen` ORDER BY `notify`.`date` $order LIMIT %d, 50",
449 intval(NOTIFY_INTRO),
465 foreach ($r as $notification) {
466 if (is_null($notification["visible"])) {
467 $notification["visible"] = true;
470 if (is_null($notification["deleted"])) {
471 $notification["deleted"] = 0;
474 if ($notification["msg_cache"]) {
475 $notification["name"] = $notification["name_cache"];
476 $notification["message"] = $notification["msg_cache"];
478 $notification["name"] = strip_tags(BBCode::convert($notification["name"]));
479 $notification["message"] = format_notification_message($notification["name"], strip_tags(BBCode::convert($notification["msg"])));
482 "UPDATE `notify` SET `name_cache` = '%s', `msg_cache` = '%s' WHERE `id` = %d",
483 dbesc($notification["name"]),
484 dbesc($notification["message"]),
485 intval($notification["id"])
489 $notification["href"] = System::baseUrl() . "/notify/view/" . $notification["id"];
491 if ($notification["visible"]
492 && !$notification["deleted"]
493 && !(x($result, $notification["parent"]) && !empty($result[$notification["parent"]]))
495 // Should we condense the notifications or show them all?
496 if (PConfig::get(local_user(), 'system', 'detailed_notif')) {
497 $result[$notification["id"]] = $notification;
499 $result[$notification["parent"]] = $notification;
503 } while ((count($result) < 50) && !$quit);
509 * @brief Backward-compatible XML formatting for ping.php output
512 * @param array $data The initial ping data array
513 * @param int $sysnotify Number of unseen system notifications
514 * @param array $notifs Complete list of notification
515 * @param array $sysmsgs List of system notice messages
516 * @param array $sysmsgs_info List of system info messages
517 * @param int $groups_unseen Number of unseen group items
518 * @param int $forums_unseen Number of unseen forum items
519 * @return array XML-transform ready data array
521 function ping_format_xml_data($data, $sysnotify, $notifs, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen)
524 foreach ($notifs as $key => $notif) {
525 $notifications[$key . ':note'] = $notif['message'];
527 $notifications[$key . ':@attributes'] = [
528 'id' => $notif['id'],
529 'href' => $notif['href'],
530 'name' => $notif['name'],
531 'url' => $notif['url'],
532 'photo' => $notif['photo'],
533 'date' => $notif['date'],
534 'seen' => $notif['seen'],
535 'timestamp' => $notif['timestamp']
540 foreach ($sysmsgs as $key => $m) {
541 $sysmsg[$key . ':notice'] = $m;
543 foreach ($sysmsgs_info as $key => $m) {
544 $sysmsg[$key . ':info'] = $m;
547 $data['notif'] = $notifications;
548 $data['@attributes'] = ['count' => $sysnotify_count + $data['intro'] + $data['mail'] + $data['register']];
549 $data['sysmsgs'] = $sysmsg;
551 if ($data['register'] == 0) {
552 unset($data['register']);
556 if (count($groups_unseen)) {
557 foreach ($groups_unseen as $key => $item) {
558 $groups[$key . ':group'] = $item['count'];
559 $groups[$key . ':@attributes'] = ['id' => $item['id']];
561 $data['groups'] = $groups;
565 if (count($forums_unseen)) {
566 foreach ($forums_unseen as $key => $item) {
567 $forums[$key . ':forum'] = $item['count'];
568 $forums[$key . ':@attributes'] = ['id' => $item['id']];
570 $data['forums'] = $forums;