]> git.mxchange.org Git - friendica.git/blobdiff - src/Module/Notifications/Ping.php
Preparations for a moderator role
[friendica.git] / src / Module / Notifications / Ping.php
index 7dc215826024dd0ccfa6a5b17c631542fec5c9db..603d6408c7bde7c008f73772441ab63d15fd76e4 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /**
- * @copyright Copyright (C) 2010-2022, the Friendica project
+ * @copyright Copyright (C) 2010-2023, the Friendica project
  *
  * @license GNU AGPL version 3 or any later version
  *
@@ -24,17 +24,22 @@ namespace Friendica\Module\Notifications;
 use Friendica\App;
 use Friendica\BaseModule;
 use Friendica\Contact\Introduction\Repository\Introduction;
-use Friendica\Content\ForumManager;
+use Friendica\Content\GroupManager;
+use Friendica\Core\Cache\Capability\ICanCache;
 use Friendica\Core\Cache\Enum\Duration;
+use Friendica\Core\Config\Capability\IManageConfigValues;
 use Friendica\Core\Hook;
 use Friendica\Core\L10n;
+use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
+use Friendica\Core\Session\Capability\IHandleUserSessions;
 use Friendica\Core\System;
+use Friendica\Database\Database;
 use Friendica\Database\DBA;
-use Friendica\DI;
-use Friendica\Model\Group;
+use Friendica\Model\Circle;
 use Friendica\Model\Post;
 use Friendica\Model\User;
 use Friendica\Model\Verb;
+use Friendica\Module\Conversation\Network;
 use Friendica\Module\Register;
 use Friendica\Module\Response;
 use Friendica\Navigation\Notifications\Entity;
@@ -42,33 +47,60 @@ use Friendica\Navigation\Notifications\Exception\NoMessageException;
 use Friendica\Navigation\Notifications\Factory;
 use Friendica\Navigation\Notifications\Repository;
 use Friendica\Navigation\Notifications\ValueObject;
+use Friendica\Navigation\SystemMessages;
+use Friendica\Network\HTTPException;
 use Friendica\Protocol\Activity;
 use Friendica\Util\DateTimeFormat;
 use Friendica\Util\Profiler;
+use Friendica\Util\Strings;
 use GuzzleHttp\Psr7\Uri;
 use Psr\Log\LoggerInterface;
 
 class Ping extends BaseModule
 {
+       /** @var SystemMessages */
+       private $systemMessages;
        /** @var Repository\Notification */
        private $notificationRepo;
        /** @var Introduction */
        private $introductionRepo;
        /** @var Factory\FormattedNavNotification */
        private $formattedNavNotification;
-
-       public function __construct(Repository\Notification $notificationRepo, Introduction $introductionRepo, Factory\FormattedNavNotification $formattedNavNotification, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, array $server, array $parameters = [])
+       /** @var IHandleUserSessions */
+       private $session;
+       /** @var IManageConfigValues */
+       private $config;
+       /** @var IManagePersonalConfigValues */
+       private $pconfig;
+       /** @var Database */
+       private $database;
+       /** @var ICanCache */
+       private $cache;
+       /** @var Repository\Notify */
+       private $notify;
+       /** @var App */
+       private $app;
+
+       public function __construct(App $app, Repository\Notify $notify, ICanCache $cache, Database $database, IManagePersonalConfigValues $pconfig, IManageConfigValues $config, IHandleUserSessions $session, SystemMessages $systemMessages, Repository\Notification $notificationRepo, Introduction $introductionRepo, Factory\FormattedNavNotification $formattedNavNotification, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, array $server, array $parameters = [])
        {
                parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
 
+               $this->systemMessages           = $systemMessages;
                $this->notificationRepo         = $notificationRepo;
                $this->introductionRepo         = $introductionRepo;
                $this->formattedNavNotification = $formattedNavNotification;
+               $this->session                  = $session;
+               $this->config                   = $config;
+               $this->pconfig                  = $pconfig;
+               $this->database                 = $database;
+               $this->cache                    = $cache;
+               $this->notify                   = $notify;
+               $this->app                      = $app;
        }
 
        protected function rawContent(array $request = [])
        {
-               $regs             = [];
+               $registrations    = [];
                $navNotifications = [];
 
                $intro_count     = 0;
@@ -77,117 +109,109 @@ class Ping extends BaseModule
                $network_count   = 0;
                $register_count  = 0;
                $sysnotify_count = 0;
+               $circles_unseen   = [];
                $groups_unseen   = [];
-               $forums_unseen   = [];
 
                $event_count          = 0;
                $today_event_count    = 0;
                $birthday_count       = 0;
                $today_birthday_count = 0;
 
-
-               if (local_user()) {
-                       if (DI::pConfig()->get(local_user(), 'system', 'detailed_notif')) {
-                               $notifications = $this->notificationRepo->selectDetailedForUser(local_user());
+               // Suppress notification display for group accounts
+               if ($this->session->getLocalUserId() && $this->session->get('page_flags', '') != User::PAGE_FLAGS_COMMUNITY) {
+                       if ($this->pconfig->get($this->session->getLocalUserId(), 'system', 'detailed_notif')) {
+                               $notifications = $this->notificationRepo->selectDetailedForUser($this->session->getLocalUserId());
                        } else {
-                               $notifications = $this->notificationRepo->selectDigestForUser(local_user());
+                               $notifications = $this->notificationRepo->selectDigestForUser($this->session->getLocalUserId());
                        }
 
                        $condition = [
                                "`unseen` AND `uid` = ? AND NOT `origin` AND (`vid` != ? OR `vid` IS NULL)",
-                               local_user(), Verb::getID(Activity::FOLLOW)
+                               $this->session->getLocalUserId(), Verb::getID(Activity::FOLLOW)
                        ];
-                       $items = Post::selectForUser(local_user(), ['wall', 'uid', 'uri-id'], $condition, ['limit' => 1000]);
-                       if (DBA::isResult($items)) {
-                               $items_unseen = Post::toArray($items, false);
-                               $arr          = ['items' => $items_unseen];
-                               Hook::callAll('network_ping', $arr);
-
-                               foreach ($items_unseen as $item) {
-                                       if ($item['wall']) {
-                                               $home_count++;
-                                       } else {
-                                               $network_count++;
-                                       }
+
+                       // No point showing counts for non-top-level posts when the network page is ordered by received field
+                       if (Network::getTimelineOrderBySession($this->session, $this->pconfig) == 'received') {
+                               $condition = DBA::mergeConditions($condition, ["`parent` = `id`"]);
+                       }
+
+                       $items_unseen = $this->database->toArray(Post::selectForUser(
+                               $this->session->getLocalUserId(),
+                               ['wall', 'uid', 'uri-id'],
+                               $condition,
+                               ['limit' => 1000],
+                       ));
+                       $arr = ['items' => $items_unseen];
+                       Hook::callAll('network_ping', $arr);
+
+                       foreach ($items_unseen as $item) {
+                               if ($item['wall']) {
+                                       $home_count++;
+                               } else {
+                                       $network_count++;
                                }
                        }
-                       DBA::close($items);
-
-                       if ($network_count) {
-                               // Find out how unseen network posts are spread across groups
-                               $group_counts = Group::countUnseen();
-                               if (DBA::isResult($group_counts)) {
-                                       foreach ($group_counts as $group_count) {
-                                               if ($group_count['count'] > 0) {
-                                                       $groups_unseen[] = $group_count;
-                                               }
+
+                       $compute_circle_counts = $this->config->get('system','compute_group_counts') ?? $this->config->get('system','compute_circle_counts');
+                       if ($network_count && $compute_circle_counts) {
+                               // Find out how unseen network posts are spread across circles
+                               foreach (Circle::countUnseen() as $circle_count) {
+                                       if ($circle_count['count'] > 0) {
+                                               $circles_unseen[] = $circle_count;
                                        }
                                }
 
-                               $forum_counts = ForumManager::countUnseenItems();
-                               if (DBA::isResult($forum_counts)) {
-                                       foreach ($forum_counts as $forum_count) {
-                                               if ($forum_count['count'] > 0) {
-                                                       $forums_unseen[] = $forum_count;
-                                               }
+                               foreach (GroupManager::countUnseenItems() as $group_count) {
+                                       if ($group_count['count'] > 0) {
+                                               $groups_unseen[] = $group_count;
                                        }
                                }
                        }
 
-                       $intros = $this->introductionRepo->selectForUser(local_user());
+                       $intros = $this->introductionRepo->selectForUser($this->session->getLocalUserId());
 
                        $intro_count = $intros->count();
 
-                       $myurl      = DI::baseUrl() . '/profile/' . DI::app()->getLoggedInUserNickname();
-                       $mail_count = DBA::count('mail', ["`uid` = ? AND NOT `seen` AND `from-url` != ?", local_user(), $myurl]);
-
-                       if (intval(DI::config()->get('config', 'register_policy')) === Register::APPROVE && DI::app()->isSiteAdmin()) {
-                               $regs = \Friendica\Model\Register::getPending();
+                       $myurl      = $this->session->getMyUrl();
+                       $mail_count = $this->database->count('mail', ["`uid` = ? AND NOT `seen` AND `from-url` != ?", $this->session->getLocalUserId(), $myurl]);
 
-                               if (DBA::isResult($regs)) {
-                                       $register_count = count($regs);
-                               }
+                       if (intval($this->config->get('config', 'register_policy')) === Register::APPROVE && $this->session->isSiteAdmin()) {
+                               $registrations = \Friendica\Model\Register::getPending();
+                               $register_count = count($registrations);
                        }
 
-                       $cachekey = 'ping:events:' . local_user();
-                       $ev       = DI::cache()->get($cachekey);
-                       if (is_null($ev)) {
-                               $ev = DBA::selectToArray('event', ['type', 'start'],
+                       $cachekey = 'ping:events:' . $this->session->getLocalUserId();
+                       $events   = $this->cache->get($cachekey);
+                       if (is_null($events)) {
+                               $events = $this->database->selectToArray('event', ['type', 'start'],
                                        ["`uid` = ? AND `start` < ? AND `finish` > ? AND NOT `ignore`",
-                                               local_user(), DateTimeFormat::utc('now + 7 days'), DateTimeFormat::utcNow()]);
-                               if (DBA::isResult($ev)) {
-                                       DI::cache()->set($cachekey, $ev, Duration::HOUR);
-                               }
+                                               $this->session->getLocalUserId(), DateTimeFormat::utc('now + 7 days'), DateTimeFormat::utcNow()]);
+                               $this->cache->set($cachekey, $events, Duration::HOUR);
                        }
 
-                       if (DBA::isResult($ev)) {
-                               $all_events = count($ev);
-
-                               if ($all_events) {
-                                       $str_now = DateTimeFormat::localNow('Y-m-d');
-                                       foreach ($ev as $x) {
-                                               $bd = false;
-                                               if ($x['type'] === 'birthday') {
-                                                       $birthday_count++;
-                                                       $bd = true;
-                                               } else {
-                                                       $event_count++;
-                                               }
-                                               if (DateTimeFormat::local($x['start'], 'Y-m-d') === $str_now) {
-                                                       if ($bd) {
-                                                               $today_birthday_count++;
-                                                       } else {
-                                                               $today_event_count++;
-                                                       }
-                                               }
+                       $now_date = DateTimeFormat::localNow('Y-m-d');
+                       foreach ($events as $event) {
+                               $is_birthday = false;
+                               if ($event['type'] === 'birthday') {
+                                       $birthday_count++;
+                                       $is_birthday = true;
+                               } else {
+                                       $event_count++;
+                               }
+
+                               if (DateTimeFormat::local($event['start'], 'Y-m-d') === $now_date) {
+                                       if ($is_birthday) {
+                                               $today_birthday_count++;
+                                       } else {
+                                               $today_event_count++;
                                        }
                                }
                        }
 
-                       $owner = User::getOwnerDataById(local_user());
+                       $owner = User::getOwnerDataById($this->session->getLocalUserId());
 
                        $navNotifications = array_map(function (Entity\Notification $notification) use ($owner) {
-                               if (!DI::notify()->NotifyOnDesktop($notification)) {
+                               if (!$this->notify->shouldShowOnDesktop($notification)) {
                                        return null;
                                }
                                if (($notification->type == Post\UserNotification::TYPE_NONE) && in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])) {
@@ -207,33 +231,31 @@ class Ping extends BaseModule
 
                        // merge all notification types in one array
                        foreach ($intros as $intro) {
-                               $navNotifications[] = $this->formattedNavNotification->createFromIntro($intro);
+                               try {
+                                       $navNotifications[] = $this->formattedNavNotification->createFromIntro($intro);
+                               } catch (HTTPException\NotFoundException $e) {
+                                       $this->introductionRepo->delete($intro);
+                               }
                        }
 
-                       if (DBA::isResult($regs)) {
-                               if (count($regs) <= 1 || DI::pConfig()->get(local_user(), 'system', 'detailed_notif')) {
-                                       foreach ($regs as $reg) {
-                                               $navNotifications[] = $this->formattedNavNotification->createFromParams(
-                                                       [
-                                                               'name' => $reg['name'],
-                                                               'url'  => $reg['url'],
-                                                       ],
-                                                       DI::l10n()->t('{0} requested registration'),
-                                                       new \DateTime($reg['created'], new \DateTimeZone('UTC')),
-                                                       new Uri(DI::baseUrl()->get(true) . '/admin/users/pending')
-                                               );
-                                       }
-                               } else {
+                       if (count($registrations) <= 1 || $this->pconfig->get($this->session->getLocalUserId(), 'system', 'detailed_notif')) {
+                               foreach ($registrations as $registration) {
                                        $navNotifications[] = $this->formattedNavNotification->createFromParams(
-                                               [
-                                                       'name' => $regs[0]['name'],
-                                                       'url'  => $regs[0]['url'],
-                                               ],
-                                               DI::l10n()->t('{0} and %d others requested registration', count($regs) - 1),
-                                               new \DateTime($regs[0]['created'], new \DateTimeZone('UTC')),
-                                               new Uri(DI::baseUrl()->get(true) . '/admin/users/pending')
+                                               $registration['name'],
+                                               $registration['url'],
+                                               $this->l10n->t('{0} requested registration'),
+                                               new \DateTime($registration['created'], new \DateTimeZone('UTC')),
+                                               new Uri($this->baseUrl . '/moderation/users/pending')
                                        );
                                }
+                       } else {
+                               $navNotifications[] = $this->formattedNavNotification->createFromParams(
+                                       $registrations[0]['name'],
+                                       $registrations[0]['url'],
+                                       $this->l10n->t('{0} and %d others requested registration', count($registrations) - 1),
+                                       new \DateTime($registrations[0]['created'], new \DateTimeZone('UTC')),
+                                       new Uri($this->baseUrl . '/moderation/users/pending')
+                               );
                        }
 
                        // sort notifications by $[]['date']
@@ -255,19 +277,6 @@ class Ping extends BaseModule
                        usort($navNotifications, $sort_function);
                }
 
-               $sysmsgs      = [];
-               $sysmsgs_info = [];
-
-               if (!empty($_SESSION['sysmsg'])) {
-                       $sysmsgs = $_SESSION['sysmsg'];
-                       unset($_SESSION['sysmsg']);
-               }
-
-               if (!empty($_SESSION['sysmsg_info'])) {
-                       $sysmsgs_info = $_SESSION['sysmsg_info'];
-                       unset($_SESSION['sysmsg_info']);
-               }
-
                $notification_count = $sysnotify_count + $intro_count + $register_count;
 
                $data             = [];
@@ -281,15 +290,15 @@ class Ping extends BaseModule
                $data['events-today']    = $today_event_count;
                $data['birthdays']       = $birthday_count;
                $data['birthdays-today'] = $today_birthday_count;
+               $data['circles']         = $circles_unseen;
                $data['groups']          = $groups_unseen;
-               $data['forums']          = $forums_unseen;
                $data['notification']    = ($notification_count < 50) ? $notification_count : '49+';
 
                $data['notifications'] = $navNotifications;
 
                $data['sysmsgs'] = [
-                       'notice' => $sysmsgs,
-                       'info'   => $sysmsgs_info
+                       'notice' => array_map([Strings::class, 'escapeHtml'], $this->systemMessages->flushNotices()),
+                       'info'   => array_map([Strings::class, 'escapeHtml'], $this->systemMessages->flushInfos()),
                ];
 
                if (isset($_GET['callback'])) {