-
Notifications
You must be signed in to change notification settings - Fork 327
Expand file tree
/
Copy pathFilesAppService.php
More file actions
341 lines (306 loc) · 11.6 KB
/
FilesAppService.php
File metadata and controls
341 lines (306 loc) · 11.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
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Deck\Service;
use OCA\Deck\BadRequestException;
use OCA\Deck\Db\Acl;
use OCA\Deck\Db\Attachment;
use OCA\Deck\Db\CardMapper;
use OCA\Deck\NoPermissionException;
use OCA\Deck\Sharing\DeckShareProvider;
use OCA\Deck\StatusException;
use OCP\AppFramework\Http\StreamResponse;
use OCP\Constants;
use OCP\Files\File;
use OCP\Files\Folder;
use OCP\Files\IFilenameValidator;
use OCP\Files\IMimeTypeDetector;
use OCP\Files\InvalidPathException;
use OCP\Files\IRootFolder;
use OCP\Files\NotFoundException;
use OCP\IDBConnection;
use OCP\IL10N;
use OCP\IPreview;
use OCP\IRequest;
use OCP\Share\Exceptions\ShareNotFound;
use OCP\Share\IManager;
use OCP\Share\IShare;
use Psr\Log\LoggerInterface;
class FilesAppService implements IAttachmentService, ICustomAttachmentService {
/**
* In MacOs case since it allows using "/", there is the conversion of "/" to ":" in file name after upload, this handling is there
* since it can be confusing for users , it's mapped now for better UX.
* Reason is not having access to the original filename because of early sanitization in the request lifecycle.
*/
private const SANITIZED_CHAR_MAPPING = [':' => '/'];
private IRequest $request;
private IRootFolder $rootFolder;
private DeckShareProvider $shareProvider;
private IManager $shareManager;
private ?string $userId;
private ConfigService $configService;
private IL10N $l10n;
private IPreview $preview;
private IMimeTypeDetector $mimeTypeDetector;
private PermissionService $permissionService;
private CardMapper $cardMapper;
private LoggerInterface $logger;
private IDBConnection $connection;
private IFilenameValidator $filenameValidator;
public function __construct(
IRequest $request,
IL10N $l10n,
IRootFolder $rootFolder,
IManager $shareManager,
ConfigService $configService,
DeckShareProvider $shareProvider,
IPreview $preview,
IMimeTypeDetector $mimeTypeDetector,
PermissionService $permissionService,
CardMapper $cardMapper,
LoggerInterface $logger,
IDBConnection $connection,
IFilenameValidator $filenameValidator,
?string $userId,
) {
$this->request = $request;
$this->l10n = $l10n;
$this->rootFolder = $rootFolder;
$this->configService = $configService;
$this->shareProvider = $shareProvider;
$this->shareManager = $shareManager;
$this->userId = $userId;
$this->preview = $preview;
$this->mimeTypeDetector = $mimeTypeDetector;
$this->permissionService = $permissionService;
$this->cardMapper = $cardMapper;
$this->logger = $logger;
$this->connection = $connection;
$this->filenameValidator = $filenameValidator;
}
public function listAttachments(int $cardId): array {
$shares = $this->shareProvider->getSharedWithByType($cardId, IShare::TYPE_DECK, -1, 0);
return array_filter(array_map(function (IShare $share) use ($cardId) {
try {
$file = $share->getNode();
} catch (NotFoundException $e) {
$this->logger->debug('Unable to find node for share with ID ' . $share->getId());
return null;
}
$attachment = new Attachment();
$attachment->setType('file');
$attachment->setId((int)$share->getId());
$attachment->setCardId($cardId);
$attachment->setCreatedBy($share->getSharedBy());
$attachment->setData($file->getName());
$attachment->setLastModified($file->getMTime());
$attachment->setCreatedAt($share->getShareTime()->getTimestamp());
$attachment->setDeletedAt($share->getPermissions() === 0 ? $share->getShareTime()->getTimestamp() : 0);
return $attachment;
}, $shares));
}
public function getAttachmentCount(int $cardId): int {
$qb = $this->connection->getQueryBuilder();
$qb->select('s.id', 'f.fileid', 'f.path')
->selectAlias('st.id', 'storage_string_id')
->from('share', 's')
->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
->andWhere($qb->expr()->eq('s.share_type', $qb->createNamedParameter(IShare::TYPE_DECK)))
->andWhere($qb->expr()->eq('s.share_with', $qb->createNamedParameter($cardId)))
->andWhere($qb->expr()->isNull('s.parent'))
->andWhere($qb->expr()->orX(
$qb->expr()->eq('s.item_type', $qb->createNamedParameter('file')),
$qb->expr()->eq('s.item_type', $qb->createNamedParameter('folder'))
));
$count = 0;
$cursor = $qb->executeQuery();
while ($data = $cursor->fetch()) {
if ($this->shareProvider->isAccessibleResult($data)) {
$count++;
}
}
$cursor->closeCursor();
return $count;
}
public function extendData(Attachment $attachment) {
$userFolder = $this->rootFolder->getUserFolder($this->userId);
$share = $this->getShareForAttachment($attachment);
$file = $userFolder->getFirstNodeById($share->getNode()->getId());
if ($file === null) {
return $attachment;
}
$attachment->setExtendedData([
'path' => $userFolder->getRelativePath($file->getPath()),
'fileid' => $file->getId(),
'data' => $file->getName(),
'filesize' => $file->getSize(),
'mimetype' => $file->getMimeType(),
'info' => pathinfo($file->getName()),
'hasPreview' => $this->preview->isAvailable($file),
'permissions' => $share->getPermissions(),
]);
return $attachment;
}
public function display(Attachment $attachment) {
// Problem: Folders
/** @psalm-suppress InvalidCatch */
try {
$share = $this->getShareForAttachment($attachment);
} catch (ShareNotFound $e) {
throw new NotFoundException('File not found');
}
$file = $share->getNode();
if (!($file instanceof File) || $share->getSharedWith() !== (string)$attachment->getCardId()) {
throw new NotFoundException('File not found');
}
$response = new StreamResponse($file->fopen('rb'));
$response->addHeader('Content-Disposition', 'attachment; filename="' . rawurldecode($file->getName()) . '"');
$response->addHeader('Content-Type', $this->mimeTypeDetector->getSecureMimeType($file->getMimeType()));
return $response;
}
public function create(Attachment $attachment) {
if ($attachment->getData() === 'DEFAULT_SAMPLE_FILE' && !$this->request->getUploadedFile('file')) {
$file = [
'name' => 'Nextcloud sample image - add your image here!.jpg',
'tmp_name' => __DIR__ . '/../../img/sample-image.jpg',
];
} else {
$file = $this->getUploadedFile();
}
$fileName = $file['name'];
$this->validateFilename($fileName);
// get shares for current card
// check if similar filename already exists
$userFolder = $this->rootFolder->getUserFolder($this->userId);
try {
$folder = $userFolder->get($this->configService->getAttachmentFolder());
} catch (NotFoundException) {
$folder = $userFolder->newFolder($this->configService->getAttachmentFolder());
}
if ($folder->isShared()) {
$folderName = $userFolder->getNonExistingName($this->configService->getAttachmentFolder());
$folder = $userFolder->newFolder($folderName);
$this->configService->setAttachmentFolder($this->userId, $folderName);
}
if (!$folder instanceof Folder || $folder->isShared()) {
throw new NotFoundException('No target folder found');
}
$fileName = $folder->getNonExistingName($fileName);
$target = $folder->newFile($fileName);
$content = fopen($file['tmp_name'], 'rb');
if ($content === false) {
throw new StatusException('Could not read file');
}
$target->putContent($content);
$share = $this->shareManager->newShare();
$share->setNode($target);
$share->setShareType(ISHARE::TYPE_DECK);
$share->setSharedWith((string)$attachment->getCardId());
$share->setPermissions(Constants::PERMISSION_READ);
$share->setSharedBy($this->userId);
$share = $this->shareManager->createShare($share);
$attachment->setId((int)$share->getId());
$attachment->setData($target->getName());
return $attachment;
}
/**
* @return array
* @throws StatusException
*/
private function getUploadedFile() {
$file = $this->request->getUploadedFile('file');
$error = null;
$phpFileUploadErrors = [
UPLOAD_ERR_OK => $this->l10n->t('The file was uploaded'),
UPLOAD_ERR_INI_SIZE => $this->l10n->t('The uploaded file exceeds the upload_max_filesize directive in php.ini'),
UPLOAD_ERR_FORM_SIZE => $this->l10n->t('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'),
UPLOAD_ERR_PARTIAL => $this->l10n->t('The file was only partially uploaded'),
UPLOAD_ERR_NO_FILE => $this->l10n->t('No file was uploaded'),
UPLOAD_ERR_NO_TMP_DIR => $this->l10n->t('Missing a temporary folder'),
UPLOAD_ERR_CANT_WRITE => $this->l10n->t('Could not write file to disk'),
UPLOAD_ERR_EXTENSION => $this->l10n->t('A PHP extension stopped the file upload'),
];
if (empty($file)) {
$error = $this->l10n->t('No file uploaded or file size exceeds maximum of %s', [\OCP\Util::humanFileSize(\OCP\Util::uploadLimit())]);
}
if (!empty($file) && array_key_exists('error', $file) && $file['error'] !== UPLOAD_ERR_OK) {
$error = $phpFileUploadErrors[$file['error']];
}
if ($error !== null) {
throw new StatusException($error);
}
return $file;
}
public function update(Attachment $attachment) {
$share = $this->getShareForAttachment($attachment);
$target = $share->getNode();
if (!($target instanceof File)) {
throw new StatusException('Target is not a file');
}
$file = $this->getUploadedFile();
$fileName = $file['name'];
$attachment->setData($fileName);
$content = fopen($file['tmp_name'], 'rb');
if ($content === false) {
throw new StatusException('Could not read file');
}
$target->putContent($content);
fclose($content);
$attachment->setLastModified(time());
return $attachment;
}
/**
* @throws NoPermissionException
* @throws NotFoundException
* @throws ShareNotFound
*/
public function delete(Attachment $attachment) {
$share = $this->getShareForAttachment($attachment);
$file = $share->getNode();
$attachment->setData($file->getName());
// Deleting a Nextcloud file attachment will remove the share to the card, keeping the source file untouched
// Opt-out of individual shares per user is no longer performed within deck but can still be done through the files app
$canEdit = $this->permissionService->checkPermission($this->cardMapper, $attachment->getCardId(), Acl::PERMISSION_EDIT);
$isFileOwner = $file->getOwner() !== null && $file->getOwner()->getUID() === $this->userId;
if ($isFileOwner || $canEdit) {
$this->shareManager->deleteShare($share);
return;
}
throw new NoPermissionException('No permission to remove the attachment from the card');
}
public function allowUndo() {
return false;
}
public function markAsDeleted(Attachment $attachment) {
throw new \Exception('Not implemented');
}
/**
* @throws NoPermissionException
*/
private function getShareForAttachment(Attachment $attachment): IShare {
try {
$share = $this->shareProvider->getShareById((string)$attachment->getId());
} catch (ShareNotFound $e) {
throw new NoPermissionException('No permission to access the attachment from the card');
}
if ((int)$share->getSharedWith() !== (int)$attachment->getCardId()) {
throw new NoPermissionException('No permission to access the attachment from the card');
}
return $share;
}
private function validateFilename(string $fileName): void {
try {
$this->filenameValidator->validateFilename($fileName);
} catch (InvalidPathException $e) {
$errorMessage = $e->getMessage();
foreach (self::SANITIZED_CHAR_MAPPING as $sanitized => $original) {
$errorMessage = str_replace($sanitized, $original, $errorMessage);
}
throw new BadRequestException($errorMessage);
}
}
}