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\Util\DateTimeFormat;
19 use Friendica\Util\Temporal;
20 use Friendica\Util\XML;
22 require_once 'include/bbcode.php';
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());
132 "SELECT `item`.`id`, `item`.`parent`, `item`.`verb`, `item`.`wall`, `item`.`author-name`,
133 `item`.`contact-id`, `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object`,
134 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`
135 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id` = `item`.`parent`
136 WHERE `item`.`unseen` = 1 AND `item`.`visible` = 1 AND
137 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `pitem`.`parent` != 0
138 AND `item`.`contact-id` != %d
139 ORDER BY `item`.`created` DESC",
140 intval(local_user()),
144 if (DBM::is_result($items_unseen)) {
145 $arr = ['items' => $items_unseen];
146 Addon::callHooks('network_ping', $arr);
148 foreach ($items_unseen as $item) {
157 if ($network_count) {
158 if (intval(Feature::isEnabled(local_user(), 'groups'))) {
159 // Find out how unseen network posts are spread across groups
160 $group_counts = Group::countUnseen();
161 if (DBM::is_result($group_counts)) {
162 foreach ($group_counts as $group_count) {
163 if ($group_count['count'] > 0) {
164 $groups_unseen[] = $group_count;
170 if (intval(Feature::isEnabled(local_user(), 'forumlist_widget'))) {
171 $forum_counts = ForumManager::countUnseenItems();
172 if (DBM::is_result($forum_counts)) {
173 foreach ($forum_counts as $forum_count) {
174 if ($forum_count['count'] > 0) {
175 $forums_unseen[] = $forum_count;
183 "SELECT `intro`.`id`, `intro`.`datetime`,
184 `fcontact`.`name`, `fcontact`.`url`, `fcontact`.`photo`
185 FROM `intro` LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
186 WHERE `intro`.`uid` = %d AND `intro`.`blocked` = 0 AND `intro`.`ignore` = 0 AND `intro`.`fid` != 0",
190 "SELECT `intro`.`id`, `intro`.`datetime`,
191 `contact`.`name`, `contact`.`url`, `contact`.`photo`
192 FROM `intro` LEFT JOIN `contact` ON `intro`.`contact-id` = `contact`.`id`
193 WHERE `intro`.`uid` = %d AND `intro`.`blocked` = 0 AND `intro`.`ignore` = 0 AND `intro`.`contact-id` != 0",
197 $intro_count = count($intros1) + count($intros2);
198 $intros = $intros1 + $intros2;
200 $myurl = System::baseUrl() . '/profile/' . $a->user['nickname'] ;
202 "SELECT `id`, `from-name`, `from-url`, `from-photo`, `created` FROM `mail`
203 WHERE `uid` = %d AND `seen` = 0 AND `from-url` != '%s' ",
204 intval(local_user()),
207 $mail_count = count($mails);
209 if ($a->config['register_policy'] == REGISTER_APPROVE && is_site_admin()) {
211 "SELECT `contact`.`name`, `contact`.`url`, `contact`.`micro`, `register`.`created`
212 FROM `contact` RIGHT JOIN `register` ON `register`.`uid` = `contact`.`uid`
213 WHERE `contact`.`self` = 1"
216 if (DBM::is_result($regs)) {
217 $register_count = count($regs);
221 $cachekey = "ping_init:".local_user();
222 $ev = Cache::get($cachekey);
225 "SELECT type, start, adjust FROM `event`
226 WHERE `event`.`uid` = %d AND `start` < '%s' AND `finish` > '%s' and `ignore` = 0
227 ORDER BY `start` ASC ",
228 intval(local_user()),
229 dbesc(DateTimeFormat::utc('now + 7 days')),
230 dbesc(DateTimeFormat::utcNow())
232 if (DBM::is_result($ev)) {
233 Cache::set($cachekey, $ev, CACHE_HOUR);
237 if (DBM::is_result($ev)) {
238 $all_events = count($ev);
241 $str_now = DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d');
242 foreach ($ev as $x) {
244 if ($x['type'] === 'birthday') {
250 if (DateTimeFormat::convert($x['start'], ((intval($x['adjust'])) ? $a->timezone : 'UTC'), 'UTC', 'Y-m-d') === $str_now) {
251 $all_events_today ++;
262 $data['intro'] = $intro_count;
263 $data['mail'] = $mail_count;
264 $data['net'] = $network_count;
265 $data['home'] = $home_count;
266 $data['register'] = $register_count;
268 $data['all-events'] = $all_events;
269 $data['all-events-today'] = $all_events_today;
270 $data['events'] = $events;
271 $data['events-today'] = $events_today;
272 $data['birthdays'] = $birthdays;
273 $data['birthdays-today'] = $birthdays_today;
275 if (DBM::is_result($notifs)) {
276 foreach ($notifs as $notif) {
277 if ($notif['seen'] == 0) {
283 // merge all notification types in one array
284 if (DBM::is_result($intros)) {
285 foreach ($intros as $intro) {
287 'href' => System::baseUrl() . '/notifications/intros/' . $intro['id'],
288 'name' => $intro['name'],
289 'url' => $intro['url'],
290 'photo' => $intro['photo'],
291 'date' => $intro['datetime'],
293 'message' => L10n::t('{0} wants to be your friend'),
299 if (DBM::is_result($mails)) {
300 foreach ($mails as $mail) {
302 'href' => System::baseUrl() . '/message/' . $mail['id'],
303 'name' => $mail['from-name'],
304 'url' => $mail['from-url'],
305 'photo' => $mail['from-photo'],
306 'date' => $mail['created'],
308 'message' => L10n::t('{0} sent you a message'),
314 if (DBM::is_result($regs)) {
315 foreach ($regs as $reg) {
317 'href' => System::baseUrl() . '/admin/users/',
318 'name' => $reg['name'],
319 'url' => $reg['url'],
320 'photo' => $reg['micro'],
321 'date' => $reg['created'],
323 'message' => L10n::t('{0} requested registration'),
329 // sort notifications by $[]['date']
330 $sort_function = function ($a, $b) {
331 $adate = strtotime($a['date']);
332 $bdate = strtotime($b['date']);
334 // Unseen messages are kept at the top
335 // The value 31536000 means one year. This should be enough :-)
343 if ($adate == $bdate) {
346 return ($adate < $bdate) ? 1 : -1;
348 usort($notifs, $sort_function);
350 if (DBM::is_result($notifs)) {
351 // Are the nofications called from the regular process or via the friendica app?
352 $regularnotifications = (intval($_GET['uid']) && intval($_GET['_']));
354 foreach ($notifs as $notif) {
355 if ($a->is_friendica_app() || !$regularnotifications) {
356 $notif['message'] = str_replace("{0}", $notif['name'], $notif['message']);
359 $contact = Contact::getDetailsByURL($notif['url']);
360 if (isset($contact['micro'])) {
361 $notif['photo'] = proxy_url($contact['micro'], false, PROXY_SIZE_MICRO);
363 $notif['photo'] = proxy_url($notif['photo'], false, PROXY_SIZE_MICRO);
366 $local_time = DateTimeFormat::local($notif['date']);
369 'id' => $notif['id'],
370 'href' => $notif['href'],
371 'name' => $notif['name'],
372 'url' => $notif['url'],
373 'photo' => $notif['photo'],
374 'date' => Temporal::getRelativeDate($notif['date']),
375 'message' => $notif['message'],
376 'seen' => $notif['seen'],
377 'timestamp' => strtotime($local_time)
386 if (x($_SESSION, 'sysmsg')) {
387 $sysmsgs = $_SESSION['sysmsg'];
388 unset($_SESSION['sysmsg']);
391 if (x($_SESSION, 'sysmsg_info')) {
392 $sysmsgs_info = $_SESSION['sysmsg_info'];
393 unset($_SESSION['sysmsg_info']);
396 if ($format == 'json') {
397 $data['groups'] = $groups_unseen;
398 $data['forums'] = $forums_unseen;
399 $data['notify'] = $sysnotify_count + $intro_count + $mail_count + $register_count;
400 $data['notifications'] = $notifications;
402 'notice' => $sysmsgs,
403 'info' => $sysmsgs_info
406 $json_payload = json_encode(["result" => $data]);
408 if (isset($_GET['callback'])) {
410 header("Content-type: application/javascript");
411 echo $_GET['callback'] . '(' . $json_payload . ')';
413 header("Content-type: application/json");
417 // Legacy slower XML format output
418 $data = ping_format_xml_data($data, $sysnotify_count, $notifications, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen);
420 header("Content-type: text/xml");
421 echo XML::fromArray(["result" => $data], $xml);
428 * @brief Retrieves the notifications array for the given user ID
430 * @param int $uid User id
431 * @return array Associative array of notifications
433 function ping_get_notifications($uid)
446 "SELECT `notify`.*, `item`.`visible`, `item`.`spam`, `item`.`deleted`
447 FROM `notify` LEFT JOIN `item` ON `item`.`id` = `notify`.`iid`
448 WHERE `notify`.`uid` = %d AND `notify`.`msg` != ''
449 AND NOT (`notify`.`type` IN (%d, %d))
450 AND $seensql `notify`.`seen` ORDER BY `notify`.`date` $order LIMIT %d, 50",
452 intval(NOTIFY_INTRO),
468 foreach ($r as $notification) {
469 if (is_null($notification["visible"])) {
470 $notification["visible"] = true;
473 if (is_null($notification["spam"])) {
474 $notification["spam"] = 0;
477 if (is_null($notification["deleted"])) {
478 $notification["deleted"] = 0;
481 if ($notification["msg_cache"]) {
482 $notification["name"] = $notification["name_cache"];
483 $notification["message"] = $notification["msg_cache"];
485 $notification["name"] = strip_tags(BBCode::convert($notification["name"]));
486 $notification["message"] = format_notification_message($notification["name"], strip_tags(BBCode::convert($notification["msg"])));
489 "UPDATE `notify` SET `name_cache` = '%s', `msg_cache` = '%s' WHERE `id` = %d",
490 dbesc($notification["name"]),
491 dbesc($notification["message"]),
492 intval($notification["id"])
496 $notification["href"] = System::baseUrl() . "/notify/view/" . $notification["id"];
498 if ($notification["visible"]
499 && !$notification["spam"]
500 && !$notification["deleted"]
501 && !(x($result, $notification["parent"]) && is_array($result[$notification["parent"]]))
503 // Should we condense the notifications or show them all?
504 if (PConfig::get(local_user(), 'system', 'detailed_notif')) {
505 $result[$notification["id"]] = $notification;
507 $result[$notification["parent"]] = $notification;
511 } while ((count($result) < 50) && !$quit);
517 * @brief Backward-compatible XML formatting for ping.php output
520 * @param array $data The initial ping data array
521 * @param int $sysnotify Number of unseen system notifications
522 * @param array $notifs Complete list of notification
523 * @param array $sysmsgs List of system notice messages
524 * @param array $sysmsgs_info List of system info messages
525 * @param int $groups_unseen Number of unseen group items
526 * @param int $forums_unseen Number of unseen forum items
527 * @return array XML-transform ready data array
529 function ping_format_xml_data($data, $sysnotify, $notifs, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen)
532 foreach ($notifs as $key => $notif) {
533 $notifications[$key . ':note'] = $notif['message'];
535 $notifications[$key . ':@attributes'] = [
536 'id' => $notif['id'],
537 'href' => $notif['href'],
538 'name' => $notif['name'],
539 'url' => $notif['url'],
540 'photo' => $notif['photo'],
541 'date' => $notif['date'],
542 'seen' => $notif['seen'],
543 'timestamp' => $notif['timestamp']
548 foreach ($sysmsgs as $key => $m) {
549 $sysmsg[$key . ':notice'] = $m;
551 foreach ($sysmsgs_info as $key => $m) {
552 $sysmsg[$key . ':info'] = $m;
555 $data['notif'] = $notifications;
556 $data['@attributes'] = ['count' => $sysnotify_count + $data['intro'] + $data['mail'] + $data['register']];
557 $data['sysmsgs'] = $sysmsg;
559 if ($data['register'] == 0) {
560 unset($data['register']);
564 if (count($groups_unseen)) {
565 foreach ($groups_unseen as $key => $item) {
566 $groups[$key . ':group'] = $item['count'];
567 $groups[$key . ':@attributes'] = ['id' => $item['id']];
569 $data['groups'] = $groups;
573 if (count($forums_unseen)) {
574 foreach ($forums_unseen as $key => $item) {
575 $forums[$key . ':forum'] = $item['count'];
576 $forums[$key . ':@attributes'] = ['id' => $item['id']];
578 $data['forums'] = $forums;