3 * @copyright Copyright (C) 2010-2021, the Friendica project
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\Notification;
32 use Friendica\Model\Post;
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 $notifications = 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 = Post::selectForUser(local_user(), ['wall', 'uid', 'uri-id'], $condition);
141 if (DBA::isResult($items)) {
142 $items_unseen = Post::toArray($items, false);
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` INNER JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
181 WHERE `intro`.`uid` = %d AND NOT `intro`.`blocked` AND NOT `intro`.`ignore` AND `intro`.`fid` != 0",
185 "SELECT `intro`.`id`, `intro`.`datetime`,
186 `contact`.`name`, `contact`.`url`, `contact`.`photo`
187 FROM `intro` INNER JOIN `contact` ON `intro`.`contact-id` = `contact`.`id`
188 WHERE `intro`.`uid` = %d AND NOT `intro`.`blocked` AND NOT `intro`.`ignore` AND `intro`.`contact-id` != 0 AND (`intro`.`fid` = 0 OR `intro`.`fid` IS NULL)",
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($notifications)) {
267 foreach ($notifications 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' => BBCode::convert($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'),
287 $notifications[] = $notif;
291 if (DBA::isResult($regs)) {
292 if (count($regs) <= 1 || DI::pConfig()->get(local_user(), 'system', 'detailed_notif')) {
293 foreach ($regs as $reg) {
296 'href' => DI::baseUrl() . '/admin/users/pending',
297 'name' => $reg['name'],
298 'url' => $reg['url'],
299 'photo' => $reg['micro'],
300 'date' => $reg['created'],
302 'message' => DI::l10n()->t('{0} requested registration'),
304 $notifications[] = $notif;
309 'href' => DI::baseUrl() . '/admin/users/pending',
310 'name' => $regs[0]['name'],
311 'url' => $regs[0]['url'],
312 'photo' => $regs[0]['micro'],
313 'date' => $regs[0]['created'],
315 'message' => DI::l10n()->t('{0} and %d others requested registration', count($regs) - 1),
317 $notifications[] = $notif;
321 // sort notifications by $[]['date']
322 $sort_function = function ($a, $b) {
323 $adate = strtotime($a['date']);
324 $bdate = strtotime($b['date']);
326 // Unseen messages are kept at the top
327 // The value 31536000 means one year. This should be enough :-)
335 if ($adate == $bdate) {
338 return ($adate < $bdate) ? 1 : -1;
340 usort($notifications, $sort_function);
342 array_walk($notifications, function (&$notification) {
343 if (empty($notification['photo'])) {
344 $contact = Contact::getByURL($notification['url'], false, ['micro', 'id', 'avatar']);
345 $notification['photo'] = Contact::getMicro($contact, $notification['photo']);
348 $notification['timestamp'] = DateTimeFormat::local($notification['date']);
349 $notification['date'] = Temporal::getRelativeDate($notification['date']);
356 if (!empty($_SESSION['sysmsg'])) {
357 $sysmsgs = $_SESSION['sysmsg'];
358 unset($_SESSION['sysmsg']);
361 if (!empty($_SESSION['sysmsg_info'])) {
362 $sysmsgs_info = $_SESSION['sysmsg_info'];
363 unset($_SESSION['sysmsg_info']);
366 if ($format == 'json') {
367 $data['groups'] = $groups_unseen;
368 $data['forums'] = $forums_unseen;
369 $data['notification'] = $sysnotify_count + $intro_count + $register_count;
370 $data['notifications'] = $notifications;
372 'notice' => $sysmsgs,
373 'info' => $sysmsgs_info
376 $json_payload = json_encode(["result" => $data]);
378 if (isset($_GET['callback'])) {
380 header("Content-type: application/javascript");
381 echo $_GET['callback'] . '(' . $json_payload . ')';
383 header("Content-type: application/json");
387 // Legacy slower XML format output
388 $data = ping_format_xml_data($data, $sysnotify_count, $notifications, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen);
390 header("Content-type: text/xml");
391 echo XML::fromArray(["result" => $data], $xml);
398 * Retrieves the notifications array for the given user ID
400 * @param int $uid User id
401 * @return array Associative array of notifications
402 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
404 function ping_get_notifications($uid)
415 "SELECT `notify`.*, `post`.`visible`, `post`.`deleted`
416 FROM `notify` LEFT JOIN `post` ON `post`.`uri-id` = `notify`.`uri-id`
417 WHERE `notify`.`uid` = %d AND `notify`.`msg` != ''
418 AND NOT (`notify`.`type` IN (%d, %d))
419 AND $seensql `notify`.`seen` ORDER BY `notify`.`date` $order LIMIT %d, 50",
421 intval(Notification\Type::INTRO),
422 intval(Notification\Type::MAIL),
437 foreach ($r as $notification) {
438 if (is_null($notification["visible"])) {
439 $notification["visible"] = true;
442 if (is_null($notification["deleted"])) {
443 $notification["deleted"] = 0;
446 if ($notification["msg_cache"]) {
447 $notification["name"] = $notification["name_cache"];
448 $notification["message"] = $notification["msg_cache"];
450 $notification["name"] = strip_tags(BBCode::convert($notification["name"]));
451 $notification["message"] = Notification::formatMessage($notification["name"], strip_tags(BBCode::convert($notification["msg"])));
454 "UPDATE `notify` SET `name_cache` = '%s', `msg_cache` = '%s' WHERE `id` = %d",
455 DBA::escape($notification["name"]),
456 DBA::escape($notification["message"]),
457 intval($notification["id"])
461 $notification["href"] = DI::baseUrl() . "/notification/" . $notification["id"];
463 if ($notification["visible"]
464 && !$notification["deleted"]
465 && empty($result[$notification['parent']])
467 // Should we condense the notifications or show them all?
468 if (DI::pConfig()->get(local_user(), 'system', 'detailed_notif')) {
469 $result[$notification["id"]] = $notification;
471 $result[$notification['parent']] = $notification;
475 } while ((count($result) < 50) && !$quit);
481 * Backward-compatible XML formatting for ping.php output
484 * @param array $data The initial ping data array
485 * @param int $sysnotify_count Number of unseen system notifications
486 * @param array $notifs Complete list of notification
487 * @param array $sysmsgs List of system notice messages
488 * @param array $sysmsgs_info List of system info messages
489 * @param array $groups_unseen List of unseen group items
490 * @param array $forums_unseen List of unseen forum items
492 * @return array XML-transform ready data array
494 function ping_format_xml_data($data, $sysnotify_count, $notifs, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen)
497 foreach ($notifs as $key => $notif) {
498 $notifications[$key . ':note'] = $notif['message'];
500 $notifications[$key . ':@attributes'] = [
501 'id' => $notif['id'],
502 'href' => $notif['href'],
503 'name' => $notif['name'],
504 'url' => $notif['url'],
505 'photo' => $notif['photo'],
506 'date' => $notif['date'],
507 'seen' => $notif['seen'],
508 'timestamp' => $notif['timestamp']
513 foreach ($sysmsgs as $key => $m) {
514 $sysmsg[$key . ':notice'] = $m;
516 foreach ($sysmsgs_info as $key => $m) {
517 $sysmsg[$key . ':info'] = $m;
520 $data['notif'] = $notifications;
521 $data['@attributes'] = ['count' => $sysnotify_count + $data['intro'] + $data['mail'] + $data['register']];
522 $data['sysmsgs'] = $sysmsg;
524 if ($data['register'] == 0) {
525 unset($data['register']);
529 if (count($groups_unseen)) {
530 foreach ($groups_unseen as $key => $item) {
531 $groups[$key . ':group'] = $item['count'];
532 $groups[$key . ':@attributes'] = ['id' => $item['id']];
534 $data['groups'] = $groups;
538 if (count($forums_unseen)) {
539 foreach ($forums_unseen as $key => $item) {
540 $forums[$key . ':forum'] = $item['count'];
541 $forums[$key . ':@attributes'] = ['id' => $item['id']];
543 $data['forums'] = $forums;