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\Proxy as ProxyUtils;
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 $notifs = ping_get_notifications(local_user());
139 $condition = ["`unseen` AND `uid` = ? AND `contact-id` != ? AND (`vid` != ? OR `vid` IS NULL)",
140 local_user(), local_user(), Verb::getID(Activity::FOLLOW)];
141 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
142 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid', 'wall', 'activity'];
143 $params = ['order' => ['received' => true]];
144 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
146 if (DBA::isResult($items)) {
147 $items_unseen = Item::inArray($items);
148 $arr = ['items' => $items_unseen];
149 Hook::callAll('network_ping', $arr);
151 foreach ($items_unseen as $item) {
160 if ($network_count) {
161 // Find out how unseen network posts are spread across groups
162 $group_counts = Group::countUnseen();
163 if (DBA::isResult($group_counts)) {
164 foreach ($group_counts as $group_count) {
165 if ($group_count['count'] > 0) {
166 $groups_unseen[] = $group_count;
171 $forum_counts = ForumManager::countUnseenItems();
172 if (DBA::isResult($forum_counts)) {
173 foreach ($forum_counts as $forum_count) {
174 if ($forum_count['count'] > 0) {
175 $forums_unseen[] = $forum_count;
182 "SELECT `intro`.`id`, `intro`.`datetime`,
183 `fcontact`.`name`, `fcontact`.`url`, `fcontact`.`photo`
184 FROM `intro` LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
185 WHERE `intro`.`uid` = %d AND `intro`.`blocked` = 0 AND `intro`.`ignore` = 0 AND `intro`.`fid` != 0",
189 "SELECT `intro`.`id`, `intro`.`datetime`,
190 `contact`.`name`, `contact`.`url`, `contact`.`photo`
191 FROM `intro` LEFT JOIN `contact` ON `intro`.`contact-id` = `contact`.`id`
192 WHERE `intro`.`uid` = %d AND `intro`.`blocked` = 0 AND `intro`.`ignore` = 0 AND `intro`.`contact-id` != 0",
196 $intro_count = count($intros1) + count($intros2);
197 $intros = $intros1 + $intros2;
199 $myurl = DI::baseUrl() . '/profile/' . $a->user['nickname'];
201 "SELECT `id`, `from-name`, `from-url`, `from-photo`, `created` FROM `mail`
202 WHERE `uid` = %d AND `seen` = 0 AND `from-url` != '%s' ",
203 intval(local_user()),
206 $mail_count = count($mails);
208 if (intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::APPROVE && is_site_admin()) {
209 $regs = Friendica\Model\Register::getPending();
211 if (DBA::isResult($regs)) {
212 $register_count = count($regs);
216 $cachekey = "ping_init:".local_user();
217 $ev = DI::cache()->get($cachekey);
220 "SELECT type, start, adjust FROM `event`
221 WHERE `event`.`uid` = %d AND `start` < '%s' AND `finish` > '%s' and `ignore` = 0
222 ORDER BY `start` ASC ",
223 intval(local_user()),
224 DBA::escape(DateTimeFormat::utc('now + 7 days')),
225 DBA::escape(DateTimeFormat::utcNow())
227 if (DBA::isResult($ev)) {
228 DI::cache()->set($cachekey, $ev, Duration::HOUR);
232 if (DBA::isResult($ev)) {
233 $all_events = count($ev);
236 $str_now = DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d');
237 foreach ($ev as $x) {
239 if ($x['type'] === 'birthday') {
245 if (DateTimeFormat::convert($x['start'], ((intval($x['adjust'])) ? $a->timezone : 'UTC'), 'UTC', 'Y-m-d') === $str_now) {
246 $all_events_today ++;
257 $data['intro'] = $intro_count;
258 $data['mail'] = $mail_count;
259 $data['net'] = $network_count;
260 $data['home'] = $home_count;
261 $data['register'] = $register_count;
263 $data['all-events'] = $all_events;
264 $data['all-events-today'] = $all_events_today;
265 $data['events'] = $events;
266 $data['events-today'] = $events_today;
267 $data['birthdays'] = $birthdays;
268 $data['birthdays-today'] = $birthdays_today;
270 if (DBA::isResult($notifs)) {
271 foreach ($notifs as $notif) {
272 if ($notif['seen'] == 0) {
278 // merge all notification types in one array
279 if (DBA::isResult($intros)) {
280 foreach ($intros as $intro) {
283 'href' => DI::baseUrl() . '/notifications/intros/' . $intro['id'],
284 'name' => $intro['name'],
285 'url' => $intro['url'],
286 'photo' => $intro['photo'],
287 'date' => $intro['datetime'],
289 'message' => DI::l10n()->t('{0} wants to be your friend'),
295 if (DBA::isResult($regs)) {
296 foreach ($regs as $reg) {
299 'href' => DI::baseUrl() . '/admin/users/',
300 'name' => $reg['name'],
301 'url' => $reg['url'],
302 'photo' => $reg['micro'],
303 'date' => $reg['created'],
305 'message' => DI::l10n()->t('{0} requested registration'),
311 // sort notifications by $[]['date']
312 $sort_function = function ($a, $b) {
313 $adate = strtotime($a['date']);
314 $bdate = strtotime($b['date']);
316 // Unseen messages are kept at the top
317 // The value 31536000 means one year. This should be enough :-)
325 if ($adate == $bdate) {
328 return ($adate < $bdate) ? 1 : -1;
330 usort($notifs, $sort_function);
332 if (DBA::isResult($notifs)) {
333 foreach ($notifs as $notif) {
334 $contact = Contact::getDetailsByURL($notif['url']);
335 if (isset($contact['micro'])) {
336 $notif['photo'] = ProxyUtils::proxifyUrl($contact['micro'], false, ProxyUtils::SIZE_MICRO);
338 $notif['photo'] = ProxyUtils::proxifyUrl($notif['photo'], false, ProxyUtils::SIZE_MICRO);
341 $local_time = DateTimeFormat::local($notif['date']);
344 'id' => $notif['id'],
345 'href' => $notif['href'],
346 'name' => $notif['name'],
347 'url' => $notif['url'],
348 'photo' => $notif['photo'],
349 'date' => Temporal::getRelativeDate($notif['date']),
350 'message' => $notif['message'],
351 'seen' => $notif['seen'],
352 'timestamp' => strtotime($local_time)
361 if (!empty($_SESSION['sysmsg'])) {
362 $sysmsgs = $_SESSION['sysmsg'];
363 unset($_SESSION['sysmsg']);
366 if (!empty($_SESSION['sysmsg_info'])) {
367 $sysmsgs_info = $_SESSION['sysmsg_info'];
368 unset($_SESSION['sysmsg_info']);
371 if ($format == 'json') {
372 $data['groups'] = $groups_unseen;
373 $data['forums'] = $forums_unseen;
374 $data['notification'] = $sysnotify_count + $intro_count + $register_count;
375 $data['notifications'] = $notifications;
377 'notice' => $sysmsgs,
378 'info' => $sysmsgs_info
381 $json_payload = json_encode(["result" => $data]);
383 if (isset($_GET['callback'])) {
385 header("Content-type: application/javascript");
386 echo $_GET['callback'] . '(' . $json_payload . ')';
388 header("Content-type: application/json");
392 // Legacy slower XML format output
393 $data = ping_format_xml_data($data, $sysnotify_count, $notifications, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen);
395 header("Content-type: text/xml");
396 echo XML::fromArray(["result" => $data], $xml);
403 * Retrieves the notifications array for the given user ID
405 * @param int $uid User id
406 * @return array Associative array of notifications
407 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
409 function ping_get_notifications($uid)
420 "SELECT `notify`.*, `item`.`visible`, `item`.`deleted`
421 FROM `notify` LEFT JOIN `item` ON `item`.`id` = `notify`.`iid`
422 WHERE `notify`.`uid` = %d AND `notify`.`msg` != ''
423 AND NOT (`notify`.`type` IN (%d, %d))
424 AND $seensql `notify`.`seen` ORDER BY `notify`.`date` $order LIMIT %d, 50",
442 foreach ($r as $notification) {
443 if (is_null($notification["visible"])) {
444 $notification["visible"] = true;
447 if (is_null($notification["deleted"])) {
448 $notification["deleted"] = 0;
451 if ($notification["msg_cache"]) {
452 $notification["name"] = $notification["name_cache"];
453 $notification["message"] = $notification["msg_cache"];
455 $notification["name"] = strip_tags(BBCode::convert($notification["name"]));
456 $notification["message"] = Friendica\Model\Notify::formatMessage($notification["name"], strip_tags(BBCode::convert($notification["msg"])));
459 "UPDATE `notify` SET `name_cache` = '%s', `msg_cache` = '%s' WHERE `id` = %d",
460 DBA::escape($notification["name"]),
461 DBA::escape($notification["message"]),
462 intval($notification["id"])
466 $notification["href"] = DI::baseUrl() . "/notification/" . $notification["id"];
468 if ($notification["visible"]
469 && !$notification["deleted"]
470 && empty($result[$notification['parent']])
472 // Should we condense the notifications or show them all?
473 if (DI::pConfig()->get(local_user(), 'system', 'detailed_notif')) {
474 $result[$notification["id"]] = $notification;
476 $result[$notification['parent']] = $notification;
480 } while ((count($result) < 50) && !$quit);
486 * Backward-compatible XML formatting for ping.php output
489 * @param array $data The initial ping data array
490 * @param int $sysnotify_count Number of unseen system notifications
491 * @param array $notifs Complete list of notification
492 * @param array $sysmsgs List of system notice messages
493 * @param array $sysmsgs_info List of system info messages
494 * @param array $groups_unseen List of unseen group items
495 * @param array $forums_unseen List of unseen forum items
497 * @return array XML-transform ready data array
499 function ping_format_xml_data($data, $sysnotify_count, $notifs, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen)
502 foreach ($notifs as $key => $notif) {
503 $notifications[$key . ':note'] = $notif['message'];
505 $notifications[$key . ':@attributes'] = [
506 'id' => $notif['id'],
507 'href' => $notif['href'],
508 'name' => $notif['name'],
509 'url' => $notif['url'],
510 'photo' => $notif['photo'],
511 'date' => $notif['date'],
512 'seen' => $notif['seen'],
513 'timestamp' => $notif['timestamp']
518 foreach ($sysmsgs as $key => $m) {
519 $sysmsg[$key . ':notice'] = $m;
521 foreach ($sysmsgs_info as $key => $m) {
522 $sysmsg[$key . ':info'] = $m;
525 $data['notif'] = $notifications;
526 $data['@attributes'] = ['count' => $sysnotify_count + $data['intro'] + $data['mail'] + $data['register']];
527 $data['sysmsgs'] = $sysmsg;
529 if ($data['register'] == 0) {
530 unset($data['register']);
534 if (count($groups_unseen)) {
535 foreach ($groups_unseen as $key => $item) {
536 $groups[$key . ':group'] = $item['count'];
537 $groups[$key . ':@attributes'] = ['id' => $item['id']];
539 $data['groups'] = $groups;
543 if (count($forums_unseen)) {
544 foreach ($forums_unseen as $key => $item) {
545 $forums[$key . ':forum'] = $item['count'];
546 $forums[$key . ':@attributes'] = ['id' => $item['id']];
548 $data['forums'] = $forums;