Passed
Push — master ( 251179...3b9d17 )
by Julito
09:58
created

UniqueAnswer::addAnswer()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 47
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 33
c 0
b 0
f 0
nc 2
nop 6
dl 0
loc 47
rs 9.392
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CourseBundle\Entity\CQuizAnswer;
6
use ChamiloSession as Session;
7
8
/**
9
 * Class UniqueAnswer.
10
 *
11
 * This class allows to instantiate an object of type UNIQUE_ANSWER
12
 * (MULTIPLE CHOICE, UNIQUE ANSWER),
13
 * extending the class question
14
 *
15
 * @author Eric Marguin
16
 * @author Julio Montoya
17
 */
18
class UniqueAnswer extends Question
19
{
20
    public $typePicture = 'mcua.png';
21
    public $explanationLangVar = 'Multiple choice';
22
23
    /**
24
     * Constructor.
25
     */
26
    public function __construct()
27
    {
28
        parent::__construct();
29
        $this->type = UNIQUE_ANSWER;
30
        $this->isContent = $this->getIsContent();
31
    }
32
33
    public function createAnswersForm($form)
34
    {
35
        // Getting the exercise list
36
        /** @var Exercise $obj_ex */
37
        $obj_ex = Session::read('objExercise');
38
39
        $editor_config = [
40
            'ToolbarSet' => 'TestProposedAnswer',
41
            'Width' => '100%',
42
            'Height' => '125',
43
        ];
44
45
        //this line defines how many questions by default appear when creating a choice question
46
        // The previous default value was 2. See task #1759.
47
        $nb_answers = isset($_POST['nb_answers']) ? (int) $_POST['nb_answers'] : 4;
48
        $nb_answers += (isset($_POST['lessAnswers']) ? -1 : (isset($_POST['moreAnswers']) ? 1 : 0));
49
50
        $feedback_title = '';
51
        switch ($obj_ex->getFeedbackType()) {
52
            case EXERCISE_FEEDBACK_TYPE_DIRECT:
53
                // Scenario
54
                $comment_title = '<th width="20%">'.get_lang('Comment').'</th>';
55
                $feedback_title = '<th width="20%">'.get_lang('Scenario').'</th>';
56
57
                break;
58
            case EXERCISE_FEEDBACK_TYPE_POPUP:
59
                $comment_title = '<th width="20%">'.get_lang('Comment').'</th>';
60
61
                break;
62
            default:
63
                $comment_title = '<th width="40%">'.get_lang('Comment').'</th>';
64
65
                break;
66
        }
67
68
        $html = '<table class="table table-striped table-hover">
69
            <thead>
70
                <tr style="text-align: center;">
71
                    <th width="5%">'.get_lang('N°').'</th>
72
                    <th width="5%"> '.get_lang('True').'</th>
73
                    <th width="40%">'.get_lang('Answer').'</th>
74
                        '.$comment_title.'
75
                        '.$feedback_title.'
76
                    <th width="10%">'.get_lang('Score').'</th>
77
                </tr>
78
            </thead>
79
            <tbody>';
80
81
        $form->addHeader(get_lang('Answers'));
82
        $form->addHtml($html);
83
84
        $defaults = [];
85
        $correct = 0;
86
        if (!empty($this->id)) {
87
            $answer = new Answer($this->id);
88
            $answer->read();
89
            if ($answer->nbrAnswers > 0 && !$form->isSubmitted()) {
90
                $nb_answers = $answer->nbrAnswers;
91
            }
92
        }
93
        $form->addElement('hidden', 'nb_answers');
94
95
        $obj_ex->setQuestionList(true);
96
        $question_list = $obj_ex->getQuestionList();
97
        $select_question = [];
98
        $select_question[0] = get_lang('Select target question');
99
        if (is_array($question_list)) {
100
            foreach ($question_list as $key => $questionid) {
101
                //To avoid warning messages
102
                if (!is_numeric($questionid)) {
103
                    continue;
104
                }
105
                $question = Question::read($questionid);
106
                $questionTitle = strip_tags($question->selectTitle());
107
                $select_question[$questionid] = "Q$key: $questionTitle";
108
            }
109
        }
110
        $select_question[-1] = get_lang('Exit test');
111
112
        $list = new LearnpathList(api_get_user_id());
113
        $flat_list = $list->get_flat_list();
114
        $select_lp_id = [];
115
        $select_lp_id[0] = get_lang('Select target course');
116
117
        foreach ($flat_list as $id => $details) {
118
            $select_lp_id[$id] = cut($details['lp_name'], 20);
119
        }
120
121
        $temp_scenario = [];
122
        if ($nb_answers < 1) {
123
            $nb_answers = 1;
124
            echo Display::return_message(
125
                get_lang('You have to create at least one answer')
126
            );
127
        }
128
129
        for ($i = 1; $i <= $nb_answers; $i++) {
130
            $form->addHtml('<tr>');
131
            if (isset($answer) && is_object($answer)) {
132
                if (isset($answer->correct[$i]) && $answer->correct[$i]) {
133
                    $correct = $i;
134
                }
135
                $defaults['answer['.$i.']'] = isset($answer->answer[$i]) ? $answer->answer[$i] : '';
136
                $defaults['comment['.$i.']'] = isset($answer->comment[$i]) ? $answer->comment[$i] : '';
137
                $defaults['weighting['.$i.']'] = isset($answer->weighting[$i]) ? float_format($answer->weighting[$i], 1) : 0;
138
                $item_list = [];
139
                if (isset($answer->destination[$i])) {
140
                    $item_list = explode('@@', $answer->destination[$i]);
141
                }
142
                $try = $item_list[0] ?? '';
143
                $lp = $item_list[1] ?? '';
144
                $list_dest = $item_list[2] ?? '';
145
                $url = $item_list[3] ?? '';
146
147
                if (0 == $try) {
148
                    $try_result = 0;
149
                } else {
150
                    $try_result = 1;
151
                }
152
                if (0 == $url) {
153
                    $url_result = '';
154
                } else {
155
                    $url_result = $url;
156
                }
157
158
                $temp_scenario['url'.$i] = $url_result;
159
                $temp_scenario['try'.$i] = $try_result;
160
                $temp_scenario['lp'.$i] = $lp;
161
                $temp_scenario['destination'.$i] = $list_dest;
162
            } else {
163
                $defaults['answer[1]'] = get_lang('A then B then C');
164
                $defaults['weighting[1]'] = 10;
165
                $defaults['answer[2]'] = get_lang('A then C then B');
166
                $defaults['weighting[2]'] = 0;
167
                $temp_scenario['destination'.$i] = ['0'];
168
                $temp_scenario['lp'.$i] = ['0'];
169
            }
170
            $defaults['scenario'] = $temp_scenario;
171
172
            $renderer = $form->defaultRenderer();
173
174
            $renderer->setElementTemplate(
175
                '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
176
                'correct'
177
            );
178
            $renderer->setElementTemplate(
179
                '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
180
                'counter['.$i.']'
181
            );
182
            $renderer->setElementTemplate(
183
                '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
184
                'answer['.$i.']'
185
            );
186
            $renderer->setElementTemplate(
187
                '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
188
                'comment['.$i.']'
189
            );
190
            $renderer->setElementTemplate(
191
                '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
192
                'weighting['.$i.']'
193
            );
194
195
            $answer_number = $form->addElement(
196
                'text',
197
                'counter['.$i.']',
198
                null,
199
                ' value = "'.$i.'"'
200
            );
201
            $answer_number->freeze();
202
            $form->addElement(
203
                'radio',
204
                'correct',
205
                null,
206
                null,
207
                $i,
208
                ['class' => 'checkbox']
209
            );
210
211
            $form->addHtmlEditor('answer['.$i.']', null, null, false, $editor_config);
212
213
            $form->addRule(
214
                'answer['.$i.']',
215
                get_lang('Required field'),
216
                'required'
217
            );
218
219
            switch ($obj_ex->getFeedbackType()) {
220
                case EXERCISE_FEEDBACK_TYPE_DIRECT:
221
                    $this->setDirectOptions($i, $form, $renderer, $select_lp_id, $select_question);
222
223
                    break;
224
                case EXERCISE_FEEDBACK_TYPE_POPUP:
225
                default:
226
                    $form->addHtmlEditor('comment['.$i.']', null, null, false, $editor_config);
227
228
                    break;
229
            }
230
            $form->addText('weighting['.$i.']', null, null, ['value' => '0']);
231
            $form->addHtml('</tr>');
232
        }
233
234
        $form->addHtml('</tbody>');
235
        $form->addHtml('</table>');
236
237
        global $text;
238
        $buttonGroup = [];
239
240
        if (true == $obj_ex->edit_exercise_in_lp ||
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
241
            (empty($this->exerciseList) && empty($obj_ex->id))
242
        ) {
243
            //setting the save button here and not in the question class.php
244
            $buttonGroup[] = $form->addButtonDelete(get_lang('Remove answer option'), 'lessAnswers', true);
245
            $buttonGroup[] = $form->addButtonCreate(get_lang('Add answer option'), 'moreAnswers', true);
246
            $buttonGroup[] = $form->addButton(
247
                'submitQuestion',
248
                $text,
249
                'check',
250
                'primary',
251
                'default',
252
                null,
253
                ['id' => 'submit-question'],
254
                true
255
            );
256
            $form->addGroup($buttonGroup);
257
        }
258
259
        // We check the first radio button to be sure a radio button will be check
260
        if (0 == $correct) {
261
            $correct = 1;
262
        }
263
264
        if (isset($_POST) && isset($_POST['correct'])) {
265
            $correct = (int) $_POST['correct'];
266
        }
267
268
        $defaults['correct'] = $correct;
269
270
        if (!empty($this->id)) {
271
            $form->setDefaults($defaults);
272
        } else {
273
            if (1 == $this->isContent) {
274
                // Default sample content.
275
                $form->setDefaults($defaults);
276
            } else {
277
                $correct = 1;
278
                if (isset($_POST) && isset($_POST['correct'])) {
279
                    $correct = (int) $_POST['correct'];
280
                }
281
282
                $form->setDefaults(['correct' => $correct]);
283
            }
284
        }
285
        $form->setConstants(['nb_answers' => $nb_answers]);
286
    }
287
288
    public function setDirectOptions($i, FormValidator $form, $renderer, $select_lp_id, $select_question)
289
    {
290
        $editor_config = [
291
            'ToolbarSet' => 'TestProposedAnswer',
292
            'Width' => '100%',
293
            'Height' => '125',
294
        ];
295
296
        $form->addHtmlEditor(
297
            'comment['.$i.']',
298
            null,
299
            null,
300
            false,
301
            $editor_config
302
        );
303
        // Direct feedback
304
        //Adding extra feedback fields
305
        $group = [];
306
        $group['try'.$i] = $form->createElement(
307
            'checkbox',
308
            'try'.$i,
309
            null,
310
            get_lang('Try again')
311
        );
312
        $group['lp'.$i] = $form->createElement(
313
            'select',
314
            'lp'.$i,
315
            get_lang('Theory link').': ',
316
            $select_lp_id
317
        );
318
        $group['destination'.$i] = $form->createElement(
319
            'select',
320
            'destination'.$i,
321
            get_lang('Go to question').': ',
322
            $select_question
323
        );
324
        $group['url'.$i] = $form->createElement(
325
            'text',
326
            'url'.$i,
327
            get_lang('Other').': ',
328
            [
329
                'class' => 'col-md-2',
330
                'placeholder' => get_lang('Other'),
331
            ]
332
        );
333
        $form->addGroup($group, 'scenario');
334
335
        $renderer->setElementTemplate(
336
            '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}',
337
            'scenario'
338
        );
339
    }
340
341
    public function processAnswersCreation($form, $exercise)
342
    {
343
        $questionWeighting = $nbrGoodAnswers = 0;
344
        $correct = $form->getSubmitValue('correct');
345
        $objAnswer = new Answer($this->id);
346
        $nb_answers = $form->getSubmitValue('nb_answers');
347
348
        for ($i = 1; $i <= $nb_answers; $i++) {
349
            $answer = trim($form->getSubmitValue('answer['.$i.']'));
350
            $comment = trim($form->getSubmitValue('comment['.$i.']'));
351
            $weighting = trim($form->getSubmitValue('weighting['.$i.']'));
352
            $scenario = $form->getSubmitValue('scenario');
353
354
            $try = null;
355
            $lp = null;
356
            $destination = null;
357
            $url = null;
358
            if (isset($scenario['try'.$i])) {
359
                $try = !empty($scenario['try'.$i]);
360
            }
361
            //$list_destination = $form -> getSubmitValue('destination'.$i);
362
            if (isset($scenario['lp'.$i])) {
363
                $lp = $scenario['lp'.$i];
364
            }
365
            //$destination_str = $form -> getSubmitValue('destination'.$i);
366
            if (isset($scenario['destination'.$i])) {
367
                $destination = $scenario['destination'.$i];
368
            }
369
370
            if (isset($scenario['url'.$i])) {
371
                $url = trim($scenario['url'.$i]);
372
            }
373
374
            /*
375
            How we are going to parse the destination value
376
377
           here we parse the destination value which is a string
378
            1@@3@@2;4;4;@@http://www.chamilo.org
379
380
            where: try_again@@lp_id@@selected_questions@@url
381
382
           try_again = is 1 || 0
383
           lp_id = id of a learning path (0 if dont select)
384
           selected_questions= ids of questions
385
           url= an url
386
387
            $destination_str='';
388
            foreach ($list_destination as $destination_id)
389
            {
390
                $destination_str.=$destination_id.';';
391
            }*/
392
393
            $goodAnswer = $correct == $i ? true : false;
394
395
            if ($goodAnswer) {
396
                $nbrGoodAnswers++;
397
                $weighting = abs($weighting);
398
                if ($weighting > 0) {
399
                    $questionWeighting += $weighting;
400
                }
401
            }
402
403
            if (empty($try)) {
404
                $try = 0;
405
            }
406
407
            if (empty($lp)) {
408
                $lp = 0;
409
            }
410
411
            if (empty($destination)) {
412
                $destination = 0;
413
            }
414
415
            if ('' == $url) {
416
                $url = 0;
417
            }
418
419
            //1@@1;2;@@2;4;4;@@http://www.chamilo.org
420
            $dest = $try.'@@'.$lp.'@@'.$destination.'@@'.$url;
421
            $objAnswer->createAnswer(
422
                $answer,
423
                $goodAnswer,
424
                $comment,
425
                $weighting,
426
                $i,
427
                null,
428
                null,
429
                $dest
430
            );
431
        }
432
433
        // saves the answers into the data base
434
        $objAnswer->save();
435
436
        // sets the total weighting of the question
437
        $this->updateWeighting($questionWeighting);
438
        $this->save($exercise);
439
    }
440
441
    public function return_header(Exercise $exercise, $counter = null, $score = [])
442
    {
443
        $header = parent::return_header($exercise, $counter, $score);
444
        $header .= '<table class="'.$this->question_table_class.'"><tr>';
445
446
        $header .= '<th>'.get_lang('Your choice').'</th>';
447
        if ($exercise->showExpectedChoiceColumn()) {
448
            $header .= '<th>'.get_lang('Expected choice').'</th>';
449
        }
450
451
        $header .= '<th>'.get_lang('Answer').'</th>';
452
        if ($exercise->showExpectedChoice()) {
453
            $header .= '<th>'.get_lang('Status').'</th>';
454
        }
455
        if (false === $exercise->hideComment) {
456
            $header .= '<th>'.get_lang('Comment').'</th>';
457
        }
458
        $header .= '</tr>';
459
460
        return $header;
461
    }
462
}
463