aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/JsonApi/Routes/Courseware/ClipboardsInsert.php
blob: 4fafc4c22c5bfce0b40578e1d33e5dcd9868b4b2 (plain)
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
<?php

namespace JsonApi\Routes\Courseware;

use JsonApi\NonJsonApiController;
use Courseware\Block;
use Courseware\Clipboard;
use Courseware\Container;
use Courseware\StructuralElement;
use JsonApi\Errors\AuthorizationFailedException;
use JsonApi\Errors\BadRequestException;
use JsonApi\Errors\RecordNotFoundException;
use JsonApi\Errors\UnprocessableEntityException;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

/**
 * 
 *
 * @author  Ron Lucke <lucke@elan-ev.de>
 * @license GPL2 or any later version
 *
 * @since   Stud.IP 5.4
 */

class ClipboardsInsert extends NonJsonApiController
{
    public function __invoke(Request $request, Response $response, array $args)
    {
        $data = $request->getParsedBody()['data'];
        $clipboard = Clipboard::find($args['id']);

        if (!$clipboard) {
            throw new RecordNotFoundException();
        }

        $user = $this->getUser($request);

        if (!Authority::canInsertFromClipboard($user, $clipboard)) {
            throw new AuthorizationFailedException();
        }

        $backup = json_decode($clipboard->backup);

        if ($clipboard->object_type === 'courseware-blocks') {
            $sectionIndex = $data['section'];
            $container = \Courseware\Container::find($data['parent_id']);
            if (!$container) {
                throw new RecordNotFoundException();
            }
            if (!Authority::canCreateBlocks($user, $container)) {
                throw new AuthorizationFailedException();
            }
            $object = Block::createFromData($user, $backup, $container, $sectionIndex);
        }

        if ($clipboard->object_type === 'courseware-containers') {
            $element = \Courseware\StructuralElement::find($data['parent_id']);
            if (!$element) {
                throw new RecordNotFoundException();
            }
            if (!Authority::canCreateContainer($user, $element)) {
                throw new AuthorizationFailedException();
            }
            $object = Container::createFromData($user, $backup, $element);
        }

        $response = $response->withHeader('Content-Type', 'application/json');
        $response->getBody()->write((string) json_encode($object));

        return $response;
    }
}