forked from aces/Loris
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfiles.class.inc
More file actions
472 lines (423 loc) · 15 KB
/
Copy pathfiles.class.inc
File metadata and controls
472 lines (423 loc) · 15 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
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
<?php declare(strict_types=1);
namespace LORIS\data_release;
use \Psr\Http\Message\ServerRequestInterface;
use \Psr\Http\Message\ResponseInterface;
/**
* Handles the /files endpoint of the module to upload or
* retrieve specific files.
*
* @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3
*/
class Files extends \NDB_Page
{
public $AjaxModule = true;
public $skipTemplate = true;
private $filesDir;
/**
* Check user permissions
*
* @param \User $user The user whose access is being checked
*
* @return bool
*/
#[\Override]
public function isAccessibleBy(\User $user) : bool
{
// check user permissions
return $user->hasAnyPermission(
[
'data_release_view',
'data_release_upload',
'data_release_edit_file_access'
]
);
}
/**
* {@inheritDoc}
*
* @param ServerRequestInterface $request The incoming PSR7 request
*
* @return ResponseInterface
*/
public function handle(ServerRequestInterface $request) : ResponseInterface
{
$factory = \NDB_Factory::singleton();
$config = $factory->config();
$this->filesDir = \Utility::appendForwardSlash(
$config->getSetting('dataReleasePath')
);
if (empty($this->filesDir) || $this->filesDir === '/') {
// Whether you're uploading or downloading, it's going to be an error
// if the dataReleasePath is misconfigured..
return new \LORIS\Http\Response\JSON\InternalServerError();
}
$action = $request->getQueryParams()['action'];
if (!empty($action)
&& ($action == 'deleteFile'
|| $action == 'hideFile'
|| $action == 'unhideFile')
) {
switch ($action) {
case 'deleteFile':
return $this->_deleteFile($request);
case 'hideFile':
return $this->_changeHideFile($request, true);
case 'unhideFile':
return $this->_changeHideFile($request, false);
default:
return new \LORIS\Http\Response\JSON\MethodNotAllowed(
['DELETE', 'HIDE']
);
}
} else {
switch ($request->getMethod()) {
case 'GET':
return $this->_handleGet($request);
case 'POST':
return $this->_handleUpload($request);
default:
return new \LORIS\Http\Response\JSON\MethodNotAllowed(
['GET', 'POST']
);
}
}
}
/**
* Handles an incoming POST request to validate and upload the file
*
* @param ServerRequestInterface $request The incoming request
*
* @return ResponseInterface
*/
private function _handleUpload(
ServerRequestInterface $request
) : ResponseInterface {
$overwrite = !empty($request->getQueryParams()['overwrite']);
try {
// Constructor handles dir exists/is_writable
$uploadhandler = new \LORIS\FilesUploadHandler(
new \SplFileInfo($this->filesDir)
);
$uploadhandler = $uploadhandler->withOverwrite($overwrite);
} catch (\ConfigurationException $e) {
// FilesUploadHandler throws an exception if there's a problem with
// the uploaddir.
return new \LORIS\Http\Response\JSON\InternalServerError(
$e->getMessage()
);
}
$file = $request->getUploadedFiles()['file'];
$fileName = $file->getClientFilename();
$user = $request->getAttribute("user");
$posted = $request->getParsedBody();
assert(is_array($posted));
$validateError = $this->_validateUserCanUpload(
$user,
$fileName,
$posted['project'],
$overwrite
);
if ($validateError !== null) {
return $validateError;
}
return $this->_moveFile(
$uploadhandler,
$user,
$fileName,
$request,
$posted['version'],
$overwrite,
$posted['project']
);
}
/**
* Validate whether a user can upload a file. Returns null
* if there are no errors, or an error response if something
* is wrong.
*
* @param \User $user The user attempting to upload
* @param string $fileName The filename being uploaded
* @param string $projectName Name of the project
* @param bool $overwrite Whether the overwrite flag is set
*
* @return ?ResponseInterface
*/
private function _validateUserCanUpload(
\User $user,
string $fileName,
string $projectName,
bool $overwrite
) : ?ResponseInterface {
// Check if file is duplicate
$DB = $this->loris->getDatabaseConnection();
$duplicateFile = $DB->pselectRow(
"SELECT id, file_name FROM data_release WHERE file_name=:f",
['f' => $fileName]
);
if (!isset($duplicateFile)) {
// File doesn't exist, user can upload as long as they have
// permission.
// Get ProjectID
$ProjectID = $DB->pselectOne(
"SELECT ProjectID FROM Project WHERE Name=:project",
['project' => $projectName]
);
if (!$user->hasPermission("data_release_upload")
|| !$user->hasProject(
\ProjectID::singleton((int)$ProjectID)
)
) {
return new \LORIS\Http\Response\JSON\Forbidden(
"Permission denied."
);
}
return null;
}
if ($overwrite) {
// File is duplicate and overwrite is set, verify permission
$userPermission = $DB->pselectRow(
"SELECT userid FROM data_release_permissions
WHERE userid=:u AND data_release_id=:d",
['u' => $user->getId(), 'd' => $duplicateFile['id']]
);
if (!isset($userPermission) && !$user->hasPermission('superuser')) {
return new \LORIS\Http\Response\JSON\Forbidden(
"Overwrite failed. A file of this name already exists which "
. " you do not have permission to overwrite."
);
}
} else {
// File is duplicate and overwrite not declared
return new \LORIS\Http\Response\JSON\Conflict(
'Can not upload duplicate file.'
);
}
return null;
}
/**
* Moves a to the appropriate place on the filesystem and inserts into
* the database, returning an appropriate HTTP response.
*
* @param \LORIS\FilesUploadHandler $files The FilesUploadHandler which
* moves the file and generates
* the response.
* @param \User $user The user uploading the file.
* @param string $fileName The file name being uploaded.
* @param ServerRequestInterface $request The incoming request.
* @param ?string $version The user submitted file version.
* @param bool $overwrite Flag to indicate if existing
* file should be overwritten.
* @param ?string $projectName Name of the project
*
* @return ResponseInterface
*/
private function _moveFile(
\LORIS\FilesUploadHandler $files,
\User $user,
string $fileName,
ServerRequestInterface $request,
?string $version,
bool $overwrite,
?string $projectName
) : ResponseInterface {
$DB = $this->loris->getDatabaseConnection();
if ($version !== null) {
$version = strtolower($version);
}
// Get ProjectID
$ProjectID = $DB->pselectOne(
"SELECT ProjectID FROM Project WHERE Name=:project",
['project' => $projectName]
);
// Get information on users with permission to the version
$releasePage = $this->Module->loadPage(
$this->loris,
'data_release',
);
assert($releasePage instanceof Data_Release);
$userVersionFiles = $releasePage->getUserVersionFiles($DB);
$upload_date = date('Y-m-d');
if ($overwrite) {
// update file in data_release table.
$DB->update(
'data_release',
[
'version' => $version,
'upload_date' => $upload_date,
'ProjectID' => $ProjectID,
],
['file_name' => $fileName]
);
} else {
// insert the file into the data_release table
$DB->insert(
'data_release',
[
'file_name' => $fileName,
'version' => $version,
'upload_date' => $upload_date,
'ProjectID' => $ProjectID,
]
);
}
$fileID = $DB->pselectOne(
"SELECT ID FROM data_release WHERE file_name=:filename",
['filename' => $fileName]
);
$DB->insertIgnore(
"data_release_permissions",
[
'userid' => $user->getId(),
'data_release_id' => $fileID,
]
);
// add permission for file to users with permission to the version
foreach ($userVersionFiles as $userid => $userVersionFile) {
if (array_key_exists('versions', $userVersionFile)
&& in_array($version, $userVersionFile['versions'])
) {
$DB->insertIgnore(
'data_release_permissions',
[
'userid' => $userid,
'data_release_id' => $fileID,
]
);
}
}
return $files->handle($request);
}
/**
* Handle an incoming HTTP GET request
*
* @param ServerRequestInterface $request The incoming PSR7 request
*
* @return ResponseInterface
*/
private function _handleGet(ServerRequestInterface $request) : ResponseInterface
{
$matches = [];
$regexmatch = preg_match(
"#files(/\d+)?(/)?$#",
$request->getURI()->getPath(),
$matches
);
if (!$regexmatch) {
return new \LORIS\Http\Response\JSON\NotFound("Not found");
}
$DB = $this->loris->getDatabaseConnection();
if (isset($matches[1])) {
$fileID = substr($matches[1], 1);
$filename = $DB->pselectOne(
"SELECT file_name FROM data_release WHERE id=:fileid",
['fileid' => $fileID]
);
if ($filename === null) {
return new \LORIS\Http\Response\JSON\NotFound("Not found");
}
$user = $request->getAttribute("user");
if (!$user->hasPermission("data_release_view")) {
return new \LORIS\Http\Response\JSON\Forbidden("Permission denied");
}
$hasFilePerm = $DB->pselectOne(
"SELECT 'x' FROM data_release_permissions WHERE
data_release_id=:fileid AND userid = :user",
['fileid' => $fileID,
'user' => $user->getId()
]
);
if ($hasFilePerm === null) {
return new \LORIS\Http\Response\JSON\Forbidden("Permission denied");
}
try {
$downloadhandler = new \LORIS\FilesDownloadHandler(
new \SplFileInfo($this->filesDir)
);
$request = $request->withAttribute("filename", $filename);
return $downloadhandler->handle($request);
} catch (\LorisException $e) {
// FilesUploadHandler throws an exception if there's a problem with
// the downloaddir.
return new \LORIS\Http\Response\JSON\InternalServerError(
$e->getMessage()
);
}
}
$filesList = $DB->pselectCol(
"SELECT file_name FROM data_release",
[]
);
$results = [
'files' => $filesList,
'maxUploadSize' => \Utility::getMaxUploadSize(),
];
return new \LORIS\Http\Response\JSON\OK($results);
}
/**
* Deletes a file from the database, returning an appropriate HTTP response.
*
* @param ServerRequestInterface $request The incoming request.
*
* @return ResponseInterface
*/
private function _deleteFile(
ServerRequestInterface $request
) : ResponseInterface {
// Get ID
$data_release_id = $request->getParsedBody()['data_release_id'] ?? null;
if (!$data_release_id) {
return new \LORIS\Http\Response\JSON\NotFound("Not found");
}
$user = $request->getAttribute("user");
if (!$user->hasPermission('data_release_delete')) {
return new \LORIS\Http\Response\JSON\Forbidden(
"Permission denied."
);
}
$DB = $this->loris->getDatabaseConnection();
$DB->delete(
'data_release_permissions',
['data_release_id' => $data_release_id,]
);
$DB->delete(
'data_release',
['id' => $data_release_id,]
);
return new \LORIS\Http\Response\JSON\OK();
}
/**
* Modifies the hidden_by_userid attribute of a file in the database.
*
* @param ServerRequestInterface $request The incoming request.
* @param bool $hide Whether it is hiding or unhiding
*
* @return ResponseInterface
*/
private function _changeHideFile(
ServerRequestInterface $request,
bool $hide
) : ResponseInterface {
// Get ID
$data_release_id = $request->getParsedBody()['data_release_id'] ?? null;
if (!$data_release_id) {
return new \LORIS\Http\Response\JSON\NotFound("Not found");
}
$user = $request->getAttribute("user");
if (!$user->hasPermission('data_release_hide')) {
return new \LORIS\Http\Response\JSON\Forbidden(
"Permission denied."
);
}
$DB = $this->loris->getDatabaseConnection();
$DB->update(
'data_release',
[
'hidden_by_userid' => ($hide ? $user->getId() : null),
],
[
'id' => $data_release_id,
]
);
return new \LORIS\Http\Response\JSON\OK();
}
}