Question::saveCategory()   B
last analyzed

Complexity

Conditions 6
Paths 6

Size

Total Lines 45
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

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

607
                Event::/** @scrutinizer ignore-call */ 
608
                       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...
608
                    LOG_QUESTION_UPDATED,
609
                    LOG_QUESTION_ID,
610
                    $this->iid
611
                );
612
            }
613
        } else {
614
            // Creates a new question
615
            $sql = "SELECT max(position)
616
                    FROM $TBL_QUESTIONS as question,
617
                    $TBL_EXERCISE_QUESTION as test_question
618
                    WHERE
619
                        question.iid = test_question.question_id AND
620
                        test_question.quiz_id = ".$exerciseId;
621
            $result = Database::query($sql);
622
            $current_position = Database::result($result, 0, 0);
623
            $this->updatePosition($current_position + 1);
624
            $position = $this->position;
625
            //$exerciseEntity = $exerciseRepo->find($exerciseId);
626
627
            $question = (new CQuizQuestion())
628
                ->setQuestion($this->question)
629
                ->setDescription($this->description)
630
                ->setPonderation($this->weighting)
631
                ->setPosition($position)
632
                ->setType($this->type)
633
                ->setExtra($this->extra)
634
                ->setLevel((int) $this->level)
635
                ->setFeedback($this->feedback)
636
                ->setParentMediaId($this->parent_id)
637
                ->setParent($courseEntity)
638
                ->setCreator(api_get_user_entity())
639
                ->addCourseLink($courseEntity, api_get_session_entity(), api_get_group_entity());
640
641
            $em->persist($question);
642
            $em->flush();
643
644
            $this->id = $question->getIid();
645
646
            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...
647
                Event::addEvent(
648
                    LOG_QUESTION_CREATED,
649
                    LOG_QUESTION_ID,
650
                    $this->id
651
                );
652
653
                $questionRepo->addFileFromFileRequest($question, 'imageUpload');
654
655
                // If hotspot, create first answer
656
                if (in_array($type, [HOT_SPOT, HOT_SPOT_COMBINATION, HOT_SPOT_ORDER])) {
657
                    $quizAnswer = new CQuizAnswer();
658
                    $quizAnswer
659
                        ->setQuestion($question)
660
                        ->setPonderation(10)
661
                        ->setPosition(1)
662
                        ->setHotspotCoordinates('0;0|0|0')
663
                        ->setHotspotType('square');
664
665
                    $em->persist($quizAnswer);
666
                    $em->flush();
667
                }
668
669
                if (HOT_SPOT_DELINEATION == $type) {
670
                    $quizAnswer = new CQuizAnswer();
671
                    $quizAnswer
672
                        ->setQuestion($question)
673
                        ->setPonderation(10)
674
                        ->setPosition(1)
675
                        ->setHotspotCoordinates('0;0|0|0')
676
                        ->setHotspotType('delineation');
677
678
                    $em->persist($quizAnswer);
679
                    $em->flush();
680
                }
681
            }
682
        }
683
684
        // if the question is created in an exercise
685
        if (!empty($exerciseId)) {
686
            // adds the exercise into the exercise list of this question
687
            $this->addToList($exerciseId, true);
688
        }
689
    }
690
691
    /**
692
     * @param int  $exerciseId
693
     * @param bool $addQs
694
     * @param bool $rmQs
695
     */
696
    public function search_engine_edit(
697
        $exerciseId,
698
        $addQs = false,
699
        $rmQs = false
700
    ) {
701
        // Chamilo 2 uses Symfony-based indexing. Legacy indexer (course_code) is not compatible.
702
        if (class_exists(XapianIndexService::class)) {
703
            return;
704
        }
705
        // update search engine and its values table if enabled
706
        if (!empty($exerciseId) && 'true' == api_get_setting('search_enabled') &&
707
            extension_loaded('xapian')
708
        ) {
709
            $course_id = api_get_course_id();
710
            // get search_did
711
            $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
712
            if ($addQs || $rmQs) {
713
                //there's only one row per question on normal db and one document per question on search engine db
714
                $sql = 'SELECT * FROM %s
715
                    WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_second_level=%s LIMIT 1';
716
                $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
717
            } else {
718
                $sql = 'SELECT * FROM %s
719
                    WHERE course_code=\'%s\' AND tool_id=\'%s\'
720
                    AND ref_id_high_level=%s AND ref_id_second_level=%s LIMIT 1';
721
                $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id);
722
            }
723
            $res = Database::query($sql);
724
725
            if (Database::num_rows($res) > 0 || $addQs) {
726
                $di = new ChamiloIndexer();
727
                if ($addQs) {
728
                    $question_exercises = [(int) $exerciseId];
729
                } else {
730
                    $question_exercises = [];
731
                }
732
                isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : $lang = 'english';
733
                $di->connectDb(null, null, $lang);
734
735
                // retrieve others exercise ids
736
                $se_ref = Database::fetch_array($res);
737
                $se_doc = $di->get_document((int) $se_ref['search_did']);
738
                if (false !== $se_doc) {
739
                    if (false !== ($se_doc_data = $di->get_document_data($se_doc))) {
740
                        $se_doc_data = UnserializeApi::unserialize(
741
                            'not_allowed_classes',
742
                            $se_doc_data
743
                        );
744
                        if (isset($se_doc_data[SE_DATA]['type']) &&
745
                            SE_DOCTYPE_EXERCISE_QUESTION == $se_doc_data[SE_DATA]['type']
746
                        ) {
747
                            if (isset($se_doc_data[SE_DATA]['exercise_ids']) &&
748
                                is_array($se_doc_data[SE_DATA]['exercise_ids'])
749
                            ) {
750
                                foreach ($se_doc_data[SE_DATA]['exercise_ids'] as $old_value) {
751
                                    if (!in_array($old_value, $question_exercises)) {
752
                                        $question_exercises[] = $old_value;
753
                                    }
754
                                }
755
                            }
756
                        }
757
                    }
758
                }
759
                if ($rmQs) {
760
                    while (false !== ($key = array_search($exerciseId, $question_exercises))) {
761
                        unset($question_exercises[$key]);
762
                    }
763
                }
764
765
                // build the chunk to index
766
                $ic_slide = new IndexableChunk();
767
                $ic_slide->addValue('title', $this->question);
768
                $ic_slide->addCourseId($course_id);
769
                $ic_slide->addToolId(TOOL_QUIZ);
770
                $xapian_data = [
771
                    SE_COURSE_ID => $course_id,
772
                    SE_TOOL_ID => TOOL_QUIZ,
773
                    SE_DATA => [
774
                        'type' => SE_DOCTYPE_EXERCISE_QUESTION,
775
                        'exercise_ids' => $question_exercises,
776
                        'question_id' => (int) $this->id,
777
                    ],
778
                    SE_USER => (int) api_get_user_id(),
779
                ];
780
                $ic_slide->xapian_data = serialize($xapian_data);
781
                $ic_slide->addValue('content', $this->description);
782
783
                //TODO: index answers, see also form validation on question_admin.inc.php
784
785
                $di->remove_document($se_ref['search_did']);
786
                $di->addChunk($ic_slide);
787
788
                //index and return search engine document id
789
                if (!empty($question_exercises)) { // if empty there is nothing to index
790
                    $did = $di->index();
791
                    unset($di);
792
                }
793
                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...
794
                    // save it to db
795
                    if ($addQs || $rmQs) {
796
                        $sql = "DELETE FROM %s
797
                            WHERE course_code = '%s' AND tool_id = '%s' AND ref_id_second_level = '%s'";
798
                        $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
799
                    } else {
800
                        $sql = "DELETE FROM %S
801
                            WHERE
802
                                course_code = '%s'
803
                                AND tool_id = '%s'
804
                                AND tool_id = '%s'
805
                                AND ref_id_high_level = '%s'
806
                                AND ref_id_second_level = '%s'";
807
                        $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id);
808
                    }
809
                    Database::query($sql);
810
                    if ($rmQs) {
811
                        if (!empty($question_exercises)) {
812
                            $sql = "INSERT INTO %s (
813
                                    id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did
814
                                )
815
                                VALUES (
816
                                    NULL, '%s', '%s', %s, %s, %s
817
                                )";
818
                            $sql = sprintf(
819
                                $sql,
820
                                $tbl_se_ref,
821
                                $course_id,
822
                                TOOL_QUIZ,
823
                                array_shift($question_exercises),
824
                                $this->id,
825
                                $did
826
                            );
827
                            Database::query($sql);
828
                        }
829
                    } else {
830
                        $sql = "INSERT INTO %s (
831
                                id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did
832
                            )
833
                            VALUES (
834
                                NULL , '%s', '%s', %s, %s, %s
835
                            )";
836
                        $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id, $did);
837
                        Database::query($sql);
838
                    }
839
                }
840
            }
841
        }
842
    }
843
844
    /**
845
     * adds an exercise into the exercise list.
846
     *
847
     * @author Olivier Brouckaert
848
     *
849
     * @param int  $exerciseId - exercise ID
850
     * @param bool $fromSave   - from $this->save() or not
851
     */
852
    public function addToList($exerciseId, $fromSave = false)
853
    {
854
        $exerciseRelQuestionTable = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
855
        $id = (int) $this->id;
856
        $exerciseId = (int) $exerciseId;
857
858
        // checks if the exercise ID is not in the list
859
        if (!empty($exerciseId) && !in_array($exerciseId, $this->exerciseList)) {
860
            $this->exerciseList[] = $exerciseId;
861
            $courseId = isset($this->course['real_id']) ? $this->course['real_id'] : 0;
862
            $newExercise = new Exercise($courseId);
863
            $newExercise->read($exerciseId, false);
864
            $count = $newExercise->getQuestionCount();
865
            $count++;
866
            $sql = "INSERT INTO $exerciseRelQuestionTable (question_id, quiz_id, question_order)
867
                    VALUES (".$id.', '.$exerciseId.", '$count')";
868
            Database::query($sql);
869
870
            // we do not want to reindex if we had just saved adnd indexed the question
871
            if (!$fromSave) {
872
                $this->search_engine_edit($exerciseId, true);
873
            }
874
        }
875
    }
876
877
    /**
878
     * removes an exercise from the exercise list.
879
     *
880
     * @author Olivier Brouckaert
881
     *
882
     * @param int $exerciseId - exercise ID
883
     * @param int $courseId
884
     *
885
     * @return bool - true if removed, otherwise false
886
     */
887
    public function removeFromList($exerciseId, $courseId = 0)
888
    {
889
        $table = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
890
        $tableQuestion = Database::get_course_table(TABLE_QUIZ_QUESTION);
891
        $id = (int) $this->id;
892
        $exerciseId = (int) $exerciseId;
893
894
        // searches the position of the exercise ID in the list
895
        $pos = array_search($exerciseId, $this->exerciseList);
896
        $courseId = empty($courseId) ? api_get_course_int_id() : (int) $courseId;
897
898
        // exercise not found
899
        if (false === $pos) {
900
            return false;
901
        } else {
902
            // deletes the position in the array containing the wanted exercise ID
903
            unset($this->exerciseList[$pos]);
904
            //update order of other elements
905
            $sql = "SELECT question_order
906
                    FROM $table
907
                    WHERE
908
                        question_id = $id AND
909
                        quiz_id = $exerciseId";
910
            $res = Database::query($sql);
911
            if (Database::num_rows($res) > 0) {
912
                $row = Database::fetch_array($res);
913
                if (!empty($row['question_order'])) {
914
                    $sql = "UPDATE $table
915
                            SET question_order = question_order-1
916
                            WHERE
917
                                quiz_id = $exerciseId AND
918
                                question_order > ".$row['question_order'];
919
                    Database::query($sql);
920
                }
921
            }
922
923
            $sql = "DELETE FROM $table
924
                    WHERE
925
                        question_id = $id AND
926
                        quiz_id = $exerciseId";
927
            Database::query($sql);
928
929
            $reset = "UPDATE $tableQuestion
930
                  SET parent_media_id = NULL
931
                  WHERE parent_media_id = $id";
932
            Database::query($reset);
933
934
            return true;
935
        }
936
    }
937
938
    /**
939
     * Deletes a question from the database
940
     * the parameter tells if the question is removed from all exercises (value = 0),
941
     * or just from one exercise (value = exercise ID).
942
     *
943
     * @author Olivier Brouckaert
944
     *
945
     * @param int $deleteFromEx - exercise ID if the question is only removed from one exercise
946
     *
947
     * @return bool
948
     */
949
    public function delete($deleteFromEx = 0)
950
    {
951
        if (empty($this->course)) {
952
            return false;
953
        }
954
955
        $courseId = $this->course['real_id'];
956
957
        if (empty($courseId)) {
958
            return false;
959
        }
960
961
        $TBL_EXERCISE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
962
        $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
963
        $TBL_REPONSES = Database::get_course_table(TABLE_QUIZ_ANSWER);
964
        $TBL_QUIZ_QUESTION_REL_CATEGORY = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
965
966
        $id = (int) $this->id;
967
968
        // if the question must be removed from all exercises
969
        if (!$deleteFromEx) {
970
            //update the question_order of each question to avoid inconsistencies
971
            $sql = "SELECT quiz_id, question_order
972
                    FROM $TBL_EXERCISE_QUESTION
973
                    WHERE question_id = ".$id;
974
975
            $res = Database::query($sql);
976
            if (Database::num_rows($res) > 0) {
977
                while ($row = Database::fetch_array($res)) {
978
                    if (!empty($row['question_order'])) {
979
                        $sql = "UPDATE $TBL_EXERCISE_QUESTION
980
                                SET question_order = question_order-1
981
                                WHERE
982
                                    quiz_id = ".(int) ($row['quiz_id']).' AND
983
                                    question_order > '.$row['question_order'];
984
                        Database::query($sql);
985
                    }
986
                }
987
            }
988
989
            $reset = "UPDATE $TBL_QUESTIONS
990
                  SET parent_media_id = NULL
991
                  WHERE parent_media_id = $id";
992
            Database::query($reset);
993
994
            $sql = "DELETE FROM $TBL_EXERCISE_QUESTION
995
                    WHERE question_id = ".$id;
996
            Database::query($sql);
997
998
            $sql = "DELETE FROM $TBL_QUESTIONS
999
                    WHERE iid = ".$id;
1000
            Database::query($sql);
1001
1002
            $sql = "DELETE FROM $TBL_REPONSES
1003
                    WHERE question_id = ".$id;
1004
            Database::query($sql);
1005
1006
            // remove the category of this question in the question_rel_category table
1007
            $sql = "DELETE FROM $TBL_QUIZ_QUESTION_REL_CATEGORY
1008
                    WHERE
1009
                        question_id = ".$id;
1010
            Database::query($sql);
1011
1012
            // Add extra fields.
1013
            $extraField = new ExtraFieldValue('question');
1014
            $extraField->deleteValuesByItem($this->iid);
1015
1016
            /*api_item_property_update(
1017
                $this->course,
1018
                TOOL_QUIZ,
1019
                $id,
1020
                'QuizQuestionDeleted',
1021
                api_get_user_id()
1022
            );*/
1023
            Event::addEvent(
1024
                LOG_QUESTION_DELETED,
1025
                LOG_QUESTION_ID,
1026
                $this->iid
1027
            );
1028
            //$this->removePicture();
1029
        } else {
1030
            // just removes the exercise from the list
1031
            $this->removeFromList($deleteFromEx, $courseId);
1032
            /*
1033
            api_item_property_update(
1034
                $this->course,
1035
                TOOL_QUIZ,
1036
                $id,
1037
                'QuizQuestionDeleted',
1038
                api_get_user_id()
1039
            );*/
1040
            Event::addEvent(
1041
                LOG_QUESTION_REMOVED_FROM_QUIZ,
1042
                LOG_QUESTION_ID,
1043
                $this->iid
1044
            );
1045
        }
1046
1047
        return true;
1048
    }
1049
1050
    /**
1051
     * Duplicates the question.
1052
     *
1053
     * @author Olivier Brouckaert
1054
     *
1055
     * @param array $courseInfo Course info of the destination course
1056
     *
1057
     * @return false|string ID of the new question
1058
     */
1059
    public function duplicate($courseInfo = [])
1060
    {
1061
        $courseInfo = empty($courseInfo) ? $this->course : $courseInfo;
1062
1063
        if (empty($courseInfo)) {
1064
            return false;
1065
        }
1066
        $TBL_QUESTION_OPTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
1067
1068
        $questionText = $this->question;
1069
        $description = $this->description;
1070
1071
        // Using the same method used in the course copy to transform URLs
1072
        if ($this->course['id'] != $courseInfo['id']) {
1073
            $description = DocumentManager::replaceUrlWithNewCourseCode(
1074
                $description,
1075
                $this->course['code'],
1076
                $courseInfo['id']
1077
            );
1078
            $questionText = DocumentManager::replaceUrlWithNewCourseCode(
1079
                $questionText,
1080
                $this->course['code'],
1081
                $courseInfo['id']
1082
            );
1083
        }
1084
1085
        $course_id = $courseInfo['real_id'];
1086
1087
        // Read the source options
1088
        $options = self::readQuestionOption($this->id, $this->course['real_id']);
1089
1090
        $em = Database::getManager();
1091
        $courseEntity = api_get_course_entity($course_id);
1092
1093
        $question = (new CQuizQuestion())
1094
            ->setQuestion($questionText)
1095
            ->setDescription($description)
1096
            ->setPonderation($this->weighting)
1097
            ->setPosition($this->position)
1098
            ->setType($this->type)
1099
            ->setExtra($this->extra)
1100
            ->setLevel($this->level)
1101
            ->setFeedback($this->feedback)
1102
            ->setParent($courseEntity)
1103
            ->addCourseLink($courseEntity)
1104
        ;
1105
1106
        $em->persist($question);
1107
        $em->flush();
1108
        $newQuestionId = $question->getIid();
1109
1110
        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...
1111
            // Add extra fields.
1112
            $extraField = new ExtraFieldValue('question');
1113
            $extraField->copy($this->iid, $newQuestionId);
1114
1115
            if (!empty($options)) {
1116
                // Saving the quiz_options
1117
                foreach ($options as $item) {
1118
                    $item['question_id'] = $newQuestionId;
1119
                    $item['c_id'] = $course_id;
1120
                    unset($item['iid']);
1121
                    unset($item['iid']);
1122
                    Database::insert($TBL_QUESTION_OPTIONS, $item);
1123
                }
1124
            }
1125
1126
            // Duplicates the picture of the hotspot
1127
            // @todo implement copy of hotspot question
1128
            if (HOT_SPOT == $this->type) {
1129
                throw new Exception('implement copy of hotspot question');
1130
            }
1131
        }
1132
1133
        return $newQuestionId;
1134
    }
1135
1136
    /**
1137
     * @return string
1138
     */
1139
    public function get_question_type_name(): string
1140
    {
1141
        $labelKey = trim((string) $this->explanationLangVar);
1142
        if ($labelKey !== '') {
1143
            $translated = get_lang($labelKey);
1144
            if ($translated !== $labelKey) {
1145
                return $translated;
1146
            }
1147
        }
1148
1149
        $def = self::$questionTypes[$this->type] ?? null;
1150
        $className = is_array($def) ? ($def[1] ?? '') : '';
1151
        if ($className !== '') {
1152
            $human = preg_replace('/(?<!^)(?=[A-Z])/', ' ', $className) ?: $className;
1153
            $translated = get_lang($human);
1154
1155
            return $translated !== $human ? $translated : $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
                // Exclude the classic open question types from the filter list
1561
                // as the system cannot provide immediate feedback on these.
1562
                if (isset($allTypes[FREE_ANSWER])) {
1563
                    unset($allTypes[FREE_ANSWER]);
1564
                }
1565
                if (isset($allTypes[ORAL_EXPRESSION])) {
1566
                    unset($allTypes[ORAL_EXPRESSION]);
1567
                }
1568
                if (isset($allTypes[ANNOTATION])) {
1569
                    unset($allTypes[ANNOTATION]);
1570
                }
1571
                if (isset($allTypes[MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY])) {
1572
                    unset($allTypes[MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY]);
1573
                }
1574
                if (isset($allTypes[UPLOAD_ANSWER])) {
1575
                    unset($allTypes[UPLOAD_ANSWER]);
1576
                }
1577
                if (isset($allTypes[ANSWER_IN_OFFICE_DOC])) {
1578
                    unset($allTypes[ANSWER_IN_OFFICE_DOC]);
1579
                }
1580
                if (isset($allTypes[PAGE_BREAK])) {
1581
                    unset($allTypes[PAGE_BREAK]);
1582
                }
1583
1584
                // Append remaining types, without overriding the original ones.
1585
                foreach ($allTypes as $typeId => $def) {
1586
                    if (!isset($questionTypeList[$typeId])) {
1587
                        $questionTypeList[$typeId] = $def;
1588
                    }
1589
                }
1590
1591
                break;
1592
            case EXERCISE_FEEDBACK_TYPE_POPUP:
1593
                $questionTypeList = [
1594
                    UNIQUE_ANSWER        => self::$questionTypes[UNIQUE_ANSWER],
1595
                    MULTIPLE_ANSWER      => self::$questionTypes[MULTIPLE_ANSWER],
1596
                    DRAGGABLE            => self::$questionTypes[DRAGGABLE],
1597
                    HOT_SPOT_DELINEATION => self::$questionTypes[HOT_SPOT_DELINEATION],
1598
                    CALCULATED_ANSWER    => self::$questionTypes[CALCULATED_ANSWER],
1599
                ];
1600
1601
                break;
1602
            default:
1603
                unset($questionTypeList[HOT_SPOT_DELINEATION]);
1604
1605
                break;
1606
        }
1607
1608
        echo '<div class="card">';
1609
        echo '  <div class="card-body">';
1610
        echo '    <ul class="qtype-menu flex flex-wrap gap-x-2 gap-y-2 items-center justify-start w-full">';
1611
        foreach ($questionTypeList as $i => $type) {
1612
            /** @var Question $type */
1613
            $type = new $type[1]();
1614
            $img  = $type->getTypePicture();
1615
            $expl = $type->getExplanation();
1616
1617
            echo '      <li class="flex items-center justify-center">';
1618
1619
            $icon = Display::url(
1620
                Display::return_icon($img, $expl, null, ICON_SIZE_BIG),
1621
                'admin.php?' . api_get_cidreq() . '&' . http_build_query([
1622
                    'newQuestion' => 'yes',
1623
                    'answerType'  => $i,
1624
                    'exerciseId'  => $exerciseId,
1625
                ]),
1626
                ['title' => $expl, 'class' => 'block']
1627
            );
1628
1629
            if (false === $objExercise->force_edit_exercise_in_lp && $objExercise->exercise_was_added_in_lp) {
1630
                $img  = pathinfo($img);
1631
                $img  = $img['filename'].'_na.'.$img['extension'];
1632
                $icon = Display::return_icon($img, $expl, null, ICON_SIZE_BIG);
1633
            }
1634
            echo $icon;
1635
            echo '      </li>';
1636
        }
1637
1638
        echo '      <li class="flex items-center justify-center">';
1639
        if ($objExercise->exercise_was_added_in_lp) {
1640
            echo Display::getMdiIcon('database', 'ch-tool-icon-disabled', null, ICON_SIZE_BIG, get_lang('Recycle existing questions'));
1641
        } else {
1642
            $href = in_array($feedbackType, [EXERCISE_FEEDBACK_TYPE_DIRECT, EXERCISE_FEEDBACK_TYPE_POPUP])
1643
                ? 'question_pool.php?' . api_get_cidreq() . "&type=1&fromExercise={$exerciseId}"
1644
                : 'question_pool.php?' . api_get_cidreq() . "&fromExercise={$exerciseId}";
1645
1646
            echo Display::url(
1647
                Display::getMdiIcon('database', 'ch-tool-icon', null, ICON_SIZE_BIG, get_lang('Recycle existing questions')),
1648
                $href,
1649
                ['class' => 'block', 'title' => get_lang('Recycle existing questions')]
1650
            );
1651
        }
1652
        echo '      </li>';
1653
1654
        echo '    </ul>';
1655
        echo '  </div>';
1656
        echo '</div>';
1657
    }
1658
1659
    /**
1660
     * @param string $name
1661
     * @param int    $position
1662
     *
1663
     * @return CQuizQuestion|null
1664
     */
1665
    public static function saveQuestionOption(CQuizQuestion $question, $name, $position = 0)
1666
    {
1667
        $option = new CQuizQuestionOption();
1668
        $option
1669
            ->setQuestion($question)
1670
            ->setTitle($name)
1671
            ->setPosition($position)
1672
        ;
1673
        $em = Database::getManager();
1674
        $em->persist($option);
1675
        $em->flush();
1676
    }
1677
1678
    /**
1679
     * @param int $question_id
1680
     * @param int $course_id
1681
     */
1682
    public static function deleteAllQuestionOptions($question_id, $course_id)
1683
    {
1684
        $table = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
1685
        Database::delete(
1686
            $table,
1687
            [
1688
                'c_id = ? AND question_id = ?' => [
1689
                    $course_id,
1690
                    $question_id,
1691
                ],
1692
            ]
1693
        );
1694
    }
1695
1696
    /**
1697
     * @param int $question_id
1698
     *
1699
     * @return array
1700
     */
1701
    public static function readQuestionOption($question_id)
1702
    {
1703
        $table = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
1704
1705
        return Database::select(
1706
            '*',
1707
            $table,
1708
            [
1709
                'where' => [
1710
                    'question_id = ?' => [
1711
                        $question_id,
1712
                    ],
1713
                ],
1714
                'order' => 'iid ASC',
1715
            ]
1716
        );
1717
    }
1718
1719
    /**
1720
     * Shows question title an description.
1721
     *
1722
     * @param int   $counter
1723
     * @param array $score
1724
     *
1725
     * @return string HTML string with the header of the question (before the answers table)
1726
     */
1727
    public function return_header(Exercise $exercise, $counter = null, $score = [])
1728
    {
1729
        $counterLabel = '';
1730
        if (!empty($counter)) {
1731
            $counterLabel = (int) $counter;
1732
        }
1733
1734
        $scoreLabel = get_lang('Wrong');
1735
        if (in_array($exercise->results_disabled, [
1736
            RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER,
1737
            RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING,
1738
        ])
1739
        ) {
1740
            $scoreLabel = get_lang('Wrong answer. The correct one was:');
1741
        }
1742
1743
        $class = 'error';
1744
        if (isset($score['pass']) && true == $score['pass']) {
1745
            $scoreLabel = get_lang('Correct');
1746
1747
            if (in_array($exercise->results_disabled, [
1748
                RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER,
1749
                RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING,
1750
            ])
1751
            ) {
1752
                $scoreLabel = get_lang('Correct answer');
1753
            }
1754
            $class = 'success';
1755
        }
1756
1757
        switch ($this->type) {
1758
            case FREE_ANSWER:
1759
            case UPLOAD_ANSWER:
1760
            case ORAL_EXPRESSION:
1761
            case ANNOTATION:
1762
                $score['revised'] = isset($score['revised']) ? $score['revised'] : false;
1763
                if (true == $score['revised']) {
1764
                    $scoreLabel = get_lang('Reviewed');
1765
                    $class = '';
1766
                } else {
1767
                    $scoreLabel = get_lang('Not reviewed');
1768
                    $class = 'warning';
1769
                    if (isset($score['weight'])) {
1770
                        $weight = float_format($score['weight'], 1);
1771
                        $score['result'] = ' ? / '.$weight;
1772
                    }
1773
                    $model = ExerciseLib::getCourseScoreModel();
1774
                    if (!empty($model)) {
1775
                        $score['result'] = ' ? ';
1776
                    }
1777
1778
                    $hide = ('true' === api_get_setting('exercise.hide_free_question_score'));
1779
                    if (true === $hide) {
1780
                        $score['result'] = '-';
1781
                    }
1782
                }
1783
1784
                break;
1785
            case UNIQUE_ANSWER:
1786
                if (in_array($exercise->results_disabled, [
1787
                    RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER,
1788
                    RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING,
1789
                ])
1790
                ) {
1791
                    if (isset($score['user_answered'])) {
1792
                        if (false === $score['user_answered']) {
1793
                            $scoreLabel = get_lang('Unanswered');
1794
                            $class = 'info';
1795
                        }
1796
                    }
1797
                }
1798
1799
                break;
1800
        }
1801
1802
        // display question category, if any
1803
        $header = '';
1804
        if ($exercise->display_category_name) {
1805
            $header = TestCategory::returnCategoryAndTitle($this->id);
1806
        }
1807
        $show_media = '';
1808
        if ($show_media) {
1809
            $header .= $this->show_media_content();
1810
        }
1811
1812
        $scoreCurrent = [
1813
            'used' => isset($score['score']) ? $score['score'] : '',
1814
            'missing' => isset($score['weight']) ? $score['weight'] : '',
1815
        ];
1816
        $header .= Display::page_subheader2($counterLabel.'. '.$this->question);
1817
1818
        $showRibbon = true;
1819
        // dont display score for certainty degree questions
1820
        if (MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY == $this->type) {
1821
            $showRibbon = false;
1822
            $ribbonResult = ('true' === api_get_setting('exercise.show_exercise_question_certainty_ribbon_result'));
1823
            if (true === $ribbonResult) {
1824
                $showRibbon = true;
1825
            }
1826
        }
1827
1828
        if ($showRibbon && isset($score['result'])) {
1829
            if (in_array($exercise->results_disabled, [
1830
                RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER,
1831
                RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING,
1832
            ])
1833
            ) {
1834
                $score['result'] = null;
1835
            }
1836
            $header .= $exercise->getQuestionRibbon($class, $scoreLabel, $score['result'], $scoreCurrent);
1837
        }
1838
1839
        if (READING_COMPREHENSION != $this->type) {
1840
            // Do not show the description (the text to read) if the question is of type READING_COMPREHENSION
1841
            $header .= Display::div(
1842
                $this->description,
1843
                ['class' => 'question-answer-result__header-description']
1844
            );
1845
        } else {
1846
            /** @var ReadingComprehension $this */
1847
            if (true === $score['pass']) {
1848
                $message = Display::div(
1849
                    sprintf(
1850
                        get_lang(
1851
                            'Congratulations, you have reached and correctly understood, at a speed of %s words per minute, a text of a total %s words.'
1852
                        ),
1853
                        ReadingComprehension::$speeds[$this->level],
1854
                        $this->getWordsCount()
1855
                    )
1856
                );
1857
            } else {
1858
                $message = Display::div(
1859
                    sprintf(
1860
                        get_lang(
1861
                            'Sorry, it seems like a speed of %s words/minute was too fast for this text of %s words.'
1862
                        ),
1863
                        ReadingComprehension::$speeds[$this->level],
1864
                        $this->getWordsCount()
1865
                    )
1866
                );
1867
            }
1868
            $header .= $message.'<br />';
1869
        }
1870
1871
        if ($exercise->hideComment && in_array($this->type, [HOT_SPOT, HOT_SPOT_COMBINATION])) {
1872
            $header .= Display::return_message(get_lang('Results only available online'));
1873
1874
            return $header;
1875
        }
1876
1877
        if (isset($score['pass']) && false === $score['pass']) {
1878
            if ($this->showFeedback($exercise)) {
1879
                $header .= $this->returnFormatFeedback();
1880
            }
1881
        }
1882
1883
        return Display::div(
1884
            $header,
1885
            ['class' => 'question-answer-result__header']
1886
        );
1887
    }
1888
1889
    /**
1890
     * @deprecated
1891
     * Create a question from a set of parameters
1892
     *
1893
     * @param int    $question_name        Quiz ID
1894
     * @param string $question_description Question name
1895
     * @param int    $max_score            Maximum result for the question
1896
     * @param int    $type                 Type of question (see constants at beginning of question.class.php)
1897
     * @param int    $level                Question level/category
1898
     * @param string $quiz_id
1899
     */
1900
    public function create_question(
1901
        $quiz_id,
1902
        $question_name,
1903
        $question_description = '',
1904
        $max_score = 0,
1905
        $type = 1,
1906
        $level = 1
1907
    ) {
1908
        $tbl_quiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
1909
        $tbl_quiz_rel_question = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
1910
1911
        $quiz_id = (int) $quiz_id;
1912
        $max_score = (float) $max_score;
1913
        $type = (int) $type;
1914
        $level = (int) $level;
1915
1916
        // Get the max position
1917
        $sql = "SELECT max(position) as max_position
1918
                FROM $tbl_quiz_question q
1919
                INNER JOIN $tbl_quiz_rel_question r
1920
                ON
1921
                    q.iid = r.question_id AND
1922
                    quiz_id = $quiz_id";
1923
        $rs_max = Database::query($sql);
1924
        $row_max = Database::fetch_object($rs_max);
1925
        $max_position = $row_max->max_position + 1;
1926
1927
        $params = [
1928
            'question' => $question_name,
1929
            'description' => $question_description,
1930
            'ponderation' => $max_score,
1931
            'position' => $max_position,
1932
            'type' => $type,
1933
            'level' => $level,
1934
            'mandatory' => 0,
1935
        ];
1936
        $question_id = Database::insert($tbl_quiz_question, $params);
1937
1938
        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...
1939
            // Get the max question_order
1940
            $sql = "SELECT max(question_order) as max_order
1941
                    FROM $tbl_quiz_rel_question
1942
                    WHERE quiz_id = $quiz_id ";
1943
            $rs_max_order = Database::query($sql);
1944
            $row_max_order = Database::fetch_object($rs_max_order);
1945
            $max_order = $row_max_order->max_order + 1;
1946
            // Attach questions to quiz
1947
            $sql = "INSERT INTO $tbl_quiz_rel_question (question_id, quiz_id, question_order)
1948
                    VALUES($question_id, $quiz_id, $max_order)";
1949
            Database::query($sql);
1950
        }
1951
1952
        return $question_id;
1953
    }
1954
1955
    /**
1956
     * @return string
1957
     */
1958
    public function getTypePicture()
1959
    {
1960
        return $this->typePicture;
1961
    }
1962
1963
    /**
1964
     * @return string
1965
     */
1966
    public function getExplanation()
1967
    {
1968
        return get_lang($this->explanationLangVar);
1969
    }
1970
1971
    /**
1972
     * Get course medias.
1973
     *
1974
     * @param int $course_id
1975
     *
1976
     * @return array
1977
     */
1978
    public static function get_course_medias(
1979
        $course_id,
1980
        $start = 0,
1981
        $limit = 100,
1982
        $sidx = 'question',
1983
        $sord = 'ASC',
1984
        $where_condition = []
1985
    ) {
1986
        $table_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
1987
        $default_where = [
1988
            'c_id = ? AND parent_id = 0 AND type = ?' => [
1989
                $course_id,
1990
                MEDIA_QUESTION,
1991
            ],
1992
        ];
1993
1994
        return Database::select(
1995
            '*',
1996
            $table_question,
1997
            [
1998
                'limit' => " $start, $limit",
1999
                'where' => $default_where,
2000
                'order' => "$sidx $sord",
2001
            ]
2002
        );
2003
    }
2004
2005
    /**
2006
     * Get count course medias.
2007
     *
2008
     * @param int $course_id course id
2009
     *
2010
     * @return int
2011
     */
2012
    public static function get_count_course_medias($course_id)
2013
    {
2014
        $table_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
2015
        $result = Database::select(
2016
            'count(*) as count',
2017
            $table_question,
2018
            [
2019
                'where' => [
2020
                    'c_id = ? AND parent_id = 0 AND type = ?' => [
2021
                        $course_id,
2022
                        MEDIA_QUESTION,
2023
                    ],
2024
                ],
2025
            ],
2026
            'first'
2027
        );
2028
2029
        if ($result && isset($result['count'])) {
2030
            return $result['count'];
2031
        }
2032
2033
        return 0;
2034
    }
2035
2036
    /**
2037
     * @param int $course_id
2038
     *
2039
     * @return array
2040
     */
2041
    public static function prepare_course_media_select(int $quizId): array
2042
    {
2043
        $tableQuestion     = Database::get_course_table(TABLE_QUIZ_QUESTION);
2044
        $tableRelQuestion  = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
2045
2046
        $medias = Database::select(
2047
            '*',
2048
            "$tableQuestion q
2049
         JOIN $tableRelQuestion rq ON rq.question_id = q.iid",
2050
            [
2051
                'where' => [
2052
                    'rq.quiz_id = ? AND (q.parent_media_id IS NULL OR q.parent_media_id = 0) AND q.type = ?'
2053
                    => [$quizId, MEDIA_QUESTION],
2054
                ],
2055
                'order' => 'question ASC',
2056
            ]
2057
        );
2058
2059
        $mediaList = [
2060
            0 => get_lang('Not linked to media'),
2061
        ];
2062
2063
        foreach ($medias as $media) {
2064
            $mediaList[$media['question_id']] = empty($media['question'])
2065
                ? get_lang('Untitled')
2066
                : $media['question'];
2067
        }
2068
2069
        return $mediaList;
2070
    }
2071
2072
    /**
2073
     * @return array
2074
     */
2075
    public static function get_default_levels()
2076
    {
2077
        return [
2078
            1 => 1,
2079
            2 => 2,
2080
            3 => 3,
2081
            4 => 4,
2082
            5 => 5,
2083
        ];
2084
    }
2085
2086
    /**
2087
     * @return string
2088
     */
2089
    public function show_media_content()
2090
    {
2091
        $html = '';
2092
        if (0 != $this->parent_id) {
2093
            $parent_question = self::read($this->parent_id);
2094
            $html = $parent_question->show_media_content();
2095
        } else {
2096
            $html .= Display::page_subheader($this->selectTitle());
2097
            $html .= $this->selectDescription();
2098
        }
2099
2100
        return $html;
2101
    }
2102
2103
    /**
2104
     * Swap between unique and multiple type answers.
2105
     *
2106
     * @return UniqueAnswer|MultipleAnswer
2107
     */
2108
    public function swapSimpleAnswerTypes()
2109
    {
2110
        $oppositeAnswers = [
2111
            UNIQUE_ANSWER => MULTIPLE_ANSWER,
2112
            MULTIPLE_ANSWER => UNIQUE_ANSWER,
2113
        ];
2114
        $this->type = $oppositeAnswers[$this->type];
2115
        Database::update(
2116
            Database::get_course_table(TABLE_QUIZ_QUESTION),
2117
            ['type' => $this->type],
2118
            ['c_id = ? AND id = ?' => [$this->course['real_id'], $this->id]]
2119
        );
2120
        $answerClasses = [
2121
            UNIQUE_ANSWER => 'UniqueAnswer',
2122
            MULTIPLE_ANSWER => 'MultipleAnswer',
2123
            MULTIPLE_ANSWER_DROPDOWN => 'MultipleAnswerDropdown',
2124
            MULTIPLE_ANSWER_DROPDOWN_COMBINATION => 'MultipleAnswerDropdownCombination',
2125
        ];
2126
        $swappedAnswer = new $answerClasses[$this->type]();
2127
        foreach ($this as $key => $value) {
2128
            $swappedAnswer->$key = $value;
2129
        }
2130
2131
        return $swappedAnswer;
2132
    }
2133
2134
    /**
2135
     * @param array $score
2136
     *
2137
     * @return bool
2138
     */
2139
    public function isQuestionWaitingReview($score)
2140
    {
2141
        $isReview = false;
2142
        if (!empty($score)) {
2143
            if (!empty($score['comments']) || $score['score'] > 0) {
2144
                $isReview = true;
2145
            }
2146
        }
2147
2148
        return $isReview;
2149
    }
2150
2151
    /**
2152
     * @param string $value
2153
     */
2154
    public function setFeedback($value)
2155
    {
2156
        $this->feedback = $value;
2157
    }
2158
2159
    /**
2160
     * @param Exercise $exercise
2161
     *
2162
     * @return bool
2163
     */
2164
    public function showFeedback($exercise)
2165
    {
2166
        if (false === $exercise->hideComment) {
2167
            return false;
2168
        }
2169
2170
        return
2171
            in_array($this->type, $this->questionTypeWithFeedback) &&
2172
            EXERCISE_FEEDBACK_TYPE_EXAM != $exercise->getFeedbackType();
2173
    }
2174
2175
    /**
2176
     * @return string
2177
     */
2178
    public function returnFormatFeedback()
2179
    {
2180
        return '<br />'.Display::return_message($this->feedback, 'normal', false);
2181
    }
2182
2183
    /**
2184
     * Check if this question exists in another exercise.
2185
     *
2186
     * @throws \Doctrine\ORM\Query\QueryException
2187
     *
2188
     * @return bool
2189
     */
2190
    public function existsInAnotherExercise()
2191
    {
2192
        $count = $this->getCountExercise();
2193
2194
        return $count > 1;
2195
    }
2196
2197
    /**
2198
     * @throws \Doctrine\ORM\Query\QueryException
2199
     *
2200
     * @return int
2201
     */
2202
    public function getCountExercise()
2203
    {
2204
        $em = Database::getManager();
2205
2206
        $count = $em
2207
            ->createQuery('
2208
            SELECT COUNT(qq.iid)
2209
            FROM ChamiloCourseBundle:CQuizRelQuestion qq
2210
            WHERE IDENTITY(qq.question) = :id
2211
        ')
2212
            ->setParameters(['id' => (int) $this->id])
2213
            ->getSingleScalarResult();
2214
2215
        return (int) $count;
2216
    }
2217
2218
    /**
2219
     * Check if this question exists in another exercise.
2220
     *
2221
     * @throws \Doctrine\ORM\Query\QueryException
2222
     */
2223
    public function getExerciseListWhereQuestionExists(): array
2224
    {
2225
        $em = Database::getManager();
2226
        $questionId = (int) $this->id;
2227
2228
        // Doctrine does not allow selecting only a JOIN alias unless it is a root alias.
2229
        // So we select CQuiz as root and join the relation entity with a WITH clause.
2230
        $dql = '
2231
        SELECT DISTINCT q
2232
        FROM ChamiloCourseBundle:CQuiz q
2233
        JOIN ChamiloCourseBundle:CQuizRelQuestion qq WITH qq.quiz = q
2234
        WHERE IDENTITY(qq.question) = :id
2235
    ';
2236
2237
        try {
2238
            return $em->createQuery($dql)
2239
                ->setParameter('id', $questionId)
2240
                ->getResult();
2241
        } catch (\Throwable $e) {
2242
            // Fallback (best effort): use DBAL on the relation table and then load quizzes.
2243
            // We keep this non-fatal to avoid breaking the admin listing.
2244
        }
2245
2246
        try {
2247
            $conn = Database::getConnection();
2248
2249
            // DBAL 2/3 schema manager compatibility
2250
            $sm = method_exists($conn, 'createSchemaManager')
2251
                ? $conn->createSchemaManager()
2252
                : $conn->getSchemaManager();
2253
2254
            $tableNames = method_exists($sm, 'listTableNames') ? $sm->listTableNames() : [];
2255
2256
            $relCandidates = [
2257
                'c_quiz_rel_question',
2258
                'quiz_rel_question',
2259
                'c_quiz_question_rel_exercise',
2260
                'quiz_question_rel_exercise',
2261
            ];
2262
2263
            $relTable = null;
2264
            foreach ($relCandidates as $t) {
2265
                if (\in_array($t, $tableNames, true)) {
2266
                    $relTable = $t;
2267
                    break;
2268
                }
2269
            }
2270
2271
            if (empty($relTable)) {
2272
                return [];
2273
            }
2274
2275
            // Detect the exercise/quiz id column name
2276
            $columns = [];
2277
            try {
2278
                foreach ($sm->listTableColumns($relTable) as $colName => $col) {
2279
                    $columns[] = $colName;
2280
                }
2281
            } catch (\Throwable $e) {
2282
                $columns = [];
2283
            }
2284
2285
            $qCol = \in_array('question_id', $columns, true) ? 'question_id' : 'question_id';
2286
            $eCol = null;
2287
            foreach (['quiz_id', 'exercise_id', 'exercice_id', 'quizid'] as $c) {
2288
                if (\in_array($c, $columns, true)) {
2289
                    $eCol = $c;
2290
                    break;
2291
                }
2292
            }
2293
            if (null === $eCol) {
2294
                return [];
2295
            }
2296
2297
            $sql = "SELECT DISTINCT $eCol AS quiz_id FROM $relTable WHERE $qCol = ?";
2298
2299
            // DBAL 3: fetchFirstColumn, DBAL 2: fetchAll
2300
            if (method_exists($conn, 'fetchFirstColumn')) {
2301
                $ids = $conn->fetchFirstColumn($sql, [$questionId]);
2302
            } else {
2303
                $rows = (array) $conn->fetchAll($sql, [$questionId]);
2304
                $ids = [];
2305
                foreach ($rows as $r) {
2306
                    $ids[] = (int) ($r['quiz_id'] ?? (is_array($r) ? reset($r) : 0));
2307
                }
2308
            }
2309
2310
            $ids = array_values(array_filter(array_map('intval', (array) $ids), static fn ($v) => $v > 0));
2311
            if (empty($ids)) {
2312
                return [];
2313
            }
2314
2315
            // Load quizzes by ids (iid is the usual PK in Chamilo entities)
2316
            return $em->getRepository(\Chamilo\CourseBundle\Entity\CQuiz::class)->findBy(['iid' => $ids]);
2317
        } catch (\Throwable $e) {
2318
            return [];
2319
        }
2320
    }
2321
2322
    /**
2323
     * @return int
2324
     */
2325
    public function countAnswers()
2326
    {
2327
        $result = Database::select(
2328
            'COUNT(1) AS c',
2329
            Database::get_course_table(TABLE_QUIZ_ANSWER),
2330
            ['where' => ['question_id = ?' => [$this->id]]],
2331
            'first'
2332
        );
2333
2334
        return (int) $result['c'];
2335
    }
2336
2337
    /**
2338
     * Add adaptive scenario selector fields (success/failure) to the question form.
2339
     *
2340
     * @param FormValidator $form
2341
     * @param array         $questionList List of question IDs from the exercise.
2342
     */
2343
    protected function addAdaptiveScenarioFields(FormValidator $form, array $questionList): void
2344
    {
2345
        // Section header
2346
        $form->addHtml('<h4 class="m-4">'.get_lang('Adaptive behavior (success/failure)').'</h4>');
2347
2348
        // Options for redirection behavior
2349
        $questionListOptions = [
2350
            ''      => get_lang('Select destination'),
2351
            'repeat'=> get_lang('Repeat question'),
2352
            '-1'    => get_lang('End of test'),
2353
            'url'   => get_lang('Other (custom URL)'),
2354
        ];
2355
2356
        // Append available questions to the dropdown
2357
        foreach ($questionList as $index => $qid) {
2358
            if (!is_numeric($qid)) {
2359
                continue;
2360
            }
2361
2362
            $q = self::read((int) $qid);
2363
            if (!$q) {
2364
                continue;
2365
            }
2366
2367
            $questionListOptions[(string) $qid] = 'Q'.$index.': '.strip_tags($q->selectTitle());
2368
        }
2369
2370
        // Success selector and optional URL field
2371
        $form->addSelect(
2372
            'scenario_success_selector',
2373
            get_lang('On success'),
2374
            $questionListOptions,
2375
            ['id' => 'scenario_success_selector']
2376
        );
2377
        $form->addText(
2378
            'scenario_success_url',
2379
            get_lang('Custom URL'),
2380
            false,
2381
            [
2382
                'class'       => 'form-control mb-5',
2383
                'id'          => 'scenario_success_url',
2384
                'placeholder' => '/main/lp/134',
2385
            ]
2386
        );
2387
2388
        // Failure selector and optional URL field
2389
        $form->addSelect(
2390
            'scenario_failure_selector',
2391
            get_lang('On failure'),
2392
            $questionListOptions,
2393
            ['id' => 'scenario_failure_selector']
2394
        );
2395
        $form->addText(
2396
            'scenario_failure_url',
2397
            get_lang('Custom URL'),
2398
            false,
2399
            [
2400
                'class'       => 'form-control mb-5',
2401
                'id'          => 'scenario_failure_url',
2402
                'placeholder' => '/main/lp/134',
2403
            ]
2404
        );
2405
2406
        // JavaScript to toggle custom URL fields when 'url' is selected
2407
        $form->addHtml('
2408
            <script>
2409
                function toggleScenarioUrlFields() {
2410
                    var successSelector = document.getElementById("scenario_success_selector");
2411
                    var successUrlRow = document.getElementById("scenario_success_url").parentNode.parentNode;
2412
2413
                    var failureSelector = document.getElementById("scenario_failure_selector");
2414
                    var failureUrlRow = document.getElementById("scenario_failure_url").parentNode.parentNode;
2415
2416
                    if (successSelector && successSelector.value === "url") {
2417
                        successUrlRow.style.display = "table-row";
2418
                    } else {
2419
                        successUrlRow.style.display = "none";
2420
                    }
2421
2422
                    if (failureSelector && failureSelector.value === "url") {
2423
                        failureUrlRow.style.display = "table-row";
2424
                    } else {
2425
                        failureUrlRow.style.display = "none";
2426
                    }
2427
                }
2428
2429
                document.addEventListener("DOMContentLoaded", toggleScenarioUrlFields);
2430
                document.getElementById("scenario_success_selector")
2431
                    .addEventListener("change", toggleScenarioUrlFields);
2432
                document.getElementById("scenario_failure_selector")
2433
                    .addEventListener("change", toggleScenarioUrlFields);
2434
            </script>
2435
        ');
2436
    }
2437
2438
    /**
2439
     * Persist adaptive scenario (success/failure) configuration for this question.
2440
     *
2441
     * This stores the "destination" JSON in TABLE_QUIZ_TEST_QUESTION for the
2442
     * current (question, exercise) pair. It is intended to be called from
2443
     * processAnswersCreation() implementations.
2444
     *
2445
     * @param FormValidator $form
2446
     * @param Exercise      $exercise
2447
     */
2448
    public function saveAdaptiveScenario(FormValidator $form, Exercise $exercise): void
2449
    {
2450
        // Global feature flag disabled → nothing to do.
2451
        if ('true' !== api_get_setting('enable_quiz_scenario')) {
2452
            return;
2453
        }
2454
2455
        // We only support adaptive scenarios when feedback is "direct".
2456
        if (EXERCISE_FEEDBACK_TYPE_DIRECT !== $exercise->getFeedbackType()) {
2457
            return;
2458
        }
2459
2460
        // This question type is not listed as "scenario capable".
2461
        if (!$this->supportsAdaptiveScenario()) {
2462
            return;
2463
        }
2464
2465
        $successSelector = trim((string) $form->getSubmitValue('scenario_success_selector'));
2466
        $successUrl      = trim((string) $form->getSubmitValue('scenario_success_url'));
2467
        $failureSelector = trim((string) $form->getSubmitValue('scenario_failure_selector'));
2468
        $failureUrl      = trim((string) $form->getSubmitValue('scenario_failure_url'));
2469
2470
        // Map "url" selector to the actual custom URL, keep other values as-is.
2471
        $success = ('url' === $successSelector) ? $successUrl : $successSelector;
2472
        $failure = ('url' === $failureSelector) ? $failureUrl : $failureSelector;
2473
2474
        // If nothing is configured at all, avoid touching the DB.
2475
        if ('' === $success && '' === $failure) {
2476
            return;
2477
        }
2478
2479
        $destination = json_encode(
2480
            [
2481
                'success' => $success ?: '',
2482
                'failure' => $failure ?: '',
2483
            ],
2484
            JSON_UNESCAPED_UNICODE
2485
        );
2486
2487
        $table      = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
2488
        $questionId = (int) $this->id;
2489
        $exerciseId = (int) $exercise->id; // Consistent with existing code in UniqueAnswer
2490
2491
        if ($questionId <= 0 || $exerciseId <= 0) {
2492
            // The (question, exercise) relation does not exist yet.
2493
            return;
2494
        }
2495
2496
        Database::update(
2497
            $table,
2498
            ['destination' => $destination],
2499
            ['question_id = ? AND quiz_id = ?' => [$questionId, $exerciseId]]
2500
        );
2501
    }
2502
2503
    /**
2504
     * Pre-fill adaptive scenario fields from the stored (question, exercise) relation.
2505
     */
2506
    protected function loadAdaptiveScenarioDefaults(FormValidator $form, Exercise $exercise): void
2507
    {
2508
        if ('true' !== api_get_setting('enable_quiz_scenario')) {
2509
            return;
2510
        }
2511
2512
        if (!$this->supportsAdaptiveScenario()) {
2513
            return;
2514
        }
2515
2516
        if (empty($this->id) || empty($exercise->id)) {
2517
            return;
2518
        }
2519
2520
        $table = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
2521
2522
        $row = Database::select(
2523
            'destination',
2524
            $table,
2525
            [
2526
                'where' => [
2527
                    'question_id = ? AND quiz_id = ?' => [
2528
                        (int) $this->id,
2529
                        (int) $exercise->id,
2530
                    ],
2531
                ],
2532
                'limit' => 1,
2533
            ],
2534
            'first'
2535
        );
2536
2537
        if (empty($row['destination'])) {
2538
            return;
2539
        }
2540
2541
        $json = json_decode((string) $row['destination'], true) ?: [];
2542
2543
        $defaults = [];
2544
2545
        if (!empty($json['success'])) {
2546
            if (str_starts_with($json['success'], '/')) {
2547
                $defaults['scenario_success_selector'] = 'url';
2548
                $defaults['scenario_success_url']      = $json['success'];
2549
            } else {
2550
                $defaults['scenario_success_selector'] = $json['success'];
2551
            }
2552
        }
2553
2554
        if (!empty($json['failure'])) {
2555
            if (str_starts_with($json['failure'], '/')) {
2556
                $defaults['scenario_failure_selector'] = 'url';
2557
                $defaults['scenario_failure_url']      = $json['failure'];
2558
            } else {
2559
                $defaults['scenario_failure_selector'] = $json['failure'];
2560
            }
2561
        }
2562
2563
        if (!empty($defaults)) {
2564
            $form->setDefaults($defaults);
2565
        }
2566
    }
2567
2568
    /**
2569
     * Check if this question type supports adaptive scenarios.
2570
     */
2571
    protected function supportsAdaptiveScenario(): bool
2572
    {
2573
        return in_array((int) $this->type, static::$adaptiveScenarioTypes, true);
2574
    }
2575
}
2576