3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
23 use Friendica\Content\ForumManager;
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Core\Cache\Duration;
26 use Friendica\Core\Hook;
27 use Friendica\Database\DBA;
29 use Friendica\Model\Contact;
30 use Friendica\Model\Group;
31 use Friendica\Model\Item;
32 use Friendica\Model\Notify\Type;
33 use Friendica\Model\Verb;
34 use Friendica\Protocol\Activity;
35 use Friendica\Util\DateTimeFormat;
36 use Friendica\Util\Temporal;
37 use Friendica\Util\XML;
40 * Outputs the counts and the lists of various notifications
42 * The output format can be controlled via the GET parameter 'format'. It can be
43 * - xml (deprecated legacy default)
44 * - json (outputs JSONP with the 'callback' GET parameter)
46 * Expected JSON structure:
55 * "all-events-today": 0,
59 * "birthdays-today": 0,
63 * "notifications": [ ],
71 * @param App $a The Friendica App instance
72 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
74 function ping_init(App $a)
78 if (isset($_GET['format']) && $_GET['format'] == 'json') {
95 $all_events_today = 0;
102 $data['intro'] = $intro_count;
103 $data['mail'] = $mail_count;
104 $data['net'] = $network_count;
105 $data['home'] = $home_count;
106 $data['register'] = $register_count;
108 $data['all-events'] = $all_events;
109 $data['all-events-today'] = $all_events_today;
110 $data['events'] = $events;
111 $data['events-today'] = $events_today;
112 $data['birthdays'] = $birthdays;
113 $data['birthdays-today'] = $birthdays_today;
116 // Different login session than the page that is calling us.
117 if (!empty($_GET['uid']) && intval($_GET['uid']) != local_user()) {
118 $data = ['result' => ['invalid' => 1]];
120 if ($format == 'json') {
121 if (isset($_GET['callback'])) {
123 header("Content-type: application/javascript");
124 echo $_GET['callback'] . '(' . json_encode($data) . ')';
126 header("Content-type: application/json");
127 echo json_encode($data);
130 header("Content-type: text/xml");
131 echo XML::fromArray($data, $xml);
136 $notifs = ping_get_notifications(local_user());
138 $condition = ["`unseen` AND `uid` = ? AND NOT `origin` AND (`vid` != ? OR `vid` IS NULL)",
139 local_user(), Verb::getID(Activity::FOLLOW)];
140 $items = Item::selectForUser(local_user(), ['wall', 'uid', 'uri-id'], $condition);
141 if (DBA::isResult($items)) {
142 $items_unseen = Item::inArray($items);
143 $arr = ['items' => $items_unseen];
144 Hook::callAll('network_ping', $arr);
146 foreach ($items_unseen as $item) {
156 if ($network_count) {
157 // Find out how unseen network posts are spread across groups
158 $group_counts = Group::countUnseen();
159 if (DBA::isResult($group_counts)) {
160 foreach ($group_counts as $group_count) {
161 if ($group_count['count'] > 0) {
162 $groups_unseen[] = $group_count;
167 $forum_counts = ForumManager::countUnseenItems();
168 if (DBA::isResult($forum_counts)) {
169 foreach ($forum_counts as $forum_count) {
170 if ($forum_count['count'] > 0) {
171 $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 = DI::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(DI::config()->get('config', 'register_policy')) === \Friendica\Module\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 = DI::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 DI::cache()->set($cachekey, $ev, Duration::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' => DI::baseUrl() . '/notifications/intros/' . $intro['id'],
280 'name' => $intro['name'],
281 'url' => $intro['url'],
282 'photo' => $intro['photo'],
283 'date' => $intro['datetime'],
285 'message' => DI::l10n()->t('{0} wants to be your friend'),
291 if (DBA::isResult($regs)) {
292 foreach ($regs as $reg) {
295 'href' => DI::baseUrl() . '/admin/users/',
296 'name' => $reg['name'],
297 'url' => $reg['url'],
298 'photo' => $reg['micro'],
299 'date' => $reg['created'],
301 'message' => DI::l10n()->t('{0} requested registration'),
307 // sort notifications by $[]['date']
308 $sort_function = function ($a, $b) {
309 $adate = strtotime($a['date']);
310 $bdate = strtotime($b['date']);
312 // Unseen messages are kept at the top
313 // The value 31536000 means one year. This should be enough :-)
321 if ($adate == $bdate) {
324 return ($adate < $bdate) ? 1 : -1;
326 usort($notifs, $sort_function);
328 if (DBA::isResult($notifs)) {
329 foreach ($notifs as $notif) {
330 $contact = Contact::getByURL($notif['url'], false, ['micro']);
331 $notif['photo'] = Contact::getMicro($contact, $notif['photo']);
333 $local_time = DateTimeFormat::local($notif['date']);
336 'id' => $notif['id'],
337 'href' => $notif['href'],
338 'name' => $notif['name'],
339 'url' => $notif['url'],
340 'photo' => $notif['photo'],
341 'date' => Temporal::getRelativeDate($notif['date']),
342 'message' => $notif['message'],
343 'seen' => $notif['seen'],
344 'timestamp' => strtotime($local_time)
353 if (!empty($_SESSION['sysmsg'])) {
354 $sysmsgs = $_SESSION['sysmsg'];
355 unset($_SESSION['sysmsg']);
358 if (!empty($_SESSION['sysmsg_info'])) {
359 $sysmsgs_info = $_SESSION['sysmsg_info'];
360 unset($_SESSION['sysmsg_info']);
363 if ($format == 'json') {
364 $data['groups'] = $groups_unseen;
365 $data['forums'] = $forums_unseen;
366 $data['notification'] = $sysnotify_count + $intro_count + $register_count;
367 $data['notifications'] = $notifications;
369 'notice' => $sysmsgs,
370 'info' => $sysmsgs_info
373 $json_payload = json_encode(["result" => $data]);
375 if (isset($_GET['callback'])) {
377 header("Content-type: application/javascript");
378 echo $_GET['callback'] . '(' . $json_payload . ')';
380 header("Content-type: application/json");
384 // Legacy slower XML format output
385 $data = ping_format_xml_data($data, $sysnotify_count, $notifications, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen);
387 header("Content-type: text/xml");
388 echo XML::fromArray(["result" => $data], $xml);
395 * Retrieves the notifications array for the given user ID
397 * @param int $uid User id
398 * @return array Associative array of notifications
399 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
401 function ping_get_notifications($uid)
412 "SELECT `notify`.*, `item`.`visible`, `item`.`deleted`
413 FROM `notify` LEFT JOIN `item` ON `item`.`id` = `notify`.`iid`
414 WHERE `notify`.`uid` = %d AND `notify`.`msg` != ''
415 AND NOT (`notify`.`type` IN (%d, %d))
416 AND $seensql `notify`.`seen` ORDER BY `notify`.`date` $order LIMIT %d, 50",
434 foreach ($r as $notification) {
435 if (is_null($notification["visible"])) {
436 $notification["visible"] = true;
439 if (is_null($notification["deleted"])) {
440 $notification["deleted"] = 0;
443 if ($notification["msg_cache"]) {
444 $notification["name"] = $notification["name_cache"];
445 $notification["message"] = $notification["msg_cache"];
447 $notification["name"] = strip_tags(BBCode::convert($notification["name"]));
448 $notification["message"] = Friendica\Model\Notify::formatMessage($notification["name"], strip_tags(BBCode::convert($notification["msg"])));
451 "UPDATE `notify` SET `name_cache` = '%s', `msg_cache` = '%s' WHERE `id` = %d",
452 DBA::escape($notification["name"]),
453 DBA::escape($notification["message"]),
454 intval($notification["id"])
458 $notification["href"] = DI::baseUrl() . "/notification/" . $notification["id"];
460 if ($notification["visible"]
461 && !$notification["deleted"]
462 && empty($result[$notification['parent']])
464 // Should we condense the notifications or show them all?
465 if (DI::pConfig()->get(local_user(), 'system', 'detailed_notif')) {
466 $result[$notification["id"]] = $notification;
468 $result[$notification['parent']] = $notification;
472 } while ((count($result) < 50) && !$quit);
478 * Backward-compatible XML formatting for ping.php output
481 * @param array $data The initial ping data array
482 * @param int $sysnotify_count Number of unseen system notifications
483 * @param array $notifs Complete list of notification
484 * @param array $sysmsgs List of system notice messages
485 * @param array $sysmsgs_info List of system info messages
486 * @param array $groups_unseen List of unseen group items
487 * @param array $forums_unseen List of unseen forum items
489 * @return array XML-transform ready data array
491 function ping_format_xml_data($data, $sysnotify_count, $notifs, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen)
494 foreach ($notifs as $key => $notif) {
495 $notifications[$key . ':note'] = $notif['message'];
497 $notifications[$key . ':@attributes'] = [
498 'id' => $notif['id'],
499 'href' => $notif['href'],
500 'name' => $notif['name'],
501 'url' => $notif['url'],
502 'photo' => $notif['photo'],
503 'date' => $notif['date'],
504 'seen' => $notif['seen'],
505 'timestamp' => $notif['timestamp']
510 foreach ($sysmsgs as $key => $m) {
511 $sysmsg[$key . ':notice'] = $m;
513 foreach ($sysmsgs_info as $key => $m) {
514 $sysmsg[$key . ':info'] = $m;
517 $data['notif'] = $notifications;
518 $data['@attributes'] = ['count' => $sysnotify_count + $data['intro'] + $data['mail'] + $data['register']];
519 $data['sysmsgs'] = $sysmsg;
521 if ($data['register'] == 0) {
522 unset($data['register']);
526 if (count($groups_unseen)) {
527 foreach ($groups_unseen as $key => $item) {
528 $groups[$key . ':group'] = $item['count'];
529 $groups[$key . ':@attributes'] = ['id' => $item['id']];
531 $data['groups'] = $groups;
535 if (count($forums_unseen)) {
536 foreach ($forums_unseen as $key => $item) {
537 $forums[$key . ':forum'] = $item['count'];
538 $forums[$key . ':@attributes'] = ['id' => $item['id']];
540 $data['forums'] = $forums;