NavigationManager.php 14 KB

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