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
57 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
59 function ping_init(App $a)
63 if (isset($_GET['format']) && $_GET['format'] == 'json') {
80 $all_events_today = 0;
87 $data['intro'] = $intro_count;
88 $data['mail'] = $mail_count;
89 $data['net'] = $network_count;
90 $data['home'] = $home_count;
91 $data['register'] = $register_count;
93 $data['all-events'] = $all_events;
94 $data['all-events-today'] = $all_events_today;
95 $data['events'] = $events;
96 $data['events-today'] = $events_today;
97 $data['birthdays'] = $birthdays;
98 $data['birthdays-today'] = $birthdays_today;
101 // Different login session than the page that is calling us.
102 if (!empty($_GET['uid']) && intval($_GET['uid']) != local_user()) {
103 $data = ['result' => ['invalid' => 1]];
105 if ($format == 'json') {
106 if (isset($_GET['callback'])) {
108 header("Content-type: application/javascript");
109 echo $_GET['callback'] . '(' . json_encode($data) . ')';
111 header("Content-type: application/json");
112 echo json_encode($data);
115 header("Content-type: text/xml");
116 echo XML::fromArray($data, $xml);
121 $notifs = ping_get_notifications(local_user());
123 $condition = ["`unseen` AND `uid` = ? AND `contact-id` != ?", local_user(), local_user()];
124 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
125 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid', 'wall'];
126 $params = ['order' => ['created' => true]];
127 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
129 if (DBA::isResult($items)) {
130 $items_unseen = Item::inArray($items);
131 $arr = ['items' => $items_unseen];
132 Hook::callAll('network_ping', $arr);
134 foreach ($items_unseen as $item) {
143 if ($network_count) {
144 // Find out how unseen network posts are spread across groups
145 $group_counts = Group::countUnseen();
146 if (DBA::isResult($group_counts)) {
147 foreach ($group_counts as $group_count) {
148 if ($group_count['count'] > 0) {
149 $groups_unseen[] = $group_count;
154 $forum_counts = ForumManager::countUnseenItems();
155 if (DBA::isResult($forum_counts)) {
156 foreach ($forum_counts as $forum_count) {
157 if ($forum_count['count'] > 0) {
158 $forums_unseen[] = $forum_count;
165 "SELECT `intro`.`id`, `intro`.`datetime`,
166 `fcontact`.`name`, `fcontact`.`url`, `fcontact`.`photo`
167 FROM `intro` LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
168 WHERE `intro`.`uid` = %d AND `intro`.`blocked` = 0 AND `intro`.`ignore` = 0 AND `intro`.`fid` != 0",
172 "SELECT `intro`.`id`, `intro`.`datetime`,
173 `contact`.`name`, `contact`.`url`, `contact`.`photo`
174 FROM `intro` LEFT JOIN `contact` ON `intro`.`contact-id` = `contact`.`id`
175 WHERE `intro`.`uid` = %d AND `intro`.`blocked` = 0 AND `intro`.`ignore` = 0 AND `intro`.`contact-id` != 0",
179 $intro_count = count($intros1) + count($intros2);
180 $intros = $intros1 + $intros2;
182 $myurl = System::baseUrl() . '/profile/' . $a->user['nickname'];
184 "SELECT `id`, `from-name`, `from-url`, `from-photo`, `created` FROM `mail`
185 WHERE `uid` = %d AND `seen` = 0 AND `from-url` != '%s' ",
186 intval(local_user()),
189 $mail_count = count($mails);
191 if (intval(Config::get('config', 'register_policy')) === \Friendica\Module\Register::APPROVE && is_site_admin()) {
192 $regs = Friendica\Model\Register::getPending();
194 if (DBA::isResult($regs)) {
195 $register_count = count($regs);
199 $cachekey = "ping_init:".local_user();
200 $ev = Cache::get($cachekey);
203 "SELECT type, start, adjust FROM `event`
204 WHERE `event`.`uid` = %d AND `start` < '%s' AND `finish` > '%s' and `ignore` = 0
205 ORDER BY `start` ASC ",
206 intval(local_user()),
207 DBA::escape(DateTimeFormat::utc('now + 7 days')),
208 DBA::escape(DateTimeFormat::utcNow())
210 if (DBA::isResult($ev)) {
211 Cache::set($cachekey, $ev, Cache::HOUR);
215 if (DBA::isResult($ev)) {
216 $all_events = count($ev);
219 $str_now = DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d');
220 foreach ($ev as $x) {
222 if ($x['type'] === 'birthday') {
228 if (DateTimeFormat::convert($x['start'], ((intval($x['adjust'])) ? $a->timezone : 'UTC'), 'UTC', 'Y-m-d') === $str_now) {
229 $all_events_today ++;
240 $data['intro'] = $intro_count;
241 $data['mail'] = $mail_count;
242 $data['net'] = $network_count;
243 $data['home'] = $home_count;
244 $data['register'] = $register_count;
246 $data['all-events'] = $all_events;
247 $data['all-events-today'] = $all_events_today;
248 $data['events'] = $events;
249 $data['events-today'] = $events_today;
250 $data['birthdays'] = $birthdays;
251 $data['birthdays-today'] = $birthdays_today;
253 if (DBA::isResult($notifs)) {
254 foreach ($notifs as $notif) {
255 if ($notif['seen'] == 0) {
261 // merge all notification types in one array
262 if (DBA::isResult($intros)) {
263 foreach ($intros as $intro) {
266 'href' => System::baseUrl() . '/notifications/intros/' . $intro['id'],
267 'name' => $intro['name'],
268 'url' => $intro['url'],
269 'photo' => $intro['photo'],
270 'date' => $intro['datetime'],
272 'message' => L10n::t('{0} wants to be your friend'),
278 if (DBA::isResult($regs)) {
279 foreach ($regs as $reg) {
282 'href' => System::baseUrl() . '/admin/users/',
283 'name' => $reg['name'],
284 'url' => $reg['url'],
285 'photo' => $reg['micro'],
286 'date' => $reg['created'],
288 'message' => L10n::t('{0} requested registration'),
294 // sort notifications by $[]['date']
295 $sort_function = function ($a, $b) {
296 $adate = strtotime($a['date']);
297 $bdate = strtotime($b['date']);
299 // Unseen messages are kept at the top
300 // The value 31536000 means one year. This should be enough :-)
308 if ($adate == $bdate) {
311 return ($adate < $bdate) ? 1 : -1;
313 usort($notifs, $sort_function);
315 if (DBA::isResult($notifs)) {
316 // Are the nofications called from the regular process or via the friendica app?
317 $regularnotifications = (!empty($_GET['uid']) && !empty($_GET['_']));
319 foreach ($notifs as $notif) {
320 if ($a->isFriendicaApp() || !$regularnotifications) {
321 $notif['message'] = str_replace("{0}", $notif['name'], $notif['message']);
324 $contact = Contact::getDetailsByURL($notif['url']);
325 if (isset($contact['micro'])) {
326 $notif['photo'] = ProxyUtils::proxifyUrl($contact['micro'], false, ProxyUtils::SIZE_MICRO);
328 $notif['photo'] = ProxyUtils::proxifyUrl($notif['photo'], false, ProxyUtils::SIZE_MICRO);
331 $local_time = DateTimeFormat::local($notif['date']);
334 'id' => $notif['id'],
335 'href' => $notif['href'],
336 'name' => $notif['name'],
337 'url' => $notif['url'],
338 'photo' => $notif['photo'],
339 'date' => Temporal::getRelativeDate($notif['date']),
340 'message' => $notif['message'],
341 'seen' => $notif['seen'],
342 'timestamp' => strtotime($local_time)
351 if (!empty($_SESSION['sysmsg'])) {
352 $sysmsgs = $_SESSION['sysmsg'];
353 unset($_SESSION['sysmsg']);
356 if (!empty($_SESSION['sysmsg_info'])) {
357 $sysmsgs_info = $_SESSION['sysmsg_info'];
358 unset($_SESSION['sysmsg_info']);
361 if ($format == 'json') {
362 $data['groups'] = $groups_unseen;
363 $data['forums'] = $forums_unseen;
364 $data['notify'] = $sysnotify_count + $intro_count + $register_count;
365 $data['notifications'] = $notifications;
367 'notice' => $sysmsgs,
368 'info' => $sysmsgs_info
371 $json_payload = json_encode(["result" => $data]);
373 if (isset($_GET['callback'])) {
375 header("Content-type: application/javascript");
376 echo $_GET['callback'] . '(' . $json_payload . ')';
378 header("Content-type: application/json");
382 // Legacy slower XML format output
383 $data = ping_format_xml_data($data, $sysnotify_count, $notifications, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen);
385 header("Content-type: text/xml");
386 echo XML::fromArray(["result" => $data], $xml);
393 * @brief Retrieves the notifications array for the given user ID
395 * @param int $uid User id
396 * @return array Associative array of notifications
397 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
399 function ping_get_notifications($uid)
410 "SELECT `notify`.*, `item`.`visible`, `item`.`deleted`
411 FROM `notify` LEFT JOIN `item` ON `item`.`id` = `notify`.`iid`
412 WHERE `notify`.`uid` = %d AND `notify`.`msg` != ''
413 AND NOT (`notify`.`type` IN (%d, %d))
414 AND $seensql `notify`.`seen` ORDER BY `notify`.`date` $order LIMIT %d, 50",
416 intval(NOTIFY_INTRO),
432 foreach ($r as $notification) {
433 if (is_null($notification["visible"])) {
434 $notification["visible"] = true;
437 if (is_null($notification["deleted"])) {
438 $notification["deleted"] = 0;
441 if ($notification["msg_cache"]) {
442 $notification["name"] = $notification["name_cache"];
443 $notification["message"] = $notification["msg_cache"];
445 $notification["name"] = strip_tags(BBCode::convert($notification["name"]));
446 $notification["message"] = format_notification_message($notification["name"], strip_tags(BBCode::convert($notification["msg"])));
449 "UPDATE `notify` SET `name_cache` = '%s', `msg_cache` = '%s' WHERE `id` = %d",
450 DBA::escape($notification["name"]),
451 DBA::escape($notification["message"]),
452 intval($notification["id"])
456 $notification["href"] = System::baseUrl() . "/notify/view/" . $notification["id"];
458 if ($notification["visible"]
459 && !$notification["deleted"]
460 && empty($result[$notification["parent"]])
462 // Should we condense the notifications or show them all?
463 if (PConfig::get(local_user(), 'system', 'detailed_notif')) {
464 $result[$notification["id"]] = $notification;
466 $result[$notification["parent"]] = $notification;
470 } while ((count($result) < 50) && !$quit);
476 * @brief Backward-compatible XML formatting for ping.php output
479 * @param array $data The initial ping data array
480 * @param int $sysnotify_count Number of unseen system notifications
481 * @param array $notifs Complete list of notification
482 * @param array $sysmsgs List of system notice messages
483 * @param array $sysmsgs_info List of system info messages
484 * @param array $groups_unseen List of unseen group items
485 * @param array $forums_unseen List of unseen forum items
487 * @return array XML-transform ready data array
489 function ping_format_xml_data($data, $sysnotify_count, $notifs, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen)
492 foreach ($notifs as $key => $notif) {
493 $notifications[$key . ':note'] = $notif['message'];
495 $notifications[$key . ':@attributes'] = [
496 'id' => $notif['id'],
497 'href' => $notif['href'],
498 'name' => $notif['name'],
499 'url' => $notif['url'],
500 'photo' => $notif['photo'],
501 'date' => $notif['date'],
502 'seen' => $notif['seen'],
503 'timestamp' => $notif['timestamp']
508 foreach ($sysmsgs as $key => $m) {
509 $sysmsg[$key . ':notice'] = $m;
511 foreach ($sysmsgs_info as $key => $m) {
512 $sysmsg[$key . ':info'] = $m;
515 $data['notif'] = $notifications;
516 $data['@attributes'] = ['count' => $sysnotify_count + $data['intro'] + $data['mail'] + $data['register']];
517 $data['sysmsgs'] = $sysmsg;
519 if ($data['register'] == 0) {
520 unset($data['register']);
524 if (count($groups_unseen)) {
525 foreach ($groups_unseen as $key => $item) {
526 $groups[$key . ':group'] = $item['count'];
527 $groups[$key . ':@attributes'] = ['id' => $item['id']];
529 $data['groups'] = $groups;
533 if (count($forums_unseen)) {
534 foreach ($forums_unseen as $key => $item) {
535 $forums[$key . ':forum'] = $item['count'];
536 $forums[$key . ':@attributes'] = ['id' => $item['id']];
538 $data['forums'] = $forums;