Passed
Push — 1.11.x ( 1872f9...79fe49 )
by Julito
10:19
created

survey_question::setForm()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use ChamiloSession as Session;
5
6
/**
7
 * Class survey_question.
8
 */
9
class survey_question
10
{
11
    public $buttonList = [];
12
    /** @var FormValidator */
13
    private $form;
14
15
    /**
16
     * @param array $surveyData
17
     */
18
    public function addParentMenu(FormValidator $form, $surveyData)
19
    {
20
        $surveyId = $surveyData['survey_id'];
21
        $questions = SurveyManager::get_questions($surveyId);
22
23
        $options = [];
24
        foreach ($questions as $question) {
25
            $options[$question['question_id']] = strip_tags($question['question']);
26
        }
27
        $form->addSelect(
28
            'parent_id',
29
            get_lang('Parent'),
30
            $options,
31
            ['id' => 'parent_id', 'placeholder' => get_lang('SelectAnOption')]
32
        );
33
        $url = api_get_path(WEB_AJAX_PATH).'survey.ajax.php?'.api_get_cidreq();
34
        $form->addHtml('
35
            <script>
36
                $(function() {
37
                    $("#parent_id").on("change", function() {
38
                        var questionId = $(this).val()
39
                        var params = {
40
                            "a": "load_question_options",
41
                            "survey_id": "'.$surveyId.'",
42
                            "question_id": questionId,
43
                        };
44
                        $.ajax({
45
                            type: "GET",
46
                            url: "'.$url.'",
47
                            data: params,
48
                            async: false,
49
                            success: function(data) {
50
                                $("#parent_options").html(data);
51
                            }
52
                        });
53
                    });
54
                });
55
            </script>
56
        ');
57
        $form->addHtml('<div id="parent_options"></div>');
58
        $form->addHidden('option_id', 0);
59
    }
60
61
    /**
62
     * @param string $type
63
     *
64
     * @return survey_question
65
     */
66
    public static function createQuestion($type)
67
    {
68
        switch ($type) {
69
            case 'comment':
70
                return new ch_comment();
71
            case 'dropdown':
72
                return new ch_dropdown();
73
            case 'multiplechoice':
74
                return new ch_multiplechoice();
75
            case 'multipleresponse':
76
                return new ch_multipleresponse();
77
            case 'open':
78
                return new ch_open();
79
            case 'pagebreak':
80
                return new ch_pagebreak();
81
            case 'percentage':
82
                return new ch_percentage();
83
            case 'personality':
84
                return new ch_personality();
85
            case 'score':
86
                return new ch_score();
87
            case 'yesno':
88
                return new ch_yesno();
89
            case 'selectivedisplay':
90
                return new ch_selectivedisplay();
91
            default:
92
                api_not_allowed(true);
93
                break;
94
        }
95
    }
96
97
    /**
98
     * Generic part of any survey question: the question field.
99
     *
100
     * @param array $surveyData
101
     * @param array $formData
102
     *
103
     * @return FormValidator
104
     */
105
    public function createForm($surveyData, $formData)
106
    {
107
        $action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : null;
108
        $questionId = isset($_GET['question_id']) ? (int) $_GET['question_id'] : null;
109
        $surveyId = isset($_GET['survey_id']) ? (int) $_GET['survey_id'] : null;
110
        $type = isset($_GET['type']) ? Security::remove_XSS($_GET['type']) : null;
111
112
        $actionHeader = get_lang('EditQuestion').': ';
113
        if ($action === 'add') {
114
            $actionHeader = get_lang('AddQuestion').': ';
115
        }
116
117
        $questionComment = '';
118
        switch ($type) {
119
            case 'open':
120
                $toolName = get_lang('Open');
121
                $questionComment = get_lang('QuestionTags');
122
                break;
123
            case 'yesno':
124
                $toolName = get_lang('YesNo');
125
                break;
126
            case 'multiplechoice':
127
                $toolName = get_lang('UniqueSelect');
128
                break;
129
            case 'multipleresponse':
130
                $toolName = get_lang('MultipleResponse');
131
                break;
132
            case 'selectivedisplay':
133
                $toolName = get_lang('SurveyQuestionSelectiveDisplay');
134
                $questionComment = get_lang('SurveyQuestionSelectiveDisplayComment');
135
                break;
136
            default:
137
                $toolName = get_lang(api_ucfirst($type));
138
        }
139
140
        $icon = Display::return_icon(
141
                SurveyManager::icon_question($type),
142
                $toolName,
143
                ['align' => 'middle', 'height' => '22px']
144
            ).' ';
145
146
        $toolName = $icon.$actionHeader.$toolName;
147
        $sharedQuestionId = isset($formData['shared_question_id']) ? $formData['shared_question_id'] : null;
148
149
        $url = api_get_self().'?action='.$action.'&type='.$type.'&survey_id='.$surveyId.'&question_id='.$questionId.'&'.api_get_cidreq();
150
        $form = new FormValidator('question_form', 'post', $url);
151
        $form->addHeader($toolName);
152
        if (!empty($questionComment)) {
153
            $form->addHtml(Display::return_message($questionComment, 'info', false));
154
        }
155
        $form->addHidden('survey_id', $surveyId);
156
        $form->addHidden('question_id', $questionId);
157
        $form->addHidden('shared_question_id', Security::remove_XSS($sharedQuestionId));
158
        $form->addHidden('type', $type);
159
160
        $config = [
161
            'ToolbarSet' => 'SurveyQuestion',
162
            'Width' => '100%',
163
            'Height' => '120',
164
        ];
165
        $form->addHtmlEditor(
166
            'question',
167
            get_lang('Question'),
168
            true,
169
            false,
170
            $config
171
        );
172
173
        if (api_get_configuration_value('allow_required_survey_questions') &&
174
            in_array($_GET['type'], ['yesno', 'multiplechoice'])) {
175
            $form->addCheckBox('is_required', get_lang('IsMandatory'), get_lang('Yes'));
176
        }
177
178
        if ($surveyData['survey_type'] == 1) {
179
            $table_survey_question_group = Database::get_course_table(TABLE_SURVEY_QUESTION_GROUP);
180
            $sql = 'SELECT id, name FROM '.$table_survey_question_group.'
181
                    WHERE survey_id = '.$surveyId.'
182
                    ORDER BY name';
183
            $rs = Database::query($sql);
184
            $glist = null;
185
            while ($row = Database::fetch_array($rs, 'NUM')) {
186
                $glist .= '<option value="'.$row[0].'" >'.$row[1].'</option>';
187
            }
188
189
            $grouplist = $grouplist1 = $grouplist2 = $glist;
190
            if (!empty($formData['assigned'])) {
191
                $grouplist = str_replace(
192
                    '<option value="'.$formData['assigned'].'"',
193
                    '<option value="'.$formData['assigned'].'" selected',
194
                    $glist
195
                );
196
            }
197
198
            if (!empty($formData['assigned1'])) {
199
                $grouplist1 = str_replace(
200
                    '<option value="'.$formData['assigned1'].'"',
201
                    '<option value="'.$formData['assigned1'].'" selected',
202
                    $glist
203
                );
204
            }
205
206
            if (!empty($formData['assigned2'])) {
207
                $grouplist2 = str_replace(
208
                    '<option value="'.$formData['assigned2'].'"',
209
                    '<option value="'.$formData['assigned2'].'" selected',
210
                    $glist
211
                );
212
            }
213
214
            $this->html .= '<tr><td colspan="">
0 ignored issues
show
Bug Best Practice introduced by
The property html does not exist on survey_question. Did you maybe forget to declare it?
Loading history...
215
			<fieldset style="border:1px solid black">
216
			    <legend>'.get_lang('Condition').'</legend>
217
			    <b>'.get_lang('Primary').'</b><br />
218
			    <input type="radio" name="choose" value="1" '.(($formData['choose'] == 1) ? 'checked' : '').'>
219
			    <select name="assigned">'.$grouplist.'</select><br />';
220
            $this->html .= '
221
			<b>'.get_lang('Secondary').'</b><br />
222
			    <input type="radio" name="choose" value="2" '.(($formData['choose'] == 2) ? 'checked' : '').'>
223
			    <select name="assigned1">'.$grouplist1.'</select>
224
                <select name="assigned2">'.$grouplist2.'</select>
225
            </fieldset><br />';
226
        }
227
228
        $this->setForm($form);
229
230
        return $form;
231
    }
232
233
    /**
234
     * Adds submit button.
235
     */
236
    public function renderForm()
237
    {
238
        if (isset($_GET['question_id']) && !empty($_GET['question_id'])) {
239
            /**
240
             * Check if survey has answers first before update it, this is because if you update it, the question
241
             * options will delete and re-insert in database loosing the iid and question_id to verify the correct answers.
242
             */
243
            $surveyId = isset($_GET['survey_id']) ? (int) $_GET['survey_id'] : 0;
244
            $answersChecker = SurveyUtil::checkIfSurveyHasAnswers($surveyId);
245
            if (!$answersChecker) {
246
                $this->buttonList[] = $this->getForm()->addButtonUpdate(get_lang('ModifyQuestionSurvey'), 'save', true);
247
            } else {
248
                $this->getForm()->addHtml('
249
                    <div class="form-group">
250
                        <label class="col-sm-2 control-label"></label>
251
                        <div class="col-sm-8">
252
                            <div class="alert alert-info">'.
253
                            get_lang('YouCantNotEditThisQuestionBecauseAlreadyExistAnswers').'</div>
254
                        </div>
255
                        <div class="col-sm-2"></div>
256
                    </div>
257
                ');
258
            }
259
        } else {
260
            $this->buttonList[] = $this->getForm()->addButtonSave(get_lang('CreateQuestionSurvey'), 'save', true);
261
        }
262
263
        $this->getForm()->addGroup($this->buttonList, 'buttons');
264
    }
265
266
    /**
267
     * @return FormValidator
268
     */
269
    public function getForm()
270
    {
271
        return $this->form;
272
    }
273
274
    /**
275
     * @param FormValidator $form
276
     */
277
    public function setForm($form)
278
    {
279
        $this->form = $form;
280
    }
281
282
    /**
283
     * @param array $formData
284
     *
285
     * @return mixed
286
     */
287
    public function preSave($formData)
288
    {
289
        $counter = Session::read('answer_count');
290
        $answerList = Session::read('answer_list');
291
292
        if (empty($answerList)) {
293
            $answerList = isset($formData['answers']) ? $formData['answers'] : [];
294
            Session::write('answer_list', $answerList);
295
        }
296
297
        if (isset($_POST['answers'])) {
298
            $formData['answers'] = $_POST['answers'];
299
        }
300
301
        if (empty($counter)) {
302
            $counter = count($answerList) - 1;
303
            Session::write('answer_count', $counter);
304
        }
305
306
        // Moving an answer up
307
        if (isset($_POST['move_up']) && $_POST['move_up']) {
308
            foreach ($_POST['move_up'] as $key => &$value) {
309
                $id1 = $key;
310
                $content1 = $formData['answers'][$id1];
311
                $id2 = $key - 1;
312
                $content2 = $formData['answers'][$id2];
313
                $formData['answers'][$id1] = $content2;
314
                $formData['answers'][$id2] = $content1;
315
            }
316
        }
317
318
        // Moving an answer down
319
        if (isset($_POST['move_down']) && $_POST['move_down']) {
320
            foreach ($_POST['move_down'] as $key => &$value) {
321
                $id1 = $key;
322
                $content1 = $formData['answers'][$id1];
323
                $id2 = $key + 1;
324
                $content2 = $formData['answers'][$id2];
325
                $formData['answers'][$id1] = $content2;
326
                $formData['answers'][$id2] = $content1;
327
            }
328
        }
329
330
        /**
331
         * Deleting a specific answer is only saved in the session until the
332
         * "Save question" button is pressed. This means all options are kept
333
         * in the survey_question_option table until the question is saved.
334
         */
335
        if (isset($_POST['delete_answer'])) {
336
            $deleted = false;
337
            foreach ($_POST['delete_answer'] as $key => &$value) {
338
                $deleted = $key;
339
                $counter--;
340
                Session::write('answer_count', $counter);
341
            }
342
343
            $newAnswers = [];
344
            $newAnswersId = [];
345
            foreach ($formData['answers'] as $key => &$value) {
346
                if ($key > $deleted) {
347
                    // swap with previous (deleted) option slot
348
                    $newAnswers[$key - 1] = $formData['answers'][$key];
349
                    $newAnswersId[$key - 1] = $formData['answersid'][$key];
350
                    unset($formData['answers'][$key]);
351
                    unset($formData['answersid'][$key]);
352
                } elseif ($key === $deleted) {
353
                    // delete option
354
                    unset($formData['answers'][$deleted]);
355
                    unset($formData['answersid'][$deleted]);
356
                } else {
357
                    // keep as is
358
                    $newAnswers[$key] = $value;
359
                    $newAnswersId[$key] = $formData['answersid'][$key];
360
                }
361
            }
362
            unset($formData['answers']);
363
            unset($formData['answersid']);
364
            $formData['answers'] = $newAnswers;
365
            $formData['answersid'] = $newAnswersId;
366
        }
367
368
        // Adding an answer
369
        if (isset($_POST['buttons']) && isset($_POST['buttons']['add_answer'])) {
370
            $counter++;
371
            Session::write('answer_count', $counter);
372
        }
373
374
        // Removing an answer
375
        if (isset($_POST['buttons']) && isset($_POST['buttons']['remove_answer'])) {
376
            $counter--;
377
            Session::write('answer_count', $counter);
378
            foreach ($formData['answers'] as $index => &$data) {
379
                if ($index > $counter) {
380
                    unset($formData['answers'][$index]);
381
                    unset($formData['answersid'][$index]);
382
                }
383
            }
384
        }
385
386
        if (!isset($_POST['delete_answer'])) {
387
            // Make sure we have an array of answers
388
            if (!isset($formData['answers'])) {
389
                $formData['answers'] = [];
390
            }
391
            // Check if no deleted answer remains at the end of the answers
392
            // array and add empty answers if the array is too short
393
            foreach ($formData['answers'] as $index => $data) {
394
                if ($index > $counter) {
395
                    unset($formData['answers'][$index]);
396
                }
397
            }
398
399
            for ($i = 0; $i <= $counter; $i++) {
400
                if (!isset($formData['answers'][$i])) {
401
                    $formData['answers'][$i] = '';
402
                }
403
            }
404
        }
405
406
        $formData['answers'] = isset($formData['answers']) ? $formData['answers'] : [];
407
        Session::write('answer_list', $formData['answers']);
408
409
        if (!isset($formData['is_required']) && api_get_configuration_value('survey_mark_question_as_required')) {
410
            $formData['is_required'] = true;
411
        }
412
413
        return $formData;
414
    }
415
416
    /**
417
     * @param array $surveyData
418
     * @param array $formData
419
     *
420
     * @return mixed
421
     */
422
    public function save($surveyData, $formData, $dataFromDatabase = [])
423
    {
424
        // Saving a question
425
        if (isset($_POST['buttons']) && isset($_POST['buttons']['save'])) {
426
            Session::erase('answer_count');
427
            Session::erase('answer_list');
428
            $message = SurveyManager::save_question($surveyData, $formData, true, $dataFromDatabase);
429
430
            if ($message === 'QuestionAdded' || $message === 'QuestionUpdated') {
431
                header('Location: '.api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.intval($_GET['survey_id']).'&message='.$message.'&'.api_get_cidreq());
432
                exit;
433
            }
434
        }
435
436
        return $formData;
437
    }
438
439
    /**
440
     * Adds two buttons. One to add an option, one to remove an option.
441
     *
442
     * @param array $data
443
     */
444
    public function addRemoveButtons($data)
445
    {
446
        $this->buttonList['remove_answer'] = $this->getForm()->createElement(
447
            'button',
448
            'remove_answer',
449
            get_lang('RemoveAnswer'),
450
            'minus',
451
            'default'
452
        );
453
454
        if (count($data['answers']) <= 2) {
455
            $this->buttonList['remove_answer']->updateAttributes(
456
                ['disabled' => 'disabled']
457
            );
458
        }
459
460
        $this->buttonList['add_answer'] = $this->getForm()->createElement(
461
            'button',
462
            'add_answer',
463
            get_lang('AddAnswer'),
464
            'plus',
465
            'default'
466
        );
467
    }
468
469
    /**
470
     * @param array $questionData
471
     * @param array $answers
472
     */
473
    public function render(FormValidator $form, $questionData = [], $answers = [])
0 ignored issues
show
Unused Code introduced by
The parameter $questionData is not used and could be removed. ( Ignorable by Annotation )

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

473
    public function render(FormValidator $form, /** @scrutinizer ignore-unused */ $questionData = [], $answers = [])

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $answers is not used and could be removed. ( Ignorable by Annotation )

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

473
    public function render(FormValidator $form, $questionData = [], /** @scrutinizer ignore-unused */ $answers = [])

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
474
    {
475
        return null;
476
    }
477
}
478