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;
178 $intros1 = DBA::toArray(DBA::p(
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` = ? AND NOT `intro`.`blocked` AND NOT `intro`.`ignore` AND `intro`.`fid` != 0",
185 $intros2 = DBA::toArray(DBA::p(
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` = ? 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->getLoggedInUserNickname();
197 $mail_count = DBA::count('mail', ["`uid` = ? AND NOT `seen` AND `from-url` != ?", local_user(), $myurl]);
199 if (intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::APPROVE && is_site_admin()) {
200 $regs = Friendica\Model\Register::getPending();
202 if (DBA::isResult($regs)) {
203 $register_count = count($regs);
207 $cachekey = "ping_init:".local_user();
208 $ev = DI::cache()->get($cachekey);
210 $ev = DBA::selectToArray('event', ['type', 'start'],
211 ["`uid` = ? AND `start` < ? AND `finish` > ? AND NOT `ignore`",
212 local_user(), DateTimeFormat::utc('now + 7 days'), DateTimeFormat::utcNow()]);
213 if (DBA::isResult($ev)) {
214 DI::cache()->set($cachekey, $ev, Duration::HOUR);
218 if (DBA::isResult($ev)) {
219 $all_events = count($ev);
222 $str_now = DateTimeFormat::localNow('Y-m-d');
223 foreach ($ev as $x) {
225 if ($x['type'] === 'birthday') {
231 if (DateTimeFormat::local($x['start'], 'Y-m-d') === $str_now) {
232 $all_events_today ++;
243 $data['intro'] = $intro_count;
244 $data['mail'] = $mail_count;
245 $data['net'] = ($network_count < 1000) ? $network_count : '999+';
246 $data['home'] = ($home_count < 1000) ? $home_count : '999+';
247 $data['register'] = $register_count;
249 $data['all-events'] = $all_events;
250 $data['all-events-today'] = $all_events_today;
251 $data['events'] = $events;
252 $data['events-today'] = $events_today;
253 $data['birthdays'] = $birthdays;
254 $data['birthdays-today'] = $birthdays_today;
256 if (DBA::isResult($notifications)) {
257 foreach ($notifications as $notif) {
258 if ($notif['seen'] == 0) {
264 // merge all notification types in one array
265 if (DBA::isResult($intros)) {
266 foreach ($intros as $intro) {
269 'href' => DI::baseUrl() . '/notifications/intros/' . $intro['id'],
270 'name' => BBCode::convert($intro['name']),
271 'url' => $intro['url'],
272 'photo' => $intro['photo'],
273 'date' => $intro['datetime'],
275 'message' => DI::l10n()->t('{0} wants to be your friend'),
277 $notifications[] = $notif;
281 if (DBA::isResult($regs)) {
282 if (count($regs) <= 1 || DI::pConfig()->get(local_user(), 'system', 'detailed_notif')) {
283 foreach ($regs as $reg) {
286 'href' => DI::baseUrl() . '/admin/users/pending',
287 'name' => $reg['name'],
288 'url' => $reg['url'],
289 'photo' => $reg['micro'],
290 'date' => $reg['created'],
292 'message' => DI::l10n()->t('{0} requested registration'),
294 $notifications[] = $notif;
299 'href' => DI::baseUrl() . '/admin/users/pending',
300 'name' => $regs[0]['name'],
301 'url' => $regs[0]['url'],
302 'photo' => $regs[0]['micro'],
303 'date' => $regs[0]['created'],
305 'message' => DI::l10n()->t('{0} and %d others requested registration', count($regs) - 1),
307 $notifications[] = $notif;
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($notifications, $sort_function);
332 array_walk($notifications, function (&$notification) {
333 $notification['photo'] = Contact::getAvatarUrlForUrl($notification['url'], local_user(), Proxy::SIZE_MICRO);
334 $notification['timestamp'] = DateTimeFormat::local($notification['date']);
335 $notification['date'] = Temporal::getRelativeDate($notification['date']);
342 if (!empty($_SESSION['sysmsg'])) {
343 $sysmsgs = $_SESSION['sysmsg'];
344 unset($_SESSION['sysmsg']);
347 if (!empty($_SESSION['sysmsg_info'])) {
348 $sysmsgs_info = $_SESSION['sysmsg_info'];
349 unset($_SESSION['sysmsg_info']);
352 if ($format == 'json') {
353 $data['groups'] = $groups_unseen;
354 $data['forums'] = $forums_unseen;
355 $data['notification'] = $sysnotify_count + $intro_count + $register_count;
356 $data['notifications'] = $notifications;
358 'notice' => $sysmsgs,
359 'info' => $sysmsgs_info
362 $json_payload = json_encode(["result" => $data]);
364 if (isset($_GET['callback'])) {
366 header("Content-type: application/javascript");
367 echo $_GET['callback'] . '(' . $json_payload . ')';
369 header("Content-type: application/json");
373 // Legacy slower XML format output
374 $data = ping_format_xml_data($data, $sysnotify_count, $notifications, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen);
376 header("Content-type: text/xml");
377 echo XML::fromArray(["result" => $data], $xml);
384 * Retrieves the notifications array for the given user ID
386 * @param int $uid User id
387 * @return array Associative array of notifications
388 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
390 function ping_get_notifications($uid)
400 $r = DBA::toArray(DBA::p(
401 "SELECT `notify`.*, `post`.`visible`, `post`.`deleted`
402 FROM `notify` LEFT JOIN `post` ON `post`.`uri-id` = `notify`.`uri-id`
403 WHERE `notify`.`uid` = ? AND `notify`.`msg` != ''
404 AND NOT (`notify`.`type` IN (?, ?))
405 AND $seensql `notify`.`seen` ORDER BY `notify`.`date` $order LIMIT ?, 50",
407 Notification\Type::INTRO,
408 Notification\Type::MAIL,
423 foreach ($r as $notification) {
424 if (is_null($notification["visible"])) {
425 $notification["visible"] = true;
428 if (is_null($notification["deleted"])) {
429 $notification["deleted"] = 0;
432 if ($notification["msg_cache"]) {
433 $notification["name"] = $notification["name_cache"];
434 $notification["message"] = $notification["msg_cache"];
436 $notification["name"] = strip_tags(BBCode::convert($notification["name"]));
437 $notification["message"] = \Friendica\Navigation\Notifications\Entity\Notify::formatMessage($notification["name"], BBCode::toPlaintext($notification["msg"]));
439 // @todo Replace this with a call of the Notify model class
440 DBA::update('notify', ['name_cache' => $notification["name"], 'msg_cache' => $notification["message"]], ['id' => $notification["id"]]);
443 $notification["href"] = DI::baseUrl() . "/notification/" . $notification["id"];
445 if ($notification["visible"]
446 && !$notification["deleted"]
447 && empty($result['p:' . $notification['parent']])
449 // Should we condense the notifications or show them all?
450 if (($notification['verb'] != Activity::POST) || DI::pConfig()->get(local_user(), 'system', 'detailed_notif')) {
451 $result[] = $notification;
453 $result['p:' . $notification['parent']] = $notification;
457 } while ((count($result) < 50) && !$quit);
463 * Backward-compatible XML formatting for ping.php output
466 * @param array $data The initial ping data array
467 * @param int $sysnotify_count Number of unseen system notifications
468 * @param array $notifs Complete list of notification
469 * @param array $sysmsgs List of system notice messages
470 * @param array $sysmsgs_info List of system info messages
471 * @param array $groups_unseen List of unseen group items
472 * @param array $forums_unseen List of unseen forum items
474 * @return array XML-transform ready data array
476 function ping_format_xml_data($data, $sysnotify_count, $notifs, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen)
479 foreach ($notifs as $key => $notif) {
480 $notifications[$key . ':note'] = $notif['message'];
482 $notifications[$key . ':@attributes'] = [
483 'id' => $notif['id'],
484 'href' => $notif['href'],
485 'name' => $notif['name'],
486 'url' => $notif['url'],
487 'photo' => $notif['photo'],
488 'date' => $notif['date'],
489 'seen' => $notif['seen'],
490 'timestamp' => $notif['timestamp']
495 foreach ($sysmsgs as $key => $m) {
496 $sysmsg[$key . ':notice'] = $m;
498 foreach ($sysmsgs_info as $key => $m) {
499 $sysmsg[$key . ':info'] = $m;
502 $data['notif'] = $notifications;
503 $data['@attributes'] = ['count' => $sysnotify_count + $data['intro'] + $data['mail'] + $data['register']];
504 $data['sysmsgs'] = $sysmsg;
506 if ($data['register'] == 0) {
507 unset($data['register']);
511 if (count($groups_unseen)) {
512 foreach ($groups_unseen as $key => $item) {
513 $groups[$key . ':group'] = $item['count'];
514 $groups[$key . ':@attributes'] = ['id' => $item['id']];
516 $data['groups'] = $groups;
520 if (count($forums_unseen)) {
521 foreach ($forums_unseen as $key => $item) {
522 $forums[$key . ':forum'] = $item['count'];
523 $forums[$key . ':@attributes'] = ['id' => $item['id']];
525 $data['forums'] = $forums;