aboutsummaryrefslogtreecommitdiff
path: root/lib/models/Courseware/Instance.php
blob: c823a4edbde736d52530cb77e140ea798e1cad92 (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
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
<?php

namespace Courseware;

/**
 * This class represents an instance of a courseware of a course or a user.
 *
 * @author  Marcus Eibrink-Lunzenauer <lunzenauer@elan-ev.de>
 * @author  Ron Lucke <lucke@elan-ev.de>
 * @license GPL2 or any later version
 *
 * @since   Stud.IP 5.0
 */
class Instance
{
    public static function deleteForRange(\Range $range): void
    {
        $root = null;
        switch ($range->getRangeType()) {
            case 'course':
                $root = StructuralElement::getCoursewareCourse($range->getRangeId());
                break;
            case 'user':
                $root = StructuralElement::getCoursewareUser($range->getRangeId());
                break;
            default:
                throw new \InvalidArgumentException('Only ranges of type "user" and "course" are currently supported.');
        }

        // there is no courseware for this course
        if (!$root) {
            return;
        }

        $instance = new self($root);

        $range->getConfiguration()->delete('COURSEWARE_SEQUENTIAL_PROGRESSION');
        $range->getConfiguration()->delete('COURSEWARE_EDITING_PERMISSION');

        $last_element_configs = \ConfigValue::findBySQL('field = ? AND value LIKE ?', [
            'COURSEWARE_LAST_ELEMENT',
            '%' . $range->getRangeId() . '%',
        ]);
        foreach ($last_element_configs as $config) {
            $arr = json_decode($config->value, true);
            $arr = array_filter(
                $arr,
                function ($key) use ($range) {
                    return $key !== $range->id;
                },
                ARRAY_FILTER_USE_KEY
            );
            \UserConfig::get($config->range_id)->unsetValue('COURSEWARE_LAST_ELEMENT');
            \UserConfig::get($config->range_id)->store('COURSEWARE_LAST_ELEMENT', $arr);
        }

        $root->delete();
    }

    /**
     * @var StructuralElement
     */
    private $root;

    /**
     * Create a new representation of a a courseware instance.
     *
     * This model class purely represents and does not create anything. Its purpose is to have all things related to a
     * single courseware instance in one place.
     *
     * @param StructuralElement $root the root of this courseware instance
     */
    public function __construct(StructuralElement $root)
    {
        $this->root = $root;
    }

    /**
     * Returns the root element of this courseware instance.
     *
     * @return StructuralElement the root element of this courseware instance
     */
    public function getRoot(): StructuralElement
    {
        return $this->root;
    }

    /**
     * Returns the range this courseware instance belongs to.
     *
     * @return \Range the range this courseware instance belongs to
     */
    public function getRange(): \Range
    {
        $rangeType = $this->root['range_type'];

        return $this->root->$rangeType;
    }

    /**
     * Returns the type of this courseware instance's range as coded in the root element.
     *
     * @return string the type of this courseware instance's range
     */
    public function getRangeType(): string
    {
        return $this->root['range_type'];
    }

    /**
     * Returns all associated block types registered to this courseware instance.
     *
     * @return array a list of all associated block types
     */
    public function getBlockTypes(): array
    {
        $types = BlockTypes\BlockType::getBlockTypes();

        return $types;
    }

    /**
     * Returns all associated container types registered to this courseware instance.
     *
     * @return array a list of all associated block types
     */
    public function getContainerTypes(): array
    {
        $types = ContainerTypes\ContainerType::getContainerTypes();

        return $types;
    }

    /**
     * Returns a user's favorite block types for this instance.
     *
     * @param \User $user the user for whom the favorite block types will be returned
     *
     * @return array a list of favorite block types
     */
    public function getFavoriteBlockTypes(\User $user): array
    {
        /** @var array $favoriteBlockTypes */
        $favoriteBlockTypes = \UserConfig::get($user->id)->getValue('COURSEWARE_FAVORITE_BLOCK_TYPES');

        return $favoriteBlockTypes;
    }

    /**
     * Sets a user's favorite block types for this courseware instance.
     *
     * @param \User $user      the user for whom the favorite block types will be set
     * @param array $favorites the list of favorite block types
     */
    public function setFavoriteBlockTypes(\User $user, array $favorites): void
    {
        \UserConfig::get($user->id)->store('COURSEWARE_FAVORITE_BLOCK_TYPES', $favorites);
    }

    /**
     * Returns whether this courseware instance uses a sequential progression through the structural elements.
     *
     * @return bool true if this courseware instance uses a sequential progression, false otherwise
     */
    public function getSequentialProgression(): bool
    {
        $range = $this->getRange();
        $config = $range->getConfiguration()->getValue('COURSEWARE_SEQUENTIAL_PROGRESSION');

        return (bool) $config;
    }

    /**
     * Sets whether this courseware instance uses a sequential progression through the structural elements.
     *
     * @param bool $isSequentialProgression true if this courseware instance uses a sequential progression
     */
    public function setSequentialProgression(bool $isSequentialProgression): void
    {
        $range = $this->getRange();
        $range->getConfiguration()->store('COURSEWARE_SEQUENTIAL_PROGRESSION', $isSequentialProgression);
    }

    const EDITING_PERMISSION_DOZENT = 'dozent';
    const EDITING_PERMISSION_TUTOR = 'tutor';

    /**
     * Returns the level needed to edit this courseware instance.
     *
     * @return string can be either `Instance::EDITING_PERMISSION_DOZENT` or  `Instance::EDITING_PERMISSION_TUTOR`
     */
    public function getEditingPermissionLevel(): string
    {
        $range = $this->getRange();
        /** @var string $editingPermissionLevel */
        $editingPermissionLevel = $range->getConfiguration()->getValue('COURSEWARE_EDITING_PERMISSION');
        $this->validateEditingPermissionLevel($editingPermissionLevel);

        return $editingPermissionLevel;
    }

    /**
     * Sets the level needed to edit this courseware instance.
     *
     * @param string $editingPermissionLevel can be either `Instance::EDITING_PERMISSION_DOZENT` or
     *                                       `Instance::EDITING_PERMISSION_TUTOR`
     */
    public function setEditingPermissionLevel(string $editingPermissionLevel): void
    {
        $this->validateEditingPermissionLevel($editingPermissionLevel);
        $range = $this->getRange();
        $range->getConfiguration()->store('COURSEWARE_EDITING_PERMISSION', $editingPermissionLevel);
    }

    /**
     * Validates a editing permission level.
     *
     * @param string $editingPermissionLevel the editing permission level to validate
     *
     * @return bool true if this editing permission level is valid, false otherwise
     */
    public function isValidEditingPermissionLevel(string $editingPermissionLevel): bool
    {
        return in_array($editingPermissionLevel, [self::EDITING_PERMISSION_DOZENT, self::EDITING_PERMISSION_TUTOR]);
    }

    private function validateEditingPermissionLevel(string $editingPermissionLevel): void
    {
        if (!$this->isValidEditingPermissionLevel($editingPermissionLevel)) {
            throw new \InvalidArgumentException('Invalid editing permission of courseware.');
        }
    }

    /**
     * Returns all bookmarks of a user associated to this courseware instance.
     *
     * @param \User $user the user for whom to find associated bookmarks for
     *
     * @return array a list of the given user's bookmarks associated to this instance
     */
    public function getUsersBookmarks(\User $user): array
    {
        return StructuralElement::findUsersBookmarksByRange($user, $this->getRange());
    }

    public function findAllStructuralElements(): iterable
    {
        $sql = 'SELECT se.*
                FROM cw_structural_elements se
                WHERE se.range_id = ? AND se.range_type = ?';
        $statement = \DBManager::get()->prepare($sql);
        $statement->execute([$this->root['range_id'], $this->root['range_type']]);

        $data = [];
        foreach ($statement as $key => $row) {
            $data[] = \Courseware\StructuralElement::build($row, false);
        }

        return $data;
    }

    public function findAllBlocks(): iterable
    {
        $sql = 'SELECT b.*
                FROM cw_structural_elements se
                JOIN cw_containers c ON se.id = c.structural_element_id
                JOIN cw_blocks b ON c.id = b.container_id
                WHERE se.range_id = ? AND se.range_type = ?';
        $statement = \DBManager::get()->prepare($sql);
        $statement->execute([$this->root['range_id'], $this->root['range_type']]);

        $data = [];
        foreach ($statement as $key => $row) {
            $data[] = \Courseware\Block::build($row, false);
        }

        return $data;
    }

    /**
     * Find all blocks of this instance and group them by their structural element's ID.
     * You may specify your own `$formatter` instead of the default one which stores the blocks as instances of \Courseware\Block.
     *
     * @param ?callable(array $row): mixed $formatter Provide your own callable if you need something else instead of
     *                                                full-blown instances of \Courseware\Block.
     * @return iterable all the (optionally formatted) blocks grouped by the IDs of the structural element containing
     *                  that block.
     */
    public function findAllBlocksGroupedByStructuralElementId(callable $formatter = null): iterable
    {
        if (!$formatter) {
            $formatter = function ($row) {
                return \Courseware\Block::build($row, false);
            };
        }

        $sql = 'SELECT se.id AS structural_element_id, b.*
                FROM cw_structural_elements se
                JOIN cw_containers c ON se.id = c.structural_element_id
                JOIN cw_blocks b ON c.id = b.container_id
                WHERE se.range_id = ? AND se.range_type = ?';

        $statement = \DBManager::get()->prepare($sql);
        $statement->execute([$this->root['range_id'], $this->root['range_type']]);

        $data = [];
        foreach ($statement as $row) {
            $structuralElementId = $row['structural_element_id'];
            unset($row['structural_element_id']);

            if (!isset($data[$structuralElementId])) {
                $data[$structuralElementId] = [];
            }
            $data[$structuralElementId][] = $formatter($row);
        }

        return $data;
    }
}