1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
|
<?php
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\DAV\SystemTag;
use OCA\DAV\Connector\Sabre\Directory;
use OCA\DAV\Connector\Sabre\FilesPlugin;
use OCA\DAV\Connector\Sabre\Node;
use OCP\AppFramework\Http;
use OCP\IGroupManager;
use OCP\IUser;
use OCP\IUserSession;
use OCP\SystemTag\ISystemTag;
use OCP\SystemTag\ISystemTagManager;
use OCP\SystemTag\ISystemTagObjectMapper;
use OCP\SystemTag\TagAlreadyExistsException;
use OCP\SystemTag\TagCreationForbiddenException;
use OCP\Util;
use Sabre\DAV\Exception\BadRequest;
use Sabre\DAV\Exception\Conflict;
use Sabre\DAV\Exception\Forbidden;
use Sabre\DAV\Exception\UnsupportedMediaType;
use Sabre\DAV\PropFind;
use Sabre\DAV\PropPatch;
use Sabre\HTTP\RequestInterface;
use Sabre\HTTP\ResponseInterface;
/**
* Sabre plugin to handle system tags:
*
* - makes it possible to create new tags with POST operation
* - get/set Webdav properties for tags
*
*/
class SystemTagPlugin extends \Sabre\DAV\ServerPlugin {
// namespace
public const NS_OWNCLOUD = 'http://owncloud.org/ns';
public const NS_NEXTCLOUD = 'http://nextcloud.org/ns';
public const ID_PROPERTYNAME = '{http://owncloud.org/ns}id';
public const DISPLAYNAME_PROPERTYNAME = '{http://owncloud.org/ns}display-name';
public const USERVISIBLE_PROPERTYNAME = '{http://owncloud.org/ns}user-visible';
public const USERASSIGNABLE_PROPERTYNAME = '{http://owncloud.org/ns}user-assignable';
public const GROUPS_PROPERTYNAME = '{http://owncloud.org/ns}groups';
public const CANASSIGN_PROPERTYNAME = '{http://owncloud.org/ns}can-assign';
public const SYSTEM_TAGS_PROPERTYNAME = '{http://nextcloud.org/ns}system-tags';
public const NUM_FILES_PROPERTYNAME = '{http://nextcloud.org/ns}files-assigned';
public const REFERENCE_FILEID_PROPERTYNAME = '{http://nextcloud.org/ns}reference-fileid';
public const OBJECTIDS_PROPERTYNAME = '{http://nextcloud.org/ns}object-ids';
public const COLOR_PROPERTYNAME = '{http://nextcloud.org/ns}color';
/**
* @var \Sabre\DAV\Server $server
*/
private $server;
/** @var array<int, string[]> */
private array $cachedTagMappings = [];
/** @var array<string, ISystemTag> */
private array $cachedTags = [];
public function __construct(
protected ISystemTagManager $tagManager,
protected IGroupManager $groupManager,
protected IUserSession $userSession,
private ISystemTagObjectMapper $tagMapper,
) {
}
/**
* This initializes the plugin.
*
* This function is called by \Sabre\DAV\Server, after
* addPlugin is called.
*
* This method should set up the required event subscriptions.
*
* @param \Sabre\DAV\Server $server
* @return void
*/
public function initialize(\Sabre\DAV\Server $server) {
$server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
$server->xml->namespaceMap[self::NS_NEXTCLOUD] = 'nc';
$server->xml->elementMap[self::OBJECTIDS_PROPERTYNAME] = SystemTagsObjectList::class;
$server->protectedProperties[] = self::ID_PROPERTYNAME;
$server->on('propFind', [$this, 'handleGetProperties']);
$server->on('propPatch', [$this, 'handleUpdateProperties']);
$server->on('method:POST', [$this, 'httpPost']);
$this->server = $server;
}
/**
* POST operation on system tag collections
*
* @param RequestInterface $request request object
* @param ResponseInterface $response response object
* @return null|false
*/
public function httpPost(RequestInterface $request, ResponseInterface $response) {
$path = $request->getPath();
// Making sure the node exists
$node = $this->server->tree->getNodeForPath($path);
if ($node instanceof SystemTagsByIdCollection || $node instanceof SystemTagsObjectMappingCollection) {
$data = $request->getBodyAsString();
$tag = $this->createTag($data, $request->getHeader('Content-Type'));
if ($node instanceof SystemTagsObjectMappingCollection) {
// also add to collection
$node->createFile($tag->getId());
$url = $request->getBaseUrl() . 'systemtags/';
} else {
$url = $request->getUrl();
}
if ($url[strlen($url) - 1] !== '/') {
$url .= '/';
}
$response->setHeader('Content-Location', $url . $tag->getId());
// created
$response->setStatus(Http::STATUS_CREATED);
return false;
}
}
/**
* Creates a new tag
*
* @param string $data JSON encoded string containing the properties of the tag to create
* @param string $contentType content type of the data
* @return ISystemTag newly created system tag
*
* @throws BadRequest if a field was missing
* @throws Conflict if a tag with the same properties already exists
* @throws UnsupportedMediaType if the content type is not supported
*/
private function createTag($data, $contentType = 'application/json') {
if (explode(';', $contentType)[0] === 'application/json') {
$data = json_decode($data, true, 512, JSON_THROW_ON_ERROR);
} else {
throw new UnsupportedMediaType();
}
if (!isset($data['name'])) {
throw new BadRequest('Missing "name" attribute');
}
$tagName = $data['name'];
$userVisible = true;
$userAssignable = true;
if (isset($data['userVisible'])) {
$userVisible = (bool)$data['userVisible'];
}
if (isset($data['userAssignable'])) {
$userAssignable = (bool)$data['userAssignable'];
}
$groups = [];
if (isset($data['groups'])) {
$groups = $data['groups'];
if (is_string($groups)) {
$groups = explode('|', $groups);
}
}
if ($userVisible === false || $userAssignable === false || !empty($groups)) {
if (!$this->userSession->isLoggedIn() || !$this->groupManager->isAdmin($this->userSession->getUser()->getUID())) {
throw new BadRequest('Not sufficient permissions');
}
}
try {
$tag = $this->tagManager->createTag($tagName, $userVisible, $userAssignable);
if (!empty($groups)) {
$this->tagManager->setTagGroups($tag, $groups);
}
return $tag;
} catch (TagAlreadyExistsException $e) {
throw new Conflict('Tag already exists', 0, $e);
} catch (TagCreationForbiddenException $e) {
throw new Forbidden('You don’t have right to create tags', 0, $e);
}
}
/**
* Retrieves system tag properties
*
* @param PropFind $propFind
* @param \Sabre\DAV\INode $node
*
* @return void
*/
public function handleGetProperties(
PropFind $propFind,
\Sabre\DAV\INode $node,
) {
if ($node instanceof Node) {
$this->propfindForFile($propFind, $node);
return;
}
if (!$node instanceof SystemTagNode && !$node instanceof SystemTagMappingNode && !$node instanceof SystemTagObjectType) {
return;
}
// child nodes from systemtags-assigned should point to normal tag endpoint
if (preg_match('/^systemtags-assigned\/[0-9]+/', $propFind->getPath())) {
$propFind->setPath(str_replace('systemtags-assigned/', 'systemtags/', $propFind->getPath()));
}
$propFind->handle(FilesPlugin::GETETAG_PROPERTYNAME, function () use ($node): string {
return '"' . ($node->getSystemTag()->getETag() ?? '') . '"';
});
$propFind->handle(self::ID_PROPERTYNAME, function () use ($node) {
return $node->getSystemTag()->getId();
});
$propFind->handle(self::DISPLAYNAME_PROPERTYNAME, function () use ($node) {
return $node->getSystemTag()->getName();
});
$propFind->handle(self::USERVISIBLE_PROPERTYNAME, function () use ($node) {
return $node->getSystemTag()->isUserVisible() ? 'true' : 'false';
});
$propFind->handle(self::USERASSIGNABLE_PROPERTYNAME, function () use ($node) {
// this is the tag's inherent property "is user assignable"
return $node->getSystemTag()->isUserAssignable() ? 'true' : 'false';
});
$propFind->handle(self::CANASSIGN_PROPERTYNAME, function () use ($node) {
// this is the effective permission for the current user
return $this->tagManager->canUserAssignTag($node->getSystemTag(), $this->userSession->getUser()) ? 'true' : 'false';
});
$propFind->handle(self::COLOR_PROPERTYNAME, function () use ($node) {
return $node->getSystemTag()->getColor() ?? '';
});
$propFind->handle(self::GROUPS_PROPERTYNAME, function () use ($node) {
if (!$this->groupManager->isAdmin($this->userSession->getUser()->getUID())) {
// property only available for admins
throw new Forbidden();
}
$groups = [];
// no need to retrieve groups for namespaces that don't qualify
if ($node->getSystemTag()->isUserVisible() && !$node->getSystemTag()->isUserAssignable()) {
$groups = $this->tagManager->getTagGroups($node->getSystemTag());
}
return implode('|', $groups);
});
if ($node instanceof SystemTagNode) {
$propFind->handle(self::NUM_FILES_PROPERTYNAME, function () use ($node): int {
return $node->getNumberOfFiles();
});
$propFind->handle(self::REFERENCE_FILEID_PROPERTYNAME, function () use ($node): int {
return $node->getReferenceFileId();
});
$propFind->handle(self::OBJECTIDS_PROPERTYNAME, function () use ($node): SystemTagsObjectList {
$objectTypes = $this->tagMapper->getAvailableObjectTypes();
$objects = [];
foreach ($objectTypes as $type) {
$systemTagObjectType = new SystemTagObjectType($node->getSystemTag(), $type, $this->tagManager, $this->tagMapper);
$objects = array_merge($objects, array_fill_keys($systemTagObjectType->getObjectsIds(), $type));
}
return new SystemTagsObjectList($objects);
});
}
if ($node instanceof SystemTagObjectType) {
$propFind->handle(self::OBJECTIDS_PROPERTYNAME, function () use ($node): SystemTagsObjectList {
return new SystemTagsObjectList(array_fill_keys($node->getObjectsIds(), $node->getName()));
});
}
}
private function propfindForFile(PropFind $propFind, Node $node): void {
if ($node instanceof Directory
&& $propFind->getDepth() !== 0
&& !is_null($propFind->getStatus(self::SYSTEM_TAGS_PROPERTYNAME))) {
$fileIds = [$node->getId()];
// note: pre-fetching only supported for depth <= 1
$folderContent = $node->getChildren();
foreach ($folderContent as $info) {
if ($info instanceof Node) {
$fileIds[] = $info->getId();
}
}
$tags = $this->tagMapper->getTagIdsForObjects($fileIds, 'files');
$this->cachedTagMappings = $this->cachedTagMappings + $tags;
$emptyFileIds = array_diff($fileIds, array_keys($tags));
// also cache the ones that were not found
foreach ($emptyFileIds as $fileId) {
$this->cachedTagMappings[$fileId] = [];
}
}
$propFind->handle(self::SYSTEM_TAGS_PROPERTYNAME, function () use ($node) {
$user = $this->userSession->getUser();
$tags = $this->getTagsForFile($node->getId(), $user);
usort($tags, function (ISystemTag $tagA, ISystemTag $tagB): int {
return Util::naturalSortCompare($tagA->getName(), $tagB->getName());
});
return new SystemTagList($tags, $this->tagManager, $user);
});
}
/**
* @param int $fileId
* @return ISystemTag[]
*/
private function getTagsForFile(int $fileId, ?IUser $user): array {
if (isset($this->cachedTagMappings[$fileId])) {
$tagIds = $this->cachedTagMappings[$fileId];
} else {
$tags = $this->tagMapper->getTagIdsForObjects([$fileId], 'files');
$fileTags = current($tags);
if ($fileTags) {
$tagIds = $fileTags;
} else {
$tagIds = [];
}
}
$tags = array_filter(array_map(function (string $tagId) {
return $this->cachedTags[$tagId] ?? null;
}, $tagIds));
$uncachedTagIds = array_filter($tagIds, function (string $tagId): bool {
return !isset($this->cachedTags[$tagId]);
});
if (count($uncachedTagIds)) {
$retrievedTags = $this->tagManager->getTagsByIds($uncachedTagIds);
foreach ($retrievedTags as $tag) {
$this->cachedTags[$tag->getId()] = $tag;
}
$tags += $retrievedTags;
}
return array_filter($tags, function (ISystemTag $tag) use ($user) {
return $this->tagManager->canUserSeeTag($tag, $user);
});
}
/**
* Updates tag attributes
*
* @param string $path
* @param PropPatch $propPatch
*
* @return void
*/
public function handleUpdateProperties($path, PropPatch $propPatch) {
$node = $this->server->tree->getNodeForPath($path);
if (!$node instanceof SystemTagNode && !$node instanceof SystemTagObjectType) {
return;
}
$propPatch->handle([self::OBJECTIDS_PROPERTYNAME], function ($props) use ($node) {
if (!$node instanceof SystemTagObjectType) {
return false;
}
if (isset($props[self::OBJECTIDS_PROPERTYNAME])) {
$propValue = $props[self::OBJECTIDS_PROPERTYNAME];
if (!$propValue instanceof SystemTagsObjectList || count($propValue->getObjects()) === 0) {
throw new BadRequest('Invalid object-ids property');
}
$objects = $propValue->getObjects();
$objectTypes = array_unique(array_values($objects));
if (count($objectTypes) !== 1 || $objectTypes[0] !== $node->getName()) {
throw new BadRequest('Invalid object-ids property. All object types must be of the same type: ' . $node->getName());
}
$this->tagMapper->setObjectIdsForTag($node->getSystemTag()->getId(), $node->getName(), array_keys($objects));
}
if ($props[self::OBJECTIDS_PROPERTYNAME] === null) {
$this->tagMapper->setObjectIdsForTag($node->getSystemTag()->getId(), $node->getName(), []);
}
return true;
});
$propPatch->handle([
self::DISPLAYNAME_PROPERTYNAME,
self::USERVISIBLE_PROPERTYNAME,
self::USERASSIGNABLE_PROPERTYNAME,
self::GROUPS_PROPERTYNAME,
self::NUM_FILES_PROPERTYNAME,
self::REFERENCE_FILEID_PROPERTYNAME,
self::COLOR_PROPERTYNAME,
], function ($props) use ($node) {
if (!$node instanceof SystemTagNode) {
return false;
}
$tag = $node->getSystemTag();
$name = $tag->getName();
$userVisible = $tag->isUserVisible();
$userAssignable = $tag->isUserAssignable();
$color = $tag->getColor();
$updateTag = false;
if (isset($props[self::DISPLAYNAME_PROPERTYNAME])) {
$name = $props[self::DISPLAYNAME_PROPERTYNAME];
$updateTag = true;
}
if (isset($props[self::USERVISIBLE_PROPERTYNAME])) {
$propValue = $props[self::USERVISIBLE_PROPERTYNAME];
$userVisible = ($propValue !== 'false' && $propValue !== '0');
$updateTag = true;
}
if (isset($props[self::USERASSIGNABLE_PROPERTYNAME])) {
$propValue = $props[self::USERASSIGNABLE_PROPERTYNAME];
$userAssignable = ($propValue !== 'false' && $propValue !== '0');
$updateTag = true;
}
if (isset($props[self::COLOR_PROPERTYNAME])) {
$propValue = $props[self::COLOR_PROPERTYNAME];
if ($propValue === '' || $propValue === 'null') {
$propValue = null;
}
$color = $propValue;
$updateTag = true;
}
if (isset($props[self::GROUPS_PROPERTYNAME])) {
if (!$this->groupManager->isAdmin($this->userSession->getUser()->getUID())) {
// property only available for admins
throw new Forbidden();
}
$propValue = $props[self::GROUPS_PROPERTYNAME];
$groupIds = explode('|', $propValue);
$this->tagManager->setTagGroups($tag, $groupIds);
}
if (isset($props[self::NUM_FILES_PROPERTYNAME]) || isset($props[self::REFERENCE_FILEID_PROPERTYNAME])) {
// read-only properties
throw new Forbidden();
}
if ($updateTag) {
$node->update($name, $userVisible, $userAssignable, $color);
}
return true;
});
}
}
|