aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/JsonApi/Routes/Courseware/StructuralElementsSharedIndex.php
blob: 2be04115d8d9ad16207e00591d5f906808a5712d (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
74
75
76
77
78
79
<?php

namespace JsonApi\Routes\Courseware;

use Courseware\StructuralElement;
use JsonApi\Errors\AuthorizationFailedException;
use JsonApi\JsonApiController;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

/**
 * Class StructuralElementsSharedIndex.
 */
class StructuralElementsSharedIndex extends JsonApiController
{
    protected $allowedPagingParameters = ['offset', 'limit'];

    protected $allowedIncludePaths = [
        'ancestors',
        'children',
        'containers',
        'containers.blocks',
        'containers.blocks.edit-blocker',
        'containers.blocks.editor',
        'containers.blocks.owner',
        'containers.blocks.user-data-field',
        'containers.blocks.user-progress',
        'course',
        'editor',
        'owner',
        'parent',
    ];

    /**
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function __invoke(Request $request, Response $response, $args)
    {
        $user = $this->getUser($request);
        if (!Authority::canIndexStructuralElementsShared($user)) {
            throw new AuthorizationFailedException();
        }

        list($offset, $limit) = $this->getOffsetAndLimit();
        $elements = [];
        $contents = StructuralElement::findBySQL(
            'range_id != ? AND range_type = ? ORDER BY mkdate ASC',
            [$user->id, 'user']
        );

        foreach ($contents as $content) {
            if (count($content->content_approval) === 0) {
                continue;
            }

            $add_content = false;

            foreach ($content->content_approval['users'] as $listedUserPerm) {
                if ($listedUserPerm['id'] == $user->id && !empty($listedUserPerm['read'])) {
                    $add_content = true;
                }
            }

            if ($add_content) {
                $elements[] = $content;
            }
        }

        $resources = [];
        foreach ($elements as $element) {
            $has_parent = array_column($elements, null, 'id')[$element->parent_id] ?? false;
            if (!$has_parent) {
                $resources[] = $element;
            }
        }

        return $this->getPaginatedContentResponse($resources, count($resources));
    }
}