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
|
<?php
namespace JsonApi\Routes\Files;
use JsonApi\Errors\BadRequestException;
use JsonApi\Errors\InternalServerError;
use JsonApi\Routes\ArrayHelperTrait;
use JsonApi\Schemas\FileRef as FileRefSchema;
use JsonApi\Schemas\Folder as FolderSchema;
use JsonApi\Schemas\ContentTermsOfUse as ContentTermsOfUseSchema;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\UploadedFileInterface;
trait RoutesHelperTrait
{
use ArrayHelperTrait {
arrayHas as array_has;
arrayGet as array_get;
}
protected function validateResourceIdentifier($json, $type, $newResource = true)
{
if (!self::array_has($json, 'data')) {
return 'Missing `data` member at document´s top level.';
}
// type
if (self::array_get($json, 'data.type')
!== $type
) {
return 'Missing `type` member of document´s `data`.';
}
// id
if ($newResource && self::array_has($json, 'data.id')) {
return 'New document must not have an `id`.';
}
}
protected function validateFileRefResourceObject($json, ?\FileRef $fileRef = null)
{
if (!self::array_has($json, 'data')) {
return 'Missing `data` member at document´s top level.';
}
// Resource Identifier
if ($err = $this->validateResourceIdentifier($json, FileRefSchema::TYPE, null === $fileRef)) {
return $err;
}
// Attributes
if ($err = $this->validateFileRefAttributes($json, $fileRef)) {
return $err;
}
// Relationship: terms-of-use
if (self::array_has($json, 'data.relationships.terms-of-use')) {
$license = self::array_get($json, 'data.relationships.terms-of-use');
if ($err = $this->validateResourceIdentifier($license, ContentTermsOfUseSchema::TYPE, false)) {
return $err;
}
$termsId = self::array_get($license, 'data.id');
if (!\ContentTermsOfUse::find($termsId)) {
return 'Invalid `terms-of-use` specified.';
}
} else {
return 'Missing `terms-of-use` relationship.';
}
}
private function validateFileRefAttributes($json)
{
// Attributes
if (!self::array_has($json, 'data.attributes')) {
return 'Missing `attributes` member of document´s `data`.';
}
// Attribute: name
$name = self::array_get($json, 'data.attributes.name');
if (!$name || 0 === mb_strlen(trim($name))) {
return '`name` must not be empty.';
}
}
protected function validateFolderAttributes($json, ?\FolderType $folder = null, $needsParent = false)
{
// Attributes needed to create a new folder
if (!$folder) {
if (!self::array_has($json, 'data.attributes')) {
return 'Missing `attributes` member of document´s `data`.';
}
if (!self::array_has($json, 'data.attributes.name')) {
return 'Missing `data.name`.';
}
}
// Attribute: name must not be empty if present
if (self::array_has($json, 'data.attributes.name')
&& !mb_strlen(trim(self::array_get($json, 'data.attributes.name', '')))) {
return '`name` must not be empty.';
}
// Relationship: parent
if (self::array_has($json, 'data.relationships.parent')) {
$parent = self::array_get($json, 'data.relationships.parent');
if ($err = $this->validateResourceIdentifier($parent, FolderSchema::TYPE, false)) {
return $err;
}
} elseif ($needsParent) {
return 'Missing `parent` relationship.';
}
}
protected function validateFolderResourceObject($json, ?\FolderType $folder = null, $needsParent = false)
{
if ($err = $this->validateResourceIdentifier($json, FolderSchema::TYPE, null === $folder)) {
return $err;
}
if ($err = $this->validateFolderAttributes($json, $folder, $needsParent)) {
return $err;
}
}
protected function editFolder(\FolderType $folder, \User $user, $name = null, $description = null)
{
// Since name must not be empty we have to check if it validates to false
// (which can happen with emtpy strings). Description on the other hand
// can be null which means it shoudln't be changed.
// If description is an empty string it shall be changed to an empty string
// if it had a filled string as value.
if (!$name && null !== $description) {
//neither name nor description are set: nothing to do, no error:
return $folder;
}
//check if folder is not a top folder:
if (!$folder->parent_id) {
//folder is a top folder which cannot be edited!
return [sprintf(
_('Ordner %s ist ein Hauptordner, der nicht bearbeitet werden kann!'),
$folder->name
)];
}
if (!$folder->isWritable($user->id)) {
return [sprintf(
_('Unzureichende Berechtigungen zum Bearbeiten des Ordners %s'),
$folder->name
)];
}
//ok, user has write permissions for this folder:
//edit name or description or both
$data = $folder->getEditTemplate();
if (!is_array($data)) {
$data = [];
}
if ($name) {
//get the parent folder to check for duplicate names
//and set the folder name to an unique name:
$data['name'] = $name;
}
if (null !== $description) {
$data['description'] = $description;
}
$folder->setDataFromEditTemplate($data);
if ($folder->store()) {
//folder successfully edited
return $folder;
}
return [sprintf(
_('Fehler beim Speichern des Ordners %s'),
$folder->name
)];
}
/**
* @SuppressWarnings(PHPMD.Superglobals)
* @return \FileRef|null
*/
protected function handleUpload(Request $request, \FolderType $folder)
{
$uploadedFile = $this->getUploadedFile($request);
$user = $this->getUser($request);
$tmpFilename = $this->moveUploadedFile($this->getTmpPath(), $uploadedFile);
$data = [
'name' => $this->getFilename($request, $uploadedFile),
'type' => $uploadedFile->getClientMediaType(),
'size' => $uploadedFile->getSize(),
'user_id' => $user->id,
'tmp_name' => $tmpFilename,
'description' => '',
'content_terms_of_use_id' => 0,
];
$file = \StandardFile::create($data);
if ($error = $folder->validateUpload($file,$user->id)) {
throw new BadRequestException($error);
}
$file = $folder->addFile($file);
if (!$file) {
throw new InternalServerError();
}
return $file->getFileRef();
}
protected function getUploadedFile($request)
{
$files = $this->getUploadedFiles($request);
if (0 === count($files)) {
throw new BadRequestException('File upload required.');
}
if (count($files) > 1) {
throw new BadRequestException('Multiple file upload not possible.');
}
$uploadedFile = reset($files);
if (UPLOAD_ERR_OK !== $uploadedFile->getError()) {
throw new BadRequestException('Upload error.');
}
return $uploadedFile;
}
protected function getUploadedFiles($request)
{
$files = [];
foreach ($request->getUploadedFiles() as $item) {
if (!is_array($item)) {
$files[] = $item;
} else {
foreach ($item as $file) {
$files[] = $file;
}
}
}
return $files;
}
/**
* Moves the uploaded file to the upload directory and assigns it a unique name
* to avoid overwriting an existing uploaded file.
*
* @param string $directory directory to which the file is moved
* @param UploadedFileInterface $uploaded file uploaded file to move
*
* @return string filename of moved file
*/
protected function moveUploadedFile($directory, UploadedFileInterface $uploadedFile)
{
$extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION);
$basename = bin2hex(random_bytes(8));
$filename = sprintf('%s.%0.8s', $basename, $extension);
$uploadedFile->moveTo($directory.DIRECTORY_SEPARATOR.$filename);
return $directory.DIRECTORY_SEPARATOR.$filename;
}
/**
* @SuppressWarnings(PHPMD.Superglobals)
*/
protected function getTmpPath()
{
return $GLOBALS['TMP_PATH'];
}
protected function getTmpFile()
{
return tempnam($this->getTmpPath(), 'jsonapi');
}
protected function getFilename($request, $uploadedFile)
{
return $request->hasHeader('slug')
? rawurldecode(reset($request->getHeader('Slug')))
: $uploadedFile->getClientFilename();
}
/**
* @SuppressWarnings(PHPMD.Superglobals)
*/
private function redirectToFileRef(Response $response, \FileRef $fileRef)
{
$pathinfo = $this->getSchema($fileRef)->getSelfLink($fileRef)->getStringRepresentation($this->container->get('json-api-integration-urlPrefix'));
$old = \URLHelper::setBaseURL($GLOBALS['ABSOLUTE_URI_STUDIP']);
$url = \URLHelper::getURL($pathinfo, [], true);
\URLHelper::setBaseURL($old);
return $response->withHeader('Location', $url)->withStatus(201);
}
}
|