Completed
Push — master ( 1320a8...a080fe )
by Julito
25:05
created

UniqueAnswerImage::return_header()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 11
nc 2
nop 3
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use ChamiloSession as Session;
5
6
/**
7
 * UniqueAnswerImage.
8
 *
9
 * @author Angel Fernando Quiroz Campos <[email protected]>
10
 */
11
class UniqueAnswerImage extends UniqueAnswer
12
{
13
    public static $typePicture = 'uaimg.png';
14
    public static $explanationLangVar = 'UniqueAnswerImage';
15
16
    /**
17
     * UniqueAnswerImage constructor.
18
     */
19
    public function __construct()
20
    {
21
        parent::__construct();
22
        $this->type = UNIQUE_ANSWER_IMAGE;
23
        $this->isContent = $this->getIsContent();
24
    }
25
26
    /**
27
     * {@inheritdoc}
28
     *
29
     * @throws Exception
30
     */
31
    public function createAnswersForm($form)
32
    {
33
        $objExercise = Session::read('objExercise');
34
        $editorConfig = [
35
            'ToolbarSet' => 'TestProposedAnswer',
36
            'Width' => '100%',
37
            'Height' => '125',
38
        ];
39
40
        //this line defines how many questions by default appear when creating a choice question
41
        // The previous default value was 2. See task #1759.
42
        $numberAnswers = isset($_POST['nb_answers']) ? (int) $_POST['nb_answers'] : 4;
43
        $numberAnswers += (isset($_POST['lessAnswers']) ? -1 : (isset($_POST['moreAnswers']) ? 1 : 0));
44
45
        $feedbackTitle = '';
46
47
        if ($objExercise->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) {
48
            //Scenario
49
            $commentTitle = '<th>'.get_lang('Comment').'</th>';
50
            $feedbackTitle = '<th>'.get_lang('Scenario').'</th>';
51
        } else {
52
            $commentTitle = '<th >'.get_lang('Comment').'</th>';
53
        }
54
55
        $html = '<div class="alert alert-success" role="alert">'.
56
                get_lang('UniqueAnswerImagePreferredSize200x150').'</div>';
57
        $html .= '<table class="table table-striped table-hover">
58
            <thead>
59
                <tr style="text-align: center;">
60
                    <th width="10">'.get_lang('Number').'</th>
61
                    <th>'.get_lang('True').'</th>
62
                    <th>'.get_lang('Answer').'</th>
63
                        '.$commentTitle.'
64
                        '.$feedbackTitle.'
65
                    <th width="15">'.get_lang('Weighting').'</th>
66
                </tr>
67
            </thead>
68
            <tbody>';
69
70
        $form->addHeader(get_lang('Answers'));
71
        $form->addHtml($html);
72
73
        $defaults = [];
74
        $correct = 0;
75
76
        if (!empty($this->id)) {
77
            $answer = new Answer($this->id);
78
            $answer->read();
79
80
            if (count($answer->nbrAnswers) > 0 && !$form->isSubmitted()) {
81
                $numberAnswers = $answer->nbrAnswers;
82
            }
83
        }
84
85
        $form->addElement('hidden', 'nb_answers');
86
87
        //Feedback SELECT
88
        $questionList = $objExercise->selectQuestionList();
89
        $selectQuestion = [];
90
        $selectQuestion[0] = get_lang('SelectTargetQuestion');
91
92
        if (is_array($questionList)) {
93
            foreach ($questionList as $key => $questionid) {
94
                //To avoid warning messages
95
                if (!is_numeric($questionid)) {
96
                    continue;
97
                }
98
99
                $question = Question::read($questionid);
100
                $selectQuestion[$questionid] = 'Q'.$key.' :'.cut(
101
                    $question->selectTitle(),
102
                    20
103
                );
104
            }
105
        }
106
107
        $selectQuestion[-1] = get_lang('ExitTest');
108
109
        $list = new LearnpathList(api_get_user_id());
110
        $flatList = $list->get_flat_list();
111
        $selectLpId = [];
112
        $selectLpId[0] = get_lang('SelectTargetLP');
113
114
        foreach ($flatList as $id => $details) {
115
            $selectLpId[$id] = cut($details['lp_name'], 20);
116
        }
117
118
        $tempScenario = [];
119
120
        if ($numberAnswers < 1) {
121
            $numberAnswers = 1;
122
            echo Display::return_message(get_lang('YouHaveToCreateAtLeastOneAnswer'));
123
        }
124
125
        for ($i = 1; $i <= $numberAnswers; ++$i) {
126
            $form->addHtml('<tr>');
127
            if (isset($answer) && is_object($answer)) {
128
                if ($answer->correct[$i]) {
129
                    $correct = $i;
130
                }
131
132
                $defaults['answer['.$i.']'] = $answer->answer[$i];
133
                $defaults['comment['.$i.']'] = $answer->comment[$i];
134
                $defaults['weighting['.$i.']'] = float_format(
135
                    $answer->weighting[$i],
136
                    1
137
                );
138
139
                $itemList = explode('@@', $answer->destination[$i]);
140
141
                $try = $itemList[0];
142
                $lp = $itemList[1];
143
                $listDestination = $itemList[2];
144
                $url = $itemList[3];
145
146
                $tryResult = 0;
147
                if ($try != 0) {
148
                    $tryResult = 1;
149
                }
150
151
                $urlResult = '';
152
                if ($url != 0) {
153
                    $urlResult = $url;
154
                }
155
156
                $tempScenario['url'.$i] = $urlResult;
157
                $tempScenario['try'.$i] = $tryResult;
158
                $tempScenario['lp'.$i] = $lp;
159
                $tempScenario['destination'.$i] = $listDestination;
160
            } else {
161
                $defaults['answer[1]'] = get_lang('DefaultUniqueAnswer1');
162
                $defaults['weighting[1]'] = 10;
163
                $defaults['answer[2]'] = get_lang('DefaultUniqueAnswer2');
164
                $defaults['weighting[2]'] = 0;
165
166
                $tempScenario['destination'.$i] = ['0'];
167
                $tempScenario['lp'.$i] = ['0'];
168
            }
169
170
            $defaults['scenario'] = $tempScenario;
171
            $renderer = $form->defaultRenderer();
172
            $renderer->setElementTemplate(
173
                '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
174
                'correct'
175
            );
176
            $renderer->setElementTemplate(
177
                '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
178
                'counter['.$i.']'
179
            );
180
            $renderer->setElementTemplate(
181
                '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
182
                'answer['.$i.']'
183
            );
184
            $renderer->setElementTemplate(
185
                '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
186
                'comment['.$i.']'
187
            );
188
            $renderer->setElementTemplate(
189
                '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
190
                'weighting['.$i.']'
191
            );
192
193
            $answerNumber = $form->addElement('text', 'counter['.$i.']', null, ' value = "'.$i.'"');
194
            $answerNumber->freeze();
195
196
            $form->addElement('radio', 'correct', null, null, $i, 'class="checkbox"');
197
            $form->addHtmlEditor('answer['.$i.']', null, null, false, $editorConfig);
198
199
            $form->addRule('answer['.$i.']', get_lang('ThisFieldIsRequired'), 'required');
200
201
            if ($objExercise->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) {
202
                $form->addHtmlEditor(
203
                    'comment['.$i.']',
204
                    null,
205
                    null,
206
                    false,
207
                    $editorConfig
208
                );
209
                // Direct feedback
210
                // Adding extra feedback fields
211
                $group = [];
212
                $group['try'.$i] = $form->createElement('checkbox', 'try'.$i, null, get_lang('TryAgain'));
213
                $group['lp'.$i] = $form->createElement(
214
                    'select',
215
                    'lp'.$i,
216
                    get_lang('SeeTheory').': ',
217
                    $selectLpId
218
                );
219
                $group['destination'.$i] = $form->createElement(
220
                    'select',
221
                    'destination'.$i,
222
                    get_lang('GoToQuestion').': ',
223
                    $selectQuestion
224
                );
225
                $group['url'.$i] = $form->createElement(
226
                    'text',
227
                    'url'.$i,
228
                    get_lang('Other').': ',
229
                    [
230
                        'class' => 'col-md-2',
231
                        'placeholder' => get_lang('Other'),
232
                    ]
233
                );
234
                $form->addGroup($group, 'scenario');
235
236
                $renderer->setElementTemplate(
237
                    '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}',
238
                    'scenario'
239
                );
240
            } else {
241
                $form->addHtmlEditor('comment['.$i.']', null, null, false, $editorConfig);
242
            }
243
            $form->addText('weighting['.$i.']', null, null, ['class' => "col-md-1", 'value' => '0']);
244
            $form->addHtml('</tr>');
245
        }
246
247
        $form->addHtml('</tbody>');
248
        $form->addHtml('</table>');
249
250
        global $text;
251
        $buttonGroup = [];
252
        if ($objExercise->edit_exercise_in_lp == true) {
253
            //setting the save button here and not in the question class.php
254
            $buttonGroup[] = $form->addButtonDelete(get_lang('LessAnswer'), 'lessAnswers', true);
255
            $buttonGroup[] = $form->addButtonCreate(get_lang('PlusAnswer'), 'moreAnswers', true);
256
            $buttonGroup[] = $form->addButtonSave($text, 'submitQuestion', true);
257
            $form->addGroup($buttonGroup);
258
        }
259
260
        // We check the first radio button to be sure a radio button will be check
261
        if ($correct == 0) {
262
            $correct = 1;
263
        }
264
265
        $defaults['correct'] = $correct;
266
267
        if (!empty($this->id)) {
268
            $form->setDefaults($defaults);
269
        } else {
270
            if ($this->isContent == 1) {
271
                // Default sample content.
272
                $form->setDefaults($defaults);
273
            } else {
274
                $form->setDefaults(['correct' => 1]);
275
            }
276
        }
277
278
        $form->setConstants(['nb_answers' => $numberAnswers]);
279
    }
280
281
    /**
282
     * {@inheritdoc}
283
     */
284
    public function processAnswersCreation($form, $exercise)
285
    {
286
        $questionWeighting = $nbrGoodAnswers = 0;
287
        $correct = $form->getSubmitValue('correct');
288
        $objAnswer = new Answer($this->id);
289
        $numberAnswers = $form->getSubmitValue('nb_answers');
290
291
        for ($i = 1; $i <= $numberAnswers; $i++) {
292
            $answer = trim(str_replace(['<p>', '</p>'], '', $form->getSubmitValue('answer['.$i.']')));
293
            $comment = trim(str_replace(['<p>', '</p>'], '', $form->getSubmitValue('comment['.$i.']')));
294
            $weighting = trim($form->getSubmitValue('weighting['.$i.']'));
295
296
            $scenario = $form->getSubmitValue('scenario');
297
298
            //$listDestination = $form -> getSubmitValue('destination'.$i);
299
            //$destinationStr = $form -> getSubmitValue('destination'.$i);
300
301
            $try = $scenario['try'.$i];
302
            $lp = $scenario['lp'.$i];
303
            $destination = $scenario['destination'.$i];
304
            $url = trim($scenario['url'.$i]);
305
306
            /*
307
              How we are going to parse the destination value
308
309
              here we parse the destination value which is a string
310
              1@@3@@2;4;4;@@http://www.chamilo.org
311
312
              where: try_again@@lp_id@@selected_questions@@url
313
314
              try_again = is 1 || 0
315
              lp_id = id of a learning path (0 if dont select)
316
              selected_questions= ids of questions
317
              url= an url
318
319
              $destinationStr='';
320
              foreach ($listDestination as $destination_id)
321
              {
322
              $destinationStr.=$destination_id.';';
323
              } */
324
            $goodAnswer = $correct == $i ? true : false;
325
            if ($goodAnswer) {
326
                $nbrGoodAnswers++;
327
                $weighting = abs($weighting);
328
329
                if ($weighting > 0) {
330
                    $questionWeighting += $weighting;
331
                }
332
            }
333
334
            if (empty($try)) {
335
                $try = 0;
336
            }
337
338
            if (empty($lp)) {
339
                $lp = 0;
340
            }
341
342
            if (empty($destination)) {
343
                $destination = 0;
344
            }
345
346
            if ($url == '') {
347
                $url = 0;
348
            }
349
350
            //1@@1;2;@@2;4;4;@@http://www.chamilo.org
351
            $dest = $try.'@@'.$lp.'@@'.$destination.'@@'.$url;
352
353
            $objAnswer->createAnswer(
354
                $answer,
355
                $goodAnswer,
356
                $comment,
357
                $weighting,
0 ignored issues
show
Bug introduced by
It seems like $weighting can also be of type string and double; however, parameter $weighting of Answer::createAnswer() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

357
                /** @scrutinizer ignore-type */ $weighting,
Loading history...
358
                $i,
359
                null,
360
                null,
361
                $dest
362
            );
363
        }
364
365
        // saves the answers into the data base
366
        $objAnswer->save();
367
368
        // sets the total weighting of the question
369
        $this->updateWeighting($questionWeighting);
0 ignored issues
show
Bug introduced by
It seems like $questionWeighting can also be of type double; however, parameter $weighting of Question::updateWeighting() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

369
        $this->updateWeighting(/** @scrutinizer ignore-type */ $questionWeighting);
Loading history...
370
        $this->save($exercise);
371
    }
372
373
    /**
374
     * @param Exercise $exercise
375
     * @param null     $counter
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $counter is correct as it would always require null to be passed?
Loading history...
Documentation Bug introduced by
Are you sure the doc-type for parameter $score is correct as it would always require null to be passed?
Loading history...
376
     * @param null     $score
377
     *
378
     * @return string
379
     */
380
    public function return_header($exercise, $counter = null, $score = null)
381
    {
382
        if ($exercise->showExpectedChoice()) {
383
            $header = '<table class="'.$this->question_table_class.'">
384
			<tr>
385
				<th>'.get_lang('Choice').'</th>
386
				<th>'.get_lang('ExpectedChoice').'</th>
387
				<th>'.get_lang('Answer').'</th>';
388
            $header .= '<th>'.get_lang('Status').'</th>';
389
            $header .= '<th>'.get_lang('Comment').'</th>';
390
            $header .= '</tr>';
391
        } else {
392
            $header = parent::return_header($exercise, $counter, $score);
393
        }
394
395
        return $header;
396
    }
397
}
398