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\Protocol\Activity;
34 use Friendica\Util\DateTimeFormat;
35 use Friendica\Util\Temporal;
36 use Friendica\Util\Proxy as ProxyUtils;
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 `contact-id` != ? AND (`activity` != ? OR `activity` IS NULL)",
139 local_user(), local_user(), Item::activityToIndex(Activity::FOLLOW)];
140 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
141 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid', 'wall', 'activity'];
142 $params = ['order' => ['received' => true]];
143 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
145 if (DBA::isResult($items)) {
146 $items_unseen = Item::inArray($items);
147 $arr = ['items' => $items_unseen];
148 Hook::callAll('network_ping', $arr);
150 foreach ($items_unseen as $item) {
159 if ($network_count) {
160 // Find out how unseen network posts are spread across groups
161 $group_counts = Group::countUnseen();
162 if (DBA::isResult($group_counts)) {
163 foreach ($group_counts as $group_count) {
164 if ($group_count['count'] > 0) {
165 $groups_unseen[] = $group_count;
170 $forum_counts = ForumManager::countUnseenItems();
171 if (DBA::isResult($forum_counts)) {
172 foreach ($forum_counts as $forum_count) {
173 if ($forum_count['count'] > 0) {
174 $forums_unseen[] = $forum_count;
181 "SELECT `intro`.`id`, `intro`.`datetime`,
182 `fcontact`.`name`, `fcontact`.`url`, `fcontact`.`photo`
183 FROM `intro` LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
184 WHERE `intro`.`uid` = %d AND `intro`.`blocked` = 0 AND `intro`.`ignore` = 0 AND `intro`.`fid` != 0",
188 "SELECT `intro`.`id`, `intro`.`datetime`,
189 `contact`.`name`, `contact`.`url`, `contact`.`photo`
190 FROM `intro` LEFT JOIN `contact` ON `intro`.`contact-id` = `contact`.`id`
191 WHERE `intro`.`uid` = %d AND `intro`.`blocked` = 0 AND `intro`.`ignore` = 0 AND `intro`.`contact-id` != 0",
195 $intro_count = count($intros1) + count($intros2);
196 $intros = $intros1 + $intros2;
198 $myurl = DI::baseUrl() . '/profile/' . $a->user['nickname'];
200 "SELECT `id`, `from-name`, `from-url`, `from-photo`, `created` FROM `mail`
201 WHERE `uid` = %d AND `seen` = 0 AND `from-url` != '%s' ",
202 intval(local_user()),
205 $mail_count = count($mails);
207 if (intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::APPROVE && is_site_admin()) {
208 $regs = Friendica\Model\Register::getPending();
210 if (DBA::isResult($regs)) {
211 $register_count = count($regs);
215 $cachekey = "ping_init:".local_user();
216 $ev = DI::cache()->get($cachekey);
219 "SELECT type, start, adjust FROM `event`
220 WHERE `event`.`uid` = %d AND `start` < '%s' AND `finish` > '%s' and `ignore` = 0
221 ORDER BY `start` ASC ",
222 intval(local_user()),
223 DBA::escape(DateTimeFormat::utc('now + 7 days')),
224 DBA::escape(DateTimeFormat::utcNow())
226 if (DBA::isResult($ev)) {
227 DI::cache()->set($cachekey, $ev, Duration::HOUR);
231 if (DBA::isResult($ev)) {
232 $all_events = count($ev);
235 $str_now = DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d');
236 foreach ($ev as $x) {
238 if ($x['type'] === 'birthday') {
244 if (DateTimeFormat::convert($x['start'], ((intval($x['adjust'])) ? $a->timezone : 'UTC'), 'UTC', 'Y-m-d') === $str_now) {
245 $all_events_today ++;
256 $data['intro'] = $intro_count;
257 $data['mail'] = $mail_count;
258 $data['net'] = $network_count;
259 $data['home'] = $home_count;
260 $data['register'] = $register_count;
262 $data['all-events'] = $all_events;
263 $data['all-events-today'] = $all_events_today;
264 $data['events'] = $events;
265 $data['events-today'] = $events_today;
266 $data['birthdays'] = $birthdays;
267 $data['birthdays-today'] = $birthdays_today;
269 if (DBA::isResult($notifs)) {
270 foreach ($notifs as $notif) {
271 if ($notif['seen'] == 0) {
277 // merge all notification types in one array
278 if (DBA::isResult($intros)) {
279 foreach ($intros as $intro) {
282 'href' => DI::baseUrl() . '/notifications/intros/' . $intro['id'],
283 'name' => $intro['name'],
284 'url' => $intro['url'],
285 'photo' => $intro['photo'],
286 'date' => $intro['datetime'],
288 'message' => DI::l10n()->t('{0} wants to be your friend'),
294 if (DBA::isResult($regs)) {
295 foreach ($regs as $reg) {
298 'href' => DI::baseUrl() . '/admin/users/',
299 'name' => $reg['name'],
300 'url' => $reg['url'],
301 'photo' => $reg['micro'],
302 'date' => $reg['created'],
304 'message' => DI::l10n()->t('{0} requested registration'),
310 // sort notifications by $[]['date']
311 $sort_function = function ($a, $b) {
312 $adate = strtotime($a['date']);
313 $bdate = strtotime($b['date']);
315 // Unseen messages are kept at the top
316 // The value 31536000 means one year. This should be enough :-)
324 if ($adate == $bdate) {
327 return ($adate < $bdate) ? 1 : -1;
329 usort($notifs, $sort_function);
331 if (DBA::isResult($notifs)) {
332 foreach ($notifs as $notif) {
333 $contact = Contact::getDetailsByURL($notif['url']);
334 if (isset($contact['micro'])) {
335 $notif['photo'] = ProxyUtils::proxifyUrl($contact['micro'], false, ProxyUtils::SIZE_MICRO);
337 $notif['photo'] = ProxyUtils::proxifyUrl($notif['photo'], false, ProxyUtils::SIZE_MICRO);
340 $local_time = DateTimeFormat::local($notif['date']);
343 'id' => $notif['id'],
344 'href' => $notif['href'],
345 'name' => $notif['name'],
346 'url' => $notif['url'],
347 'photo' => $notif['photo'],
348 'date' => Temporal::getRelativeDate($notif['date']),
349 'message' => $notif['message'],
350 'seen' => $notif['seen'],
351 'timestamp' => strtotime($local_time)
360 if (!empty($_SESSION['sysmsg'])) {
361 $sysmsgs = $_SESSION['sysmsg'];
362 unset($_SESSION['sysmsg']);
365 if (!empty($_SESSION['sysmsg_info'])) {
366 $sysmsgs_info = $_SESSION['sysmsg_info'];
367 unset($_SESSION['sysmsg_info']);
370 if ($format == 'json') {
371 $data['groups'] = $groups_unseen;
372 $data['forums'] = $forums_unseen;
373 $data['notification'] = $sysnotify_count + $intro_count + $register_count;
374 $data['notifications'] = $notifications;
376 'notice' => $sysmsgs,
377 'info' => $sysmsgs_info
380 $json_payload = json_encode(["result" => $data]);
382 if (isset($_GET['callback'])) {
384 header("Content-type: application/javascript");
385 echo $_GET['callback'] . '(' . $json_payload . ')';
387 header("Content-type: application/json");
391 // Legacy slower XML format output
392 $data = ping_format_xml_data($data, $sysnotify_count, $notifications, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen);
394 header("Content-type: text/xml");
395 echo XML::fromArray(["result" => $data], $xml);
402 * Retrieves the notifications array for the given user ID
404 * @param int $uid User id
405 * @return array Associative array of notifications
406 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
408 function ping_get_notifications($uid)
419 "SELECT `notify`.*, `item`.`visible`, `item`.`deleted`
420 FROM `notify` LEFT JOIN `item` ON `item`.`id` = `notify`.`iid`
421 WHERE `notify`.`uid` = %d AND `notify`.`msg` != ''
422 AND NOT (`notify`.`type` IN (%d, %d))
423 AND $seensql `notify`.`seen` ORDER BY `notify`.`date` $order LIMIT %d, 50",
441 foreach ($r as $notification) {
442 if (is_null($notification["visible"])) {
443 $notification["visible"] = true;
446 if (is_null($notification["deleted"])) {
447 $notification["deleted"] = 0;
450 if ($notification["msg_cache"]) {
451 $notification["name"] = $notification["name_cache"];
452 $notification["message"] = $notification["msg_cache"];
454 $notification["name"] = strip_tags(BBCode::convert($notification["name"]));
455 $notification["message"] = Friendica\Model\Notify::formatMessage($notification["name"], strip_tags(BBCode::convert($notification["msg"])));
458 "UPDATE `notify` SET `name_cache` = '%s', `msg_cache` = '%s' WHERE `id` = %d",
459 DBA::escape($notification["name"]),
460 DBA::escape($notification["message"]),
461 intval($notification["id"])
465 $notification["href"] = DI::baseUrl() . "/notification/" . $notification["id"];
467 if ($notification["visible"]
468 && !$notification["deleted"]
469 && empty($result[$notification["parent"]])
471 // Should we condense the notifications or show them all?
472 if (DI::pConfig()->get(local_user(), 'system', 'detailed_notif')) {
473 $result[$notification["id"]] = $notification;
475 $result[$notification["parent"]] = $notification;
479 } while ((count($result) < 50) && !$quit);
485 * Backward-compatible XML formatting for ping.php output
488 * @param array $data The initial ping data array
489 * @param int $sysnotify_count Number of unseen system notifications
490 * @param array $notifs Complete list of notification
491 * @param array $sysmsgs List of system notice messages
492 * @param array $sysmsgs_info List of system info messages
493 * @param array $groups_unseen List of unseen group items
494 * @param array $forums_unseen List of unseen forum items
496 * @return array XML-transform ready data array
498 function ping_format_xml_data($data, $sysnotify_count, $notifs, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen)
501 foreach ($notifs as $key => $notif) {
502 $notifications[$key . ':note'] = $notif['message'];
504 $notifications[$key . ':@attributes'] = [
505 'id' => $notif['id'],
506 'href' => $notif['href'],
507 'name' => $notif['name'],
508 'url' => $notif['url'],
509 'photo' => $notif['photo'],
510 'date' => $notif['date'],
511 'seen' => $notif['seen'],
512 'timestamp' => $notif['timestamp']
517 foreach ($sysmsgs as $key => $m) {
518 $sysmsg[$key . ':notice'] = $m;
520 foreach ($sysmsgs_info as $key => $m) {
521 $sysmsg[$key . ':info'] = $m;
524 $data['notif'] = $notifications;
525 $data['@attributes'] = ['count' => $sysnotify_count + $data['intro'] + $data['mail'] + $data['register']];
526 $data['sysmsgs'] = $sysmsg;
528 if ($data['register'] == 0) {
529 unset($data['register']);
533 if (count($groups_unseen)) {
534 foreach ($groups_unseen as $key => $item) {
535 $groups[$key . ':group'] = $item['count'];
536 $groups[$key . ':@attributes'] = ['id' => $item['id']];
538 $data['groups'] = $groups;
542 if (count($forums_unseen)) {
543 foreach ($forums_unseen as $key => $item) {
544 $forums[$key . ':forum'] = $item['count'];
545 $forums[$key . ':@attributes'] = ['id' => $item['id']];
547 $data['forums'] = $forums;