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 // Find out how unseen network posts are spread across groups
154 $group_counts = Group::countUnseen();
155 if (DBA::isResult($group_counts)) {
156 foreach ($group_counts as $group_count) {
157 if ($group_count['count'] > 0) {
158 $groups_unseen[] = $group_count;
163 $forum_counts = ForumManager::countUnseenItems();
164 if (DBA::isResult($forum_counts)) {
165 foreach ($forum_counts as $forum_count) {
166 if ($forum_count['count'] > 0) {
167 $forums_unseen[] = $forum_count;
174 "SELECT `intro`.`id`, `intro`.`datetime`,
175 `fcontact`.`name`, `fcontact`.`url`, `fcontact`.`photo`
176 FROM `intro` LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
177 WHERE `intro`.`uid` = %d AND `intro`.`blocked` = 0 AND `intro`.`ignore` = 0 AND `intro`.`fid` != 0",
181 "SELECT `intro`.`id`, `intro`.`datetime`,
182 `contact`.`name`, `contact`.`url`, `contact`.`photo`
183 FROM `intro` LEFT JOIN `contact` ON `intro`.`contact-id` = `contact`.`id`
184 WHERE `intro`.`uid` = %d AND `intro`.`blocked` = 0 AND `intro`.`ignore` = 0 AND `intro`.`contact-id` != 0",
188 $intro_count = count($intros1) + count($intros2);
189 $intros = $intros1 + $intros2;
191 $myurl = System::baseUrl() . '/profile/' . $a->user['nickname'] ;
193 "SELECT `id`, `from-name`, `from-url`, `from-photo`, `created` FROM `mail`
194 WHERE `uid` = %d AND `seen` = 0 AND `from-url` != '%s' ",
195 intval(local_user()),
198 $mail_count = count($mails);
200 if (intval(Config::get('config', 'register_policy')) === REGISTER_APPROVE && is_site_admin()) {
201 $regs = Friendica\Model\Register::getPending();
203 if (DBA::isResult($regs)) {
204 $register_count = count($regs);
208 $cachekey = "ping_init:".local_user();
209 $ev = Cache::get($cachekey);
212 "SELECT type, start, adjust FROM `event`
213 WHERE `event`.`uid` = %d AND `start` < '%s' AND `finish` > '%s' and `ignore` = 0
214 ORDER BY `start` ASC ",
215 intval(local_user()),
216 DBA::escape(DateTimeFormat::utc('now + 7 days')),
217 DBA::escape(DateTimeFormat::utcNow())
219 if (DBA::isResult($ev)) {
220 Cache::set($cachekey, $ev, Cache::HOUR);
224 if (DBA::isResult($ev)) {
225 $all_events = count($ev);
228 $str_now = DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d');
229 foreach ($ev as $x) {
231 if ($x['type'] === 'birthday') {
237 if (DateTimeFormat::convert($x['start'], ((intval($x['adjust'])) ? $a->timezone : 'UTC'), 'UTC', 'Y-m-d') === $str_now) {
238 $all_events_today ++;
249 $data['intro'] = $intro_count;
250 $data['mail'] = $mail_count;
251 $data['net'] = $network_count;
252 $data['home'] = $home_count;
253 $data['register'] = $register_count;
255 $data['all-events'] = $all_events;
256 $data['all-events-today'] = $all_events_today;
257 $data['events'] = $events;
258 $data['events-today'] = $events_today;
259 $data['birthdays'] = $birthdays;
260 $data['birthdays-today'] = $birthdays_today;
262 if (DBA::isResult($notifs)) {
263 foreach ($notifs as $notif) {
264 if ($notif['seen'] == 0) {
270 // merge all notification types in one array
271 if (DBA::isResult($intros)) {
272 foreach ($intros as $intro) {
275 'href' => System::baseUrl() . '/notifications/intros/' . $intro['id'],
276 'name' => $intro['name'],
277 'url' => $intro['url'],
278 'photo' => $intro['photo'],
279 'date' => $intro['datetime'],
281 'message' => L10n::t('{0} wants to be your friend'),
287 if (DBA::isResult($mails)) {
288 foreach ($mails as $mail) {
291 'href' => System::baseUrl() . '/message/' . $mail['id'],
292 'name' => $mail['from-name'],
293 'url' => $mail['from-url'],
294 'photo' => $mail['from-photo'],
295 'date' => $mail['created'],
297 'message' => L10n::t('{0} sent you a message'),
303 if (DBA::isResult($regs)) {
304 foreach ($regs as $reg) {
307 'href' => System::baseUrl() . '/admin/users/',
308 'name' => $reg['name'],
309 'url' => $reg['url'],
310 'photo' => $reg['micro'],
311 'date' => $reg['created'],
313 'message' => L10n::t('{0} requested registration'),
319 // sort notifications by $[]['date']
320 $sort_function = function ($a, $b) {
321 $adate = strtotime($a['date']);
322 $bdate = strtotime($b['date']);
324 // Unseen messages are kept at the top
325 // The value 31536000 means one year. This should be enough :-)
333 if ($adate == $bdate) {
336 return ($adate < $bdate) ? 1 : -1;
338 usort($notifs, $sort_function);
340 if (DBA::isResult($notifs)) {
341 // Are the nofications called from the regular process or via the friendica app?
342 $regularnotifications = (!empty($_GET['uid']) && !empty($_GET['_']));
344 foreach ($notifs as $notif) {
345 if ($a->isFriendicaApp() || !$regularnotifications) {
346 $notif['message'] = str_replace("{0}", $notif['name'], $notif['message']);
349 $contact = Contact::getDetailsByURL($notif['url']);
350 if (isset($contact['micro'])) {
351 $notif['photo'] = ProxyUtils::proxifyUrl($contact['micro'], false, ProxyUtils::SIZE_MICRO);
353 $notif['photo'] = ProxyUtils::proxifyUrl($notif['photo'], false, ProxyUtils::SIZE_MICRO);
356 $local_time = DateTimeFormat::local($notif['date']);
359 'id' => $notif['id'],
360 'href' => $notif['href'],
361 'name' => $notif['name'],
362 'url' => $notif['url'],
363 'photo' => $notif['photo'],
364 'date' => Temporal::getRelativeDate($notif['date']),
365 'message' => $notif['message'],
366 'seen' => $notif['seen'],
367 'timestamp' => strtotime($local_time)
376 if (x($_SESSION, 'sysmsg')) {
377 $sysmsgs = $_SESSION['sysmsg'];
378 unset($_SESSION['sysmsg']);
381 if (x($_SESSION, 'sysmsg_info')) {
382 $sysmsgs_info = $_SESSION['sysmsg_info'];
383 unset($_SESSION['sysmsg_info']);
386 if ($format == 'json') {
387 $data['groups'] = $groups_unseen;
388 $data['forums'] = $forums_unseen;
389 $data['notify'] = $sysnotify_count + $intro_count + $mail_count + $register_count;
390 $data['notifications'] = $notifications;
392 'notice' => $sysmsgs,
393 'info' => $sysmsgs_info
396 $json_payload = json_encode(["result" => $data]);
398 if (isset($_GET['callback'])) {
400 header("Content-type: application/javascript");
401 echo $_GET['callback'] . '(' . $json_payload . ')';
403 header("Content-type: application/json");
407 // Legacy slower XML format output
408 $data = ping_format_xml_data($data, $sysnotify_count, $notifications, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen);
410 header("Content-type: text/xml");
411 echo XML::fromArray(["result" => $data], $xml);
418 * @brief Retrieves the notifications array for the given user ID
420 * @param int $uid User id
421 * @return array Associative array of notifications
423 function ping_get_notifications($uid)
436 "SELECT `notify`.*, `item`.`visible`, `item`.`deleted`
437 FROM `notify` LEFT JOIN `item` ON `item`.`id` = `notify`.`iid`
438 WHERE `notify`.`uid` = %d AND `notify`.`msg` != ''
439 AND NOT (`notify`.`type` IN (%d, %d))
440 AND $seensql `notify`.`seen` ORDER BY `notify`.`date` $order LIMIT %d, 50",
442 intval(NOTIFY_INTRO),
458 foreach ($r as $notification) {
459 if (is_null($notification["visible"])) {
460 $notification["visible"] = true;
463 if (is_null($notification["deleted"])) {
464 $notification["deleted"] = 0;
467 if ($notification["msg_cache"]) {
468 $notification["name"] = $notification["name_cache"];
469 $notification["message"] = $notification["msg_cache"];
471 $notification["name"] = strip_tags(BBCode::convert($notification["name"]));
472 $notification["message"] = format_notification_message($notification["name"], strip_tags(BBCode::convert($notification["msg"])));
475 "UPDATE `notify` SET `name_cache` = '%s', `msg_cache` = '%s' WHERE `id` = %d",
476 DBA::escape($notification["name"]),
477 DBA::escape($notification["message"]),
478 intval($notification["id"])
482 $notification["href"] = System::baseUrl() . "/notify/view/" . $notification["id"];
484 if ($notification["visible"]
485 && !$notification["deleted"]
486 && !(x($result, $notification["parent"]) && !empty($result[$notification["parent"]]))
488 // Should we condense the notifications or show them all?
489 if (PConfig::get(local_user(), 'system', 'detailed_notif')) {
490 $result[$notification["id"]] = $notification;
492 $result[$notification["parent"]] = $notification;
496 } while ((count($result) < 50) && !$quit);
502 * @brief Backward-compatible XML formatting for ping.php output
505 * @param array $data The initial ping data array
506 * @param int $sysnotify_count Number of unseen system notifications
507 * @param array $notifs Complete list of notification
508 * @param array $sysmsgs List of system notice messages
509 * @param array $sysmsgs_info List of system info messages
510 * @param int $groups_unseen Number of unseen group items
511 * @param int $forums_unseen Number of unseen forum items
513 * @return array XML-transform ready data array
515 function ping_format_xml_data($data, $sysnotify_count, $notifs, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen)
518 foreach ($notifs as $key => $notif) {
519 $notifications[$key . ':note'] = $notif['message'];
521 $notifications[$key . ':@attributes'] = [
522 'id' => $notif['id'],
523 'href' => $notif['href'],
524 'name' => $notif['name'],
525 'url' => $notif['url'],
526 'photo' => $notif['photo'],
527 'date' => $notif['date'],
528 'seen' => $notif['seen'],
529 'timestamp' => $notif['timestamp']
534 foreach ($sysmsgs as $key => $m) {
535 $sysmsg[$key . ':notice'] = $m;
537 foreach ($sysmsgs_info as $key => $m) {
538 $sysmsg[$key . ':info'] = $m;
541 $data['notif'] = $notifications;
542 $data['@attributes'] = ['count' => $sysnotify_count + $data['intro'] + $data['mail'] + $data['register']];
543 $data['sysmsgs'] = $sysmsg;
545 if ($data['register'] == 0) {
546 unset($data['register']);
550 if (count($groups_unseen)) {
551 foreach ($groups_unseen as $key => $item) {
552 $groups[$key . ':group'] = $item['count'];
553 $groups[$key . ':@attributes'] = ['id' => $item['id']];
555 $data['groups'] = $groups;
559 if (count($forums_unseen)) {
560 foreach ($forums_unseen as $key => $item) {
561 $forums[$key . ':forum'] = $item['count'];
562 $forums[$key . ':@attributes'] = ['id' => $item['id']];
564 $data['forums'] = $forums;