UniqueAnswerImage::createAnswersForm()   F
last analyzed

Complexity

Conditions 34
Paths > 20000

Size

Total Lines 303
Code Lines 176

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 34
eloc 176
nc 2073600
nop 1
dl 0
loc 303
rs 0
c 0
b 0
f 0

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