Skip to content
Open
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
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 @@ -77,7 +78,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 @@ -146,6 +150,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 @@ -159,26 +170,9 @@ public function findAll(?string $userId = null): array {
$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 ((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 @@ -209,24 +203,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 @@ -245,7 +242,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 @@ -261,25 +258,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
97 changes: 97 additions & 0 deletions lib/Db/MenuItem.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
<?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];

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');
}

/**
* @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,
];
}
}
112 changes: 112 additions & 0 deletions lib/Db/MenuItemMapper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
<?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 OCP\AppFramework\Db\QBMapper;
use OCP\AppFramework\Db\TTransactional;
use OCP\DB\Exception;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\IDBConnection;

/** @template-extends QBMapper<MenuItem> */
class MenuItemMapper extends QBMapper {
use TTransactional;

private const DB_CHUNK_SIZE = 1_000;

protected string $table = 'tables_contexts_menu_item';

public function __construct(IDBConnection $db) {
parent::__construct($db, $this->table, MenuItem::class);
}

/**
* Inserts a menu item under the default technical name `item_<id>`.
*
* @throws Exception
*/
public function insertWithDefaultName(MenuItem $menuItem): MenuItem {
return $this->atomic(function () use ($menuItem): MenuItem {
$menuItem = $this->insert($menuItem);
$menuItem->setTechnicalName('item_' . $menuItem->getId());
return $this->update($menuItem);
}, $this->db);
}

/**
* @return MenuItem[] ordered by their position in the menu
* @throws Exception
*/
public function findByContextId(int $contextId): array {
return $this->findByContextIds([$contextId])[$contextId] ?? [];
}

/**
* The menu items of the given contexts, each list ordered by position. An item whose
* view or table no longer exists, or whose page is gone or belongs to another context,
* is marked broken.
*
* @param int[] $contextIds
* @return array<int, list<MenuItem>> keyed by context id
* @throws Exception
*/
public function findByContextIds(array $contextIds): array {
if ($contextIds === []) {
return [];
}

$qb = $this->db->getQueryBuilder();
$brokenExpression = sprintf(
'CASE WHEN (m.target_type = %s AND v.id IS NULL) OR (m.target_type = %s AND t.id IS NULL) OR (m.target_type = %s AND p.id IS NULL) THEN 1 ELSE 0 END',
$qb->createNamedParameter(MenuItem::TARGET_VIEW),
$qb->createNamedParameter(MenuItem::TARGET_TABLE),
$qb->createNamedParameter(MenuItem::TARGET_PAGE),
);
$qb->select('m.*')
->selectAlias($qb->createFunction($brokenExpression), 'broken')
->from($this->table, 'm')
->leftJoin('m', 'tables_views', 'v', $qb->expr()->andX(
$qb->expr()->eq('v.id', 'm.target_id'),
$qb->expr()->eq('m.target_type', $qb->createNamedParameter(MenuItem::TARGET_VIEW)),
))
->leftJoin('m', 'tables_tables', 't', $qb->expr()->andX(
$qb->expr()->eq('t.id', 'm.target_id'),
$qb->expr()->eq('m.target_type', $qb->createNamedParameter(MenuItem::TARGET_TABLE)),
))
->leftJoin('m', 'tables_contexts_page', 'p', $qb->expr()->andX(
$qb->expr()->eq('p.id', 'm.target_id'),
$qb->expr()->eq('m.target_type', $qb->createNamedParameter(MenuItem::TARGET_PAGE)),
$qb->expr()->eq('p.context_id', 'm.context_id'),
))
->where($qb->expr()->in('m.context_id', $qb->createParameter('contextIds')))
->orderBy('m.context_id', 'ASC')
->addOrderBy('m.order', 'ASC')
->addOrderBy('m.id', 'ASC');

$byContext = [];
foreach (array_chunk(array_values(array_unique($contextIds)), self::DB_CHUNK_SIZE) as $chunk) {
$qb->setParameter('contextIds', $chunk, IQueryBuilder::PARAM_INT_ARRAY);
foreach ($this->findEntities($qb) as $menuItem) {
$byContext[$menuItem->getContextId()][] = $menuItem;
}
}
return $byContext;
}

/**
* @throws Exception
*/
public function deleteAllByContextId(int $contextId): void {
$qb = $this->db->getQueryBuilder();
$qb->delete($this->table)
->where($qb->expr()->eq('context_id', $qb->createNamedParameter($contextId, IQueryBuilder::PARAM_INT)));
$qb->executeStatement();
}
}
Loading
Loading