1
0

NavigationManager.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud GmbH
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC;
  8. use InvalidArgumentException;
  9. use OC\App\AppManager;
  10. use OC\Group\Manager;
  11. use OCP\App\IAppManager;
  12. use OCP\EventDispatcher\IEventDispatcher;
  13. use OCP\IConfig;
  14. use OCP\IGroupManager;
  15. use OCP\INavigationManager;
  16. use OCP\IURLGenerator;
  17. use OCP\IUser;
  18. use OCP\IUserSession;
  19. use OCP\L10N\IFactory;
  20. use OCP\Navigation\Events\LoadAdditionalEntriesEvent;
  21. use Psr\Log\LoggerInterface;
  22. /**
  23. * Manages the ownCloud navigation
  24. */
  25. class NavigationManager implements INavigationManager {
  26. protected $entries = [];
  27. protected $closureEntries = [];
  28. protected $activeEntry;
  29. protected $unreadCounters = [];
  30. /** @var bool */
  31. protected $init = false;
  32. /** @var IAppManager|AppManager */
  33. protected $appManager;
  34. /** @var IURLGenerator */
  35. private $urlGenerator;
  36. /** @var IFactory */
  37. private $l10nFac;
  38. /** @var IUserSession */
  39. private $userSession;
  40. /** @var Manager */
  41. private $groupManager;
  42. /** @var IConfig */
  43. private $config;
  44. /** User defined app order (cached for the `add` function) */
  45. private array $customAppOrder;
  46. private LoggerInterface $logger;
  47. public function __construct(
  48. IAppManager $appManager,
  49. IURLGenerator $urlGenerator,
  50. IFactory $l10nFac,
  51. IUserSession $userSession,
  52. IGroupManager $groupManager,
  53. IConfig $config,
  54. LoggerInterface $logger,
  55. protected IEventDispatcher $eventDispatcher,
  56. ) {
  57. $this->appManager = $appManager;
  58. $this->urlGenerator = $urlGenerator;
  59. $this->l10nFac = $l10nFac;
  60. $this->userSession = $userSession;
  61. $this->groupManager = $groupManager;
  62. $this->config = $config;
  63. $this->logger = $logger;
  64. }
  65. /**
  66. * @inheritDoc
  67. */
  68. public function add($entry) {
  69. if ($entry instanceof \Closure) {
  70. $this->closureEntries[] = $entry;
  71. return;
  72. }
  73. $this->init();
  74. $id = $entry['id'];
  75. $entry['active'] = false;
  76. $entry['unread'] = $this->unreadCounters[$id] ?? 0;
  77. if (!isset($entry['icon'])) {
  78. $entry['icon'] = '';
  79. }
  80. if (!isset($entry['classes'])) {
  81. $entry['classes'] = '';
  82. }
  83. if (!isset($entry['type'])) {
  84. $entry['type'] = 'link';
  85. }
  86. if ($entry['type'] === 'link') {
  87. // app might not be set when using closures, in this case try to fallback to ID
  88. if (!isset($entry['app']) && $this->appManager->isEnabledForUser($id)) {
  89. $entry['app'] = $id;
  90. }
  91. // Set order from user defined app order
  92. $entry['order'] = (int)($this->customAppOrder[$id]['order'] ?? $entry['order'] ?? 100);
  93. }
  94. $this->entries[$id] = $entry;
  95. // Needs to be done after adding the new entry to account for the default entries containing this new entry.
  96. $this->updateDefaultEntries();
  97. }
  98. private function updateDefaultEntries() {
  99. foreach ($this->entries as $id => $entry) {
  100. if ($entry['type'] === 'link') {
  101. $this->entries[$id]['default'] = $id === $this->getDefaultEntryIdForUser($this->userSession->getUser(), false);
  102. }
  103. }
  104. }
  105. /**
  106. * @inheritDoc
  107. */
  108. public function getAll(string $type = 'link'): array {
  109. $this->init();
  110. foreach ($this->closureEntries as $c) {
  111. $this->add($c());
  112. }
  113. $this->closureEntries = [];
  114. $result = $this->entries;
  115. if ($type !== 'all') {
  116. $result = array_filter($this->entries, function ($entry) use ($type) {
  117. return $entry['type'] === $type;
  118. });
  119. }
  120. return $this->proceedNavigation($result, $type);
  121. }
  122. /**
  123. * Sort navigation entries default app is always sorted first, then by order, name and set active flag
  124. *
  125. * @param array $list
  126. * @return array
  127. */
  128. private function proceedNavigation(array $list, string $type): array {
  129. uasort($list, function ($a, $b) {
  130. if (($a['default'] ?? false) xor ($b['default'] ?? false)) {
  131. // Always sort the default app first
  132. return ($a['default'] ?? false) ? -1 : 1;
  133. } elseif (isset($a['order']) && isset($b['order'])) {
  134. // Sort by order
  135. return ($a['order'] < $b['order']) ? -1 : 1;
  136. } elseif (isset($a['order']) || isset($b['order'])) {
  137. // Sort the one that has an order property first
  138. return isset($a['order']) ? -1 : 1;
  139. } else {
  140. // Sort by name otherwise
  141. return ($a['name'] < $b['name']) ? -1 : 1;
  142. }
  143. });
  144. if ($type === 'all' || $type === 'link') {
  145. // There might be the case that no default app was set, in this case the first app is the default app.
  146. // Otherwise the default app is already the ordered first, so setting the default prop will make no difference.
  147. foreach ($list as $index => &$navEntry) {
  148. if ($navEntry['type'] === 'link') {
  149. $navEntry['default'] = true;
  150. break;
  151. }
  152. }
  153. unset($navEntry);
  154. }
  155. $activeEntry = $this->getActiveEntry();
  156. if ($activeEntry !== null) {
  157. foreach ($list as $index => &$navEntry) {
  158. if ($navEntry['id'] == $activeEntry) {
  159. $navEntry['active'] = true;
  160. } else {
  161. $navEntry['active'] = false;
  162. }
  163. }
  164. unset($navEntry);
  165. }
  166. return $list;
  167. }
  168. /**
  169. * removes all the entries
  170. */
  171. public function clear($loadDefaultLinks = true) {
  172. $this->entries = [];
  173. $this->closureEntries = [];
  174. $this->init = !$loadDefaultLinks;
  175. }
  176. /**
  177. * @inheritDoc
  178. */
  179. public function setActiveEntry($appId) {
  180. $this->activeEntry = $appId;
  181. }
  182. /**
  183. * @inheritDoc
  184. */
  185. public function getActiveEntry() {
  186. return $this->activeEntry;
  187. }
  188. private function init() {
  189. if ($this->init) {
  190. return;
  191. }
  192. $this->init = true;
  193. $l = $this->l10nFac->get('lib');
  194. if ($this->config->getSystemValueBool('knowledgebaseenabled', true)) {
  195. $this->add([
  196. 'type' => 'settings',
  197. 'id' => 'help',
  198. 'order' => 99998,
  199. 'href' => $this->urlGenerator->linkToRoute('settings.Help.help'),
  200. 'name' => $l->t('Help & privacy'),
  201. 'icon' => $this->urlGenerator->imagePath('settings', 'help.svg'),
  202. ]);
  203. }
  204. if ($this->userSession->isLoggedIn()) {
  205. // Profile
  206. $this->add([
  207. 'type' => 'settings',
  208. 'id' => 'profile',
  209. 'order' => 1,
  210. 'href' => $this->urlGenerator->linkToRoute(
  211. 'profile.ProfilePage.index',
  212. ['targetUserId' => $this->userSession->getUser()->getUID()],
  213. ),
  214. 'name' => $l->t('View profile'),
  215. ]);
  216. // Accessibility settings
  217. if ($this->appManager->isEnabledForUser('theming', $this->userSession->getUser())) {
  218. $this->add([
  219. 'type' => 'settings',
  220. 'id' => 'accessibility_settings',
  221. 'order' => 2,
  222. 'href' => $this->urlGenerator->linkToRoute('settings.PersonalSettings.index', ['section' => 'theming']),
  223. 'name' => $l->t('Appearance and accessibility'),
  224. 'icon' => $this->urlGenerator->imagePath('theming', 'accessibility-dark.svg'),
  225. ]);
  226. }
  227. if ($this->isAdmin()) {
  228. // App management
  229. $this->add([
  230. 'type' => 'settings',
  231. 'id' => 'core_apps',
  232. 'order' => 5,
  233. 'href' => $this->urlGenerator->linkToRoute('settings.AppSettings.viewApps'),
  234. 'icon' => $this->urlGenerator->imagePath('settings', 'apps.svg'),
  235. 'name' => $l->t('Apps'),
  236. ]);
  237. // Personal settings
  238. $this->add([
  239. 'type' => 'settings',
  240. 'id' => 'settings',
  241. 'order' => 3,
  242. 'href' => $this->urlGenerator->linkToRoute('settings.PersonalSettings.index'),
  243. 'name' => $l->t('Personal settings'),
  244. 'icon' => $this->urlGenerator->imagePath('settings', 'personal.svg'),
  245. ]);
  246. // Admin settings
  247. $this->add([
  248. 'type' => 'settings',
  249. 'id' => 'admin_settings',
  250. 'order' => 4,
  251. 'href' => $this->urlGenerator->linkToRoute('settings.AdminSettings.index', ['section' => 'overview']),
  252. 'name' => $l->t('Administration settings'),
  253. 'icon' => $this->urlGenerator->imagePath('settings', 'admin.svg'),
  254. ]);
  255. } else {
  256. // Personal settings
  257. $this->add([
  258. 'type' => 'settings',
  259. 'id' => 'settings',
  260. 'order' => 3,
  261. 'href' => $this->urlGenerator->linkToRoute('settings.PersonalSettings.index'),
  262. 'name' => $l->t('Settings'),
  263. 'icon' => $this->urlGenerator->imagePath('settings', 'admin.svg'),
  264. ]);
  265. }
  266. $logoutUrl = \OC_User::getLogoutUrl($this->urlGenerator);
  267. if ($logoutUrl !== '') {
  268. // Logout
  269. $this->add([
  270. 'type' => 'settings',
  271. 'id' => 'logout',
  272. 'order' => 99999,
  273. 'href' => $logoutUrl,
  274. 'name' => $l->t('Log out'),
  275. 'icon' => $this->urlGenerator->imagePath('core', 'actions/logout.svg'),
  276. ]);
  277. }
  278. if ($this->isSubadmin()) {
  279. // User management
  280. $this->add([
  281. 'type' => 'settings',
  282. 'id' => 'core_users',
  283. 'order' => 6,
  284. 'href' => $this->urlGenerator->linkToRoute('settings.Users.usersList'),
  285. 'name' => $l->t('Accounts'),
  286. 'icon' => $this->urlGenerator->imagePath('settings', 'users.svg'),
  287. ]);
  288. }
  289. }
  290. $this->eventDispatcher->dispatchTyped(new LoadAdditionalEntriesEvent());
  291. if ($this->userSession->isLoggedIn()) {
  292. $user = $this->userSession->getUser();
  293. $apps = $this->appManager->getEnabledAppsForUser($user);
  294. $this->customAppOrder = json_decode($this->config->getUserValue($user->getUID(), 'core', 'apporder', '[]'), true, flags:JSON_THROW_ON_ERROR);
  295. } else {
  296. $apps = $this->appManager->getInstalledApps();
  297. $this->customAppOrder = [];
  298. }
  299. foreach ($apps as $app) {
  300. if (!$this->userSession->isLoggedIn() && !$this->appManager->isEnabledForUser($app, $this->userSession->getUser())) {
  301. continue;
  302. }
  303. // load plugins and collections from info.xml
  304. $info = $this->appManager->getAppInfo($app);
  305. if (!isset($info['navigations']['navigation'])) {
  306. continue;
  307. }
  308. foreach ($info['navigations']['navigation'] as $key => $nav) {
  309. $nav['type'] = $nav['type'] ?? 'link';
  310. if (!isset($nav['name'])) {
  311. continue;
  312. }
  313. // Allow settings navigation items with no route entry, all other types require one
  314. if (!isset($nav['route']) && $nav['type'] !== 'settings') {
  315. continue;
  316. }
  317. $role = $nav['@attributes']['role'] ?? 'all';
  318. if ($role === 'admin' && !$this->isAdmin()) {
  319. continue;
  320. }
  321. $l = $this->l10nFac->get($app);
  322. $id = $nav['id'] ?? $app . ($key === 0 ? '' : $key);
  323. $order = $nav['order'] ?? 100;
  324. $type = $nav['type'];
  325. $route = !empty($nav['route']) ? $this->urlGenerator->linkToRoute($nav['route']) : '';
  326. $icon = $nav['icon'] ?? null;
  327. if ($icon !== null) {
  328. try {
  329. $icon = $this->urlGenerator->imagePath($app, $icon);
  330. } catch (\RuntimeException $ex) {
  331. // ignore
  332. }
  333. }
  334. if ($icon === null) {
  335. $icon = $this->appManager->getAppIcon($app);
  336. }
  337. if ($icon === null) {
  338. $icon = $this->urlGenerator->imagePath('core', 'default-app-icon');
  339. }
  340. $this->add(array_merge([
  341. // Navigation id
  342. 'id' => $id,
  343. // Order where this entry should be shown
  344. 'order' => $order,
  345. // Target of the navigation entry
  346. 'href' => $route,
  347. // The icon used for the naviation entry
  348. 'icon' => $icon,
  349. // Type of the navigation entry ('link' vs 'settings')
  350. 'type' => $type,
  351. // Localized name of the navigation entry
  352. 'name' => $l->t($nav['name']),
  353. ], $type === 'link' ? [
  354. // App that registered this navigation entry (not necessarly the same as the id)
  355. 'app' => $app,
  356. ] : []
  357. ));
  358. }
  359. }
  360. }
  361. private function isAdmin() {
  362. $user = $this->userSession->getUser();
  363. if ($user !== null) {
  364. return $this->groupManager->isAdmin($user->getUID());
  365. }
  366. return false;
  367. }
  368. private function isSubadmin() {
  369. $user = $this->userSession->getUser();
  370. if ($user !== null) {
  371. return $this->groupManager->getSubAdmin()->isSubAdmin($user);
  372. }
  373. return false;
  374. }
  375. public function setUnreadCounter(string $id, int $unreadCounter): void {
  376. $this->unreadCounters[$id] = $unreadCounter;
  377. }
  378. public function get(string $id): ?array {
  379. $this->init();
  380. foreach ($this->closureEntries as $c) {
  381. $this->add($c());
  382. }
  383. $this->closureEntries = [];
  384. return $this->entries[$id];
  385. }
  386. public function getDefaultEntryIdForUser(?IUser $user = null, bool $withFallbacks = true): string {
  387. $this->init();
  388. // Disable fallbacks here, as we need to override them with the user defaults if none are configured.
  389. $defaultEntryIds = $this->getDefaultEntryIds(false);
  390. $user ??= $this->userSession->getUser();
  391. if ($user !== null) {
  392. $userDefaultEntryIds = explode(',', $this->config->getUserValue($user->getUID(), 'core', 'defaultapp'));
  393. $defaultEntryIds = array_filter(array_merge($userDefaultEntryIds, $defaultEntryIds));
  394. if (empty($defaultEntryIds) && $withFallbacks) {
  395. /* Fallback on user defined apporder */
  396. $customOrders = json_decode($this->config->getUserValue($user->getUID(), 'core', 'apporder', '[]'), true, flags: JSON_THROW_ON_ERROR);
  397. if (!empty($customOrders)) {
  398. // filter only entries with app key (when added using closures or NavigationManager::add the app is not guaranteed to be set)
  399. $customOrders = array_filter($customOrders, static fn ($entry) => isset($entry['app']));
  400. // sort apps by order
  401. usort($customOrders, static fn ($a, $b) => $a['order'] - $b['order']);
  402. // set default apps to sorted apps
  403. $defaultEntryIds = array_map(static fn ($entry) => $entry['app'], $customOrders);
  404. }
  405. }
  406. }
  407. if (empty($defaultEntryIds) && $withFallbacks) {
  408. $defaultEntryIds = ['dashboard','files'];
  409. }
  410. $entryIds = array_keys($this->entries);
  411. // Find the first app that is enabled for the current user
  412. foreach ($defaultEntryIds as $defaultEntryId) {
  413. if (in_array($defaultEntryId, $entryIds, true)) {
  414. return $defaultEntryId;
  415. }
  416. }
  417. // Set fallback to always-enabled files app
  418. return $withFallbacks ? 'files' : '';
  419. }
  420. public function getDefaultEntryIds(bool $withFallbacks = true): array {
  421. $this->init();
  422. $storedIds = explode(',', $this->config->getSystemValueString('defaultapp', $withFallbacks ? 'dashboard,files' : ''));
  423. $ids = [];
  424. $entryIds = array_keys($this->entries);
  425. foreach ($storedIds as $id) {
  426. if (in_array($id, $entryIds, true)) {
  427. $ids[] = $id;
  428. break;
  429. }
  430. }
  431. return array_filter($ids);
  432. }
  433. public function setDefaultEntryIds(array $ids): void {
  434. $this->init();
  435. $entryIds = array_keys($this->entries);
  436. foreach ($ids as $id) {
  437. if (!in_array($id, $entryIds, true)) {
  438. $this->logger->debug('Cannot set unavailable entry as default entry', ['missing_entry' => $id]);
  439. throw new InvalidArgumentException('Entry not available');
  440. }
  441. }
  442. $this->config->setSystemValue('defaultapp', join(',', $ids));
  443. }
  444. }