aboutsummaryrefslogtreecommitdiff
path: root/lib/models/Courseware/Unit.php
blob: 08fe9e2e22d98d91c940170324ed5e8215595429 (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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
<?php

namespace Courseware;

use JSONArrayObject;
use User;

/**
 * Courseware's units.
 *
 * @author  Ron Lucke <lucke@elan-ev.de>
 * @license GPL2 or any later version
 *
 * @since   Stud.IP 5.3
 *
 * @property int $id database column
 * @property string|null $range_id database column
 * @property string|null $range_type database column
 * @property int $structural_element_id database column
 * @property string $content_type database column
 * @property int|null $position database column
 * @property int $public database column
 * @property string|null $creator_id database column
 * @property string $permission_scope database column
 * @property string $permission_type database column
 * @property string $visible database column
 * @property bool $visible_all database column
 * @property int|null $visible_start_date database column
 * @property int|null $visible_end_date database column
 * @property string $writable database column
 * @property bool $writable_all database column
 * @property int|null $writable_start_date database column
 * @property int|null $writable_end_date database column
 * @property \JSONArrayObject $visible_approval database column
 * @property \JSONArrayObject $writable_approval database column
 * @property \JSONArrayObject $config database column
 * @property int $mkdate database column
 * @property int $chdate database column
 * @property \Course|null $course belongs_to \Course
 * @property \User|null $user belongs_to \User
 * @property \User|null $creator belongs_to \User
 * @property StructuralElement $structural_element has_one StructuralElement
 */

class Unit extends \SimpleORMap implements \PrivacyObject, \FeedbackRange
{
    protected static function configure($config = [])
    {
        $config['db_table'] = 'cw_units';

        $config['serialized_fields']['config'] = JSONArrayObject::class;
        $config['serialized_fields']['visible_approval'] = JSONArrayObject::class;
        $config['serialized_fields']['writable_approval'] = JSONArrayObject::class;

        $config['has_one']['structural_element'] = [
            'class_name' => StructuralElement::class,
            'foreign_key' => 'structural_element_id',
            'on_delete' => 'delete',
        ];
        $config['belongs_to']['course'] = [
            'class_name' => \Course::class,
            'foreign_key' => 'range_id',
            'assoc_foreign_key' => 'seminar_id',
        ];
        $config['belongs_to']['user'] = [
            'class_name' => User::class,
            'foreign_key' => 'range_id',
            'assoc_foreign_key' => 'user_id',
        ];
        $config['belongs_to']['creator'] = [
            'class_name' => User::class,
            'foreign_key' => 'creator_id',
        ];

        $config['registered_callbacks']['after_delete'][] = 'updatePositionsAfterDelete';
        $config['registered_callbacks']['before_delete'][] = 'cbBeforeDelete';

        parent::configure($config);
    }

    public function cbBeforeDelete()
    {
        \FeedbackElement::deleteBySQL('range_id = ? AND range_type = ?', [$this->id, self::class]);
    }

    public static function findCoursesUnits(\Course $course): array
    {
        return self::findBySQL('range_id = ? AND range_type = ?', [$course->id, 'course']);
    }

    public static function findUsersUnits(User $user): array
    {
        return self::findBySQL('range_id = ? AND range_type = ?', [$user->id, 'user']);
    }

    public function canRead(User $user): bool
    {
        if ($this->canEdit($user) || $this->canEditContent($user)) {
            return true;
        }
        if ($this->permission_scope === 'unit') {
            if ($this->permission_type === 'all' || $this->visible_all) {
                if ($this->isVisible()) {
                    return true;
                }
                return false;
            }
            if ($this->permission_type === 'users') {
                return in_array($user->id, json_decode($this->visible_approval)) && $this->isVisible();
            }
            if ($this->permission_type === 'groups') {
                $groups = json_decode($this->visible_approval);
                foreach ($groups as $groupId) {
                    $group = \Statusgruppen::find($groupId);
                    if ($group && $group->isMember($user->id)) {
                        return $this->isVisible();
                    }
                }
            }
        }

        return true;
    }

    private function isVisible(): bool
    {
        if ($this->visible === 'always') {
            return true;
        }
        if ($this->visible === 'never') {
            return false;
        }

        return
            (empty($this->visible_start_date) || $this->visible_start_date <= strtotime('today'))
            && (empty($this->visible_end_date) || $this->visible_end_date >= strtotime('today'));
    }

    public function canEdit(User $user): bool
    {
        if ($user->id === $this->range_id) {
            return true;
        }

        return $GLOBALS['perm']->have_perm('root', $user->id) || $GLOBALS['perm']->have_studip_perm('tutor', $this->range_id, $user->id);
    }

    public function canEditContent(User $user): bool
    {
        if ($this->canEdit($user)) {
            return true;
        }
        if ($this->permission_scope === 'unit') {
            if ($this->permission_type === 'all' || $this->writable_all) {
                if ($this->isWritable()) {
                    return true;
                }
                return false;
            }
            if ($this->permission_type === 'users') {
                return in_array($user->id, json_decode($this->writable_approval)) && $this->isWritable();
            }
            if ($this->permission_type === 'groups') {
                $groups = json_decode($this->writable_approval);
                foreach ($groups as $groupId) {
                    $group = \Statusgruppen::find($groupId);
                    if ($group && $group->isMember($user->id)) {
                        return $this->isWritable();
                    }
                }
            }
        }

        return false;
    }

    private function isWritable(): bool
    {
        if ($this->writable === 'always') {
            return true;
        }
        if ($this->writable === 'never') {
            return false;
        }

        return
            (empty($this->writable_start_date) || $this->writable_start_date < strtotime('today'))
            && (empty($this->writable_end_date) || $this->writable_end_date >= strtotime('today'));
    }

    public function copy(
        User $user,
        string $rangeId,
        string $rangeType,
        array $modified = null,
        bool $duplicate = false
    ): Unit {
        $sourceUnitElement = $this->structural_element;

        $newElement = $sourceUnitElement->copyToRange($user, $rangeId, $rangeType, '', $duplicate);

        if ($modified !== null) {
            $newElement->title = $modified['title'] ?? $newElement->title;
            $newElement->payload['color'] = $modified['color'] ?? 'studip-blue';
            $newElement->payload['description'] = $modified['description'] ?? $newElement->payload['description'];
            $newElement->store();
        }

        $newUnit = \Courseware\Unit::build([
            'range_id' => $rangeId,
            'range_type' => $rangeType,
            'structural_element_id' => $newElement->id,
            'content_type' => 'courseware',
            'position' => $this->getNewPosition($rangeId),
            'creator_id' => $user->id,
            'public' => '',
            'permission_scope' => $duplicate ? $this->permission_scope : 'unit',
            'permission_type' => $duplicate ? $this->permission_type : 'all',
            'visible' => $duplicate ? $this->visible : 'always',
            'visible_all' => $duplicate ? $this->visible_all : 0,
            'visible_start_date' => $duplicate ? $this->visible_start_date : null,
            'visible_end_date' => $duplicate ? $this->visible_end_date : null,
            'visible_approval' => $duplicate ? $this->visible_approval : '',
            'writable' => $duplicate ? $this->writable : 'never',
            'writable_all' => $duplicate ? $this->writable_all : 0,
            'writable_start_date' => $duplicate ? $this->writable_start_date : null,
            'writable_end_date' => $duplicate ? $this->writable_end_date : null,
            'writable_approval' => $duplicate ? $this->writable_approval : '',
            'config' => $this->config,
        ]);

        $newUnit->store();

        return $newUnit;
    }
    /**
     * Export available data of a given user into a storage object
     * (an instance of the StoredUserData class) for that user.
     *
     * @param StoredUserData $storage object to store data into
     */
    public static function exportUserData(\StoredUserData $storage)
    {
        $units = \DBManager::get()->fetchAll(
            'SELECT * FROM cw_units WHERE creator_id = ?',
            [$storage->user_id]
        );
        if ($units) {
            $storage->addTabularData(_('Courseware Lernmaterialien'), 'cw_units', $units);
        }

    }

    public static function getNewPosition($range_id): int
    {
        return static::countBySQL('range_id = ?', [$range_id]);
    }

    public function updatePositionsAfterDelete(): void
    {
        if (is_null($this->position)) {
            return;
        }

        $db = \DBManager::get();
        $stmt = $db->prepare(
            sprintf(
                'UPDATE
              %s
            SET
              position = position - 1
            WHERE
              range_id = :range_id AND
              position > :position',
                'cw_units'
            )
        );
        $stmt->bindValue(':range_id', $this->range_id);
        $stmt->bindValue(':position', $this->position);
        $stmt->execute();
    }

    public static function updatePositions($range, $positions): void
    {
        $db = \DBManager::get();
        $query = sprintf(
            'UPDATE
                %s 
            SET
                position = FIND_IN_SET(id, ?) - 1
            WHERE
                range_id = ?',
            'cw_units'
        );
        $args = array(join(',', $positions), $range->id);
        $stmt = $db->prepare($query);
        $stmt->execute($args);
    }

    public function hasRootLayout()
    {
        return !isset($this->config['root_layout']) || $this->config['root_layout'] !== 'none';
    }

    public function findOrCreateFirstElement(): StructuralElement
    {
        if ($this->hasRootLayout()) {
            return $this->structural_element;
        }

        $children = $this->structural_element->children;
        if (count($children) > 0) {
            return $children[0];
        }

        $struct = StructuralElement::create([
            'parent_id' => $this->structural_element->id,
            'range_id' => $this->range_id,
            'range_type' => $this->range_type,
            'owner_id' => $this->structural_element->owner_id,
            'editor_id' => $this->structural_element->editor_id,
            'title' => _('neue Seite'),
        ]);


        return $struct;
    }

    public function getRangeCourseId(): string
    {
        return $this->range_id;
    }

    public function getRangeName(): string
    {
        return $this->structural_element->title;
    }

    public function getRangeIcon($role): string
    {
        return \Icon::create('content2', $role);
    }

    public function getRangeUrl(): string
    {
        if ($this->structural_element->range_type === 'user') {
            return 'contents/courseware/';
        }

        return 'course/courseware/' . '?cid=' . $this->range_id;
    }

    public function isRangeAccessible(string $user_id = null): bool
    {
        $user = \User::find($user_id);
        if ($user) {
            return $this->canRead($user);
        }

        return false;
    }

    public function getFeedbackElement()
    {
        return \FeedbackElement::findOneBySQL(
            'range_id = ? AND range_type = ?',
            [$this->id, self::class]
        );
    }

    public function getRange()
    {
        return $this->range_type::find($this->range_id);
    }
}