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\Proxy;
37 use Friendica\Util\Temporal;
38 use Friendica\Util\XML;
41 * Outputs the counts and the lists of various notifications
43 * The output format can be controlled via the GET parameter 'format'. It can be
44 * - xml (deprecated legacy default)
45 * - json (outputs JSONP with the 'callback' GET parameter)
47 * Expected JSON structure:
56 * "all-events-today": 0,
60 * "birthdays-today": 0,
64 * "notifications": [ ],
72 * @param App $a The Friendica App instance
73 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
75 function ping_init(App $a)
79 if (isset($_GET['format']) && $_GET['format'] == 'json') {
96 $all_events_today = 0;
100 $birthdays_today = 0;
103 $data['intro'] = $intro_count;
104 $data['mail'] = $mail_count;
105 $data['net'] = $network_count;
106 $data['home'] = $home_count;
107 $data['register'] = $register_count;
109 $data['all-events'] = $all_events;
110 $data['all-events-today'] = $all_events_today;
111 $data['events'] = $events;
112 $data['events-today'] = $events_today;
113 $data['birthdays'] = $birthdays;
114 $data['birthdays-today'] = $birthdays_today;
117 // Different login session than the page that is calling us.
118 if (!empty($_GET['uid']) && intval($_GET['uid']) != local_user()) {
119 $data = ['result' => ['invalid' => 1]];
121 if ($format == 'json') {
122 if (isset($_GET['callback'])) {
124 header("Content-type: application/javascript");
125 echo $_GET['callback'] . '(' . json_encode($data) . ')';
127 header("Content-type: application/json");
128 echo json_encode($data);
131 header("Content-type: text/xml");
132 echo XML::fromArray($data, $xml);
137 $notifications = ping_get_notifications(local_user());
139 $condition = ["`unseen` AND `uid` = ? AND NOT `origin` AND (`vid` != ? OR `vid` IS NULL)",
140 local_user(), Verb::getID(Activity::FOLLOW)];
141 $items = Post::selectForUser(local_user(), ['wall', 'uid', 'uri-id'], $condition, ['limit' => 1000]);
142 if (DBA::isResult($items)) {
143 $items_unseen = Post::toArray($items, false);
144 $arr = ['items' => $items_unseen];
145 Hook::callAll('network_ping', $arr);
147 foreach ($items_unseen as $item) {
157 if ($network_count) {
158 // Find out how unseen network posts are spread across groups
159 $group_counts = Group::countUnseen();
160 if (DBA::isResult($group_counts)) {
161 foreach ($group_counts as $group_count) {
162 if ($group_count['count'] > 0) {
163 $groups_unseen[] = $group_count;
168 $forum_counts = ForumManager::countUnseenItems();
169 if (DBA::isResult($forum_counts)) {
170 foreach ($forum_counts as $forum_count) {
171 if ($forum_count['count'] > 0) {
172 $forums_unseen[] = $forum_count;
179 "SELECT `intro`.`id`, `intro`.`datetime`,
180 `fcontact`.`name`, `fcontact`.`url`, `fcontact`.`photo`
181 FROM `intro` INNER JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
182 WHERE `intro`.`uid` = %d AND NOT `intro`.`blocked` AND NOT `intro`.`ignore` AND `intro`.`fid` != 0",
186 "SELECT `intro`.`id`, `intro`.`datetime`,
187 `contact`.`name`, `contact`.`url`, `contact`.`photo`
188 FROM `intro` INNER JOIN `contact` ON `intro`.`contact-id` = `contact`.`id`
189 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)",
193 $intro_count = count($intros1) + count($intros2);
194 $intros = $intros1 + $intros2;
196 $myurl = DI::baseUrl() . '/profile/' . $a->user['nickname'];
198 "SELECT `id`, `from-name`, `from-url`, `from-photo`, `created` FROM `mail`
199 WHERE `uid` = %d AND `seen` = 0 AND `from-url` != '%s' ",
200 intval(local_user()),
203 $mail_count = count($mails);
205 if (intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::APPROVE && is_site_admin()) {
206 $regs = Friendica\Model\Register::getPending();
208 if (DBA::isResult($regs)) {
209 $register_count = count($regs);
213 $cachekey = "ping_init:".local_user();
214 $ev = DI::cache()->get($cachekey);
217 "SELECT type, start, adjust FROM `event`
218 WHERE `event`.`uid` = %d AND `start` < '%s' AND `finish` > '%s' and `ignore` = 0
219 ORDER BY `start` ASC ",
220 intval(local_user()),
221 DBA::escape(DateTimeFormat::utc('now + 7 days')),
222 DBA::escape(DateTimeFormat::utcNow())
224 if (DBA::isResult($ev)) {
225 DI::cache()->set($cachekey, $ev, Duration::HOUR);
229 if (DBA::isResult($ev)) {
230 $all_events = count($ev);
233 $str_now = DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d');
234 foreach ($ev as $x) {
236 if ($x['type'] === 'birthday') {
242 if (DateTimeFormat::convert($x['start'], ((intval($x['adjust'])) ? $a->timezone : 'UTC'), 'UTC', 'Y-m-d') === $str_now) {
243 $all_events_today ++;
254 $data['intro'] = $intro_count;
255 $data['mail'] = $mail_count;
256 $data['net'] = ($network_count < 1000) ? $network_count : '999+';
257 $data['home'] = ($home_count < 1000) ? $home_count : '999+';
258 $data['register'] = $register_count;
260 $data['all-events'] = $all_events;
261 $data['all-events-today'] = $all_events_today;
262 $data['events'] = $events;
263 $data['events-today'] = $events_today;
264 $data['birthdays'] = $birthdays;
265 $data['birthdays-today'] = $birthdays_today;
267 if (DBA::isResult($notifications)) {
268 foreach ($notifications as $notif) {
269 if ($notif['seen'] == 0) {
275 // merge all notification types in one array
276 if (DBA::isResult($intros)) {
277 foreach ($intros as $intro) {
280 'href' => DI::baseUrl() . '/notifications/intros/' . $intro['id'],
281 'name' => BBCode::convert($intro['name']),
282 'url' => $intro['url'],
283 'photo' => $intro['photo'],
284 'date' => $intro['datetime'],
286 'message' => DI::l10n()->t('{0} wants to be your friend'),
288 $notifications[] = $notif;
292 if (DBA::isResult($regs)) {
293 if (count($regs) <= 1 || DI::pConfig()->get(local_user(), 'system', 'detailed_notif')) {
294 foreach ($regs as $reg) {
297 'href' => DI::baseUrl() . '/admin/users/pending',
298 'name' => $reg['name'],
299 'url' => $reg['url'],
300 'photo' => $reg['micro'],
301 'date' => $reg['created'],
303 'message' => DI::l10n()->t('{0} requested registration'),
305 $notifications[] = $notif;
310 'href' => DI::baseUrl() . '/admin/users/pending',
311 'name' => $regs[0]['name'],
312 'url' => $regs[0]['url'],
313 'photo' => $regs[0]['micro'],
314 'date' => $regs[0]['created'],
316 'message' => DI::l10n()->t('{0} and %d others requested registration', count($regs) - 1),
318 $notifications[] = $notif;
322 // sort notifications by $[]['date']
323 $sort_function = function ($a, $b) {
324 $adate = strtotime($a['date']);
325 $bdate = strtotime($b['date']);
327 // Unseen messages are kept at the top
328 // The value 31536000 means one year. This should be enough :-)
336 if ($adate == $bdate) {
339 return ($adate < $bdate) ? 1 : -1;
341 usort($notifications, $sort_function);
343 array_walk($notifications, function (&$notification) {
344 $notification['photo'] = Contact::getAvatarUrlForUrl($notification['url'], local_user(), Proxy::SIZE_MICRO);
345 $notification['timestamp'] = DateTimeFormat::local($notification['date']);
346 $notification['date'] = Temporal::getRelativeDate($notification['date']);
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`.*, `post`.`visible`, `post`.`deleted`
413 FROM `notify` LEFT JOIN `post` ON `post`.`uri-id` = `notify`.`uri-id`
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",
418 intval(Notification\Type::INTRO),
419 intval(Notification\Type::MAIL),
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"] = Notification::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;