Completed
Push — master ( 76a038...0c6f8d )
by Julito
10:18
created

UniqueAnswerImage::createAnswersForm()   F

Complexity

Conditions 31
Paths > 20000

Size

Total Lines 305
Code Lines 174

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 31
eloc 174
nop 1
dl 0
loc 305
rs 0
c 0
b 0
f 0
nc 580608

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use ChamiloSession as Session;
6
7
/**
8
 * UniqueAnswerImage.
9
 *
10
 * @author Angel Fernando Quiroz Campos <[email protected]>
11
 */
12
class UniqueAnswerImage extends UniqueAnswer
13
{
14
    public $typePicture = 'uaimg.png';
15
    public $explanationLangVar = 'Unique answer image';
16
17
    /**
18
     * UniqueAnswerImage constructor.
19
     */
20
    public function __construct()
21
    {
22
        parent::__construct();
23
        $this->type = UNIQUE_ANSWER_IMAGE;
24
        $this->isContent = $this->getIsContent();
25
    }
26
27
    /**
28
     * @throws Exception
29
     */
30
    public function createAnswersForm($form)
31
    {
32
        $objExercise = Session::read('objExercise');
33
        $editorConfig = [
34
            'ToolbarSet' => 'TestProposedAnswer',
35
            'Width' => '100%',
36
            'Height' => '125',
37
        ];
38
39
        //this line defines how many questions by default appear when creating a choice question
40
        // The previous default value was 2. See task #1759.
41
        $numberAnswers = isset($_POST['nb_answers']) ? (int) $_POST['nb_answers'] : 4;
42
        $numberAnswers += (isset($_POST['lessAnswers']) ? -1 : (isset($_POST['moreAnswers']) ? 1 : 0));
43
44
        $feedbackTitle = '';
45
        switch ($objExercise->getFeedbackType()) {
46
            case EXERCISE_FEEDBACK_TYPE_DIRECT:
47
                // Scenario
48
                $commentTitle = '<th width="20%">'.get_lang('Comment').'</th>';
49
                $feedbackTitle = '<th width="20%">'.get_lang('Scenario').'</th>';
50
51
                break;
52
            case EXERCISE_FEEDBACK_TYPE_POPUP:
53
                $commentTitle = '<th width="20%">'.get_lang('Comment').'</th>';
54
55
                break;
56
            default:
57
                $commentTitle = '<th width="40%">'.get_lang('Comment').'</th>';
58
59
                break;
60
        }
61
62
        $html = '<div class="alert alert-success" role="alert">'.
63
                get_lang('UniqueAnswerImagePreferredSize200x150').'</div>';
64
65
        $zoomOptions = api_get_configuration_value('quiz_image_zoom');
66
        if (isset($zoomOptions['options'])) {
67
            $finderFolder = api_get_path(WEB_PATH).'vendor/studio-42/elfinder/';
68
            $html .= '<!-- elFinder CSS (REQUIRED) -->';
69
            $html .= '<link rel="stylesheet" type="text/css" media="screen"
70
                href="'.$finderFolder.'css/elfinder.full.css">';
71
            $html .= '<link rel="stylesheet" type="text/css" media="screen" href="'.$finderFolder.'css/theme.css">';
72
73
            $html .= '<!-- elFinder JS (REQUIRED) -->';
74
            $html .= '<script type="text/javascript" src="'.$finderFolder.'js/elfinder.full.js"></script>';
75
76
            $html .= '<!-- elFinder translation (OPTIONAL) -->';
77
            $language = 'en';
78
            $platformLanguage = api_get_interface_language();
79
            $iso = api_get_language_isocode($platformLanguage);
80
            $filePart = "vendor/studio-42/elfinder/js/i18n/elfinder.$iso.js";
81
            $file = api_get_path(SYS_PATH).$filePart;
82
            $includeFile = '';
83
            if (file_exists($file)) {
84
                $includeFile = '<script type="text/javascript" src="'.api_get_path(WEB_PATH).$filePart.'"></script>';
85
                $language = $iso;
86
            }
87
            $html .= $includeFile;
88
89
            $html .= '<script type="text/javascript" charset="utf-8">
90
            $(document).ready(function () {
91
                $(".add_img_link").on("click", function(e){
92
                    e.preventDefault();
93
                    e.stopPropagation();
94
95
                    var name = $(this).prop("name");
96
                    var id = parseInt(name.match(/[0-9]+/));
97
98
                    $([document.documentElement, document.body]).animate({
99
                        scrollTop: $("#elfinder").offset().top
100
                    }, 1000);
101
102
                    var elf = $("#elfinder").elfinder({
103
                        url : "'.api_get_path(WEB_LIBRARY_PATH).'elfinder/connectorAction.php?'.api_get_cidreq().'",
104
                        getFileCallback: function(file) {
105
                            var filePath = file; //file contains the relative url.
106
                            var imageZoom = filePath.url;
107
                            var iname = "answer["+id+"]";
108
109
                            CKEDITOR.instances[iname].insertHtml(\'
110
                                <img
111
                                    id="zoom_picture"
112
                                    class="zoom_picture"
113
                                    src="\'+imageZoom+\'"
114
                                    data-zoom-image="\'+imageZoom+\'"
115
                                    width="200px"
116
                                    height="150px"
117
                                />\');
118
119
                            $("#elfinder").elfinder("destroy"); //close the window after image is selected
120
                        },
121
                        startPathHash: "l2_Lw", // Sets the course driver as default
122
                        resizable: false,
123
                        lang: "'.$language.'"
124
                    }).elfinder("instance"+id);
125
                });
126
            });
127
            </script>';
128
            $html .= '<div id="elfinder"></div>';
129
        }
130
131
        $html .= '<table class="table table-striped table-hover">
132
            <thead>
133
                <tr style="text-align: center;">
134
                    <th width="10">'.get_lang('N°').'</th>
135
                    <th>'.get_lang('True').'</th>
136
                    <th>'.get_lang('Answer').'</th>
137
                        '.$commentTitle.'
138
                        '.$feedbackTitle.'
139
                    <th width="15">'.get_lang('Score').'</th>
140
                </tr>
141
            </thead>
142
            <tbody>';
143
144
        $form->addHeader(get_lang('Answers'));
145
        $form->addHtml($html);
146
147
        $defaults = [];
148
        $correct = 0;
149
150
        if (!empty($this->id)) {
151
            $answer = new Answer($this->id);
152
            $answer->read();
153
154
            if ($answer->nbrAnswers > 0 && !$form->isSubmitted()) {
155
                $numberAnswers = $answer->nbrAnswers;
156
            }
157
        }
158
159
        $form->addElement('hidden', 'nb_answers');
160
161
        //Feedback SELECT
162
        $questionList = $objExercise->selectQuestionList();
163
        $selectQuestion = [];
164
        $selectQuestion[0] = get_lang('Select target question');
165
166
        if (is_array($questionList)) {
167
            foreach ($questionList as $key => $questionid) {
168
                //To avoid warning messages
169
                if (!is_numeric($questionid)) {
170
                    continue;
171
                }
172
173
                $question = Question::read($questionid);
174
                $questionTitle = strip_tags($question->selectTitle());
175
                $selectQuestion[$questionid] = "Q$key: $questionTitle";
176
            }
177
        }
178
179
        $selectQuestion[-1] = get_lang('Exit test');
180
181
        $list = new LearnpathList(api_get_user_id());
182
        $flatList = $list->get_flat_list();
183
        $selectLpId = [];
184
        $selectLpId[0] = get_lang('Select target course');
185
186
        foreach ($flatList as $id => $details) {
187
            $selectLpId[$id] = cut($details['lp_name'], 20);
188
        }
189
190
        $tempScenario = [];
191
        if ($numberAnswers < 1) {
192
            $numberAnswers = 1;
193
            echo Display::return_message(get_lang('You have to create at least one answer'));
194
        }
195
196
        for ($i = 1; $i <= $numberAnswers; $i++) {
197
            $form->addHtml('<tr>');
198
            if (isset($answer) && is_object($answer)) {
199
                if ($answer->correct[$i]) {
200
                    $correct = $i;
201
                }
202
203
                $defaults['answer['.$i.']'] = $answer->answer[$i];
204
                $defaults['comment['.$i.']'] = $answer->comment[$i];
205
                $defaults['weighting['.$i.']'] = float_format(
206
                    $answer->weighting[$i],
207
                    1
208
                );
209
210
                $itemList = explode('@@', $answer->destination[$i]);
211
212
                $try = $itemList[0];
213
                $lp = $itemList[1];
214
                $listDestination = $itemList[2];
215
                $url = $itemList[3];
216
217
                $tryResult = 0;
218
                if (0 != $try) {
219
                    $tryResult = 1;
220
                }
221
222
                $urlResult = '';
223
                if (0 != $url) {
224
                    $urlResult = $url;
225
                }
226
227
                $tempScenario['url'.$i] = $urlResult;
228
                $tempScenario['try'.$i] = $tryResult;
229
                $tempScenario['lp'.$i] = $lp;
230
                $tempScenario['destination'.$i] = $listDestination;
231
            } else {
232
                $defaults['answer[1]'] = get_lang('A then B then C');
233
                $defaults['weighting[1]'] = 10;
234
                $defaults['answer[2]'] = get_lang('A then C then B');
235
                $defaults['weighting[2]'] = 0;
236
237
                $tempScenario['destination'.$i] = ['0'];
238
                $tempScenario['lp'.$i] = ['0'];
239
            }
240
241
            $defaults['scenario'] = $tempScenario;
242
            $renderer = $form->defaultRenderer();
243
            $renderer->setElementTemplate(
244
                '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
245
                'correct'
246
            );
247
            $renderer->setElementTemplate(
248
                '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
249
                'counter['.$i.']'
250
            );
251
            $renderer->setElementTemplate(
252
                '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}'.
253
                    (isset($zoomOptions['options']) ?
254
                    '<br><div class="form-group ">
255
                        <label for="question_admin_form_btn_add_img['.$i.']" class="col-sm-2 control-label"></label>
256
                        <div class="col-sm-8">
257
                            <button class="add_img_link btn btn-info btn-sm"
258
                                name="btn_add_img['.$i.']"
259
                                type="submit"
260
                                id="question_admin_form_btn_add_img['.$i.']">
261
                                <em class="fa fa-plus"></em> '.get_lang('AddImageWithZoom').'
262
                            </button>
263
                        </div>
264
                        <div class="col-sm-2"></div>
265
                    </div>' : '').'</td>',
266
                'answer['.$i.']'
267
            );
268
            $renderer->setElementTemplate(
269
                '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
270
                'comment['.$i.']'
271
            );
272
            $renderer->setElementTemplate(
273
                '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
274
                'weighting['.$i.']'
275
            );
276
277
            $answerNumber = $form->addElement('text', 'counter['.$i.']', null, ' value = "'.$i.'"');
278
            $answerNumber->freeze();
279
280
            $form->addElement('radio', 'correct', null, null, $i, 'class="checkbox"');
281
            $form->addHtmlEditor('answer['.$i.']', null, null, false, $editorConfig);
282
283
            $form->addRule('answer['.$i.']', get_lang('Required field'), 'required');
284
285
            switch ($objExercise->getFeedbackType()) {
286
                case EXERCISE_FEEDBACK_TYPE_DIRECT:
287
                    $this->setDirectOptions($i, $form, $renderer, $selectLpId, $selectQuestion);
288
289
                    break;
290
                case EXERCISE_FEEDBACK_TYPE_POPUP:
291
                default:
292
                    $form->addHtmlEditor('comment['.$i.']', null, null, false, $editorConfig);
293
294
                    break;
295
            }
296
297
            $form->addText('weighting['.$i.']', null, null, ['class' => 'col-md-1', 'value' => '0']);
298
            $form->addHtml('</tr>');
299
        }
300
301
        $form->addHtml('</tbody>');
302
        $form->addHtml('</table>');
303
304
        global $text;
305
        $buttonGroup = [];
306
        if (true == $objExercise->edit_exercise_in_lp ||
307
            (empty($this->exerciseList) && empty($objExercise->id))
308
        ) {
309
            //setting the save button here and not in the question class.php
310
            $buttonGroup[] = $form->addButtonDelete(get_lang('Remove answer option'), 'lessAnswers', true);
311
            $buttonGroup[] = $form->addButtonCreate(get_lang('Add answer option'), 'moreAnswers', true);
312
            $buttonGroup[] = $form->addButtonSave($text, 'submitQuestion', true);
313
            $form->addGroup($buttonGroup);
314
        }
315
316
        // We check the first radio button to be sure a radio button will be check
317
        if (0 == $correct) {
318
            $correct = 1;
319
        }
320
321
        $defaults['correct'] = $correct;
322
323
        if (!empty($this->id)) {
324
            $form->setDefaults($defaults);
325
        } else {
326
            if (1 == $this->isContent) {
327
                // Default sample content.
328
                $form->setDefaults($defaults);
329
            } else {
330
                $form->setDefaults(['correct' => 1]);
331
            }
332
        }
333
334
        $form->setConstants(['nb_answers' => $numberAnswers]);
335
    }
336
337
    public function processAnswersCreation($form, $exercise)
338
    {
339
        $questionWeighting = $nbrGoodAnswers = 0;
340
        $correct = $form->getSubmitValue('correct');
341
        $objAnswer = new Answer($this->id);
342
        $numberAnswers = $form->getSubmitValue('nb_answers');
343
344
        for ($i = 1; $i <= $numberAnswers; $i++) {
345
            $answer = trim(str_replace(['<p>', '</p>'], '', $form->getSubmitValue('answer['.$i.']')));
346
            $comment = trim(str_replace(['<p>', '</p>'], '', $form->getSubmitValue('comment['.$i.']')));
347
            $weighting = trim($form->getSubmitValue('weighting['.$i.']'));
348
349
            $scenario = $form->getSubmitValue('scenario');
350
351
            //$listDestination = $form -> getSubmitValue('destination'.$i);
352
            //$destinationStr = $form -> getSubmitValue('destination'.$i);
353
354
            $try = $scenario['try'.$i];
355
            $lp = $scenario['lp'.$i];
356
            $destination = $scenario['destination'.$i];
357
            $url = trim($scenario['url'.$i]);
358
359
            /*
360
              How we are going to parse the destination value
361
362
              here we parse the destination value which is a string
363
              1@@3@@2;4;4;@@http://www.chamilo.org
364
365
              where: try_again@@lp_id@@selected_questions@@url
366
367
              try_again = is 1 || 0
368
              lp_id = id of a learning path (0 if dont select)
369
              selected_questions= ids of questions
370
              url= an url
371
372
              $destinationStr='';
373
              foreach ($listDestination as $destination_id)
374
              {
375
              $destinationStr.=$destination_id.';';
376
              } */
377
            $goodAnswer = $correct == $i ? true : false;
378
            if ($goodAnswer) {
379
                $nbrGoodAnswers++;
380
                $weighting = abs($weighting);
381
382
                if ($weighting > 0) {
383
                    $questionWeighting += $weighting;
384
                }
385
            }
386
387
            if (empty($try)) {
388
                $try = 0;
389
            }
390
391
            if (empty($lp)) {
392
                $lp = 0;
393
            }
394
395
            if (empty($destination)) {
396
                $destination = 0;
397
            }
398
399
            if ('' == $url) {
400
                $url = 0;
401
            }
402
403
            //1@@1;2;@@2;4;4;@@http://www.chamilo.org
404
            $dest = $try.'@@'.$lp.'@@'.$destination.'@@'.$url;
405
406
            $objAnswer->createAnswer(
407
                $answer,
408
                $goodAnswer,
409
                $comment,
410
                $weighting,
411
                $i,
412
                null,
413
                null,
414
                $dest
415
            );
416
        }
417
418
        // saves the answers into the data base
419
        $objAnswer->save();
420
421
        // sets the total weighting of the question
422
        $this->updateWeighting($questionWeighting);
423
        $this->save($exercise);
424
    }
425
426
    public function return_header(Exercise $exercise, $counter = null, $score = [])
427
    {
428
        if ($exercise->showExpectedChoice()) {
429
            $header = '<table class="'.$this->question_table_class.'">
430
			<tr>
431
				<th>'.get_lang('Your choice').'</th>';
432
            if ($exercise->showExpectedChoiceColumn()) {
433
                $header .= '<th>'.get_lang('ExpectedYour choice').'</th>';
434
            }
435
            $header .= '<th>'.get_lang('Answer').'</th>';
436
            $header .= '<th>'.get_lang('Status').'</th>';
437
            $header .= '<th>'.get_lang('Comment').'</th>';
438
            $header .= '</tr>';
439
        } else {
440
            $header = parent::return_header($exercise, $counter, $score);
441
        }
442
443
        return $header;
444
    }
445
}
446