forked from nextcloud/text
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAttachmentController.php
More file actions
315 lines (293 loc) Β· 10.5 KB
/
Copy pathAttachmentController.php
File metadata and controls
315 lines (293 loc) Β· 10.5 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
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2021 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Text\Controller;
use Exception;
use OCA\Text\Exception\InvalidSessionException;
use OCA\Text\Exception\UploadException;
use OCA\Text\Middleware\Attribute\RequireDocumentSession;
use OCA\Text\Middleware\Attribute\RequireDocumentSessionOrUserOrShareToken;
use OCA\Text\Service\AttachmentService;
use OCP\AppFramework\ApiController;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\Attribute\NoAdminRequired;
use OCP\AppFramework\Http\Attribute\NoCSRFRequired;
use OCP\AppFramework\Http\Attribute\PublicPage;
use OCP\AppFramework\Http\DataDownloadResponse;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\Http\RedirectResponse;
use OCP\Files\IMimeTypeDetector;
use OCP\Files\InvalidPathException;
use OCP\IL10N;
use OCP\IRequest;
use OCP\Util;
use Psr\Log\LoggerInterface;
class AttachmentController extends ApiController implements ISessionAwareController {
use TSessionAwareController;
public const IMAGE_MIME_TYPES = [
'image/png',
'image/jpeg',
'image/jpg',
'image/gif',
'image/x-xbitmap',
'image/x-ms-bmp',
'image/bmp',
'image/svg+xml',
'image/webp',
'image/heic',
'image/heif',
];
public const BROWSER_SUPPORTED_IMAGE_MIME_TYPES = [
'image/png',
'image/jpeg',
'image/jpg',
'image/gif',
'image/x-xbitmap',
'image/x-ms-bmp',
'image/bmp',
'image/svg+xml',
'image/webp',
];
public function __construct(
string $appName,
IRequest $request,
private IL10N $l10n,
private LoggerInterface $logger,
private IMimeTypeDetector $mimeTypeDetector,
private AttachmentService $attachmentService,
) {
parent::__construct($appName, $request);
}
#[NoAdminRequired]
#[PublicPage]
#[RequireDocumentSessionOrUserOrShareToken]
public function getAttachmentList(string $shareToken = ''): DataResponse {
$documentId = $this->getDocumentId();
try {
$session = $this->getSession();
} catch (InvalidSessionException) {
$session = null;
}
if ($shareToken) {
$attachments = $this->attachmentService->getAttachmentList($documentId, null, $session, $shareToken);
} else {
$userId = $this->getUserId();
$attachments = $this->attachmentService->getAttachmentList($documentId, $userId, $session);
}
return new DataResponse($attachments);
}
#[NoAdminRequired]
#[PublicPage]
#[RequireDocumentSession]
public function insertAttachmentFile(string $filePath): DataResponse {
$userId = $this->getSession()->getUserId();
try {
$insertResult = $this->attachmentService->insertAttachmentFile($this->getSession()->getDocumentId(), $filePath, $userId);
if (isset($insertResult['error'])) {
return new DataResponse($insertResult, Http::STATUS_BAD_REQUEST);
} else {
return new DataResponse($insertResult);
}
} catch (Exception $e) {
$this->logger->error('File insertion error', ['exception' => $e]);
return new DataResponse(['error' => 'File insertion error'], Http::STATUS_BAD_REQUEST);
}
}
#[NoAdminRequired]
#[PublicPage]
#[RequireDocumentSession]
public function uploadAttachment(string $token = ''): DataResponse {
$documentId = $this->getSession()->getDocumentId();
try {
$file = $this->getUploadedFile('file');
if (isset($file['tmp_name'], $file['name'], $file['type'])) {
$newFileResource = fopen($file['tmp_name'], 'rb');
if ($newFileResource === false) {
throw new Exception('Could not read file');
}
$newFileName = $file['name'];
if ($token) {
$uploadResult = $this->attachmentService->uploadAttachmentPublic($documentId, $newFileName, $newFileResource, $token);
} else {
$userId = $this->getSession()->getUserId();
$uploadResult = $this->attachmentService->uploadAttachment($documentId, $newFileName, $newFileResource, $userId);
}
if (isset($uploadResult['error'])) {
return new DataResponse($uploadResult, Http::STATUS_BAD_REQUEST);
} else {
return new DataResponse($uploadResult);
}
}
return new DataResponse(['error' => 'No uploaded file'], Http::STATUS_BAD_REQUEST);
} catch (InvalidPathException $e) {
$this->logger->error('Upload error', ['exception' => $e]);
$error = $e->getMessage() ?: 'Upload error';
return new DataResponse(['error' => $error], Http::STATUS_BAD_REQUEST);
} catch (Exception $e) {
$this->logger->error('Upload error', ['exception' => $e]);
return new DataResponse(['error' => 'Upload error'], Http::STATUS_BAD_REQUEST);
}
}
#[NoAdminRequired]
#[PublicPage]
#[RequireDocumentSession]
public function createAttachment(string $token = ''): DataResponse {
$documentId = $this->getSession()->getDocumentId();
try {
$userId = $this->getSession()->getUserId();
$newFileName = $this->request->getParam('fileName', 'text.md');
$createResult = $this->attachmentService->createAttachmentFile($documentId, $newFileName, $userId);
if (isset($createResult['error'])) {
return new DataResponse($createResult, Http::STATUS_BAD_REQUEST);
} else {
return new DataResponse($createResult);
}
} catch (InvalidPathException $e) {
$this->logger->error('File creation error', ['exception' => $e]);
$error = $e->getMessage() ?: 'Upload error';
return new DataResponse(['error' => $error], Http::STATUS_BAD_REQUEST);
} catch (Exception $e) {
$this->logger->error('File creation error', ['exception' => $e]);
return new DataResponse(['error' => 'File creation error'], Http::STATUS_BAD_REQUEST);
}
}
private function getUploadedFile(string $key): array {
$file = $this->request->getUploadedFile($key);
$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', [Util::humanFileSize(Util::uploadLimit())]);
}
if (!empty($file) && array_key_exists('error', $file) && $file['error'] !== UPLOAD_ERR_OK) {
$error = $phpFileUploadErrors[$file['error']];
}
if ($error !== null) {
throw new UploadException($error);
}
return $file;
}
/**
* Serve the image files in the editor
*
* @return DataDownloadResponse|DataResponse
*
* @psalm-return DataDownloadResponse<200, string, array<never, never>>|DataResponse<404, '', array<never, never>>
*/
#[NoAdminRequired]
#[PublicPage]
#[NoCSRFRequired]
#[RequireDocumentSessionOrUserOrShareToken]
public function getImageFile(string $imageFileName, string $shareToken = '',
int $preferRawImage = 0): DataResponse|DataDownloadResponse {
$documentId = $this->getDocumentId();
try {
if ($shareToken) {
$imageFile = $this->attachmentService->getImageFilePublic($documentId, $imageFileName, $shareToken, $preferRawImage === 1);
} else {
$userId = $this->getUserId();
$imageFile = $this->attachmentService->getImageFile($documentId, $imageFileName, $userId, $preferRawImage === 1);
}
return $imageFile !== null
? new DataDownloadResponse(
$imageFile->getContent(),
$imageFile->getName(),
$this->getSecureMimeType($imageFile->getMimeType())
)
: new DataResponse('', Http::STATUS_NOT_FOUND);
} catch (Exception $e) {
$this->logger->error('getImageFile error', ['exception' => $e]);
return new DataResponse('', Http::STATUS_NOT_FOUND);
}
}
/**
* Serve the media files in the editor
*
* @return DataDownloadResponse|DataResponse
*
* @psalm-return DataDownloadResponse<200, string, array<never, never>>|DataResponse<404, '', array<never, never>>
*/
#[NoAdminRequired]
#[PublicPage]
#[NoCSRFRequired]
#[RequireDocumentSessionOrUserOrShareToken]
public function getMediaFile(string $mediaFileName, string $shareToken = ''): DataResponse|DataDownloadResponse {
$documentId = $this->getDocumentId();
try {
if ($shareToken) {
$mediaFile = $this->attachmentService->getMediaFilePublic($documentId, $mediaFileName, $shareToken);
} else {
$userId = $this->getUserId();
$mediaFile = $this->attachmentService->getMediaFile($documentId, $mediaFileName, $userId);
}
return $mediaFile !== null
? new DataDownloadResponse(
$mediaFile->getContent(),
$mediaFile->getName(),
$this->getSecureMimeType($mediaFile->getMimeType())
)
: new DataResponse('', Http::STATUS_NOT_FOUND);
} catch (Exception $e) {
$this->logger->error('getMediaFile error', ['exception' => $e]);
return new DataResponse('', Http::STATUS_NOT_FOUND);
}
}
/**
* Serve the media files preview in the editor
* @return DataDownloadResponse|DataResponse|RedirectResponse
*/
#[NoAdminRequired]
#[PublicPage]
#[NoCSRFRequired]
#[RequireDocumentSessionOrUserOrShareToken]
public function getMediaFilePreview(string $mediaFileName, string $shareToken = '') {
$documentId = $this->getDocumentId();
try {
if ($shareToken) {
$preview = $this->attachmentService->getMediaFilePreviewPublic($documentId, $mediaFileName, $shareToken);
} else {
$userId = $this->getUserId();
$preview = $this->attachmentService->getMediaFilePreview($documentId, $mediaFileName, $userId);
}
if ($preview === null) {
return new DataResponse('', Http::STATUS_NOT_FOUND);
}
if ($preview['type'] === 'file') {
return new DataDownloadResponse(
$preview['file']->getContent(),
$mediaFileName,
$this->getSecureMimeType($preview['file']->getMimeType())
);
} elseif ($preview['type'] === 'icon') {
return new RedirectResponse($preview['iconUrl']);
}
} catch (Exception $e) {
$this->logger->error('getMediaFilePreview error', ['exception' => $e]);
}
return new DataResponse('', Http::STATUS_NOT_FOUND);
}
/**
* Allow all supported mimetypes
* Use mimetype detector for the other ones
*
* @param string $mimetype
* @return string
*/
private function getSecureMimeType(string $mimetype): string {
if (in_array($mimetype, self::IMAGE_MIME_TYPES)) {
return $mimetype;
}
return $this->mimeTypeDetector->getSecureMimeType($mimetype);
}
}