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
|
<?php
namespace JsonApi\Routes\Courseware;
use Courseware\Filesystem\PublicFolder;
use Courseware\StructuralElement;
use JsonApi\Errors\AuthorizationFailedException;
use JsonApi\Errors\BadRequestException;
use JsonApi\Errors\InternalServerError;
use JsonApi\Errors\RecordNotFoundException;
use JsonApi\NonJsonApiController;
use JsonApi\Routes\Files\RoutesHelperTrait as FilesRoutesHelper;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use StandardFile;
class StructuralElementsImageUpload extends NonJsonApiController
{
use CoursewareInstancesHelper, FilesRoutesHelper;
public function invoke(Request $request, Response $response, array $args): Response
{
if (!($structuralElement = StructuralElement::find($args['id']))) {
throw new RecordNotFoundException();
}
if (!Authority::canUploadStructuralElementsImage($this->getUser($request), $structuralElement)) {
throw new AuthorizationFailedException();
}
$instance = $this->findInstanceWithRange($structuralElement['range_type'], $structuralElement['range_id']);
$publicFolder = PublicFolder::findOrCreateTopFolder($instance);
$fileRef = $this->handleUpload($request, $publicFolder, $structuralElement);
// remove existing image
if ($structuralElement->image) {
$structuralElement->image->getFileType()->delete();
}
// refer to newly uploaded image
$structuralElement->image_id = $fileRef->id;
$structuralElement->store();
return $response->withStatus(201);
}
protected function handleUpload(Request $request, PublicFolder $folder, StructuralElement $structuralElement)
{
$uploadedFile = $this->getUploadedFile($request);
$user = $this->getUser($request);
$tmpFilename = $this->moveUploadedFile($this->getTmpPath(), $uploadedFile);
$name = sprintf(
'structural-element-%s.%s',
$structuralElement->id,
mb_strtolower(pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION))
);
$data = [
'name' => $name,
'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();
}
}
|