Passed
Push — master ( 346325...dc78e4 )
by
unknown
23:25 queued 14:41
created

Question::loadAdaptiveScenarioDefaults()   C

Complexity

Conditions 12
Paths 22

Size

Total Lines 59
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 34
nc 22
nop 2
dl 0
loc 59
rs 6.9666
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 Chamilo\CoreBundle\Framework\Container;
6
use Chamilo\CourseBundle\Entity\CQuizAnswer;
7
use Chamilo\CourseBundle\Entity\CQuizQuestion;
8
use Chamilo\CourseBundle\Entity\CQuizQuestionOption;
9
10
/**
11
 * Class Question.
12
 *
13
 * This class allows to instantiate an object of type Question
14
 *
15
 * @author Olivier Brouckaert, original author
16
 * @author Patrick Cool, LaTeX support
17
 * @author Julio Montoya <[email protected]> lot of bug fixes
18
 * @author [email protected] - add question categories
19
 */
20
abstract class Question
21
{
22
    public $id;
23
    public $iid;
24
    public $question;
25
    public $description;
26
    public $weighting;
27
    public $position;
28
    public $type;
29
    public $level;
30
    public $picture;
31
    public $exerciseList; // array with the list of exercises which this question is in
32
    public $category_list;
33
    public $parent_id;
34
    public $category;
35
    public $mandatory;
36
    public $isContent;
37
    public $course;
38
    public $feedback;
39
    public $typePicture = 'new_question.png';
40
    public $explanationLangVar = '';
41
    public $questionTableClass = 'table table-striped question-answer-result__detail';
42
    public $questionTypeWithFeedback;
43
    public $extra;
44
    public $export = false;
45
    public $code;
46
    public static $questionTypes = [
47
        // — Single-choice
48
        UNIQUE_ANSWER                => ['unique_answer.class.php', 'UniqueAnswer', 'Unique answer'],
49
        UNIQUE_ANSWER_IMAGE          => ['UniqueAnswerImage.php', 'UniqueAnswerImage', 'Unique answer (image)'],
50
        UNIQUE_ANSWER_NO_OPTION      => ['unique_answer_no_option.class.php', 'UniqueAnswerNoOption', 'Unique answer (no options)'],
51
52
        // — Multiple-choice (all variants together)
53
        MULTIPLE_ANSWER              => ['multiple_answer.class.php', 'MultipleAnswer', 'Multiple answer'],
54
        GLOBAL_MULTIPLE_ANSWER       => ['global_multiple_answer.class.php', 'GlobalMultipleAnswer', 'Global multiple answer'],
55
        MULTIPLE_ANSWER_DROPDOWN     => ['MultipleAnswerDropdown.php', 'MultipleAnswerDropdown', 'Multiple answer (dropdown)'],
56
        MULTIPLE_ANSWER_DROPDOWN_COMBINATION => ['MultipleAnswerDropdownCombination.php', 'MultipleAnswerDropdownCombination', 'Multiple answer (dropdown combination)'],
57
        MULTIPLE_ANSWER_COMBINATION  => ['multiple_answer_combination.class.php', 'MultipleAnswerCombination', 'Multiple answer (combination)'],
58
        MULTIPLE_ANSWER_TRUE_FALSE   => ['multiple_answer_true_false.class.php', 'MultipleAnswerTrueFalse', 'True/False multiple answer'],
59
        MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE => [
60
            'multiple_answer_combination_true_false.class.php', 'MultipleAnswerCombinationTrueFalse', 'True/False combination multiple answer'
61
        ],
62
        MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY => [
63
            'MultipleAnswerTrueFalseDegreeCertainty.php', 'MultipleAnswerTrueFalseDegreeCertainty', 'True/False with degree of certainty'
64
        ],
65
66
        // — Matching / draggable
67
        MATCHING                     => ['matching.class.php', 'Matching', 'Matching'],
68
        MATCHING_COMBINATION         => ['MatchingCombination.php', 'MatchingCombination', 'Matching (combination)'],
69
        DRAGGABLE                    => ['Draggable.php', 'Draggable', 'Draggable'],
70
        MATCHING_DRAGGABLE           => ['MatchingDraggable.php', 'MatchingDraggable', 'Matching (draggable)'],
71
        MATCHING_DRAGGABLE_COMBINATION => ['MatchingDraggableCombination.php', 'MatchingDraggableCombination', 'Matching (draggable combination)'],
72
73
        // — Fill-in-the-blanks / calculated
74
        FILL_IN_BLANKS               => ['fill_blanks.class.php', 'FillBlanks', 'Fill in the blanks'],
75
        FILL_IN_BLANKS_COMBINATION   => ['FillBlanksCombination.php', 'FillBlanksCombination', 'Fill in the blanks (combination)'],
76
        CALCULATED_ANSWER            => ['calculated_answer.class.php', 'CalculatedAnswer', 'Calculated answer'],
77
78
        // — Open answers / expression
79
        FREE_ANSWER                  => ['freeanswer.class.php', 'FreeAnswer', 'Free answer'],
80
        ORAL_EXPRESSION              => ['oral_expression.class.php', 'OralExpression', 'Oral expression'],
81
82
        // — Hotspot
83
        HOT_SPOT                     => ['hotspot.class.php', 'HotSpot', 'Hotspot'],
84
        HOT_SPOT_COMBINATION         => ['HotSpotCombination.php', 'HotSpotCombination', 'Hotspot (combination)'],
85
        HOT_SPOT_DELINEATION         => ['HotSpotDelineation.php', 'HotSpotDelineation', 'Hotspot delineation'],
86
87
        // — Media / annotation
88
        MEDIA_QUESTION               => ['MediaQuestion.php', 'MediaQuestion', 'Media question'],
89
        ANNOTATION                   => ['Annotation.php', 'Annotation', 'Annotation'],
90
91
        // — Special
92
        READING_COMPREHENSION        => ['ReadingComprehension.php', 'ReadingComprehension', 'Reading comprehension'],
93
        PAGE_BREAK                   => ['PageBreakQuestion.php', 'PageBreakQuestion', 'Page break'],
94
        UPLOAD_ANSWER                => ['UploadAnswer.php', 'UploadAnswer', 'Upload answer'],
95
    ];
96
97
    /**
98
     * Question types that support adaptive scenario.
99
     */
100
    protected static $adaptiveScenarioTypes = [
101
        UNIQUE_ANSWER,
102
        MULTIPLE_ANSWER,
103
        MULTIPLE_ANSWER_COMBINATION,
104
        MULTIPLE_ANSWER_TRUE_FALSE,
105
        MATCHING,
106
        MATCHING_COMBINATION,
107
        DRAGGABLE,
108
        MATCHING_DRAGGABLE,
109
        MATCHING_DRAGGABLE_COMBINATION,
110
        HOT_SPOT_DELINEATION,
111
        FILL_IN_BLANKS,
112
        FILL_IN_BLANKS_COMBINATION,
113
        CALCULATED_ANSWER,
114
        ANNOTATION,
115
        // Do NOT include FREE_ANSWER, ORAL_EXPRESSION, UPLOAD_ANSWER, MEDIA_QUESTION, PAGE_BREAK, etc.
116
    ];
117
118
    /**
119
     * constructor of the class.
120
     *
121
     * @author Olivier Brouckaert
122
     */
123
    public function __construct()
124
    {
125
        $this->id = 0;
126
        $this->iid = 0;
127
        $this->question = '';
128
        $this->description = '';
129
        $this->weighting = 0;
130
        $this->position = 1;
131
        $this->picture = '';
132
        $this->level = 1;
133
        $this->category = 0;
134
        // This variable is used when loading an exercise like an scenario with
135
        // an special hotspot: final_overlap, final_missing, final_excess
136
        $this->extra = '';
137
        $this->exerciseList = [];
138
        $this->course = api_get_course_info();
139
        $this->category_list = [];
140
        $this->parent_id = 0;
141
        $this->mandatory = 0;
142
        // See BT#12611
143
        $this->questionTypeWithFeedback = [
144
            MATCHING,
145
            MATCHING_COMBINATION,
146
            MATCHING_DRAGGABLE,
147
            MATCHING_DRAGGABLE_COMBINATION,
148
            DRAGGABLE,
149
            FILL_IN_BLANKS,
150
            FILL_IN_BLANKS_COMBINATION,
151
            FREE_ANSWER,
152
            UPLOAD_ANSWER,
153
            ORAL_EXPRESSION,
154
            CALCULATED_ANSWER,
155
            ANNOTATION,
156
        ];
157
    }
158
159
    public function getId()
160
    {
161
        return $this->iid;
162
    }
163
164
    /**
165
     * @return int|null
166
     */
167
    public function getIsContent()
168
    {
169
        $isContent = null;
170
        if (isset($_REQUEST['isContent'])) {
171
            $isContent = (int) $_REQUEST['isContent'];
172
        }
173
174
        return $this->isContent = $isContent;
175
    }
176
177
    /**
178
     * Reads question information from the data base.
179
     *
180
     * @param int   $id              - question ID
181
     * @param array $course_info
182
     * @param bool  $getExerciseList
183
     *
184
     * @return Question
185
     *
186
     * @author Olivier Brouckaert
187
     */
188
    public static function read($id, $course_info = [], $getExerciseList = true)
189
    {
190
        $id = (int) $id;
191
        if (empty($course_info)) {
192
            $course_info = api_get_course_info();
193
        }
194
        $course_id = $course_info['real_id'];
195
196
        if (empty($course_id) || -1 == $course_id) {
197
            return false;
198
        }
199
200
        $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
201
        $TBL_EXERCISE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
202
203
        $sql = "SELECT *
204
                FROM $TBL_QUESTIONS
205
                WHERE iid = $id ";
206
        $result = Database::query($sql);
207
208
        // if the question has been found
209
        if ($object = Database::fetch_object($result)) {
210
            $objQuestion = self::getInstance($object->type);
211
            if (!empty($objQuestion)) {
212
                $objQuestion->id = $id;
213
                $objQuestion->iid = (int) $object->iid;
214
                $objQuestion->question = $object->question;
215
                $objQuestion->description = $object->description;
216
                $objQuestion->weighting = $object->ponderation;
217
                $objQuestion->position = $object->position;
218
                $objQuestion->type = (int) $object->type;
219
                $objQuestion->picture = $object->picture;
220
                $objQuestion->level = (int) $object->level;
221
                $objQuestion->extra = $object->extra;
222
                $objQuestion->course = $course_info;
223
                $objQuestion->feedback = isset($object->feedback) ? $object->feedback : '';
224
                $objQuestion->category = TestCategory::getCategoryForQuestion($id, $course_id);
225
                $objQuestion->code = isset($object->code) ? $object->code : '';
226
                $categoryInfo = TestCategory::getCategoryInfoForQuestion($id, $course_id);
227
228
                if (!empty($categoryInfo)) {
229
                    if (isset($categoryInfo['category_id'])) {
230
                        $objQuestion->category = (int) $categoryInfo['category_id'];
231
                    }
232
233
                    if (('true' === api_get_setting('exercise.allow_mandatory_question_in_category')) &&
234
                        isset($categoryInfo['mandatory'])
235
                    ) {
236
                        $objQuestion->mandatory = (int) $categoryInfo['mandatory'];
237
                    }
238
                }
239
240
                if ($getExerciseList) {
241
                    $tblQuiz   = Database::get_course_table(TABLE_QUIZ_TEST);
242
                    $sessionId = (int) api_get_session_id();
243
                    $sessionJoin = $sessionId > 0 ? "rl.session_id = $sessionId" : "rl.session_id IS NULL";
244
245
                    $sql = "SELECT DISTINCT q.quiz_id
246
            FROM $TBL_EXERCISE_QUESTION q
247
            INNER JOIN $tblQuiz e  ON e.iid = q.quiz_id
248
            INNER JOIN resource_node rn ON rn.id = e.resource_node_id
249
            INNER JOIN resource_link rl ON rl.resource_node_id = rn.id AND $sessionJoin
250
            WHERE q.question_id = $id
251
              AND rl.deleted_at IS NULL";
252
                    $result = Database::query($sql);
253
                    while ($obj = Database::fetch_object($result)) {
254
                        $objQuestion->exerciseList[] = (int) $obj->quiz_id;
255
                    }
256
                }
257
258
                $objQuestion->parent_id = isset($object->parent_media_id)
259
                    ? (int) $object->parent_media_id
260
                    : 0;
261
262
                return $objQuestion;
263
            }
264
        }
265
266
        // question not found
267
        return false;
268
    }
269
270
    /**
271
     * returns the question title.
272
     *
273
     * @author Olivier Brouckaert
274
     *
275
     * @return string - question title
276
     */
277
    public function selectTitle()
278
    {
279
        if ('true' !== api_get_setting('editor.save_titles_as_html')) {
280
            return $this->question;
281
        }
282
283
        return Display::div($this->question, ['style' => 'display: inline-block;']);
284
    }
285
286
    public function getTitleToDisplay(Exercise $exercise, int $itemNumber): string
287
    {
288
        $showQuestionTitleHtml = ('true' === api_get_setting('editor.save_titles_as_html'));
289
        $title = '';
290
        if ('true' === api_get_setting('exercise.show_question_id')) {
291
            $title .= '<h4>#'.$this->course['code'].'-'.$this->iid.'</h4>';
292
        }
293
294
        $title .= $showQuestionTitleHtml ? '' : '<strong>';
295
        if (1 !== $exercise->getHideQuestionNumber()) {
296
            $title .= $itemNumber.'. ';
297
        }
298
        $title .= $this->selectTitle();
299
        $title .= $showQuestionTitleHtml ? '' : '</strong>';
300
301
        return Display::div(
302
            $title,
303
            ['class' => 'question_title']
304
        );
305
    }
306
307
    /**
308
     * returns the question description.
309
     *
310
     * @author Olivier Brouckaert
311
     *
312
     * @return string - question description
313
     */
314
    public function selectDescription()
315
    {
316
        return $this->description;
317
    }
318
319
    /**
320
     * returns the question weighting.
321
     *
322
     * @author Olivier Brouckaert
323
     *
324
     * @return int - question weighting
325
     */
326
    public function selectWeighting()
327
    {
328
        return $this->weighting;
329
    }
330
331
    /**
332
     * returns the answer type.
333
     *
334
     * @author Olivier Brouckaert
335
     *
336
     * @return int - answer type
337
     */
338
    public function selectType()
339
    {
340
        return $this->type;
341
    }
342
343
    /**
344
     * returns the level of the question.
345
     *
346
     * @author Nicolas Raynaud
347
     *
348
     * @return int - level of the question, 0 by default
349
     */
350
    public function getLevel()
351
    {
352
        return $this->level;
353
    }
354
355
    /**
356
     * changes the question title.
357
     *
358
     * @param string $title - question title
359
     *
360
     * @author Olivier Brouckaert
361
     */
362
    public function updateTitle($title)
363
    {
364
        $this->question = $title;
365
    }
366
367
    /**
368
     * changes the question description.
369
     *
370
     * @param string $description - question description
371
     *
372
     * @author Olivier Brouckaert
373
     */
374
    public function updateDescription($description)
375
    {
376
        $this->description = $description;
377
    }
378
379
    /**
380
     * changes the question weighting.
381
     *
382
     * @param int $weighting - question weighting
383
     *
384
     * @author Olivier Brouckaert
385
     */
386
    public function updateWeighting($weighting)
387
    {
388
        $this->weighting = $weighting;
389
    }
390
391
    /**
392
     * @param array $category
393
     *
394
     * @author Hubert Borderiou 12-10-2011
395
     */
396
    public function updateCategory($category)
397
    {
398
        $this->category = $category;
399
    }
400
401
    public function setMandatory($value)
402
    {
403
        $this->mandatory = (int) $value;
404
    }
405
406
    /**
407
     * in this version, a question can only have 1 category
408
     * if category is 0, then question has no category then delete the category entry.
409
     *
410
     * @author Hubert Borderiou 12-10-2011
411
     */
412
    public function saveCategory(int $categoryId): bool
413
    {
414
        if ($categoryId <= 0) {
415
            $this->deleteCategory();
416
        } else {
417
            // update or add category for a question
418
            $table = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
419
            $categoryId = (int) $categoryId;
420
            $questionId = (int) $this->id;
421
            $sql = "SELECT count(*) AS nb FROM $table
422
                    WHERE
423
                        question_id = $questionId
424
                    ";
425
            $res = Database::query($sql);
426
            $row = Database::fetch_array($res);
427
            $allowMandatory = ('true' === api_get_setting('exercise.allow_mandatory_question_in_category'));
428
            if ($row['nb'] > 0) {
429
                $extraMandatoryCondition = '';
430
                if ($allowMandatory) {
431
                    $extraMandatoryCondition = ", mandatory = {$this->mandatory}";
432
                }
433
                $sql = "UPDATE $table
434
                        SET category_id = $categoryId
435
                        $extraMandatoryCondition
436
                        WHERE
437
                            question_id = $questionId
438
                        ";
439
                Database::query($sql);
440
            } else {
441
                $sql = "INSERT INTO $table (question_id, category_id)
442
                        VALUES ($questionId, $categoryId)
443
                        ";
444
                Database::query($sql);
445
                if ($allowMandatory) {
446
                    $id = Database::insert_id();
447
                    if ($id) {
448
                        $sql = "UPDATE $table SET mandatory = {$this->mandatory}
449
                                WHERE iid = $id";
450
                        Database::query($sql);
451
                    }
452
                }
453
            }
454
        }
455
456
        return true;
457
    }
458
459
    /**
460
     * @author hubert borderiou 12-10-2011
461
     *
462
     *                      delete any category entry for question id
463
     *                      delete the category for question
464
     */
465
    public function deleteCategory(): bool
466
    {
467
        $table = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
468
        $questionId = (int) $this->id;
469
        if (empty($questionId)) {
470
            return false;
471
        }
472
        $sql = "DELETE FROM $table
473
                WHERE
474
                    question_id = $questionId
475
                ";
476
        Database::query($sql);
477
478
        return true;
479
    }
480
481
    /**
482
     * changes the question position.
483
     *
484
     * @param int $position - question position
485
     *
486
     * @author Olivier Brouckaert
487
     */
488
    public function updatePosition($position)
489
    {
490
        $this->position = $position;
491
    }
492
493
    /**
494
     * changes the question level.
495
     *
496
     * @param int $level - question level
497
     *
498
     * @author Nicolas Raynaud
499
     */
500
    public function updateLevel($level)
501
    {
502
        $this->level = $level;
503
    }
504
505
    /**
506
     * changes the answer type. If the user changes the type from "unique answer" to "multiple answers"
507
     * (or conversely) answers are not deleted, otherwise yes.
508
     *
509
     * @param int $type - answer type
510
     *
511
     * @author Olivier Brouckaert
512
     */
513
    public function updateType($type)
514
    {
515
        $table = Database::get_course_table(TABLE_QUIZ_ANSWER);
516
        $course_id = $this->course['real_id'];
517
518
        if (empty($course_id)) {
519
            $course_id = api_get_course_int_id();
520
        }
521
        // if we really change the type
522
        if ($type != $this->type) {
523
            // if we don't change from "unique answer" to "multiple answers" (or conversely)
524
            if (!in_array($this->type, [UNIQUE_ANSWER, MULTIPLE_ANSWER]) ||
525
                !in_array($type, [UNIQUE_ANSWER, MULTIPLE_ANSWER])
526
            ) {
527
                // removes old answers
528
                $sql = "DELETE FROM $table
529
                        WHERE c_id = $course_id AND question_id = ".(int) ($this->id);
530
                Database::query($sql);
531
            }
532
533
            $this->type = $type;
534
        }
535
    }
536
537
    /**
538
     * Set title.
539
     *
540
     * @param string $title
541
     */
542
    public function setTitle($title)
543
    {
544
        $this->question = $title;
545
    }
546
547
    /**
548
     * Sets extra info.
549
     *
550
     * @param string $extra
551
     */
552
    public function setExtra($extra)
553
    {
554
        $this->extra = $extra;
555
    }
556
557
    /**
558
     * updates the question in the data base
559
     * if an exercise ID is provided, we add that exercise ID into the exercise list.
560
     *
561
     * @author Olivier Brouckaert
562
     *
563
     * @param Exercise $exercise
564
     */
565
    public function save($exercise)
566
    {
567
        $TBL_EXERCISE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
568
        $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
569
        $em = Database::getManager();
570
        $exerciseId = $exercise->iId;
571
572
        $id = $this->id;
573
        $type = $this->type;
574
        $c_id = $this->course['real_id'];
575
576
        $courseEntity = api_get_course_entity($c_id);
577
        $categoryId = $this->category;
578
579
        $questionCategoryRepo = Container::getQuestionCategoryRepository();
580
        $questionRepo = Container::getQuestionRepository();
581
582
        // question already exists
583
        if (!empty($id)) {
584
            /** @var CQuizQuestion $question */
585
            $question = $questionRepo->find($id);
586
            if ($question) {
0 ignored issues
show
introduced by
$question is of type Chamilo\CourseBundle\Entity\CQuizQuestion, thus it always evaluated to true.
Loading history...
587
                $question
588
                    ->setQuestion($this->question)
589
                    ->setDescription($this->description)
590
                    ->setPonderation($this->weighting)
591
                    ->setPosition($this->position)
592
                    ->setType($this->type)
593
                    ->setExtra($this->extra)
594
                    ->setLevel((int) $this->level)
595
                    ->setFeedback($this->feedback)
596
                    ->setParentMediaId($this->parent_id);
597
598
                if (!empty($categoryId)) {
599
                    $category = $questionCategoryRepo->find($categoryId);
600
                    $question->updateCategory($category);
601
                }
602
603
                $em->persist($question);
604
                $em->flush();
605
606
                Event::addEvent(
0 ignored issues
show
Bug introduced by
The method addEvent() does not exist on Event. ( Ignorable by Annotation )

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

606
                Event::/** @scrutinizer ignore-call */ 
607
                       addEvent(

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
607
                    LOG_QUESTION_UPDATED,
608
                    LOG_QUESTION_ID,
609
                    $this->iid
610
                );
611
                if ('true' === api_get_setting('search_enabled')) {
612
                    $this->search_engine_edit($exerciseId);
613
                }
614
            }
615
        } else {
616
            // Creates a new question
617
            $sql = "SELECT max(position)
618
                    FROM $TBL_QUESTIONS as question,
619
                    $TBL_EXERCISE_QUESTION as test_question
620
                    WHERE
621
                        question.iid = test_question.question_id AND
622
                        test_question.quiz_id = ".$exerciseId;
623
            $result = Database::query($sql);
624
            $current_position = Database::result($result, 0, 0);
625
            $this->updatePosition($current_position + 1);
626
            $position = $this->position;
627
            //$exerciseEntity = $exerciseRepo->find($exerciseId);
628
629
            $question = (new CQuizQuestion())
630
                ->setQuestion($this->question)
631
                ->setDescription($this->description)
632
                ->setPonderation($this->weighting)
633
                ->setPosition($position)
634
                ->setType($this->type)
635
                ->setExtra($this->extra)
636
                ->setLevel((int) $this->level)
637
                ->setFeedback($this->feedback)
638
                ->setParentMediaId($this->parent_id)
639
                ->setParent($courseEntity)
640
                ->addCourseLink($courseEntity, api_get_session_entity(), api_get_group_entity());
641
642
            $em->persist($question);
643
            $em->flush();
644
645
            $this->id = $question->getIid();
646
647
            if ($this->id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->id of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
648
                Event::addEvent(
649
                    LOG_QUESTION_CREATED,
650
                    LOG_QUESTION_ID,
651
                    $this->id
652
                );
653
654
                $questionRepo->addFileFromFileRequest($question, 'imageUpload');
655
656
                // If hotspot, create first answer
657
                if (in_array($type, [HOT_SPOT, HOT_SPOT_COMBINATION, HOT_SPOT_ORDER])) {
658
                    $quizAnswer = new CQuizAnswer();
659
                    $quizAnswer
660
                        ->setQuestion($question)
661
                        ->setPonderation(10)
662
                        ->setPosition(1)
663
                        ->setHotspotCoordinates('0;0|0|0')
664
                        ->setHotspotType('square');
665
666
                    $em->persist($quizAnswer);
667
                    $em->flush();
668
                }
669
670
                if (HOT_SPOT_DELINEATION == $type) {
671
                    $quizAnswer = new CQuizAnswer();
672
                    $quizAnswer
673
                        ->setQuestion($question)
674
                        ->setPonderation(10)
675
                        ->setPosition(1)
676
                        ->setHotspotCoordinates('0;0|0|0')
677
                        ->setHotspotType('delineation');
678
679
                    $em->persist($quizAnswer);
680
                    $em->flush();
681
                }
682
683
                if ('true' === api_get_setting('search_enabled')) {
684
                    $this->search_engine_edit($exerciseId, true);
685
                }
686
            }
687
        }
688
689
        // if the question is created in an exercise
690
        if (!empty($exerciseId)) {
691
            // adds the exercise into the exercise list of this question
692
            $this->addToList($exerciseId, true);
693
        }
694
    }
695
696
    /**
697
     * @param int  $exerciseId
698
     * @param bool $addQs
699
     * @param bool $rmQs
700
     */
701
    public function search_engine_edit(
702
        $exerciseId,
703
        $addQs = false,
704
        $rmQs = false
705
    ) {
706
        // update search engine and its values table if enabled
707
        if (!empty($exerciseId) && 'true' == api_get_setting('search_enabled') &&
708
            extension_loaded('xapian')
709
        ) {
710
            $course_id = api_get_course_id();
711
            // get search_did
712
            $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
713
            if ($addQs || $rmQs) {
714
                //there's only one row per question on normal db and one document per question on search engine db
715
                $sql = 'SELECT * FROM %s
716
                    WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_second_level=%s LIMIT 1';
717
                $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
718
            } else {
719
                $sql = 'SELECT * FROM %s
720
                    WHERE course_code=\'%s\' AND tool_id=\'%s\'
721
                    AND ref_id_high_level=%s AND ref_id_second_level=%s LIMIT 1';
722
                $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id);
723
            }
724
            $res = Database::query($sql);
725
726
            if (Database::num_rows($res) > 0 || $addQs) {
727
                $di = new ChamiloIndexer();
728
                if ($addQs) {
729
                    $question_exercises = [(int) $exerciseId];
730
                } else {
731
                    $question_exercises = [];
732
                }
733
                isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : $lang = 'english';
734
                $di->connectDb(null, null, $lang);
735
736
                // retrieve others exercise ids
737
                $se_ref = Database::fetch_array($res);
738
                $se_doc = $di->get_document((int) $se_ref['search_did']);
739
                if (false !== $se_doc) {
740
                    if (false !== ($se_doc_data = $di->get_document_data($se_doc))) {
741
                        $se_doc_data = UnserializeApi::unserialize(
742
                            'not_allowed_classes',
743
                            $se_doc_data
744
                        );
745
                        if (isset($se_doc_data[SE_DATA]['type']) &&
746
                            SE_DOCTYPE_EXERCISE_QUESTION == $se_doc_data[SE_DATA]['type']
747
                        ) {
748
                            if (isset($se_doc_data[SE_DATA]['exercise_ids']) &&
749
                                is_array($se_doc_data[SE_DATA]['exercise_ids'])
750
                            ) {
751
                                foreach ($se_doc_data[SE_DATA]['exercise_ids'] as $old_value) {
752
                                    if (!in_array($old_value, $question_exercises)) {
753
                                        $question_exercises[] = $old_value;
754
                                    }
755
                                }
756
                            }
757
                        }
758
                    }
759
                }
760
                if ($rmQs) {
761
                    while (false !== ($key = array_search($exerciseId, $question_exercises))) {
762
                        unset($question_exercises[$key]);
763
                    }
764
                }
765
766
                // build the chunk to index
767
                $ic_slide = new IndexableChunk();
768
                $ic_slide->addValue('title', $this->question);
769
                $ic_slide->addCourseId($course_id);
770
                $ic_slide->addToolId(TOOL_QUIZ);
771
                $xapian_data = [
772
                    SE_COURSE_ID => $course_id,
773
                    SE_TOOL_ID => TOOL_QUIZ,
774
                    SE_DATA => [
775
                        'type' => SE_DOCTYPE_EXERCISE_QUESTION,
776
                        'exercise_ids' => $question_exercises,
777
                        'question_id' => (int) $this->id,
778
                    ],
779
                    SE_USER => (int) api_get_user_id(),
780
                ];
781
                $ic_slide->xapian_data = serialize($xapian_data);
782
                $ic_slide->addValue('content', $this->description);
783
784
                //TODO: index answers, see also form validation on question_admin.inc.php
785
786
                $di->remove_document($se_ref['search_did']);
787
                $di->addChunk($ic_slide);
788
789
                //index and return search engine document id
790
                if (!empty($question_exercises)) { // if empty there is nothing to index
791
                    $did = $di->index();
792
                    unset($di);
793
                }
794
                if ($did || $rmQs) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $did does not seem to be defined for all execution paths leading up to this point.
Loading history...
795
                    // save it to db
796
                    if ($addQs || $rmQs) {
797
                        $sql = "DELETE FROM %s
798
                            WHERE course_code = '%s' AND tool_id = '%s' AND ref_id_second_level = '%s'";
799
                        $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
800
                    } else {
801
                        $sql = "DELETE FROM %S
802
                            WHERE
803
                                course_code = '%s'
804
                                AND tool_id = '%s'
805
                                AND tool_id = '%s'
806
                                AND ref_id_high_level = '%s'
807
                                AND ref_id_second_level = '%s'";
808
                        $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id);
809
                    }
810
                    Database::query($sql);
811
                    if ($rmQs) {
812
                        if (!empty($question_exercises)) {
813
                            $sql = "INSERT INTO %s (
814
                                    id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did
815
                                )
816
                                VALUES (
817
                                    NULL, '%s', '%s', %s, %s, %s
818
                                )";
819
                            $sql = sprintf(
820
                                $sql,
821
                                $tbl_se_ref,
822
                                $course_id,
823
                                TOOL_QUIZ,
824
                                array_shift($question_exercises),
825
                                $this->id,
826
                                $did
827
                            );
828
                            Database::query($sql);
829
                        }
830
                    } else {
831
                        $sql = "INSERT INTO %s (
832
                                id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did
833
                            )
834
                            VALUES (
835
                                NULL , '%s', '%s', %s, %s, %s
836
                            )";
837
                        $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id, $did);
838
                        Database::query($sql);
839
                    }
840
                }
841
            }
842
        }
843
    }
844
845
    /**
846
     * adds an exercise into the exercise list.
847
     *
848
     * @author Olivier Brouckaert
849
     *
850
     * @param int  $exerciseId - exercise ID
851
     * @param bool $fromSave   - from $this->save() or not
852
     */
853
    public function addToList($exerciseId, $fromSave = false)
854
    {
855
        $exerciseRelQuestionTable = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
856
        $id = (int) $this->id;
857
        $exerciseId = (int) $exerciseId;
858
859
        // checks if the exercise ID is not in the list
860
        if (!empty($exerciseId) && !in_array($exerciseId, $this->exerciseList)) {
861
            $this->exerciseList[] = $exerciseId;
862
            $courseId = isset($this->course['real_id']) ? $this->course['real_id'] : 0;
863
            $newExercise = new Exercise($courseId);
864
            $newExercise->read($exerciseId, false);
865
            $count = $newExercise->getQuestionCount();
866
            $count++;
867
            $sql = "INSERT INTO $exerciseRelQuestionTable (question_id, quiz_id, question_order)
868
                    VALUES (".$id.', '.$exerciseId.", '$count')";
869
            Database::query($sql);
870
871
            // we do not want to reindex if we had just saved adnd indexed the question
872
            if (!$fromSave) {
873
                $this->search_engine_edit($exerciseId, true);
874
            }
875
        }
876
    }
877
878
    /**
879
     * removes an exercise from the exercise list.
880
     *
881
     * @author Olivier Brouckaert
882
     *
883
     * @param int $exerciseId - exercise ID
884
     * @param int $courseId
885
     *
886
     * @return bool - true if removed, otherwise false
887
     */
888
    public function removeFromList($exerciseId, $courseId = 0)
889
    {
890
        $table = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
891
        $tableQuestion = Database::get_course_table(TABLE_QUIZ_QUESTION);
892
        $id = (int) $this->id;
893
        $exerciseId = (int) $exerciseId;
894
895
        // searches the position of the exercise ID in the list
896
        $pos = array_search($exerciseId, $this->exerciseList);
897
        $courseId = empty($courseId) ? api_get_course_int_id() : (int) $courseId;
898
899
        // exercise not found
900
        if (false === $pos) {
901
            return false;
902
        } else {
903
            // deletes the position in the array containing the wanted exercise ID
904
            unset($this->exerciseList[$pos]);
905
            //update order of other elements
906
            $sql = "SELECT question_order
907
                    FROM $table
908
                    WHERE
909
                        question_id = $id AND
910
                        quiz_id = $exerciseId";
911
            $res = Database::query($sql);
912
            if (Database::num_rows($res) > 0) {
913
                $row = Database::fetch_array($res);
914
                if (!empty($row['question_order'])) {
915
                    $sql = "UPDATE $table
916
                            SET question_order = question_order-1
917
                            WHERE
918
                                quiz_id = $exerciseId AND
919
                                question_order > ".$row['question_order'];
920
                    Database::query($sql);
921
                }
922
            }
923
924
            $sql = "DELETE FROM $table
925
                    WHERE
926
                        question_id = $id AND
927
                        quiz_id = $exerciseId";
928
            Database::query($sql);
929
930
            $reset = "UPDATE $tableQuestion
931
                  SET parent_media_id = NULL
932
                  WHERE parent_media_id = $id";
933
            Database::query($reset);
934
935
            return true;
936
        }
937
    }
938
939
    /**
940
     * Deletes a question from the database
941
     * the parameter tells if the question is removed from all exercises (value = 0),
942
     * or just from one exercise (value = exercise ID).
943
     *
944
     * @author Olivier Brouckaert
945
     *
946
     * @param int $deleteFromEx - exercise ID if the question is only removed from one exercise
947
     *
948
     * @return bool
949
     */
950
    public function delete($deleteFromEx = 0)
951
    {
952
        if (empty($this->course)) {
953
            return false;
954
        }
955
956
        $courseId = $this->course['real_id'];
957
958
        if (empty($courseId)) {
959
            return false;
960
        }
961
962
        $TBL_EXERCISE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
963
        $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
964
        $TBL_REPONSES = Database::get_course_table(TABLE_QUIZ_ANSWER);
965
        $TBL_QUIZ_QUESTION_REL_CATEGORY = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
966
967
        $id = (int) $this->id;
968
969
        // if the question must be removed from all exercises
970
        if (!$deleteFromEx) {
971
            //update the question_order of each question to avoid inconsistencies
972
            $sql = "SELECT quiz_id, question_order
973
                    FROM $TBL_EXERCISE_QUESTION
974
                    WHERE question_id = ".$id;
975
976
            $res = Database::query($sql);
977
            if (Database::num_rows($res) > 0) {
978
                while ($row = Database::fetch_array($res)) {
979
                    if (!empty($row['question_order'])) {
980
                        $sql = "UPDATE $TBL_EXERCISE_QUESTION
981
                                SET question_order = question_order-1
982
                                WHERE
983
                                    quiz_id = ".(int) ($row['quiz_id']).' AND
984
                                    question_order > '.$row['question_order'];
985
                        Database::query($sql);
986
                    }
987
                }
988
            }
989
990
            $reset = "UPDATE $TBL_QUESTIONS
991
                  SET parent_media_id = NULL
992
                  WHERE parent_media_id = $id";
993
            Database::query($reset);
994
995
            $sql = "DELETE FROM $TBL_EXERCISE_QUESTION
996
                    WHERE question_id = ".$id;
997
            Database::query($sql);
998
999
            $sql = "DELETE FROM $TBL_QUESTIONS
1000
                    WHERE iid = ".$id;
1001
            Database::query($sql);
1002
1003
            $sql = "DELETE FROM $TBL_REPONSES
1004
                    WHERE question_id = ".$id;
1005
            Database::query($sql);
1006
1007
            // remove the category of this question in the question_rel_category table
1008
            $sql = "DELETE FROM $TBL_QUIZ_QUESTION_REL_CATEGORY
1009
                    WHERE
1010
                        question_id = ".$id;
1011
            Database::query($sql);
1012
1013
            // Add extra fields.
1014
            $extraField = new ExtraFieldValue('question');
1015
            $extraField->deleteValuesByItem($this->iid);
1016
1017
            /*api_item_property_update(
1018
                $this->course,
1019
                TOOL_QUIZ,
1020
                $id,
1021
                'QuizQuestionDeleted',
1022
                api_get_user_id()
1023
            );*/
1024
            Event::addEvent(
1025
                LOG_QUESTION_DELETED,
1026
                LOG_QUESTION_ID,
1027
                $this->iid
1028
            );
1029
            //$this->removePicture();
1030
        } else {
1031
            // just removes the exercise from the list
1032
            $this->removeFromList($deleteFromEx, $courseId);
1033
            if ('true' == api_get_setting('search_enabled') && extension_loaded('xapian')) {
1034
                // disassociate question with this exercise
1035
                $this->search_engine_edit($deleteFromEx, false, true);
1036
            }
1037
            /*
1038
            api_item_property_update(
1039
                $this->course,
1040
                TOOL_QUIZ,
1041
                $id,
1042
                'QuizQuestionDeleted',
1043
                api_get_user_id()
1044
            );*/
1045
            Event::addEvent(
1046
                LOG_QUESTION_REMOVED_FROM_QUIZ,
1047
                LOG_QUESTION_ID,
1048
                $this->iid
1049
            );
1050
        }
1051
1052
        return true;
1053
    }
1054
1055
    /**
1056
     * Duplicates the question.
1057
     *
1058
     * @author Olivier Brouckaert
1059
     *
1060
     * @param array $courseInfo Course info of the destination course
1061
     *
1062
     * @return false|string ID of the new question
1063
     */
1064
    public function duplicate($courseInfo = [])
1065
    {
1066
        $courseInfo = empty($courseInfo) ? $this->course : $courseInfo;
1067
1068
        if (empty($courseInfo)) {
1069
            return false;
1070
        }
1071
        $TBL_QUESTION_OPTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
1072
1073
        $questionText = $this->question;
1074
        $description = $this->description;
1075
1076
        // Using the same method used in the course copy to transform URLs
1077
        if ($this->course['id'] != $courseInfo['id']) {
1078
            $description = DocumentManager::replaceUrlWithNewCourseCode(
1079
                $description,
1080
                $this->course['code'],
1081
                $courseInfo['id']
1082
            );
1083
            $questionText = DocumentManager::replaceUrlWithNewCourseCode(
1084
                $questionText,
1085
                $this->course['code'],
1086
                $courseInfo['id']
1087
            );
1088
        }
1089
1090
        $course_id = $courseInfo['real_id'];
1091
1092
        // Read the source options
1093
        $options = self::readQuestionOption($this->id, $this->course['real_id']);
1094
1095
        $em = Database::getManager();
1096
        $courseEntity = api_get_course_entity($course_id);
1097
1098
        $question = (new CQuizQuestion())
1099
            ->setQuestion($questionText)
1100
            ->setDescription($description)
1101
            ->setPonderation($this->weighting)
1102
            ->setPosition($this->position)
1103
            ->setType($this->type)
1104
            ->setExtra($this->extra)
1105
            ->setLevel($this->level)
1106
            ->setFeedback($this->feedback)
1107
            ->setParent($courseEntity)
1108
            ->addCourseLink($courseEntity)
1109
        ;
1110
1111
        $em->persist($question);
1112
        $em->flush();
1113
        $newQuestionId = $question->getIid();
1114
1115
        if ($newQuestionId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $newQuestionId of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
1116
            // Add extra fields.
1117
            $extraField = new ExtraFieldValue('question');
1118
            $extraField->copy($this->iid, $newQuestionId);
1119
1120
            if (!empty($options)) {
1121
                // Saving the quiz_options
1122
                foreach ($options as $item) {
1123
                    $item['question_id'] = $newQuestionId;
1124
                    $item['c_id'] = $course_id;
1125
                    unset($item['iid']);
1126
                    unset($item['iid']);
1127
                    Database::insert($TBL_QUESTION_OPTIONS, $item);
1128
                }
1129
            }
1130
1131
            // Duplicates the picture of the hotspot
1132
            // @todo implement copy of hotspot question
1133
            if (HOT_SPOT == $this->type) {
1134
                throw new Exception('implement copy of hotspot question');
1135
            }
1136
        }
1137
1138
        return $newQuestionId;
1139
    }
1140
1141
    /**
1142
     * @return string
1143
     */
1144
    public function get_question_type_name(): string
1145
    {
1146
        $label = trim((string) $this->explanationLangVar);
1147
        if ($label !== '') {
1148
            return get_lang($label);
1149
        }
1150
1151
        $def = self::$questionTypes[$this->type] ?? null;
1152
        $className = is_array($def) ? ($def[1] ?? '') : '';
1153
        if ($className !== '') {
1154
            $human = preg_replace('/(?<!^)(?=[A-Z])/', ' ', $className) ?: $className;
1155
            return get_lang(trim($human));
1156
        }
1157
1158
        return '';
1159
    }
1160
1161
    /**
1162
     * @param string $type
1163
     */
1164
    public static function get_question_type($type)
1165
    {
1166
        return self::$questionTypes[$type];
1167
    }
1168
1169
    /**
1170
     * @return array
1171
     */
1172
    public static function getQuestionTypeList(): array
1173
    {
1174
        $list = self::$questionTypes;
1175
1176
        if ('true' !== api_get_setting('enable_quiz_scenario')) {
1177
            unset($list[HOT_SPOT_DELINEATION]);
1178
        }
1179
1180
        ksort($list, SORT_NUMERIC);
1181
1182
        return $list;
1183
    }
1184
1185
    /**
1186
     * Returns an instance of the class corresponding to the type.
1187
     *
1188
     * @param int $type the type of the question
1189
     *
1190
     * @return $this instance of a Question subclass (or of Questionc class by default)
1191
     */
1192
    public static function getInstance($type)
1193
    {
1194
        if (null !== $type) {
1195
            [$fileName, $className] = self::get_question_type($type);
1196
            if (!empty($fileName)) {
1197
                if (class_exists($className)) {
1198
                    return new $className();
1199
                } else {
1200
                    echo 'Can\'t instanciate class '.$className.' of type '.$type;
1201
                }
1202
            }
1203
        }
1204
1205
        return null;
1206
    }
1207
1208
    /**
1209
     * Creates the form to create / edit a question
1210
     * A subclass can redefine this function to add fields...
1211
     *
1212
     * @param FormValidator $form
1213
     * @param Exercise      $exercise
1214
     */
1215
    public function createForm(&$form, $exercise)
1216
    {
1217
        $zoomOptions = api_get_setting('exercise.quiz_image_zoom', true);
1218
        if (isset($zoomOptions['options'])) {
1219
            $finderFolder = api_get_path(WEB_PATH).'vendor/studio-42/elfinder/';
1220
            echo '<!-- elFinder CSS (REQUIRED) -->';
1221
            echo '<link rel="stylesheet" type="text/css" media="screen" href="'.$finderFolder.'css/elfinder.full.css">';
1222
            echo '<link rel="stylesheet" type="text/css" media="screen" href="'.$finderFolder.'css/theme.css">';
1223
1224
            echo '<!-- elFinder JS (REQUIRED) -->';
1225
            echo '<script src="'.$finderFolder.'js/elfinder.full.js"></script>';
1226
1227
            echo '<!-- elFinder translation (OPTIONAL) -->';
1228
            $language = 'en';
1229
            $platformLanguage = api_get_language_isocode();
1230
            $iso = api_get_language_isocode($platformLanguage);
1231
            $filePart = "vendor/studio-42/elfinder/js/i18n/elfinder.$iso.js";
1232
            $file = api_get_path(SYS_PATH).$filePart;
1233
            $includeFile = '';
1234
            if (file_exists($file)) {
1235
                $includeFile = '<script src="'.api_get_path(WEB_PATH).$filePart.'"></script>';
1236
                $language = $iso;
1237
            }
1238
            echo $includeFile;
1239
            echo '<script>
1240
        $(function() {
1241
            $(".create_img_link").click(function(e){
1242
                e.preventDefault();
1243
                e.stopPropagation();
1244
                var imageZoom = $("input[name=\'imageZoom\']").val();
1245
                var imageWidth = $("input[name=\'imageWidth\']").val();
1246
                CKEDITOR.instances.questionDescription.insertHtml(\'<img id="zoom_picture" class="zoom_picture" src="\'+imageZoom+\'" data-zoom-image="\'+imageZoom+\'" width="\'+imageWidth+\'px" />\');
1247
            });
1248
1249
            $("input[name=\'imageZoom\']").on("click", function(){
1250
                var elf = $("#elfinder").elfinder({
1251
                    url : "'.api_get_path(WEB_LIBRARY_PATH).'elfinder/connectorAction.php?'.api_get_cidreq().'",
1252
                    getFileCallback: function(file) {
1253
                        var filePath = file; //file contains the relative url.
1254
                        var imgPath = "<img src = \'"+filePath+"\'/>";
1255
                        $("input[name=\'imageZoom\']").val(filePath.url);
1256
                        $("#elfinder").remove(); //close the window after image is selected
1257
                    },
1258
                    startPathHash: "l2_Lw", // Sets the course driver as default
1259
                    resizable: false,
1260
                    lang: "'.$language.'"
1261
                }).elfinder("instance");
1262
            });
1263
        });
1264
        </script>';
1265
            echo '<div id="elfinder"></div>';
1266
        }
1267
1268
        // Question name
1269
        if ('true' === api_get_setting('editor.save_titles_as_html')) {
1270
            $editorConfig = ['ToolbarSet' => 'TitleAsHtml'];
1271
            $form->addHtmlEditor(
1272
                'questionName',
1273
                get_lang('Question'),
1274
                false,
1275
                false,
1276
                $editorConfig
1277
            );
1278
        } else {
1279
            $form->addText('questionName', get_lang('Question'));
1280
        }
1281
1282
        $form->addRule('questionName', get_lang('Please type the question'), 'required');
1283
1284
        // Default content
1285
        $isContent = isset($_REQUEST['isContent']) ? (int) $_REQUEST['isContent'] : null;
1286
1287
        // Question type (answer type)
1288
        $answerType = isset($_REQUEST['answerType']) ? (int) $_REQUEST['answerType'] : null;
1289
        $form->addHidden('answerType', $answerType);
1290
1291
        // HTML editor for description
1292
        $editorConfig = [
1293
            'ToolbarSet' => 'TestQuestionDescription',
1294
            'Height' => '150',
1295
        ];
1296
1297
        if (!api_is_allowed_to_edit(null, true)) {
1298
            $editorConfig['UserStatus'] = 'student';
1299
        }
1300
1301
        $form->addButtonAdvancedSettings('advanced_params');
1302
        $form->addHtml('<div id="advanced_params_options" style="display:none">');
1303
1304
        if (isset($zoomOptions['options'])) {
1305
            $form->addElement('text', 'imageZoom', get_lang('Image URL'));
1306
            $form->addElement('text', 'imageWidth', get_lang('px width'));
1307
            $form->addButton('btn_create_img', get_lang('Add to editor'), 'plus', 'info', 'small', 'create_img_link');
1308
        }
1309
1310
        $form->addHtmlEditor(
1311
            'questionDescription',
1312
            get_lang('Enrich question'),
1313
            false,
1314
            false,
1315
            $editorConfig
1316
        );
1317
1318
        if (MEDIA_QUESTION != $this->type) {
1319
            // Advanced parameters.
1320
            $form->addSelect(
1321
                'questionLevel',
1322
                get_lang('Difficulty'),
1323
                self::get_default_levels()
1324
            );
1325
1326
            // Categories.
1327
            $form->addSelect(
1328
                'questionCategory',
1329
                get_lang('Category'),
1330
                TestCategory::getCategoriesIdAndName()
1331
            );
1332
1333
            $courseMedias = self::prepare_course_media_select($exercise->iId);
1334
            $form->addSelect(
1335
                'parent_id',
1336
                get_lang('Attach to media'),
1337
                $courseMedias
1338
            );
1339
1340
            if (EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_RANDOM == $exercise->getQuestionSelectionType() &&
1341
                ('true' === api_get_setting('exercise.allow_mandatory_question_in_category'))
1342
            ) {
1343
                $form->addCheckBox('mandatory', get_lang('Mandatory?'));
1344
            }
1345
1346
            $text = get_lang('Save the question');
1347
            switch ($this->type) {
1348
                case UNIQUE_ANSWER:
1349
                    $buttonGroup = [];
1350
                    $buttonGroup[] = $form->addButtonSave(
1351
                        $text,
1352
                        'submitQuestion',
1353
                        true
1354
                    );
1355
                    $buttonGroup[] = $form->addButton(
1356
                        'convertAnswer',
1357
                        get_lang('Convert to multiple answer'),
1358
                        'dot-circle-o',
1359
                        'default',
1360
                        null,
1361
                        null,
1362
                        null,
1363
                        true
1364
                    );
1365
                    $form->addGroup($buttonGroup);
1366
1367
                    break;
1368
                case MULTIPLE_ANSWER:
1369
                    $buttonGroup = [];
1370
                    $buttonGroup[] = $form->addButtonSave(
1371
                        $text,
1372
                        'submitQuestion',
1373
                        true
1374
                    );
1375
                    $buttonGroup[] = $form->addButton(
1376
                        'convertAnswer',
1377
                        get_lang('Convert to unique answer'),
1378
                        'check-square-o',
1379
                        'default',
1380
                        null,
1381
                        null,
1382
                        null,
1383
                        true
1384
                    );
1385
                    $form->addGroup($buttonGroup);
1386
1387
                    break;
1388
            }
1389
        }
1390
1391
        $form->addElement('html', '</div>');
1392
1393
        // Sample default questions when creating from templates
1394
        if (!isset($_GET['fromExercise'])) {
1395
            switch ($answerType) {
1396
                case 1:
1397
                    $this->question = get_lang('Select the good reasoning');
1398
1399
                    break;
1400
                case 2:
1401
                    $this->question = get_lang('The marasmus is a consequence of');
1402
1403
                    break;
1404
                case 3:
1405
                    $this->question = get_lang('Calculate the Body Mass Index');
1406
1407
                    break;
1408
                case 4:
1409
                    $this->question = get_lang('Order the operations');
1410
1411
                    break;
1412
                case 5:
1413
                    $this->question = get_lang('List what you consider the 10 top qualities of a good project manager?');
1414
1415
                    break;
1416
                case 9:
1417
                    $this->question = get_lang('The marasmus is a consequence of');
1418
1419
                    break;
1420
            }
1421
        }
1422
1423
        // -------------------------------------------------------------------------
1424
        // Adaptive scenario (success/failure) — centralised for supported types
1425
        // -------------------------------------------------------------------------
1426
        $scenarioEnabled    = ('true' === api_get_setting('enable_quiz_scenario'));
1427
        $hasExercise        = ($exercise instanceof Exercise);
1428
        $isAdaptiveFeedback = $hasExercise &&
1429
            EXERCISE_FEEDBACK_TYPE_DIRECT === $exercise->getFeedbackType();
1430
        $supportsScenario   = in_array(
1431
            (int) $this->type,
1432
            static::$adaptiveScenarioTypes,
1433
            true
1434
        );
1435
1436
        if ($scenarioEnabled && $isAdaptiveFeedback && $supportsScenario && $hasExercise) {
1437
            // Build the question list once per exercise to feed the scenario selector
1438
            $exercise->setQuestionList(true);
1439
            $questionList = $exercise->getQuestionList();
1440
1441
            if (is_array($questionList) && !empty($questionList)) {
1442
                $this->addAdaptiveScenarioFields($form, $questionList);
1443
                // Pre-fill selector defaults when editing an existing question in this exercise.
1444
                if (!empty($this->id)) {
1445
                    $this->loadAdaptiveScenarioDefaults($form, $exercise);
1446
                }
1447
            }
1448
        }
1449
1450
        if (null !== $exercise) {
1451
            if ($exercise->questionFeedbackEnabled && $this->showFeedback($exercise)) {
1452
                $form->addTextarea('feedback', get_lang('Feedback if not correct'));
1453
            }
1454
        }
1455
1456
        $extraField = new ExtraField('question');
1457
        $extraField->addElements($form, $this->iid);
1458
1459
        // Default values
1460
        $defaults = [
1461
            'questionName'        => $this->question,
1462
            'questionDescription' => $this->description,
1463
            'questionLevel'       => $this->level,
1464
            'questionCategory'    => $this->category,
1465
            'feedback'            => $this->feedback,
1466
            'mandatory'           => $this->mandatory,
1467
            'parent_id'           => $this->parent_id,
1468
        ];
1469
1470
        // Came from the question pool
1471
        if (isset($_GET['fromExercise'])) {
1472
            $form->setDefaults($defaults);
1473
        }
1474
1475
        if (!isset($_GET['newQuestion']) || $isContent) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $isContent of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
1476
            $form->setDefaults($defaults);
1477
        }
1478
1479
        /*if (!empty($_REQUEST['myid'])) {
1480
            $form->setDefaults($defaults);
1481
        } else {
1482
            if ($isContent == 1) {
1483
                $form->setDefaults($defaults);
1484
            }
1485
        }*/
1486
    }
1487
1488
    /**
1489
     * Function which process the creation of questions.
1490
     */
1491
    public function processCreation(FormValidator $form, Exercise $exercise)
1492
    {
1493
        $this->parent_id = (int) $form->getSubmitValue('parent_id');
1494
        $this->updateTitle($form->getSubmitValue('questionName'));
1495
        $this->updateDescription($form->getSubmitValue('questionDescription'));
1496
        $this->updateLevel($form->getSubmitValue('questionLevel'));
1497
        $this->updateCategory($form->getSubmitValue('questionCategory'));
1498
        $this->setMandatory($form->getSubmitValue('mandatory'));
1499
        $this->setFeedback($form->getSubmitValue('feedback'));
1500
1501
        //Save normal question if NOT media
1502
        if (MEDIA_QUESTION != $this->type) {
1503
            $this->save($exercise);
1504
            // modify the exercise
1505
            $exercise->addToList($this->id);
1506
            $exercise->update_question_positions();
1507
1508
            $params = $form->exportValues();
1509
            $params['item_id'] = $this->id;
1510
1511
            $extraFieldValues = new ExtraFieldValue('question');
1512
            $extraFieldValues->saveFieldValues($params);
1513
        }
1514
    }
1515
1516
    /**
1517
     * Creates the form to create / edit the answers of the question.
1518
     */
1519
    abstract public function createAnswersForm(FormValidator $form);
1520
1521
    /**
1522
     * Process the creation of answers.
1523
     *
1524
     * @param FormValidator $form
1525
     * @param Exercise      $exercise
1526
     */
1527
    abstract public function processAnswersCreation($form, $exercise);
1528
1529
    /**
1530
     * Displays the menu of question types.
1531
     *
1532
     * @param Exercise $objExercise
1533
     */
1534
    public static function displayTypeMenu(Exercise $objExercise)
1535
    {
1536
        if (empty($objExercise)) {
1537
            return '';
1538
        }
1539
1540
        $feedbackType = $objExercise->getFeedbackType();
1541
        $exerciseId   = $objExercise->id;
1542
1543
        $questionTypeList = self::getQuestionTypeList();
1544
1545
        if (!isset($feedbackType)) {
1546
            $feedbackType = 0;
1547
        }
1548
1549
        switch ($feedbackType) {
1550
            case EXERCISE_FEEDBACK_TYPE_DIRECT:
1551
                // Keep original behavior: base types for adaptative tests.
1552
                $questionTypeList = [
1553
                    UNIQUE_ANSWER        => self::$questionTypes[UNIQUE_ANSWER],
1554
                    HOT_SPOT_DELINEATION => self::$questionTypes[HOT_SPOT_DELINEATION],
1555
                ];
1556
1557
                // Add all other non-open question types.
1558
                $allTypes = self::getQuestionTypeList();
1559
1560
                // The task explicitly mentions NOT including free-answer questions.
1561
                // So we only exclude FREE_ANSWER here.
1562
                if (isset($allTypes[FREE_ANSWER])) {
1563
                    unset($allTypes[FREE_ANSWER]);
1564
                }
1565
1566
                // Append remaining types, without overriding the original ones.
1567
                foreach ($allTypes as $typeId => $def) {
1568
                    if (!isset($questionTypeList[$typeId])) {
1569
                        $questionTypeList[$typeId] = $def;
1570
                    }
1571
                }
1572
1573
                break;
1574
            case EXERCISE_FEEDBACK_TYPE_POPUP:
1575
                $questionTypeList = [
1576
                    UNIQUE_ANSWER        => self::$questionTypes[UNIQUE_ANSWER],
1577
                    MULTIPLE_ANSWER      => self::$questionTypes[MULTIPLE_ANSWER],
1578
                    DRAGGABLE            => self::$questionTypes[DRAGGABLE],
1579
                    HOT_SPOT_DELINEATION => self::$questionTypes[HOT_SPOT_DELINEATION],
1580
                    CALCULATED_ANSWER    => self::$questionTypes[CALCULATED_ANSWER],
1581
                ];
1582
1583
                break;
1584
            default:
1585
                unset($questionTypeList[HOT_SPOT_DELINEATION]);
1586
1587
                break;
1588
        }
1589
1590
        echo '<div class="card">';
1591
        echo '  <div class="card-body">';
1592
        echo '    <ul class="qtype-menu flex flex-wrap gap-x-2 gap-y-2 items-center justify-start w-full">';
1593
        foreach ($questionTypeList as $i => $type) {
1594
            /** @var Question $type */
1595
            $type = new $type[1]();
1596
            $img  = $type->getTypePicture();
1597
            $expl = $type->getExplanation();
1598
1599
            echo '      <li class="flex items-center justify-center">';
1600
1601
            $icon = Display::url(
1602
                Display::return_icon($img, $expl, null, ICON_SIZE_BIG),
1603
                'admin.php?' . api_get_cidreq() . '&' . http_build_query([
1604
                    'newQuestion' => 'yes',
1605
                    'answerType'  => $i,
1606
                    'exerciseId'  => $exerciseId,
1607
                ]),
1608
                ['title' => $expl, 'class' => 'block']
1609
            );
1610
1611
            if (false === $objExercise->force_edit_exercise_in_lp && $objExercise->exercise_was_added_in_lp) {
1612
                $img  = pathinfo($img);
1613
                $img  = $img['filename'].'_na.'.$img['extension'];
1614
                $icon = Display::return_icon($img, $expl, null, ICON_SIZE_BIG);
1615
            }
1616
            echo $icon;
1617
            echo '      </li>';
1618
        }
1619
1620
        echo '      <li class="flex items-center justify-center">';
1621
        if ($objExercise->exercise_was_added_in_lp) {
1622
            echo Display::getMdiIcon('database', 'ch-tool-icon-disabled', null, ICON_SIZE_BIG, get_lang('Recycle existing questions'));
1623
        } else {
1624
            $href = in_array($feedbackType, [EXERCISE_FEEDBACK_TYPE_DIRECT, EXERCISE_FEEDBACK_TYPE_POPUP])
1625
                ? 'question_pool.php?' . api_get_cidreq() . "&type=1&fromExercise={$exerciseId}"
1626
                : 'question_pool.php?' . api_get_cidreq() . "&fromExercise={$exerciseId}";
1627
1628
            echo Display::url(
1629
                Display::getMdiIcon('database', 'ch-tool-icon', null, ICON_SIZE_BIG, get_lang('Recycle existing questions')),
1630
                $href,
1631
                ['class' => 'block', 'title' => get_lang('Recycle existing questions')]
1632
            );
1633
        }
1634
        echo '      </li>';
1635
1636
        echo '    </ul>';
1637
        echo '  </div>';
1638
        echo '</div>';
1639
    }
1640
1641
    /**
1642
     * @param string $name
1643
     * @param int    $position
1644
     *
1645
     * @return CQuizQuestion|null
1646
     */
1647
    public static function saveQuestionOption(CQuizQuestion $question, $name, $position = 0)
1648
    {
1649
        $option = new CQuizQuestionOption();
1650
        $option
1651
            ->setQuestion($question)
1652
            ->setTitle($name)
1653
            ->setPosition($position)
1654
        ;
1655
        $em = Database::getManager();
1656
        $em->persist($option);
1657
        $em->flush();
1658
    }
1659
1660
    /**
1661
     * @param int $question_id
1662
     * @param int $course_id
1663
     */
1664
    public static function deleteAllQuestionOptions($question_id, $course_id)
1665
    {
1666
        $table = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
1667
        Database::delete(
1668
            $table,
1669
            [
1670
                'c_id = ? AND question_id = ?' => [
1671
                    $course_id,
1672
                    $question_id,
1673
                ],
1674
            ]
1675
        );
1676
    }
1677
1678
    /**
1679
     * @param int $question_id
1680
     *
1681
     * @return array
1682
     */
1683
    public static function readQuestionOption($question_id)
1684
    {
1685
        $table = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
1686
1687
        return Database::select(
1688
            '*',
1689
            $table,
1690
            [
1691
                'where' => [
1692
                    'question_id = ?' => [
1693
                        $question_id,
1694
                    ],
1695
                ],
1696
                'order' => 'iid ASC',
1697
            ]
1698
        );
1699
    }
1700
1701
    /**
1702
     * Shows question title an description.
1703
     *
1704
     * @param int   $counter
1705
     * @param array $score
1706
     *
1707
     * @return string HTML string with the header of the question (before the answers table)
1708
     */
1709
    public function return_header(Exercise $exercise, $counter = null, $score = [])
1710
    {
1711
        $counterLabel = '';
1712
        if (!empty($counter)) {
1713
            $counterLabel = (int) $counter;
1714
        }
1715
1716
        $scoreLabel = get_lang('Wrong');
1717
        if (in_array($exercise->results_disabled, [
1718
            RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER,
1719
            RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING,
1720
        ])
1721
        ) {
1722
            $scoreLabel = get_lang('Wrong answer. The correct one was:');
1723
        }
1724
1725
        $class = 'error';
1726
        if (isset($score['pass']) && true == $score['pass']) {
1727
            $scoreLabel = get_lang('Correct');
1728
1729
            if (in_array($exercise->results_disabled, [
1730
                RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER,
1731
                RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING,
1732
            ])
1733
            ) {
1734
                $scoreLabel = get_lang('Correct answer');
1735
            }
1736
            $class = 'success';
1737
        }
1738
1739
        switch ($this->type) {
1740
            case FREE_ANSWER:
1741
            case UPLOAD_ANSWER:
1742
            case ORAL_EXPRESSION:
1743
            case ANNOTATION:
1744
                $score['revised'] = isset($score['revised']) ? $score['revised'] : false;
1745
                if (true == $score['revised']) {
1746
                    $scoreLabel = get_lang('Reviewed');
1747
                    $class = '';
1748
                } else {
1749
                    $scoreLabel = get_lang('Not reviewed');
1750
                    $class = 'warning';
1751
                    if (isset($score['weight'])) {
1752
                        $weight = float_format($score['weight'], 1);
1753
                        $score['result'] = ' ? / '.$weight;
1754
                    }
1755
                    $model = ExerciseLib::getCourseScoreModel();
1756
                    if (!empty($model)) {
1757
                        $score['result'] = ' ? ';
1758
                    }
1759
1760
                    $hide = ('true' === api_get_setting('exercise.hide_free_question_score'));
1761
                    if (true === $hide) {
1762
                        $score['result'] = '-';
1763
                    }
1764
                }
1765
1766
                break;
1767
            case UNIQUE_ANSWER:
1768
                if (in_array($exercise->results_disabled, [
1769
                    RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER,
1770
                    RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING,
1771
                ])
1772
                ) {
1773
                    if (isset($score['user_answered'])) {
1774
                        if (false === $score['user_answered']) {
1775
                            $scoreLabel = get_lang('Unanswered');
1776
                            $class = 'info';
1777
                        }
1778
                    }
1779
                }
1780
1781
                break;
1782
        }
1783
1784
        // display question category, if any
1785
        $header = '';
1786
        if ($exercise->display_category_name) {
1787
            $header = TestCategory::returnCategoryAndTitle($this->id);
1788
        }
1789
        $show_media = '';
1790
        if ($show_media) {
1791
            $header .= $this->show_media_content();
1792
        }
1793
1794
        $scoreCurrent = [
1795
            'used' => isset($score['score']) ? $score['score'] : '',
1796
            'missing' => isset($score['weight']) ? $score['weight'] : '',
1797
        ];
1798
        $header .= Display::page_subheader2($counterLabel.'. '.$this->question);
1799
1800
        $showRibbon = true;
1801
        // dont display score for certainty degree questions
1802
        if (MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY == $this->type) {
1803
            $showRibbon = false;
1804
            $ribbonResult = ('true' === api_get_setting('exercise.show_exercise_question_certainty_ribbon_result'));
1805
            if (true === $ribbonResult) {
1806
                $showRibbon = true;
1807
            }
1808
        }
1809
1810
        if ($showRibbon && isset($score['result'])) {
1811
            if (in_array($exercise->results_disabled, [
1812
                RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER,
1813
                RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING,
1814
            ])
1815
            ) {
1816
                $score['result'] = null;
1817
            }
1818
            $header .= $exercise->getQuestionRibbon($class, $scoreLabel, $score['result'], $scoreCurrent);
1819
        }
1820
1821
        if (READING_COMPREHENSION != $this->type) {
1822
            // Do not show the description (the text to read) if the question is of type READING_COMPREHENSION
1823
            $header .= Display::div(
1824
                $this->description,
1825
                ['class' => 'question-answer-result__header-description']
1826
            );
1827
        } else {
1828
            /** @var ReadingComprehension $this */
1829
            if (true === $score['pass']) {
1830
                $message = Display::div(
1831
                    sprintf(
1832
                        get_lang(
1833
                            'Congratulations, you have reached and correctly understood, at a speed of %s words per minute, a text of a total %s words.'
1834
                        ),
1835
                        ReadingComprehension::$speeds[$this->level],
1836
                        $this->getWordsCount()
1837
                    )
1838
                );
1839
            } else {
1840
                $message = Display::div(
1841
                    sprintf(
1842
                        get_lang(
1843
                            'Sorry, it seems like a speed of %s words/minute was too fast for this text of %s words.'
1844
                        ),
1845
                        ReadingComprehension::$speeds[$this->level],
1846
                        $this->getWordsCount()
1847
                    )
1848
                );
1849
            }
1850
            $header .= $message.'<br />';
1851
        }
1852
1853
        if ($exercise->hideComment && in_array($this->type, [HOT_SPOT, HOT_SPOT_COMBINATION])) {
1854
            $header .= Display::return_message(get_lang('Results only available online'));
1855
1856
            return $header;
1857
        }
1858
1859
        if (isset($score['pass']) && false === $score['pass']) {
1860
            if ($this->showFeedback($exercise)) {
1861
                $header .= $this->returnFormatFeedback();
1862
            }
1863
        }
1864
1865
        return Display::div(
1866
            $header,
1867
            ['class' => 'question-answer-result__header']
1868
        );
1869
    }
1870
1871
    /**
1872
     * @deprecated
1873
     * Create a question from a set of parameters
1874
     *
1875
     * @param int    $question_name        Quiz ID
1876
     * @param string $question_description Question name
1877
     * @param int    $max_score            Maximum result for the question
1878
     * @param int    $type                 Type of question (see constants at beginning of question.class.php)
1879
     * @param int    $level                Question level/category
1880
     * @param string $quiz_id
1881
     */
1882
    public function create_question(
1883
        $quiz_id,
1884
        $question_name,
1885
        $question_description = '',
1886
        $max_score = 0,
1887
        $type = 1,
1888
        $level = 1
1889
    ) {
1890
        $tbl_quiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
1891
        $tbl_quiz_rel_question = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
1892
1893
        $quiz_id = (int) $quiz_id;
1894
        $max_score = (float) $max_score;
1895
        $type = (int) $type;
1896
        $level = (int) $level;
1897
1898
        // Get the max position
1899
        $sql = "SELECT max(position) as max_position
1900
                FROM $tbl_quiz_question q
1901
                INNER JOIN $tbl_quiz_rel_question r
1902
                ON
1903
                    q.iid = r.question_id AND
1904
                    quiz_id = $quiz_id";
1905
        $rs_max = Database::query($sql);
1906
        $row_max = Database::fetch_object($rs_max);
1907
        $max_position = $row_max->max_position + 1;
1908
1909
        $params = [
1910
            'question' => $question_name,
1911
            'description' => $question_description,
1912
            'ponderation' => $max_score,
1913
            'position' => $max_position,
1914
            'type' => $type,
1915
            'level' => $level,
1916
            'mandatory' => 0,
1917
        ];
1918
        $question_id = Database::insert($tbl_quiz_question, $params);
1919
1920
        if ($question_id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $question_id of type false|integer is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
1921
            // Get the max question_order
1922
            $sql = "SELECT max(question_order) as max_order
1923
                    FROM $tbl_quiz_rel_question
1924
                    WHERE quiz_id = $quiz_id ";
1925
            $rs_max_order = Database::query($sql);
1926
            $row_max_order = Database::fetch_object($rs_max_order);
1927
            $max_order = $row_max_order->max_order + 1;
1928
            // Attach questions to quiz
1929
            $sql = "INSERT INTO $tbl_quiz_rel_question (question_id, quiz_id, question_order)
1930
                    VALUES($question_id, $quiz_id, $max_order)";
1931
            Database::query($sql);
1932
        }
1933
1934
        return $question_id;
1935
    }
1936
1937
    /**
1938
     * @return string
1939
     */
1940
    public function getTypePicture()
1941
    {
1942
        return $this->typePicture;
1943
    }
1944
1945
    /**
1946
     * @return string
1947
     */
1948
    public function getExplanation()
1949
    {
1950
        return get_lang($this->explanationLangVar);
1951
    }
1952
1953
    /**
1954
     * Get course medias.
1955
     *
1956
     * @param int $course_id
1957
     *
1958
     * @return array
1959
     */
1960
    public static function get_course_medias(
1961
        $course_id,
1962
        $start = 0,
1963
        $limit = 100,
1964
        $sidx = 'question',
1965
        $sord = 'ASC',
1966
        $where_condition = []
1967
    ) {
1968
        $table_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
1969
        $default_where = [
1970
            'c_id = ? AND parent_id = 0 AND type = ?' => [
1971
                $course_id,
1972
                MEDIA_QUESTION,
1973
            ],
1974
        ];
1975
1976
        return Database::select(
1977
            '*',
1978
            $table_question,
1979
            [
1980
                'limit' => " $start, $limit",
1981
                'where' => $default_where,
1982
                'order' => "$sidx $sord",
1983
            ]
1984
        );
1985
    }
1986
1987
    /**
1988
     * Get count course medias.
1989
     *
1990
     * @param int $course_id course id
1991
     *
1992
     * @return int
1993
     */
1994
    public static function get_count_course_medias($course_id)
1995
    {
1996
        $table_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
1997
        $result = Database::select(
1998
            'count(*) as count',
1999
            $table_question,
2000
            [
2001
                'where' => [
2002
                    'c_id = ? AND parent_id = 0 AND type = ?' => [
2003
                        $course_id,
2004
                        MEDIA_QUESTION,
2005
                    ],
2006
                ],
2007
            ],
2008
            'first'
2009
        );
2010
2011
        if ($result && isset($result['count'])) {
2012
            return $result['count'];
2013
        }
2014
2015
        return 0;
2016
    }
2017
2018
    /**
2019
     * @param int $course_id
2020
     *
2021
     * @return array
2022
     */
2023
    public static function prepare_course_media_select(int $quizId): array
2024
    {
2025
        $tableQuestion     = Database::get_course_table(TABLE_QUIZ_QUESTION);
2026
        $tableRelQuestion  = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
2027
2028
        $medias = Database::select(
2029
            '*',
2030
            "$tableQuestion q
2031
         JOIN $tableRelQuestion rq ON rq.question_id = q.iid",
2032
            [
2033
                'where' => [
2034
                    'rq.quiz_id = ? AND (q.parent_media_id IS NULL OR q.parent_media_id = 0) AND q.type = ?'
2035
                    => [$quizId, MEDIA_QUESTION],
2036
                ],
2037
                'order' => 'question ASC',
2038
            ]
2039
        );
2040
2041
        $mediaList = [
2042
            0 => get_lang('Not linked to media'),
2043
        ];
2044
2045
        foreach ($medias as $media) {
2046
            $mediaList[$media['question_id']] = empty($media['question'])
2047
                ? get_lang('Untitled')
2048
                : $media['question'];
2049
        }
2050
2051
        return $mediaList;
2052
    }
2053
2054
    /**
2055
     * @return array
2056
     */
2057
    public static function get_default_levels()
2058
    {
2059
        return [
2060
            1 => 1,
2061
            2 => 2,
2062
            3 => 3,
2063
            4 => 4,
2064
            5 => 5,
2065
        ];
2066
    }
2067
2068
    /**
2069
     * @return string
2070
     */
2071
    public function show_media_content()
2072
    {
2073
        $html = '';
2074
        if (0 != $this->parent_id) {
2075
            $parent_question = self::read($this->parent_id);
2076
            $html = $parent_question->show_media_content();
2077
        } else {
2078
            $html .= Display::page_subheader($this->selectTitle());
2079
            $html .= $this->selectDescription();
2080
        }
2081
2082
        return $html;
2083
    }
2084
2085
    /**
2086
     * Swap between unique and multiple type answers.
2087
     *
2088
     * @return UniqueAnswer|MultipleAnswer
2089
     */
2090
    public function swapSimpleAnswerTypes()
2091
    {
2092
        $oppositeAnswers = [
2093
            UNIQUE_ANSWER => MULTIPLE_ANSWER,
2094
            MULTIPLE_ANSWER => UNIQUE_ANSWER,
2095
        ];
2096
        $this->type = $oppositeAnswers[$this->type];
2097
        Database::update(
2098
            Database::get_course_table(TABLE_QUIZ_QUESTION),
2099
            ['type' => $this->type],
2100
            ['c_id = ? AND id = ?' => [$this->course['real_id'], $this->id]]
2101
        );
2102
        $answerClasses = [
2103
            UNIQUE_ANSWER => 'UniqueAnswer',
2104
            MULTIPLE_ANSWER => 'MultipleAnswer',
2105
            MULTIPLE_ANSWER_DROPDOWN => 'MultipleAnswerDropdown',
2106
            MULTIPLE_ANSWER_DROPDOWN_COMBINATION => 'MultipleAnswerDropdownCombination',
2107
        ];
2108
        $swappedAnswer = new $answerClasses[$this->type]();
2109
        foreach ($this as $key => $value) {
2110
            $swappedAnswer->$key = $value;
2111
        }
2112
2113
        return $swappedAnswer;
2114
    }
2115
2116
    /**
2117
     * @param array $score
2118
     *
2119
     * @return bool
2120
     */
2121
    public function isQuestionWaitingReview($score)
2122
    {
2123
        $isReview = false;
2124
        if (!empty($score)) {
2125
            if (!empty($score['comments']) || $score['score'] > 0) {
2126
                $isReview = true;
2127
            }
2128
        }
2129
2130
        return $isReview;
2131
    }
2132
2133
    /**
2134
     * @param string $value
2135
     */
2136
    public function setFeedback($value)
2137
    {
2138
        $this->feedback = $value;
2139
    }
2140
2141
    /**
2142
     * @param Exercise $exercise
2143
     *
2144
     * @return bool
2145
     */
2146
    public function showFeedback($exercise)
2147
    {
2148
        if (false === $exercise->hideComment) {
2149
            return false;
2150
        }
2151
2152
        return
2153
            in_array($this->type, $this->questionTypeWithFeedback) &&
2154
            EXERCISE_FEEDBACK_TYPE_EXAM != $exercise->getFeedbackType();
2155
    }
2156
2157
    /**
2158
     * @return string
2159
     */
2160
    public function returnFormatFeedback()
2161
    {
2162
        return '<br />'.Display::return_message($this->feedback, 'normal', false);
2163
    }
2164
2165
    /**
2166
     * Check if this question exists in another exercise.
2167
     *
2168
     * @throws \Doctrine\ORM\Query\QueryException
2169
     *
2170
     * @return bool
2171
     */
2172
    public function existsInAnotherExercise()
2173
    {
2174
        $count = $this->getCountExercise();
2175
2176
        return $count > 1;
2177
    }
2178
2179
    /**
2180
     * @throws \Doctrine\ORM\Query\QueryException
2181
     *
2182
     * @return int
2183
     */
2184
    public function getCountExercise()
2185
    {
2186
        $em = Database::getManager();
2187
2188
        $count = $em
2189
            ->createQuery('
2190
                SELECT COUNT(qq.iid) FROM ChamiloCourseBundle:CQuizRelQuestion qq
2191
                WHERE qq.question = :id
2192
            ')
2193
            ->setParameters(['id' => (int) $this->id])
2194
            ->getSingleScalarResult();
2195
2196
        return (int) $count;
2197
    }
2198
2199
    /**
2200
     * Check if this question exists in another exercise.
2201
     *
2202
     * @throws \Doctrine\ORM\Query\QueryException
2203
     */
2204
    public function getExerciseListWhereQuestionExists()
2205
    {
2206
        $em = Database::getManager();
2207
2208
        return $em
2209
            ->createQuery('
2210
                SELECT e
2211
                FROM ChamiloCourseBundle:CQuizRelQuestion qq
2212
                JOIN ChamiloCourseBundle:CQuiz e
2213
                WHERE e.iid = qq.exerciceId AND qq.questionId = :id
2214
            ')
2215
            ->setParameters(['id' => (int) $this->id])
2216
            ->getResult();
2217
    }
2218
2219
    /**
2220
     * @return int
2221
     */
2222
    public function countAnswers()
2223
    {
2224
        $result = Database::select(
2225
            'COUNT(1) AS c',
2226
            Database::get_course_table(TABLE_QUIZ_ANSWER),
2227
            ['where' => ['question_id = ?' => [$this->id]]],
2228
            'first'
2229
        );
2230
2231
        return (int) $result['c'];
2232
    }
2233
2234
    /**
2235
     * Add adaptive scenario selector fields (success/failure) to the question form.
2236
     *
2237
     * @param FormValidator $form
2238
     * @param array         $questionList List of question IDs from the exercise.
2239
     */
2240
    protected function addAdaptiveScenarioFields(FormValidator $form, array $questionList): void
2241
    {
2242
        // Section header
2243
        $form->addHtml('<h4 class="m-4">'.get_lang('Adaptive behavior (success/failure)').'</h4>');
2244
2245
        // Options for redirection behavior
2246
        $questionListOptions = [
2247
            ''      => get_lang('Select destination'),
2248
            'repeat'=> get_lang('Repeat question'),
2249
            '-1'    => get_lang('End of test'),
2250
            'url'   => get_lang('Other (custom URL)'),
2251
        ];
2252
2253
        // Append available questions to the dropdown
2254
        foreach ($questionList as $index => $qid) {
2255
            if (!is_numeric($qid)) {
2256
                continue;
2257
            }
2258
2259
            $q = self::read((int) $qid);
2260
            if (!$q) {
2261
                continue;
2262
            }
2263
2264
            $questionListOptions[(string) $qid] = 'Q'.$index.': '.strip_tags($q->selectTitle());
2265
        }
2266
2267
        // Success selector and optional URL field
2268
        $form->addSelect(
2269
            'scenario_success_selector',
2270
            get_lang('On success'),
2271
            $questionListOptions,
2272
            ['id' => 'scenario_success_selector']
2273
        );
2274
        $form->addText(
2275
            'scenario_success_url',
2276
            get_lang('Custom URL'),
2277
            false,
2278
            [
2279
                'class'       => 'form-control mb-5',
2280
                'id'          => 'scenario_success_url',
2281
                'placeholder' => '/main/lp/134',
2282
            ]
2283
        );
2284
2285
        // Failure selector and optional URL field
2286
        $form->addSelect(
2287
            'scenario_failure_selector',
2288
            get_lang('On failure'),
2289
            $questionListOptions,
2290
            ['id' => 'scenario_failure_selector']
2291
        );
2292
        $form->addText(
2293
            'scenario_failure_url',
2294
            get_lang('Custom URL'),
2295
            false,
2296
            [
2297
                'class'       => 'form-control mb-5',
2298
                'id'          => 'scenario_failure_url',
2299
                'placeholder' => '/main/lp/134',
2300
            ]
2301
        );
2302
2303
        // JavaScript to toggle custom URL fields when 'url' is selected
2304
        $form->addHtml('
2305
            <script>
2306
                function toggleScenarioUrlFields() {
2307
                    var successSelector = document.getElementById("scenario_success_selector");
2308
                    var successUrlRow = document.getElementById("scenario_success_url").parentNode.parentNode;
2309
2310
                    var failureSelector = document.getElementById("scenario_failure_selector");
2311
                    var failureUrlRow = document.getElementById("scenario_failure_url").parentNode.parentNode;
2312
2313
                    if (successSelector && successSelector.value === "url") {
2314
                        successUrlRow.style.display = "table-row";
2315
                    } else {
2316
                        successUrlRow.style.display = "none";
2317
                    }
2318
2319
                    if (failureSelector && failureSelector.value === "url") {
2320
                        failureUrlRow.style.display = "table-row";
2321
                    } else {
2322
                        failureUrlRow.style.display = "none";
2323
                    }
2324
                }
2325
2326
                document.addEventListener("DOMContentLoaded", toggleScenarioUrlFields);
2327
                document.getElementById("scenario_success_selector")
2328
                    .addEventListener("change", toggleScenarioUrlFields);
2329
                document.getElementById("scenario_failure_selector")
2330
                    .addEventListener("change", toggleScenarioUrlFields);
2331
            </script>
2332
        ');
2333
    }
2334
2335
    /**
2336
     * Persist adaptive scenario (success/failure) configuration for this question.
2337
     *
2338
     * This stores the "destination" JSON in TABLE_QUIZ_TEST_QUESTION for the
2339
     * current (question, exercise) pair. It is intended to be called from
2340
     * processAnswersCreation() implementations.
2341
     *
2342
     * @param FormValidator $form
2343
     * @param Exercise      $exercise
2344
     */
2345
    public function saveAdaptiveScenario(FormValidator $form, Exercise $exercise): void
2346
    {
2347
        // Global feature flag disabled → nothing to do.
2348
        if ('true' !== api_get_setting('enable_quiz_scenario')) {
2349
            return;
2350
        }
2351
2352
        // We only support adaptive scenarios when feedback is "direct".
2353
        if (EXERCISE_FEEDBACK_TYPE_DIRECT !== $exercise->getFeedbackType()) {
2354
            return;
2355
        }
2356
2357
        // This question type is not listed as "scenario capable".
2358
        if (!$this->supportsAdaptiveScenario()) {
2359
            return;
2360
        }
2361
2362
        $successSelector = trim((string) $form->getSubmitValue('scenario_success_selector'));
2363
        $successUrl      = trim((string) $form->getSubmitValue('scenario_success_url'));
2364
        $failureSelector = trim((string) $form->getSubmitValue('scenario_failure_selector'));
2365
        $failureUrl      = trim((string) $form->getSubmitValue('scenario_failure_url'));
2366
2367
        // Map "url" selector to the actual custom URL, keep other values as-is.
2368
        $success = ('url' === $successSelector) ? $successUrl : $successSelector;
2369
        $failure = ('url' === $failureSelector) ? $failureUrl : $failureSelector;
2370
2371
        // If nothing is configured at all, avoid touching the DB.
2372
        if ('' === $success && '' === $failure) {
2373
            return;
2374
        }
2375
2376
        $destination = json_encode(
2377
            [
2378
                'success' => $success ?: '',
2379
                'failure' => $failure ?: '',
2380
            ],
2381
            JSON_UNESCAPED_UNICODE
2382
        );
2383
2384
        $table      = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
2385
        $questionId = (int) $this->id;
2386
        $exerciseId = (int) $exercise->id; // Consistent with existing code in UniqueAnswer
2387
2388
        if ($questionId <= 0 || $exerciseId <= 0) {
2389
            // The (question, exercise) relation does not exist yet.
2390
            return;
2391
        }
2392
2393
        Database::update(
2394
            $table,
2395
            ['destination' => $destination],
2396
            ['question_id = ? AND quiz_id = ?' => [$questionId, $exerciseId]]
2397
        );
2398
    }
2399
2400
    /**
2401
     * Pre-fill adaptive scenario fields from the stored (question, exercise) relation.
2402
     */
2403
    protected function loadAdaptiveScenarioDefaults(FormValidator $form, Exercise $exercise): void
2404
    {
2405
        if ('true' !== api_get_setting('enable_quiz_scenario')) {
2406
            return;
2407
        }
2408
2409
        if (!$this->supportsAdaptiveScenario()) {
2410
            return;
2411
        }
2412
2413
        if (empty($this->id) || empty($exercise->id)) {
2414
            return;
2415
        }
2416
2417
        $table = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
2418
2419
        $row = Database::select(
2420
            'destination',
2421
            $table,
2422
            [
2423
                'where' => [
2424
                    'question_id = ? AND quiz_id = ?' => [
2425
                        (int) $this->id,
2426
                        (int) $exercise->id,
2427
                    ],
2428
                ],
2429
                'limit' => 1,
2430
            ],
2431
            'first'
2432
        );
2433
2434
        if (empty($row['destination'])) {
2435
            return;
2436
        }
2437
2438
        $json = json_decode((string) $row['destination'], true) ?: [];
2439
2440
        $defaults = [];
2441
2442
        if (!empty($json['success'])) {
2443
            if (str_starts_with($json['success'], '/')) {
2444
                $defaults['scenario_success_selector'] = 'url';
2445
                $defaults['scenario_success_url']      = $json['success'];
2446
            } else {
2447
                $defaults['scenario_success_selector'] = $json['success'];
2448
            }
2449
        }
2450
2451
        if (!empty($json['failure'])) {
2452
            if (str_starts_with($json['failure'], '/')) {
2453
                $defaults['scenario_failure_selector'] = 'url';
2454
                $defaults['scenario_failure_url']      = $json['failure'];
2455
            } else {
2456
                $defaults['scenario_failure_selector'] = $json['failure'];
2457
            }
2458
        }
2459
2460
        if (!empty($defaults)) {
2461
            $form->setDefaults($defaults);
2462
        }
2463
    }
2464
2465
    /**
2466
     * Check if this question type supports adaptive scenarios.
2467
     */
2468
    protected function supportsAdaptiveScenario(): bool
2469
    {
2470
        return in_array((int) $this->type, static::$adaptiveScenarioTypes, true);
2471
    }
2472
}
2473