aboutsummaryrefslogtreecommitdiff
path: root/lib/models/vips/SingleChoiceTask.php
blob: c275f532b1bb39980229bc4cfa6546ddcbeda852 (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
<?php
/*
 * SingleChoiceTask.php - Vips plugin for Stud.IP
 * Copyright (c) 2006-2009  Elmar Ludwig, Martin Schröder
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 */

/**
 * @license GPL2 or any later version
 *
 * @property int $id database column
 * @property string $type database column
 * @property string $title database column
 * @property string $description database column
 * @property string $task database column
 * @property string $user_id database column
 * @property int $mkdate database column
 * @property int $chdate database column
 * @property JSONArrayObject $options database column
 * @property SimpleORMapCollection<VipsExerciseRef> $exercise_refs has_many VipsExerciseRef
 * @property SimpleORMapCollection<VipsSolution> $solutions has_many VipsSolution
 * @property User $user belongs_to User
 * @property Folder $folder has_one Folder
 * @property SimpleORMapCollection<VipsTest> $tests has_and_belongs_to_many VipsTest
 */
class SingleChoiceTask extends Exercise
{
    /**
     * Get the icon of this exercise type.
     */
    public static function getTypeIcon(string $role = Icon::DEFAULT_ROLE): Icon
    {
        return Icon::create('task-single-choice', $role);
    }

    /**
     * Get a description of this exercise type.
     */
    public static function getTypeDescription(): string
    {
        return _('Einfachauswahl aus einer Liste');
    }

    /**
     * Initialize a new instance of this class.
     */
    public function __construct($id = null)
    {
        parent::__construct($id);

        if (!isset($id)) {
            $this->task = [];
        }
    }

    /**
     * Initialize this instance from the current request environment.
     */
    public function initFromRequest($request): void
    {
        parent::initFromRequest($request);

        $this->task = [];

        foreach ($request['answer'] as $group => $answergroup) {
            $task = [];
            $description = trim($request['description'][$group]);
            $description = Studip\Markup::purifyHtml($description);

            if ($this->task && $description != '') {
                $task['description'] = $description;
            }

            foreach ($answergroup as $i => $answer) {
                $answer = self::purifyFlexibleInput($answer);

                if (trim($answer) != '') {
                    $task['answers'][] = [
                        'text'  => trim($answer),
                        'score' => $request['correct'][$group] == $i ? 1 : 0
                    ];
                }
            }

            if ($task) {
                $this->task[] = $task;
            }
        }

        if ($request['optional']) {
            $this->options['optional'] = 1;
        }
    }

    /**
     * Computes the default maximum points which can be reached in this
     * exercise, dependent on the number of groups.
     *
     * @return int maximum points
     */
    public function itemCount(): int
    {
        return count($this->task);
    }

    /**
     * Shuffle the answer alternatives.
     *
     * @param $user_id string used for initialising the randomizer.
     */
    public function shuffleAnswers(string $user_id): void
    {
        srand(crc32($this->id . ':' . $user_id));

        for ($block = 0; $block < count($this->task); $block++) {
            $random_order = range(0, count($this->task[$block]['answers']) - 1);
            shuffle($random_order);

            $answer_temp = [];
            foreach ($random_order as $index) {
                $answer_temp[$index] = $this->task[$block]['answers'][$index];
            }
            $this->task[$block]['answers'] = $answer_temp;
        }

        srand();
    }

    /**
     * Returns true if this exercise type is considered as multiple choice.
     * In this case, the evaluation mode set on the assignment is applied.
     */
    public function isMultipleChoice(): bool
    {
        return true;
    }

    /**
     * Evaluates a student's solution for the individual items in this
     * exercise. Returns an array of ('points' => float, 'safe' => boolean).
     *
     * @param mixed $solution The solution XML string as returned by responseFromRequest().
     */
    public function evaluateItems($solution): array
    {
        $result = [];

        $response = $solution->response;

        foreach ($this->task as $i => $task) {
            if (!isset($response[$i]) || $response[$i] === '' || $response[$i] == -1) {
                $points = null;
            } else {
                $points = $task['answers'][$response[$i]]['score'];
            }

            $result[] = ['points' => $points, 'safe' => true];
        }

        return $result;
    }

    /**
     * Return the list of keywords used for text export. The first keyword
     * in the list must be the keyword for the exercise type.
     */
    public static function getTextKeywords(): array
    {
        return ['SCO?-Frage|JN-Frage', '[+~]?Antwort'];
    }

    /**
     * Initialize this instance from the given text data array.
     */
    public function initText(array $exercise): void
    {
        parent::initText($exercise);

        $block = 0;

        foreach ($exercise as $tag) {
            if (key($tag) === 'Type' && current($tag) === 'SCO-Frage') {
                $this->options['optional'] = 1;
            }

            if (key($tag) === '+Antwort' || key($tag) === 'Antwort') {
                if (preg_match('/\n--$/', current($tag))) {
                    $text = trim(substr(current($tag), 0, -3));
                    $incr = 1;
                } else {
                    $text = current($tag);
                    $incr = 0;
                }

                $score = key($tag) === '+Antwort' ? 1 : 0;

                $this->task[$block]['answers'][] = [
                    'text'  => Studip\Markup::purifyHtml($text),
                    'score' => $score
                ];

                $block += $incr;
            }
        }
    }

    /**
     * Initialize this instance from the given SimpleXMLElement object.
     */
    public function initXML($exercise): void
    {
        parent::initXML($exercise);

        foreach ($exercise->items->item as $item) {
            $task = [];

            if ($item->description) {
                $task['description'] = Studip\Markup::purifyHtml(trim($item->description->text));
            }

            foreach ($item->answers->answer as $answer) {
                if ($answer['default'] == 'true') {
                    $this->options['optional'] = 1;
                } else {
                    $task['answers'][] = [
                        'text'  => Studip\Markup::purifyHtml(trim($answer)),
                        'score' => (int) $answer['score']
                    ];
                }
            }

            $this->task[] = $task;
        }
    }

    /**
     * Creates a template for editing a SingleChoiceTask.
     */
    public function getEditTemplate(?VipsAssignment $assignment): Flexi\Template
    {
        if (!$this->task) {
            $this->task[0]['answers'] = array_fill(0, 5, ['text' => '', 'score' => 0]);
        }

        return parent::getEditTemplate($assignment);
    }

    /**
     * Create a template for viewing an exercise.
     */
    public function getViewTemplate(
        string $view,
        ?VipsSolution $solution,
        VipsAssignment $assignment,
        ?string $user_id
    ): Flexi\Template {
        $template = parent::getViewTemplate($view, $solution, $assignment, $user_id);

        if (isset($this->options['optional']) && $this->options['optional']) {
            $template->optional_answer = [-1 => ['text' => _('keine Antwort'), 'score' => 0]];
        } else {
            $template->optional_answer = [];
        }

        return $template;
    }

    /**
     * Export a response for this exercise into an array of strings.
     */
    public function exportResponse(array $response): array
    {
        return array_map(function($a) { return $a == -1 ? '' : $a; }, $response);
    }
}