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\Util\DateTimeFormat;
34 use Friendica\Util\Temporal;
35 use Friendica\Util\Proxy as ProxyUtils;
36 use Friendica\Util\XML;
39 * Outputs the counts and the lists of various notifications
41 * The output format can be controlled via the GET parameter 'format'. It can be
42 * - xml (deprecated legacy default)
43 * - json (outputs JSONP with the 'callback' GET parameter)
45 * Expected JSON structure:
54 * "all-events-today": 0,
58 * "birthdays-today": 0,
62 * "notifications": [ ],
70 * @param App $a The Friendica App instance
71 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
73 function ping_init(App $a)
77 if (isset($_GET['format']) && $_GET['format'] == 'json') {
94 $all_events_today = 0;
101 $data['intro'] = $intro_count;
102 $data['mail'] = $mail_count;
103 $data['net'] = $network_count;
104 $data['home'] = $home_count;
105 $data['register'] = $register_count;
107 $data['all-events'] = $all_events;
108 $data['all-events-today'] = $all_events_today;
109 $data['events'] = $events;
110 $data['events-today'] = $events_today;
111 $data['birthdays'] = $birthdays;
112 $data['birthdays-today'] = $birthdays_today;
115 // Different login session than the page that is calling us.
116 if (!empty($_GET['uid']) && intval($_GET['uid']) != local_user()) {
117 $data = ['result' => ['invalid' => 1]];
119 if ($format == 'json') {
120 if (isset($_GET['callback'])) {
122 header("Content-type: application/javascript");
123 echo $_GET['callback'] . '(' . json_encode($data) . ')';
125 header("Content-type: application/json");
126 echo json_encode($data);
129 header("Content-type: text/xml");
130 echo XML::fromArray($data, $xml);
135 $notifs = ping_get_notifications(local_user());
137 $condition = ["`unseen` AND `uid` = ? AND `contact-id` != ?", local_user(), local_user()];
138 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
139 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid', 'wall'];
140 $params = ['order' => ['received' => true]];
141 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
143 if (DBA::isResult($items)) {
144 $items_unseen = Item::inArray($items);
145 $arr = ['items' => $items_unseen];
146 Hook::callAll('network_ping', $arr);
148 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` LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
182 WHERE `intro`.`uid` = %d AND `intro`.`blocked` = 0 AND `intro`.`ignore` = 0 AND `intro`.`fid` != 0",
186 "SELECT `intro`.`id`, `intro`.`datetime`,
187 `contact`.`name`, `contact`.`url`, `contact`.`photo`
188 FROM `intro` LEFT JOIN `contact` ON `intro`.`contact-id` = `contact`.`id`
189 WHERE `intro`.`uid` = %d AND `intro`.`blocked` = 0 AND `intro`.`ignore` = 0 AND `intro`.`contact-id` != 0",
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;
257 $data['home'] = $home_count;
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($notifs)) {
268 foreach ($notifs 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' => $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'),
292 if (DBA::isResult($regs)) {
293 foreach ($regs as $reg) {
296 'href' => DI::baseUrl() . '/admin/users/',
297 'name' => $reg['name'],
298 'url' => $reg['url'],
299 'photo' => $reg['micro'],
300 'date' => $reg['created'],
302 'message' => DI::l10n()->t('{0} requested registration'),
308 // sort notifications by $[]['date']
309 $sort_function = function ($a, $b) {
310 $adate = strtotime($a['date']);
311 $bdate = strtotime($b['date']);
313 // Unseen messages are kept at the top
314 // The value 31536000 means one year. This should be enough :-)
322 if ($adate == $bdate) {
325 return ($adate < $bdate) ? 1 : -1;
327 usort($notifs, $sort_function);
329 if (DBA::isResult($notifs)) {
330 foreach ($notifs as $notif) {
331 $contact = Contact::getDetailsByURL($notif['url']);
332 if (isset($contact['micro'])) {
333 $notif['photo'] = ProxyUtils::proxifyUrl($contact['micro'], false, ProxyUtils::SIZE_MICRO);
335 $notif['photo'] = ProxyUtils::proxifyUrl($notif['photo'], false, ProxyUtils::SIZE_MICRO);
338 $local_time = DateTimeFormat::local($notif['date']);
341 'id' => $notif['id'],
342 'href' => $notif['href'],
343 'name' => $notif['name'],
344 'url' => $notif['url'],
345 'photo' => $notif['photo'],
346 'date' => Temporal::getRelativeDate($notif['date']),
347 'message' => $notif['message'],
348 'seen' => $notif['seen'],
349 'timestamp' => strtotime($local_time)
358 if (!empty($_SESSION['sysmsg'])) {
359 $sysmsgs = $_SESSION['sysmsg'];
360 unset($_SESSION['sysmsg']);
363 if (!empty($_SESSION['sysmsg_info'])) {
364 $sysmsgs_info = $_SESSION['sysmsg_info'];
365 unset($_SESSION['sysmsg_info']);
368 if ($format == 'json') {
369 $data['groups'] = $groups_unseen;
370 $data['forums'] = $forums_unseen;
371 $data['notification'] = $sysnotify_count + $intro_count + $register_count;
372 $data['notifications'] = $notifications;
374 'notice' => $sysmsgs,
375 'info' => $sysmsgs_info
378 $json_payload = json_encode(["result" => $data]);
380 if (isset($_GET['callback'])) {
382 header("Content-type: application/javascript");
383 echo $_GET['callback'] . '(' . $json_payload . ')';
385 header("Content-type: application/json");
389 // Legacy slower XML format output
390 $data = ping_format_xml_data($data, $sysnotify_count, $notifications, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen);
392 header("Content-type: text/xml");
393 echo XML::fromArray(["result" => $data], $xml);
400 * Retrieves the notifications array for the given user ID
402 * @param int $uid User id
403 * @return array Associative array of notifications
404 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
406 function ping_get_notifications($uid)
417 "SELECT `notify`.*, `item`.`visible`, `item`.`deleted`
418 FROM `notify` LEFT JOIN `item` ON `item`.`id` = `notify`.`iid`
419 WHERE `notify`.`uid` = %d AND `notify`.`msg` != ''
420 AND NOT (`notify`.`type` IN (%d, %d))
421 AND $seensql `notify`.`seen` ORDER BY `notify`.`date` $order LIMIT %d, 50",
439 foreach ($r as $notification) {
440 if (is_null($notification["visible"])) {
441 $notification["visible"] = true;
444 if (is_null($notification["deleted"])) {
445 $notification["deleted"] = 0;
448 if ($notification["msg_cache"]) {
449 $notification["name"] = $notification["name_cache"];
450 $notification["message"] = $notification["msg_cache"];
452 $notification["name"] = strip_tags(BBCode::convert($notification["name"]));
453 $notification["message"] = Friendica\Model\Notify::formatMessage($notification["name"], strip_tags(BBCode::convert($notification["msg"])));
456 "UPDATE `notify` SET `name_cache` = '%s', `msg_cache` = '%s' WHERE `id` = %d",
457 DBA::escape($notification["name"]),
458 DBA::escape($notification["message"]),
459 intval($notification["id"])
463 $notification["href"] = DI::baseUrl() . "/notification/" . $notification["id"];
465 if ($notification["visible"]
466 && !$notification["deleted"]
467 && empty($result[$notification["parent"]])
469 // Should we condense the notifications or show them all?
470 if (DI::pConfig()->get(local_user(), 'system', 'detailed_notif')) {
471 $result[$notification["id"]] = $notification;
473 $result[$notification["parent"]] = $notification;
477 } while ((count($result) < 50) && !$quit);
483 * Backward-compatible XML formatting for ping.php output
486 * @param array $data The initial ping data array
487 * @param int $sysnotify_count Number of unseen system notifications
488 * @param array $notifs Complete list of notification
489 * @param array $sysmsgs List of system notice messages
490 * @param array $sysmsgs_info List of system info messages
491 * @param array $groups_unseen List of unseen group items
492 * @param array $forums_unseen List of unseen forum items
494 * @return array XML-transform ready data array
496 function ping_format_xml_data($data, $sysnotify_count, $notifs, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen)
499 foreach ($notifs as $key => $notif) {
500 $notifications[$key . ':note'] = $notif['message'];
502 $notifications[$key . ':@attributes'] = [
503 'id' => $notif['id'],
504 'href' => $notif['href'],
505 'name' => $notif['name'],
506 'url' => $notif['url'],
507 'photo' => $notif['photo'],
508 'date' => $notif['date'],
509 'seen' => $notif['seen'],
510 'timestamp' => $notif['timestamp']
515 foreach ($sysmsgs as $key => $m) {
516 $sysmsg[$key . ':notice'] = $m;
518 foreach ($sysmsgs_info as $key => $m) {
519 $sysmsg[$key . ':info'] = $m;
522 $data['notif'] = $notifications;
523 $data['@attributes'] = ['count' => $sysnotify_count + $data['intro'] + $data['mail'] + $data['register']];
524 $data['sysmsgs'] = $sysmsg;
526 if ($data['register'] == 0) {
527 unset($data['register']);
531 if (count($groups_unseen)) {
532 foreach ($groups_unseen as $key => $item) {
533 $groups[$key . ':group'] = $item['count'];
534 $groups[$key . ':@attributes'] = ['id' => $item['id']];
536 $data['groups'] = $groups;
540 if (count($forums_unseen)) {
541 foreach ($forums_unseen as $key => $item) {
542 $forums[$key . ':forum'] = $item['count'];
543 $forums[$key . ':@attributes'] = ['id' => $item['id']];
545 $data['forums'] = $forums;