Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions lib/Controller/ContextController.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use OCA\Tables\Errors\PermissionError;
use OCA\Tables\Helper\IconHelper;
use OCA\Tables\Middleware\Attribute\RequirePermission;
use OCA\Tables\Model\MenuItemInput;
use OCA\Tables\ResponseDefinitions;
use OCA\Tables\Service\ColumnService;
use OCA\Tables\Service\ContextService;
Expand Down Expand Up @@ -101,6 +102,7 @@ public function show(int $contextId): DataResponse {
* @param string $iconName Material design icon name of the context
* @param string $description Descriptive text of the context
* @psalm-param list<array{id: int, type: int, permissions?: int}> $nodes optional nodes to be connected to this context
* @psalm-param ?list<array{label: string, icon?: string, description?: string, targetType?: 'view'|'table'|'url'|'page', targetId?: int, url?: string, technicalName?: string}> $menuItems optional menu of the context, in order; the views and tables it opens become nodes of the context and a page item without a targetId opens the start page; without a menu the context gets one item opening the start page
*
* @return DataResponse<Http::STATUS_OK, TablesContext, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_BAD_REQUEST|Http::STATUS_FORBIDDEN, array{message: string}, array{}>
*
Expand All @@ -109,7 +111,7 @@ public function show(int $contextId): DataResponse {
* 403: lacking permissions on a resource
*/
#[NoAdminRequired]
public function create(string $name, string $iconName, string $description = '', array $nodes = []): DataResponse {
public function create(string $name, string $iconName, string $description = '', array $nodes = [], ?array $menuItems = null): DataResponse {
try {
if (!$this->isValidIcon($iconName)) {
return new DataResponse(['message' => 'Invalid icon name'], Http::STATUS_BAD_REQUEST);
Expand All @@ -121,13 +123,16 @@ public function create(string $name, string $iconName, string $description = '',
$this->sanitizeInputNodes($nodes),
$this->userId,
0,
$menuItems !== null ? MenuItemInput::createListFromInputArray($menuItems, allowNewStartPage: true) : null,
)->jsonSerialize());
} catch (Exception $e) {
return $this->handleError($e);
} catch (PermissionError $e) {
return $this->handlePermissionError($e);
} catch (BadRequestError $e) {
return $this->handleBadRequestError($e);
} catch (InvalidArgumentException $e) {
return $this->handleError(new InternalError($e->getMessage(), $e->getCode(), $e));
return $this->handleBadRequestError(new BadRequestError($e->getMessage(), $e->getCode(), $e));
}
}

Expand All @@ -139,6 +144,7 @@ public function create(string $name, string $iconName, string $description = '',
* @param ?string $iconName provide this parameter to set a new icon
* @param ?string $description provide this parameter to set a new description
* @param ?array{id: int, type: int, permissions: int, order: int} $nodes provide this parameter to set a new list of nodes.
* @psalm-param ?list<array{label: string, icon?: string, description?: string, targetType?: 'view'|'table'|'url'|'page', targetId?: int, url?: string, technicalName?: string}> $menuItems provide this parameter to replace the menu; the views and tables it opens become nodes of the context, and an item without a technicalName keeps the one stored for the same target
*
* @return DataResponse<Http::STATUS_OK, TablesContext, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_NOT_FOUND|Http::STATUS_FORBIDDEN|Http::STATUS_BAD_REQUEST, array{message: string}, array{}>
*
Expand All @@ -150,7 +156,7 @@ public function create(string $name, string $iconName, string $description = '',
* @CanManageContext
*/
#[NoAdminRequired]
public function update(int $contextId, ?string $name, ?string $iconName, ?string $description, ?array $nodes): DataResponse {
public function update(int $contextId, ?string $name, ?string $iconName, ?string $description, ?array $nodes, ?array $menuItems = null): DataResponse {
try {
if ($iconName !== null && !$this->isValidIcon($iconName)) {
return new DataResponse(['message' => 'Invalid icon name'], Http::STATUS_BAD_REQUEST);
Expand All @@ -163,13 +169,18 @@ public function update(int $contextId, ?string $name, ?string $iconName, ?string
$iconName,
$description,
$nodes,
$menuItems !== null ? MenuItemInput::createListFromInputArray($menuItems) : null,
)->jsonSerialize());
} catch (Exception|MultipleObjectsReturnedException $e) {
return $this->handleError($e);
} catch (PermissionError $e) {
return $this->handlePermissionError($e);
} catch (DoesNotExistException $e) {
return $this->handleNotFoundError(new NotFoundError($e->getMessage(), $e->getCode(), $e));
} catch (BadRequestError $e) {
return $this->handleBadRequestError($e);
} catch (InvalidArgumentException $e) {
return $this->handleBadRequestError(new BadRequestError($e->getMessage(), $e->getCode(), $e));
}
}

Expand Down
11 changes: 9 additions & 2 deletions lib/Db/Context.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
* @method setNodes(array $value): void
* @method getPages(): array
* @method setPages(array $value): void
* @method getMenuItems(): array
* @method setMenuItems(array $value): void
*/
class Context extends EntitySuper implements JsonSerializable {
protected ?string $name = null;
Expand All @@ -40,8 +42,9 @@ class Context extends EntitySuper implements JsonSerializable {
protected ?array $sharing = null;
protected ?array $nodes = null;
protected ?array $pages = null;
protected ?array $menuItems = null;

protected const VIRTUAL_PROPERTIES = ['sharing', 'nodes', 'pages'];
protected const VIRTUAL_PROPERTIES = ['sharing', 'nodes', 'pages', 'menuItems'];

public function __construct() {
$this->addType('id', 'integer');
Expand All @@ -56,8 +59,12 @@ public function jsonSerialize(): array {
'iconName' => $this->getIcon(),
'description' => $this->getDescription(),
'owner' => $this->getOwnerId(),
'ownerType' => $this->getOwnerType()
'ownerType' => $this->getOwnerType(),
];
// left out where the menus are not loaded, such as for the navigation bar
if (is_array($this->menuItems)) {
$data['menuItems'] = array_values($this->menuItems);
}

// extended data
if (is_array($this->sharing) || is_array($this->nodes) || is_array($this->pages)) {
Expand Down
88 changes: 34 additions & 54 deletions lib/Db/ContextMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ public function __construct(
IDBConnection $db,
protected UserHelper $userHelper,
protected GroupHelper $groupHelper,
protected MenuItemMapper $menuItemMapper,
) {
parent::__construct($db, $this->table, Context::class);
}
Expand Down Expand Up @@ -81,7 +82,10 @@ protected function getFindContextBaseQuery(?string $userId): IQueryBuilder {
return $qb;
}

protected function formatResultRows(array $rows, ?string $userId) {
/**
* @param array<int, list<MenuItem>>|null $menuItemsByContext the menus by context id, null when they are not loaded
*/
protected function formatResultRows(array $rows, ?string $userId, ?array $menuItemsByContext = null) {
$formatted = [
'id' => $rows[0]['id'],
'name' => $rows[0]['name'],
Expand Down Expand Up @@ -150,6 +154,13 @@ protected function formatResultRows(array $rows, ?string $userId) {
return $carry;
}, []);

if ($menuItemsByContext !== null) {
$formatted['menu_items'] = array_map(
static fn (MenuItem $menuItem): array => $menuItem->jsonSerialize(),
$menuItemsByContext[(int)$rows[0]['id']] ?? [],
);
}

return $this->mapRowToEntity($formatted);
}

Expand All @@ -163,26 +174,9 @@ public function findAll(?string $userId = null): array {
$result = $qb->executeQuery();
$r = $this->withOtherPages($result->fetchAllAssociative());

$contextIds = [];
foreach ($r as $row) {
$contextIds[$row['id']] = 1;
}
$contextIds = array_keys($contextIds);
unset($row);

$resultEntities = [];
foreach ($contextIds as $contextId) {
$workArray = [];
foreach ($r as $row) {
if ((int)$row['id'] === $contextId) {
$workArray[] = $row;
}
}
$resultEntities[] = $this->formatResultRows($workArray, $userId);
}

return $resultEntities;
return $this->formatResultSet($r, $userId, true);
}

public function findForNavBar(string $userId): array {
$qb = $this->getFindContextBaseQuery($userId);
$groupIDs = $this->userHelper->getGroupIdsForUser($userId);
Expand Down Expand Up @@ -213,24 +207,27 @@ public function findForNavBar(string $userId): array {
$result = $qb->executeQuery();
$r = $result->fetchAllAssociative();

$contextIds = [];
foreach ($r as $row) {
$contextIds[$row['id']] = 1;
// the navigation bar shows the applications only, not their menus
return $this->formatResultSet($r, $userId, false);
}

/**
* Groups the joined rows per context, loading the menus of all contexts in one query.
*
* @return Context[]
* @throws Exception
*/
private function formatResultSet(array $rows, ?string $userId, bool $withMenuItems): array {
$rowsByContext = [];
foreach ($rows as $row) {
$rowsByContext[(int)$row['id']][] = $row;
}
$contextIds = array_keys($contextIds);
unset($row);
$menuItemsByContext = $withMenuItems ? $this->menuItemMapper->findByContextIds(array_keys($rowsByContext)) : null;

$resultEntities = [];
foreach ($contextIds as $contextId) {
$workArray = [];
foreach ($r as $row) {
if ((int)$row['id'] === $contextId) {
$workArray[] = $row;
}
}
$resultEntities[] = $this->formatResultRows($workArray, $userId);
foreach ($rowsByContext as $contextRows) {
$resultEntities[] = $this->formatResultRows($contextRows, $userId, $menuItemsByContext);
}

return $resultEntities;
}

Expand All @@ -249,7 +246,7 @@ public function findById(int $contextId, ?string $userId = null): Context {
throw new NotFoundError('Context does not exist');
}

return $this->formatResultRows($r, $userId);
return $this->formatResultRows($r, $userId, $this->menuItemMapper->findByContextIds([$contextId]));
}

/**
Expand All @@ -265,25 +262,8 @@ public function findAllContainingNode(int $nodeType, int $nodeId, string $userId
$result = $qb->executeQuery();
$r = $result->fetchAllAssociative();

$contextIds = [];
foreach ($r as $row) {
$contextIds[$row['id']] = 1;
}
$contextIds = array_keys($contextIds);
unset($row);

$resultEntities = [];
foreach ($contextIds as $contextId) {
$workArray = [];
foreach ($r as $row) {
if ($row['id'] === $contextId) {
$workArray[] = $row;
}
}
$resultEntities[] = $this->formatResultRows($workArray, $userId);
}

return $resultEntities;
// permission checks read the nodes only, not the menus
return $this->formatResultSet($r, $userId, false);
}

/**
Expand Down
15 changes: 15 additions & 0 deletions lib/Db/ContextNodeRelation.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,21 @@ public function __construct() {
$this->addType('permissions', 'integer');
}

/**
* The relation as an application carries it among its nodes, in the shape the
* context mapper reads it.
*
* @return array{id: int, node_id: int, node_type: int, permissions: int}
*/
public function toContextNode(): array {
return [
'id' => (int)$this->getId(),
'node_id' => (int)$this->getNodeId(),
'node_type' => (int)$this->getNodeType(),
'permissions' => (int)$this->getPermissions(),
];
}

public function jsonSerialize(): array {
return [
'id' => $this->getId(),
Expand Down
107 changes: 107 additions & 0 deletions lib/Db/MenuItem.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Tables\Db;

use JsonSerializable;

/**
* An item of the menu of an application. It opens a view, a table, a page of the
* application or a link, and may sit under a top-level item.
*
* @method getContextId(): int
* @method setContextId(int $contextId): void
* @method getLabel(): string
* @method setLabel(string $label): void
* @method getIcon(): ?string
* @method setIcon(?string $icon): void
* @method getDescription(): ?string
* @method setDescription(?string $description): void
* @method getTargetType(): string
* @method setTargetType(string $targetType): void
* @method getTargetId(): ?int
* @method setTargetId(?int $targetId): void
* @method getUrl(): ?string
* @method setUrl(?string $url): void
* @method getTechnicalName(): string
* @method setTechnicalName(string $technicalName): void
* @method getOrder(): int
* @method setOrder(int $order): void
* @method getParentId(): ?int
* @method setParentId(?int $parentId): void
* @method isBroken(): bool
* @method setBroken(bool $broken): void
*/
class MenuItem extends EntitySuper implements JsonSerializable {
public const TARGET_VIEW = 'view';
public const TARGET_TABLE = 'table';
public const TARGET_URL = 'url';
public const TARGET_PAGE = 'page';
public const TARGET_TYPES = [self::TARGET_VIEW, self::TARGET_TABLE, self::TARGET_URL, self::TARGET_PAGE];
public const DEFAULT_NAME_PREFIX = 'item_';
public const MAX_ITEMS_PER_APPLICATION = 200;

protected ?int $contextId = null;
protected ?string $label = null;
protected ?string $icon = null;
protected ?string $description = null;
protected ?string $targetType = null;
protected ?int $targetId = null;
protected ?string $url = null;
protected ?string $technicalName = null;
protected ?int $order = null;
protected ?int $parentId = null;

/** True when the view, table or page the item opens is gone; not stored. */
protected bool $broken = false;

protected const VIRTUAL_PROPERTIES = ['broken'];

public function __construct() {
$this->addType('id', 'integer');
$this->addType('contextId', 'integer');
$this->addType('targetId', 'integer');
$this->addType('order', 'integer');
$this->addType('parentId', 'integer');
$this->addType('broken', 'boolean');
}

/**
* Whether a technical name has the form of the automatic `item_<id>`. Such names are
* reserved, so a given name never collides with the name a later item gets.
*/
public static function isDefaultName(string $technicalName): bool {
return preg_match('/^' . self::DEFAULT_NAME_PREFIX . '[0-9]+$/', $technicalName) === 1;
}

/**
* @return array{id: int, contextId: int, label: string, icon: string|null, description: string|null, targetType: 'view'|'table'|'url'|'page', targetId: int|null, url: string|null, technicalName: string, order: int, parentId: int|null, broken: bool}
*/
public function jsonSerialize(): array {
return [
'id' => $this->getId(),
'contextId' => $this->getContextId(),
'label' => $this->getLabel() ?? '',
'icon' => $this->getIcon(),
'description' => $this->getDescription(),
'targetType' => match ($this->targetType) {
self::TARGET_VIEW => self::TARGET_VIEW,
self::TARGET_TABLE => self::TARGET_TABLE,
self::TARGET_PAGE => self::TARGET_PAGE,
default => self::TARGET_URL,
},
'targetId' => $this->getTargetId(),
'url' => $this->getUrl(),
'technicalName' => $this->technicalName ?? '',
'order' => $this->getOrder() ?? 0,
'parentId' => $this->getParentId(),
'broken' => $this->broken,
];
}
}
Loading
Loading