Skip to content

Commit 29131fa

Browse files
committed
[FEATURE] Name the last editor of recently changed pages and content
get_recently_changed_pages and get_recently_changed_content add "changedBy" for administrators: the username of the newest entry in the record history. For a page that is the newest change of the page, one of its translations or one of its content elements. For every other user the key is missing, like all other information about backend users.
1 parent bfde8a4 commit 29131fa

9 files changed

Lines changed: 322 additions & 14 deletions

File tree

‎Classes/Domain/Mcp/Tool/Content/GetRecentlyChangedContentTool.php‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ public function getDescription(): string
2929
{
3030
return 'Returns the content elements that were changed most recently, newest first, together with the'
3131
. ' title and slug of their page. Hidden elements are included and marked. Times are ISO 8601.'
32+
. ' For administrators "changedBy" names the backend user of the change.'
3233
. ' Pass "pageUid" to look only at one site or section.';
3334
}
3435

‎Classes/Domain/Mcp/Tool/Page/GetRecentlyChangedPagesTool.php‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ public function getDescription(): string
2929
return 'Returns the pages that were changed most recently, newest first. A page counts as changed when its'
3030
. ' properties, one of its translations or one of its content elements changed - "lastChanged" is the'
3131
. ' newest of these, "pagePropertiesChanged" and "contentChanged" tell them apart. Times are ISO 8601.'
32+
. ' For administrators "changedBy" names the backend user of that change.'
3233
. ' Pass "pageUid" to look only at one site or section.';
3334
}
3435

‎Classes/Domain/Repository/BackendUserActivityRepository.php‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,57 @@ public function findRecentChanges(int $userUid, string $table, int $limit): arra
142142
return $queryBuilder->executeQuery()->fetchAllAssociative();
143143
}
144144

145+
/**
146+
* @param array<string, list<int>> $recordUidsByTable
147+
* @return list<array{tablename: string, recuid: int, userid: int}> newest first
148+
* @throws Exception
149+
*/
150+
public function findHistoryOfRecords(array $recordUidsByTable, int $since): array
151+
{
152+
$queryBuilder = $this->getQueryBuilder(self::HISTORY_TABLE);
153+
$recordConstraints = [];
154+
foreach ($recordUidsByTable as $table => $recordUids) {
155+
if ($recordUids === []) {
156+
continue;
157+
}
158+
$recordConstraints[] = $queryBuilder->expr()->and(
159+
$queryBuilder->expr()->eq('tablename', $queryBuilder->createNamedParameter($table)),
160+
$queryBuilder->expr()->in(
161+
'recuid',
162+
$queryBuilder->createNamedParameter($recordUids, Connection::PARAM_INT_ARRAY)
163+
)
164+
);
165+
}
166+
if ($recordConstraints === []) {
167+
return [];
168+
}
169+
170+
$rows = $queryBuilder
171+
->select('tablename', 'recuid', 'userid')
172+
->from(self::HISTORY_TABLE)
173+
->where(
174+
$this->getBackendUserConstraint($queryBuilder),
175+
$queryBuilder->expr()->gte(
176+
'tstamp',
177+
$queryBuilder->createNamedParameter($since, Connection::PARAM_INT)
178+
),
179+
$queryBuilder->expr()->or(...$recordConstraints)
180+
)
181+
->orderBy('tstamp', 'DESC')
182+
->addOrderBy('uid', 'DESC')
183+
->executeQuery()
184+
->fetchAllAssociative();
185+
186+
return array_map(
187+
static fn(array $row): array => [
188+
'tablename' => (string)$row['tablename'],
189+
'recuid' => (int)$row['recuid'],
190+
'userid' => (int)$row['userid'],
191+
],
192+
$rows
193+
);
194+
}
195+
145196
private function getBackendUserConstraint(QueryBuilder $queryBuilder): string
146197
{
147198
return (string)$queryBuilder->expr()->and(

‎Classes/Domain/Repository/RecentChangeRepository.php‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,41 @@ public function findPagesByUids(array $pageUids): array
133133
return array_column($pages, null, 'uid');
134134
}
135135

136+
/**
137+
* Deleted records are included, because deleting one is a change of its page as well
138+
*
139+
* @param list<int> $pageUids
140+
* @return array<int, int> uid of a content element or a page translation => uid of the page it belongs to
141+
* @throws Exception
142+
*/
143+
public function findRecordsOfPages(string $table, array $pageUids): array
144+
{
145+
if ($pageUids === []) {
146+
return [];
147+
}
148+
149+
$pageField = $table === PageRepository::TABLE_NAME ? 'l10n_parent' : 'pid';
150+
$queryBuilder = $this->connectionPool->getQueryBuilderForTable($table);
151+
$queryBuilder->getRestrictions()->removeAll();
152+
$rows = $queryBuilder
153+
->select('uid', $pageField)
154+
->from($table)
155+
->where(
156+
$queryBuilder->expr()->in(
157+
$pageField,
158+
$queryBuilder->createNamedParameter($pageUids, Connection::PARAM_INT_ARRAY)
159+
)
160+
)
161+
->executeQuery()
162+
->fetchAllAssociative();
163+
164+
$pageUidsByRecord = [];
165+
foreach ($rows as $row) {
166+
$pageUidsByRecord[(int)$row['uid']] = (int)$row[$pageField];
167+
}
168+
return $pageUidsByRecord;
169+
}
170+
136171
/**
137172
* @param list<int>|null $pageUids null means every page
138173
* @return list<array<string, mixed>>
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace In2code\In2mcp\Domain\Service;
6+
7+
use Doctrine\DBAL\Exception;
8+
use In2code\In2mcp\Domain\Repository\BackendUserActivityRepository;
9+
use In2code\In2mcp\Domain\Repository\ContentRepository;
10+
use In2code\In2mcp\Domain\Repository\PageRepository;
11+
use In2code\In2mcp\Domain\Repository\RecentChangeRepository;
12+
use In2code\In2mcp\Exception\UserNotFoundException;
13+
14+
/**
15+
* Who changed a record last is information about backend users, so it is given to administrators only
16+
*/
17+
class LastEditorService
18+
{
19+
/**
20+
* A history entry is written in the same request as the change, so its time may differ by a moment
21+
*/
22+
private const HISTORY_TOLERANCE_SECONDS = 60;
23+
24+
public function __construct(
25+
private readonly BackendUserActivityRepository $backendUserActivityRepository,
26+
private readonly RecentChangeRepository $recentChangeRepository,
27+
private readonly BackendUserService $backendUserService,
28+
) {
29+
}
30+
31+
/**
32+
* @throws UserNotFoundException
33+
*/
34+
public function isAvailable(): bool
35+
{
36+
return $this->backendUserService->isAdmin();
37+
}
38+
39+
/**
40+
* A page counts as changed by whoever changed it, one of its translations or one of its content elements last
41+
*
42+
* @param array<int, int> $lastChangeByPage page uid => timestamp of its last change
43+
* @return array<int, string> page uid => username
44+
* @throws Exception
45+
* @throws UserNotFoundException
46+
*/
47+
public function findEditorsOfPages(array $lastChangeByPage): array
48+
{
49+
if ($this->isAvailable() === false || $lastChangeByPage === []) {
50+
return [];
51+
}
52+
53+
$pageUids = array_keys($lastChangeByPage);
54+
$pageUidsByRecord = [
55+
PageRepository::TABLE_NAME => array_combine($pageUids, $pageUids)
56+
+ $this->recentChangeRepository->findRecordsOfPages(PageRepository::TABLE_NAME, $pageUids),
57+
ContentRepository::TABLE_NAME => $this->recentChangeRepository->findRecordsOfPages(
58+
ContentRepository::TABLE_NAME,
59+
$pageUids
60+
),
61+
];
62+
return $this->findEditors($pageUidsByRecord, min($lastChangeByPage));
63+
}
64+
65+
/**
66+
* @param array<int, int> $changeByContent content uid => timestamp of its change
67+
* @return array<int, string> content uid => username
68+
* @throws Exception
69+
* @throws UserNotFoundException
70+
*/
71+
public function findEditorsOfContent(array $changeByContent): array
72+
{
73+
if ($this->isAvailable() === false || $changeByContent === []) {
74+
return [];
75+
}
76+
77+
$contentUids = array_keys($changeByContent);
78+
return $this->findEditors(
79+
[ContentRepository::TABLE_NAME => array_combine($contentUids, $contentUids)],
80+
min($changeByContent)
81+
);
82+
}
83+
84+
/**
85+
* @param list<array{tablename: string, recuid: int, userid: int}> $historyEntries newest first
86+
* @param array<string, array<int, int>> $keysByRecord table => record uid => key the editor is reported for
87+
* @return array<int, int> key => uid of the backend user of the newest entry
88+
*/
89+
public function pickNewestEditors(array $historyEntries, array $keysByRecord): array
90+
{
91+
$editors = [];
92+
foreach ($historyEntries as $entry) {
93+
$key = $keysByRecord[$entry['tablename']][$entry['recuid']] ?? null;
94+
if ($key !== null && array_key_exists($key, $editors) === false) {
95+
$editors[$key] = $entry['userid'];
96+
}
97+
}
98+
return $editors;
99+
}
100+
101+
/**
102+
* @param array<string, array<int, int>> $keysByRecord
103+
* @return array<int, string>
104+
* @throws Exception
105+
*/
106+
private function findEditors(array $keysByRecord, int $oldestChange): array
107+
{
108+
$historyEntries = $this->backendUserActivityRepository->findHistoryOfRecords(
109+
array_map(static fn(array $keys): array => array_keys($keys), $keysByRecord),
110+
$oldestChange - self::HISTORY_TOLERANCE_SECONDS
111+
);
112+
$editorUids = $this->pickNewestEditors($historyEntries, $keysByRecord);
113+
$usernames = $this->backendUserActivityRepository->findUsernames(array_values(array_unique($editorUids)));
114+
115+
$editors = [];
116+
foreach ($editorUids as $key => $userUid) {
117+
$editors[$key] = $usernames[$userUid] ?? ('#' . $userUid);
118+
}
119+
return $editors;
120+
}
121+
}

‎Classes/Domain/Service/RecentChangeService.php‎

Lines changed: 42 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ public function __construct(
3838
private readonly PageRepository $pageRepository,
3939
private readonly BackendUserService $backendUserService,
4040
private readonly TcaService $tcaService,
41+
private readonly LastEditorService $lastEditorService,
4142
) {
4243
}
4344

@@ -57,11 +58,14 @@ public function getRecentlyChangedPages(int $rootPageUid, int $limit): array
5758
$limit
5859
);
5960
$pages = $this->recentChangeRepository->findPagesByUids(array_keys($ranking));
61+
$editors = $this->lastEditorService->findEditorsOfPages(
62+
array_map(static fn(array $changes): int => $changes['lastChanged'], $ranking)
63+
);
6064

6165
$result = [];
6266
foreach ($ranking as $pageUid => $changes) {
6367
if (isset($pages[$pageUid])) {
64-
$result[] = $this->buildPage($pages[$pageUid], $changes);
68+
$result[] = $this->addEditor($this->buildPage($pages[$pageUid], $changes), $editors, $pageUid);
6569
}
6670
}
6771
return $result;
@@ -75,26 +79,52 @@ public function getRecentlyChangedPages(int $rootPageUid, int $limit): array
7579
public function getRecentlyChangedContent(int $rootPageUid, ?int $languageId, int $limit): array
7680
{
7781
$contentTypeNames = array_column($this->tcaService->getContentTypes(), 'label', 'value');
78-
return array_map(
79-
fn(array $contentElement): array => $this->removeUnreadableFields(ContentRepository::TABLE_NAME, [
82+
$contentElements = $this->recentChangeRepository->findRecentContent(
83+
$this->getPageUidsInScope($rootPageUid),
84+
$languageId,
85+
$limit
86+
);
87+
$changeByContent = [];
88+
foreach ($contentElements as $contentElement) {
89+
$changeByContent[(int)$contentElement['uid']] = (int)$contentElement['tstamp'];
90+
}
91+
$editors = $this->lastEditorService->findEditorsOfContent($changeByContent);
92+
93+
$result = [];
94+
foreach ($contentElements as $contentElement) {
95+
$contentType = (string)$contentElement['CType'];
96+
$record = $this->removeUnreadableFields(ContentRepository::TABLE_NAME, [
8097
'uid' => (int)$contentElement['uid'],
8198
'pid' => (int)$contentElement['pid'],
82-
'CType' => (string)$contentElement['CType'],
83-
'contentTypeName' => (string)($contentTypeNames[$contentElement['CType']] ?? $contentElement['CType']),
99+
'CType' => $contentType,
100+
'contentTypeName' => (string)($contentTypeNames[$contentType] ?? $contentType),
84101
'header' => (string)$contentElement['header'],
85102
'colPos' => (int)$contentElement['colPos'],
86103
'sys_language_uid' => (int)$contentElement['sys_language_uid'],
87104
'hidden' => (int)$contentElement['hidden'],
88105
'changed' => $this->formatTimestamp((int)$contentElement['tstamp']),
89106
'pageTitle' => (string)$contentElement['page_title'],
90107
'pageSlug' => (string)$contentElement['page_slug'],
91-
]),
92-
$this->recentChangeRepository->findRecentContent(
93-
$this->getPageUidsInScope($rootPageUid),
94-
$languageId,
95-
$limit
96-
)
97-
);
108+
]);
109+
$result[] = $this->addEditor($record, $editors, (int)$contentElement['uid']);
110+
}
111+
return $result;
112+
}
113+
114+
/**
115+
* "changedBy" is only part of the answer for administrators, for everybody else the key is missing
116+
*
117+
* @param array<string, mixed> $record
118+
* @param array<int, string> $editors
119+
* @return array<string, mixed>
120+
* @throws UserNotFoundException
121+
*/
122+
private function addEditor(array $record, array $editors, int $key): array
123+
{
124+
if ($this->lastEditorService->isAvailable()) {
125+
$record['changedBy'] = $editors[$key] ?? null;
126+
}
127+
return $record;
98128
}
99129

100130
/**

‎Documentation/McpServer.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -438,7 +438,9 @@ in a regular backend request, and every read and write runs through the regular
438438
change never leave the server. Note that every MCP request logs its backend user in, so the last login of a user
439439
connected through MCP is the time of its last request.
440440
- `get_recently_changed_pages` and `get_recently_changed_content` apply the page permissions, the page mounts,
441-
the allowed languages and the exclude fields of the user, just like the other reading tools.
441+
the allowed languages and the exclude fields of the user, just like the other reading tools. Only for
442+
administrators they add `changedBy`, the username of the last change taken from the record history; for every
443+
other user that key is missing.
442444
- `sys_file` can be read, but not written with the record tools - a file is deleted with `delete_file`, which
443445
goes through the file storage. The list is `TableAccessService::READ_ONLY_TABLES`.
444446

0 commit comments

Comments
 (0)