-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathCollectiveFolderManager.php
More file actions
351 lines (310 loc) · 10.6 KB
/
Copy pathCollectiveFolderManager.php
File metadata and controls
351 lines (310 loc) · 10.6 KB
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
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2020 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Collectives\Mount;
use Exception;
use OC;
use OC\Files\Node\LazyFolder;
use OC\Files\Storage\Wrapper\Jail;
use OC\Files\Storage\Wrapper\PermissionsMask;
use OCA\Collectives\ACL\ACLStorageWrapper;
use OCA\Collectives\Model\FileInfo;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\Files\Cache\ICacheEntry;
use OCP\Files\Folder;
use OCP\Files\InvalidPathException;
use OCP\Files\IRootFolder;
use OCP\Files\Mount\IMountPoint;
use OCP\Files\NotFoundException;
use OCP\Files\NotPermittedException;
use OCP\Files\Storage\IStorageFactory;
use OCP\IConfig;
use OCP\IDBConnection;
use OCP\IRequest;
use OCP\IUser;
use OCP\IUserSession;
use OCP\L10N\IFactory;
use OCP\Server;
class CollectiveFolderManager {
private const SKELETON_DIR = 'skeleton';
private const LANDING_PAGE_TITLE = 'Readme';
private const SUFFIX = '.md';
private ?string $rootPath = null;
private ?int $rootFolderId = null;
private ?Folder $collectivesRootFolder = null;
public function __construct(
private IRootFolder $rootFolder,
private IDBConnection $connection,
private IConfig $config,
private IUserSession $userSession,
private IRequest $request,
private IFactory $l10nFactory,
) {
}
private function getAppdataPath(): string {
$instanceId = $this->config->getSystemValueString('instanceid');
return 'appdata_' . $instanceId;
}
public function getRootPath(): string {
if ($this->rootPath !== null) {
return $this->rootPath;
}
$this->rootPath = $this->getAppdataPath() . '/collectives';
return $this->rootPath;
}
public function getRootFolder(): Folder {
if ($this->collectivesRootFolder !== null) {
return $this->collectivesRootFolder;
}
$rootFolder = $this->rootFolder;
$appdataPath = $this->getAppdataPath();
$this->collectivesRootFolder = new LazyFolder($rootFolder, function () use ($rootFolder, $appdataPath) {
/** @var Folder $appdata */
$appdata = $rootFolder->get($appdataPath);
try {
return $appdata->get('/collectives');
} catch (NotFoundException) {
return $appdata->newFolder('collectives');
}
}, [
'path' => '/' . $this->getRootPath(),
]);
return $this->collectivesRootFolder;
}
private function getCurrentUID(): ?string {
try {
// wopi requests are not logged in, instead we need to get the editor user from the access token
if (strpos($this->request->getRawPathInfo(), 'apps/richdocuments/wopi') && class_exists(\OCA\Richdocuments\Db\WopiMapper::class)) {
$wopiMapper = Server::get(\OCA\Richdocuments\Db\WopiMapper::class);
$token = $this->request->getParam('access_token');
if ($token) {
return $wopiMapper->getPathForToken($token)->getEditorUid();
}
}
} catch (Exception) {
}
return $this->userSession->getUser()?->getUID();
}
/**
* @throws InvalidPathException
* @throws NotFoundException
*/
public function getMount(int $id,
string $mountPoint,
int $permissions,
?ICacheEntry $cacheEntry = null,
?IStorageFactory $loader = null,
?IUser $user = null): ?IMountPoint {
if (!$cacheEntry) {
try {
$folder = $this->getOrCreateFolder($id);
} catch (InvalidPathException|NotPermittedException) {
return null;
}
$cacheEntry = $this->getRootFolder()->getStorage()->getCache()->get($folder->getId());
if ($cacheEntry === false) {
return null;
}
}
$storage = new NoExcludePropagatorStorageWrapper(['storage' => $this->getRootFolder()->getStorage()]);
$rootPath = $this->getJailPath($id);
// apply acl before jail
if ($user) {
$inShare = !OC::$CLI && ($this->getCurrentUID() === null || $this->getCurrentUID() !== $user->getUID());
$storage = new ACLStorageWrapper([
'storage' => $storage,
'permissions' => $permissions,
'in_share' => $inShare
]);
$cacheEntry['permissions'] &= $permissions;
}
$baseStorage = new Jail([
'storage' => $storage,
'root' => $rootPath
]);
$collectiveStorage = new CollectiveStorage([
'storage' => $baseStorage,
'folder_id' => $id,
'rootCacheEntry' => $cacheEntry,
'mountOwner' => $user
]);
$maskedStorage = new PermissionsMask([
'storage' => $collectiveStorage,
'mask' => $permissions
]);
return new CollectiveMountPoint(
$id,
$this,
$maskedStorage,
$mountPoint,
null,
$loader
);
}
private function getJailPath(int $folderId): string {
return $this->getRootFolder()->getInternalPath() . '/' . $folderId;
}
/**
* @throws NotFoundException
*/
private function getRootFolderId(): int {
if ($this->rootFolderId === null) {
$qb = $this->connection->getQueryBuilder();
$qb->select('f.fileid')
->from('filecache', 'f')
->where($qb->expr()->eq('storage', $qb->createNamedParameter($this->getRootFolderStorageId())))
->andWhere($qb->expr()->eq('path_hash', $qb->createNamedParameter(md5($this->getRootPath()))));
$this->rootFolderId = (int)$qb->executeQuery()->fetchColumn();
}
return $this->rootFolderId;
}
private function getRootFolderStorageId(): int {
return $this->getRootFolder()->getStorage()->getCache()->getNumericStorageId();
}
/**
* @throws NotPermittedException
*/
private function getSkeletonFolder(Folder $folder): Folder {
try {
$skeletonFolder = $folder->get(self::SKELETON_DIR);
if (!$skeletonFolder instanceof Folder) {
throw new NotFoundException('Not a folder: ' . $skeletonFolder->getPath());
}
} catch (NotFoundException) {
$skeletonFolder = $folder->newFolder(self::SKELETON_DIR);
}
return $skeletonFolder;
}
/**
* @throws NotFoundException
* @throws \OCP\DB\Exception
* @psalm-suppress MoreSpecificReturnType
* @return array<int, array{
* folder_id: int,
* fileid: int,
* storage: int,
* path: string,
* name: string,
* mimetype: string,
* mimepart: string,
* size: int|float,
* mtime: int,
* storage_mtime: int,
* etag: string,
* encrypted: bool,
* parent: int,
* permissions: int,
* }|null>
*/
public function getFolderFileCachePerCollectiveId(array $ids): array {
if (!$ids) {
return [];
}
$qb = $this->connection->getQueryBuilder();
$qb->select(
'co.id AS folder_id', 'fc.fileid', 'fc.storage', 'fc.path', 'fc.name AS name',
'fc.mimetype', 'fc.mimepart', 'fc.size', 'fc.mtime', 'fc.storage_mtime', 'fc.etag', 'fc.encrypted', 'fc.parent', 'fc.permissions AS permissions')
->from('collectives', 'co')
->leftJoin('co', 'filecache', 'fc', $qb->expr()->eq('fc.name', $qb->expr()->castColumn('co.id', IQueryBuilder::PARAM_STR)))
->where($qb->expr()->in('co.id', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
->andWhere($qb->expr()->eq('fc.parent', $qb->createNamedParameter($this->getRootFolderId())))
->andWhere($qb->expr()->eq('fc.storage', $qb->createNamedParameter($this->getRootFolderStorageId(), IQueryBuilder::PARAM_INT)));
$rows = $qb->executeQuery()->fetchAll();
$result = [];
foreach ($rows as $row) {
$result[$row['folder_id']] = $row;
}
/** @psalm-suppress LessSpecificReturnStatement */
return $result;
}
/**
* Load all filecache entries (files and folders) of a collective folder in a single query.
*
* @return FileInfo[] Indexed by file id, with paths relative to the collective root folder
*
* @throws NotFoundException
* @throws \OCP\DB\Exception
*/
public function getFileCacheForCollective(int $collectiveId): array {
$jailPath = $this->getJailPath($collectiveId);
$storageId = $this->getRootFolderStorageId();
$qb = $this->connection->getQueryBuilder();
$qb->select('fileid', 'storage', 'path', 'parent', 'name', 'mimetype', 'mimepart',
'size', 'mtime', 'storage_mtime', 'encrypted', 'etag', 'permissions')
->from('filecache')
->where($qb->expr()->eq('storage', $qb->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)))
// Trailing slash matters: it restricts to descendants of this collective and
// avoids matching sibling collectives (e.g. `16` must not match `160`).
->andWhere($qb->expr()->like('path', $qb->createNamedParameter($this->connection->escapeLikeParameter($jailPath . '/') . '%')));
$prefixLength = strlen($jailPath . '/');
$result = [];
$cursor = $qb->executeQuery();
while ($row = $cursor->fetch()) {
$relativePath = substr($row['path'], $prefixLength);
$result[(int)$row['fileid']] = new FileInfo(
fileId: (int)$row['fileid'],
storage: (int)$row['storage'],
path: $relativePath,
parent: (int)$row['parent'],
name: (string)$row['name'],
mimetype: (int)$row['mimetype'],
mimepart: (int)$row['mimepart'],
size: (int)$row['size'],
mtime: (int)$row['mtime'],
storageMtime: (int)$row['storage_mtime'],
encrypted: (int)$row['encrypted'],
etag: (string)$row['etag'],
permissions: (int)$row['permissions'],
);
}
$cursor->closeCursor();
return $result;
}
/**
* @throws InvalidPathException
* @throws NotFoundException
*/
public function getFolder(int $id): Folder {
$folder = $this->getRootFolder()->get((string)$id);
if (!$folder instanceof Folder) {
throw new InvalidPathException('Not a folder: ' . $folder->getPath());
}
return $folder;
}
/**
* @throws InvalidPathException
* @throws NotPermittedException
*/
public function getOrCreateFolder(int $id): Folder {
try {
$folder = $this->getFolder($id);
} catch (NotFoundException) {
/** @var Folder $folder */
$folder = $this->getSkeletonFolder($this->getRootFolder())
->copy($this->getRootFolder()->getPath() . '/' . $id);
}
return $folder;
}
/**
* @throws InvalidPathException
* @throws NotPermittedException
*/
public function initializeFolder(int $id, string $lang, string $name): Folder {
$folder = $this->getOrCreateFolder($id);
$landingPageFileName = self::LANDING_PAGE_TITLE . self::SUFFIX;
if (!$folder->nodeExists($landingPageFileName)) {
$content = $this->getLandingPageContent($name, $lang);
$folder->newFile($landingPageFileName, $content);
}
return $folder;
}
private function getLandingPageContent(string $name, string $lang): string {
$l10n = $this->l10nFactory->get('collectives', $lang);
return '# ' . $l10n->t('Welcome %s', $name) . "\n\n"
. $l10n->t('Add pages with the ➕ in the page list! You can drag them to change the order. Dragging them into the editor will create a 🔗 link.') . "\n\n"
. $l10n->t('Press `✏️ Edit` to change this text and make yourself at home! Multiple people can edit together. Find out more in the [documentation](https://docs.nextcloud.com/server/latest/user_manual/en/collectives/index.html) or ask [the community](https://help.nextcloud.com/tag/collectives-app).');
}
}