Passed
Push — master ( 4f94a6...d3ab1d )
by Julito
09:11
created

Question::setExtra()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Framework\Container;
6
use Chamilo\CourseBundle\Entity\CQuizAnswer;
7
use Chamilo\CourseBundle\Entity\CQuizQuestion;
8
9
/**
10
 * Class Question.
11
 *
12
 * This class allows to instantiate an object of type Question
13
 *
14
 * @author Olivier Brouckaert, original author
15
 * @author Patrick Cool, LaTeX support
16
 * @author Julio Montoya <[email protected]> lot of bug fixes
17
 * @author [email protected] - add question categories
18
 */
19
abstract class Question
20
{
21
    public $id;
22
    public $iid;
23
    public $question;
24
    public $description;
25
    public $weighting;
26
    public $position;
27
    public $type;
28
    public $level;
29
    public $picture;
30
    public $exerciseList; // array with the list of exercises which this question is in
31
    public $category_list;
32
    public $parent_id;
33
    public $category;
34
    public $mandatory;
35
    public $isContent;
36
    public $course;
37
    public $feedback;
38
    public $typePicture = 'new_question.png';
39
    public $explanationLangVar = '';
40
    public $question_table_class = 'table table-striped';
41
    public $questionTypeWithFeedback;
42
    public $extra;
43
    public $export = false;
44
    public $code;
45
    public static $questionTypes = [
46
        UNIQUE_ANSWER => ['unique_answer.class.php', 'UniqueAnswer'],
47
        MULTIPLE_ANSWER => ['multiple_answer.class.php', 'MultipleAnswer'],
48
        FILL_IN_BLANKS => ['fill_blanks.class.php', 'FillBlanks'],
49
        MATCHING => ['matching.class.php', 'Matching'],
50
        FREE_ANSWER => ['freeanswer.class.php', 'FreeAnswer'],
51
        ORAL_EXPRESSION => ['oral_expression.class.php', 'OralExpression'],
52
        HOT_SPOT => ['hotspot.class.php', 'HotSpot'],
53
        HOT_SPOT_DELINEATION => ['HotSpotDelineation.php', 'HotSpotDelineation'],
54
        MULTIPLE_ANSWER_COMBINATION => ['multiple_answer_combination.class.php', 'MultipleAnswerCombination'],
55
        UNIQUE_ANSWER_NO_OPTION => ['unique_answer_no_option.class.php', 'UniqueAnswerNoOption'],
56
        MULTIPLE_ANSWER_TRUE_FALSE => ['multiple_answer_true_false.class.php', 'MultipleAnswerTrueFalse'],
57
        MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY => [
58
            'MultipleAnswerTrueFalseDegreeCertainty.php',
59
            'MultipleAnswerTrueFalseDegreeCertainty',
60
        ],
61
        MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE => [
62
            'multiple_answer_combination_true_false.class.php',
63
            'MultipleAnswerCombinationTrueFalse',
64
        ],
65
        GLOBAL_MULTIPLE_ANSWER => ['global_multiple_answer.class.php', 'GlobalMultipleAnswer'],
66
        CALCULATED_ANSWER => ['calculated_answer.class.php', 'CalculatedAnswer'],
67
        UNIQUE_ANSWER_IMAGE => ['UniqueAnswerImage.php', 'UniqueAnswerImage'],
68
        DRAGGABLE => ['Draggable.php', 'Draggable'],
69
        MATCHING_DRAGGABLE => ['MatchingDraggable.php', 'MatchingDraggable'],
70
        //MEDIA_QUESTION => array('media_question.class.php' , 'MediaQuestion')
71
        ANNOTATION => ['Annotation.php', 'Annotation'],
72
        READING_COMPREHENSION => ['ReadingComprehension.php', 'ReadingComprehension'],
73
    ];
74
75
    /**
76
     * constructor of the class.
77
     *
78
     * @author Olivier Brouckaert
79
     */
80
    public function __construct()
81
    {
82
        $this->id = 0;
83
        $this->iid = 0;
84
        $this->question = '';
85
        $this->description = '';
86
        $this->weighting = 0;
87
        $this->position = 1;
88
        $this->picture = '';
89
        $this->level = 1;
90
        $this->category = 0;
91
        // This variable is used when loading an exercise like an scenario with
92
        // an special hotspot: final_overlap, final_missing, final_excess
93
        $this->extra = '';
94
        $this->exerciseList = [];
95
        $this->course = api_get_course_info();
96
        $this->category_list = [];
97
        $this->parent_id = 0;
98
        $this->mandatory = 0;
99
        // See BT#12611
100
        $this->questionTypeWithFeedback = [
101
            MATCHING,
102
            MATCHING_DRAGGABLE,
103
            DRAGGABLE,
104
            FILL_IN_BLANKS,
105
            FREE_ANSWER,
106
            ORAL_EXPRESSION,
107
            CALCULATED_ANSWER,
108
            ANNOTATION,
109
        ];
110
    }
111
112
    public function getId()
113
    {
114
        return $this->iid;
115
    }
116
117
    /**
118
     * @return int|null
119
     */
120
    public function getIsContent()
121
    {
122
        $isContent = null;
123
        if (isset($_REQUEST['isContent'])) {
124
            $isContent = (int) $_REQUEST['isContent'];
125
        }
126
127
        return $this->isContent = $isContent;
128
    }
129
130
    /**
131
     * Reads question information from the data base.
132
     *
133
     * @param int   $id              - question ID
134
     * @param array $course_info
135
     * @param bool  $getExerciseList
136
     *
137
     * @return Question
138
     *
139
     * @author Olivier Brouckaert
140
     */
141
    public static function read($id, $course_info = [], $getExerciseList = true)
142
    {
143
        $id = (int) $id;
144
        if (empty($course_info)) {
145
            $course_info = api_get_course_info();
146
        }
147
        $course_id = $course_info['real_id'];
148
149
        if (empty($course_id) || -1 == $course_id) {
150
            return false;
151
        }
152
153
        $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
154
        $TBL_EXERCISE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
155
156
        $sql = "SELECT *
157
                FROM $TBL_QUESTIONS
158
                WHERE iid = $id ";
159
        $result = Database::query($sql);
160
161
        // if the question has been found
162
        if ($object = Database::fetch_object($result)) {
163
            $objQuestion = self::getInstance($object->type);
164
            if (!empty($objQuestion)) {
165
                $objQuestion->id = (int) $id;
166
                $objQuestion->iid = (int) $object->iid;
167
                $objQuestion->question = $object->question;
168
                $objQuestion->description = $object->description;
169
                $objQuestion->weighting = $object->ponderation;
170
                $objQuestion->position = $object->position;
171
                $objQuestion->type = (int) $object->type;
172
                $objQuestion->picture = $object->picture;
173
                $objQuestion->level = (int) $object->level;
174
                $objQuestion->extra = $object->extra;
175
                $objQuestion->course = $course_info;
176
                $objQuestion->feedback = isset($object->feedback) ? $object->feedback : '';
177
                $objQuestion->category = TestCategory::getCategoryForQuestion($id, $course_id);
178
                $objQuestion->code = isset($object->code) ? $object->code : '';
179
                $categoryInfo = TestCategory::getCategoryInfoForQuestion($id, $course_id);
180
181
                if (!empty($categoryInfo)) {
182
                    if (isset($categoryInfo['category_id'])) {
183
                        $objQuestion->category = (int) $categoryInfo['category_id'];
184
                    }
185
186
                    if (api_get_configuration_value('allow_mandatory_question_in_category') &&
187
                        isset($categoryInfo['mandatory'])
188
                    ) {
189
                        $objQuestion->mandatory = (int) $categoryInfo['mandatory'];
190
                    }
191
                }
192
193
                if ($getExerciseList) {
194
                    $tblQuiz = Database::get_course_table(TABLE_QUIZ_TEST);
195
                    $sql = "SELECT DISTINCT q.exercice_id
196
                            FROM $TBL_EXERCISE_QUESTION q
197
                            INNER JOIN $tblQuiz e
198
                            ON e.c_id = q.c_id AND e.iid = q.exercice_id
199
                            WHERE
200
                                q.c_id = $course_id AND
201
                                q.question_id = $id AND
202
                                e.active >= 0";
203
204
                    $result = Database::query($sql);
205
206
                    // fills the array with the exercises which this question is in
207
                    if ($result) {
0 ignored issues
show
introduced by
$result is of type Doctrine\DBAL\Driver\Statement, thus it always evaluated to true.
Loading history...
208
                        while ($obj = Database::fetch_object($result)) {
209
                            $objQuestion->exerciseList[] = $obj->exercice_id;
210
                        }
211
                    }
212
                }
213
214
                return $objQuestion;
215
            }
216
        }
217
218
        // question not found
219
        return false;
220
    }
221
222
    /**
223
     * returns the question title.
224
     *
225
     * @author Olivier Brouckaert
226
     *
227
     * @return string - question title
228
     */
229
    public function selectTitle()
230
    {
231
        if (!api_get_configuration_value('save_titles_as_html')) {
232
            return $this->question;
233
        }
234
235
        return Display::div($this->question, ['style' => 'display: inline-block;']);
236
    }
237
238
    /**
239
     * @param int $itemNumber
240
     *
241
     * @return string
242
     */
243
    public function getTitleToDisplay($itemNumber)
244
    {
245
        $showQuestionTitleHtml = api_get_configuration_value('save_titles_as_html');
246
        $title = '';
247
        if (api_get_configuration_value('show_question_id')) {
248
            $title .= '<h4>#'.$this->course['code'].'-'.$this->iid.'</h4>';
249
        }
250
251
        $title .= $showQuestionTitleHtml ? '' : '<strong>';
252
        $title .= $itemNumber.'. '.$this->selectTitle();
253
        $title .= $showQuestionTitleHtml ? '' : '</strong>';
254
255
        return Display::div(
256
            $title,
257
            ['class' => 'question_title']
258
        );
259
    }
260
261
    /**
262
     * returns the question description.
263
     *
264
     * @author Olivier Brouckaert
265
     *
266
     * @return string - question description
267
     */
268
    public function selectDescription()
269
    {
270
        return $this->description;
271
    }
272
273
    /**
274
     * returns the question weighting.
275
     *
276
     * @author Olivier Brouckaert
277
     *
278
     * @return int - question weighting
279
     */
280
    public function selectWeighting()
281
    {
282
        return $this->weighting;
283
    }
284
285
    /**
286
     * returns the answer type.
287
     *
288
     * @author Olivier Brouckaert
289
     *
290
     * @return int - answer type
291
     */
292
    public function selectType()
293
    {
294
        return $this->type;
295
    }
296
297
    /**
298
     * returns the level of the question.
299
     *
300
     * @author Nicolas Raynaud
301
     *
302
     * @return int - level of the question, 0 by default
303
     */
304
    public function getLevel()
305
    {
306
        return $this->level;
307
    }
308
309
    /**
310
     * changes the question title.
311
     *
312
     * @param string $title - question title
313
     *
314
     * @author Olivier Brouckaert
315
     */
316
    public function updateTitle($title)
317
    {
318
        $this->question = $title;
319
    }
320
321
    /**
322
     * changes the question description.
323
     *
324
     * @param string $description - question description
325
     *
326
     * @author Olivier Brouckaert
327
     */
328
    public function updateDescription($description)
329
    {
330
        $this->description = $description;
331
    }
332
333
    /**
334
     * changes the question weighting.
335
     *
336
     * @param int $weighting - question weighting
337
     *
338
     * @author Olivier Brouckaert
339
     */
340
    public function updateWeighting($weighting)
341
    {
342
        $this->weighting = $weighting;
343
    }
344
345
    /**
346
     * @param array $category
347
     *
348
     * @author Hubert Borderiou 12-10-2011
349
     */
350
    public function updateCategory($category)
351
    {
352
        $this->category = $category;
353
    }
354
355
    public function setMandatory($value)
356
    {
357
        $this->mandatory = (int) $value;
358
    }
359
    /**
360
     * in this version, a question can only have 1 category
361
     * if category is 0, then question has no category then delete the category entry.
362
     *
363
     * @param int $categoryId
364
     * @param int $courseId
365
     *
366
     * @return bool
367
     *
368
     * @author Hubert Borderiou 12-10-2011
369
     */
370
    public function saveCategory($categoryId, $courseId = 0)
371
    {
372
        $courseId = empty($courseId) ? api_get_course_int_id() : (int) $courseId;
373
374
        if (empty($courseId)) {
375
            return false;
376
        }
377
378
        if ($categoryId <= 0) {
379
            $this->deleteCategory($courseId);
380
        } else {
381
            // update or add category for a question
382
            $table = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
383
            $categoryId = (int) $categoryId;
384
            $question_id = (int) $this->id;
385
            $sql = "SELECT count(*) AS nb FROM $table
386
                    WHERE
387
                        question_id = $question_id AND
388
                        c_id = ".$courseId;
389
            $res = Database::query($sql);
390
            $row = Database::fetch_array($res);
391
            $allowMandatory = api_get_configuration_value('allow_mandatory_question_in_category');
392
            if ($row['nb'] > 0) {
393
                $extraMandatoryCondition = '';
394
                if ($allowMandatory) {
395
                    $extraMandatoryCondition = ", mandatory = {$this->mandatory}";
396
                }
397
                $sql = "UPDATE $table
398
                        SET category_id = $categoryId
399
                        $extraMandatoryCondition
400
                        WHERE
401
                            question_id = $question_id ";
402
                Database::query($sql);
403
            } else {
404
                $sql = "INSERT INTO $table (question_id, category_id)
405
                        VALUES ($question_id, $categoryId)";
406
                Database::query($sql);
407
                if ($allowMandatory) {
408
                    $id = Database::insert_id();
409
                    if ($id) {
410
                        $sql = "UPDATE $table SET mandatory = {$this->mandatory}
411
                                WHERE iid = $id";
412
                        Database::query($sql);
413
                    }
414
                }
415
            }
416
417
            return true;
418
        }
419
    }
420
421
    /**
422
     * @author hubert borderiou 12-10-2011
423
     *
424
     * @param int $courseId
425
     *                      delete any category entry for question id
426
     *                      delete the category for question
427
     *
428
     * @deprecated
429
     *
430
     * @return bool
431
     */
432
    public function deleteCategory($courseId = 0)
433
    {
434
        $courseId = empty($courseId) ? api_get_course_int_id() : (int) $courseId;
435
        $table = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
436
        $questionId = (int) $this->id;
437
        if (empty($courseId) || empty($questionId)) {
438
            return false;
439
        }
440
        $sql = "DELETE FROM $table
441
                WHERE
442
                    question_id = $questionId";
443
        Database::query($sql);
444
445
        return true;
446
    }
447
448
    /**
449
     * changes the question position.
450
     *
451
     * @param int $position - question position
452
     *
453
     * @author Olivier Brouckaert
454
     */
455
    public function updatePosition($position)
456
    {
457
        $this->position = $position;
458
    }
459
460
    /**
461
     * changes the question level.
462
     *
463
     * @param int $level - question level
464
     *
465
     * @author Nicolas Raynaud
466
     */
467
    public function updateLevel($level)
468
    {
469
        $this->level = $level;
470
    }
471
472
    /**
473
     * changes the answer type. If the user changes the type from "unique answer" to "multiple answers"
474
     * (or conversely) answers are not deleted, otherwise yes.
475
     *
476
     * @param int $type - answer type
477
     *
478
     * @author Olivier Brouckaert
479
     */
480
    public function updateType($type)
481
    {
482
        $table = Database::get_course_table(TABLE_QUIZ_ANSWER);
483
        $course_id = $this->course['real_id'];
484
485
        if (empty($course_id)) {
486
            $course_id = api_get_course_int_id();
487
        }
488
        // if we really change the type
489
        if ($type != $this->type) {
490
            // if we don't change from "unique answer" to "multiple answers" (or conversely)
491
            if (!in_array($this->type, [UNIQUE_ANSWER, MULTIPLE_ANSWER]) ||
492
                !in_array($type, [UNIQUE_ANSWER, MULTIPLE_ANSWER])
493
            ) {
494
                // removes old answers
495
                $sql = "DELETE FROM $table
496
                        WHERE c_id = $course_id AND question_id = ".(int) ($this->id);
497
                Database::query($sql);
498
            }
499
500
            $this->type = $type;
501
        }
502
    }
503
504
    /**
505
     * Set title.
506
     *
507
     * @param string $title
508
     */
509
    public function setTitle($title)
510
    {
511
        $this->question = $title;
512
    }
513
514
    /**
515
     * Sets extra info.
516
     *
517
     * @param string $extra
518
     */
519
    public function setExtra($extra)
520
    {
521
        $this->extra = $extra;
522
    }
523
524
    /**
525
     * updates the question in the data base
526
     * if an exercise ID is provided, we add that exercise ID into the exercise list.
527
     *
528
     * @author Olivier Brouckaert
529
     *
530
     * @param Exercise $exercise
531
     */
532
    public function save($exercise)
533
    {
534
        $TBL_EXERCISE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
535
        $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
536
        $em = Database::getManager();
537
        $exerciseId = $exercise->iId;
538
539
        $id = $this->id;
540
        $type = $this->type;
541
        $c_id = $this->course['real_id'];
542
543
        $courseEntity = api_get_course_entity($c_id);
544
        $categoryId = $this->category;
545
546
        $questionCategoryRepo = Container::getQuestionCategoryRepository();
547
        $questionRepo = Container::getQuestionRepository();
548
        $exerciseRepo = Container::getQuizRepository();
549
550
        // question already exists
551
        if (!empty($id)) {
552
            /** @var CQuizQuestion $question */
553
            $question = $questionRepo->find($id);
554
            $question
555
                ->setQuestion($this->question)
556
                ->setDescription($this->description)
557
                ->setPonderation($this->weighting)
558
                ->setPosition($this->position)
559
                ->setType($this->type)
560
                ->setExtra($this->extra)
561
                ->setLevel($this->level)
562
                ->setFeedback($this->feedback)
563
            ;
564
565
            if (!empty($categoryId)) {
566
                $category = $questionCategoryRepo->find($categoryId);
567
                $question->updateCategory($category);
568
            }
569
570
            $em->persist($question);
571
            $em->flush();
572
573
            Event::addEvent(
574
                LOG_QUESTION_UPDATED,
575
                LOG_QUESTION_ID,
576
                $this->iid
577
            );
578
            if ('true' === api_get_setting('search_enabled')) {
579
                $this->search_engine_edit($exerciseId);
580
            }
581
        } else {
582
            // Creates a new question
583
            $sql = "SELECT max(position)
584
                    FROM $TBL_QUESTIONS as question,
585
                    $TBL_EXERCISE_QUESTION as test_question
586
                    WHERE
587
                        question.iid = test_question.question_id AND
588
                        test_question.exercice_id = ".$exerciseId." AND
589
                        question.c_id = $c_id AND
590
                        test_question.c_id = $c_id ";
591
            $result = Database::query($sql);
592
            $current_position = Database::result($result, 0, 0);
593
            $this->updatePosition($current_position + 1);
594
            $position = $this->position;
595
            $exerciseEntity = $exerciseRepo->find($exerciseId);
596
597
            $question = new CQuizQuestion();
598
            $question
599
                ->setCId($c_id)
600
                ->setQuestion($this->question)
601
                ->setDescription($this->description)
602
                ->setPonderation($this->weighting)
603
                ->setPosition($position)
604
                ->setType($this->type)
605
                ->setExtra($this->extra)
606
                ->setLevel($this->level)
607
                ->setFeedback($this->feedback)
608
                //->setParent($exerciseEntity)
609
                ->setParent($courseEntity)
610
                ->addCourseLink(
611
                    $courseEntity,
612
                    api_get_session_entity(),
613
                    api_get_group_entity()
614
                )
615
            ;
616
617
            $em->persist($question);
618
            $em->flush();
619
620
            $this->id = $question->getIid();
621
622
            if ($this->id) {
623
                Event::addEvent(
624
                    LOG_QUESTION_CREATED,
625
                    LOG_QUESTION_ID,
626
                    $this->id
627
                );
628
                $request = Container::getRequest();
629
                if ($request->files->has('imageUpload')) {
630
                    $file = $request->files->get('imageUpload');
631
                    $questionRepo->addFile($question, $file);
632
633
                    $em->flush();
634
                }
635
636
                // If hotspot, create first answer
637
                if (HOT_SPOT == $type || HOT_SPOT_ORDER == $type) {
638
                    $quizAnswer = new CQuizAnswer();
639
                    $quizAnswer
640
                        ->setCId($c_id)
641
                        ->setQuestionId($this->id)
642
                        ->setAnswer('')
643
                        ->setPonderation(10)
644
                        ->setPosition(1)
645
                        ->setHotspotCoordinates('0;0|0|0')
646
                        ->setHotspotType('square');
647
648
                    $em->persist($quizAnswer);
649
                    $em->flush();
650
                }
651
652
                if (HOT_SPOT_DELINEATION == $type) {
653
                    $quizAnswer = new CQuizAnswer();
654
                    $quizAnswer
655
                        ->setCId($c_id)
656
                        ->setQuestionId($this->id)
657
                        ->setAnswer('')
658
                        ->setPonderation(10)
659
                        ->setPosition(1)
660
                        ->setHotspotCoordinates('0;0|0|0')
661
                        ->setHotspotType('delineation');
662
663
                    $em->persist($quizAnswer);
664
                    $em->flush();
665
                }
666
667
                if ('true' === api_get_setting('search_enabled')) {
668
                    $this->search_engine_edit($exerciseId, true);
669
                }
670
            }
671
        }
672
673
        // if the question is created in an exercise
674
        if (!empty($exerciseId)) {
675
            // adds the exercise into the exercise list of this question
676
            $this->addToList($exerciseId, true);
677
        }
678
    }
679
680
    /**
681
     * @param int  $exerciseId
682
     * @param bool $addQs
683
     * @param bool $rmQs
684
     */
685
    public function search_engine_edit(
686
        $exerciseId,
687
        $addQs = false,
688
        $rmQs = false
689
    ) {
690
        // update search engine and its values table if enabled
691
        if (!empty($exerciseId) && 'true' == api_get_setting('search_enabled') &&
692
            extension_loaded('xapian')
693
        ) {
694
            $course_id = api_get_course_id();
695
            // get search_did
696
            $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
697
            if ($addQs || $rmQs) {
698
                //there's only one row per question on normal db and one document per question on search engine db
699
                $sql = 'SELECT * FROM %s
700
                    WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_second_level=%s LIMIT 1';
701
                $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
702
            } else {
703
                $sql = 'SELECT * FROM %s
704
                    WHERE course_code=\'%s\' AND tool_id=\'%s\'
705
                    AND ref_id_high_level=%s AND ref_id_second_level=%s LIMIT 1';
706
                $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id);
707
            }
708
            $res = Database::query($sql);
709
710
            if (Database::num_rows($res) > 0 || $addQs) {
711
                $di = new ChamiloIndexer();
712
                if ($addQs) {
713
                    $question_exercises = [(int) $exerciseId];
714
                } else {
715
                    $question_exercises = [];
716
                }
717
                isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : $lang = 'english';
718
                $di->connectDb(null, null, $lang);
719
720
                // retrieve others exercise ids
721
                $se_ref = Database::fetch_array($res);
722
                $se_doc = $di->get_document((int) $se_ref['search_did']);
723
                if (false !== $se_doc) {
724
                    if (false !== ($se_doc_data = $di->get_document_data($se_doc))) {
725
                        $se_doc_data = UnserializeApi::unserialize(
726
                            'not_allowed_classes',
727
                            $se_doc_data
728
                        );
729
                        if (isset($se_doc_data[SE_DATA]['type']) &&
730
                            SE_DOCTYPE_EXERCISE_QUESTION == $se_doc_data[SE_DATA]['type']
731
                        ) {
732
                            if (isset($se_doc_data[SE_DATA]['exercise_ids']) &&
733
                                is_array($se_doc_data[SE_DATA]['exercise_ids'])
734
                            ) {
735
                                foreach ($se_doc_data[SE_DATA]['exercise_ids'] as $old_value) {
736
                                    if (!in_array($old_value, $question_exercises)) {
737
                                        $question_exercises[] = $old_value;
738
                                    }
739
                                }
740
                            }
741
                        }
742
                    }
743
                }
744
                if ($rmQs) {
745
                    while (false !== ($key = array_search($exerciseId, $question_exercises))) {
746
                        unset($question_exercises[$key]);
747
                    }
748
                }
749
750
                // build the chunk to index
751
                $ic_slide = new IndexableChunk();
752
                $ic_slide->addValue('title', $this->question);
753
                $ic_slide->addCourseId($course_id);
754
                $ic_slide->addToolId(TOOL_QUIZ);
755
                $xapian_data = [
756
                    SE_COURSE_ID => $course_id,
757
                    SE_TOOL_ID => TOOL_QUIZ,
758
                    SE_DATA => [
759
                        'type' => SE_DOCTYPE_EXERCISE_QUESTION,
760
                        'exercise_ids' => $question_exercises,
761
                        'question_id' => (int) $this->id,
762
                    ],
763
                    SE_USER => (int) api_get_user_id(),
764
                ];
765
                $ic_slide->xapian_data = serialize($xapian_data);
766
                $ic_slide->addValue('content', $this->description);
767
768
                //TODO: index answers, see also form validation on question_admin.inc.php
769
770
                $di->remove_document($se_ref['search_did']);
771
                $di->addChunk($ic_slide);
772
773
                //index and return search engine document id
774
                if (!empty($question_exercises)) { // if empty there is nothing to index
775
                    $did = $di->index();
776
                    unset($di);
777
                }
778
                if ($did || $rmQs) {
779
                    // save it to db
780
                    if ($addQs || $rmQs) {
781
                        $sql = "DELETE FROM %s
782
                            WHERE course_code = '%s' AND tool_id = '%s' AND ref_id_second_level = '%s'";
783
                        $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
784
                    } else {
785
                        $sql = "DELETE FROM %S
786
                            WHERE
787
                                course_code = '%s'
788
                                AND tool_id = '%s'
789
                                AND tool_id = '%s'
790
                                AND ref_id_high_level = '%s'
791
                                AND ref_id_second_level = '%s'";
792
                        $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id);
793
                    }
794
                    Database::query($sql);
795
                    if ($rmQs) {
796
                        if (!empty($question_exercises)) {
797
                            $sql = "INSERT INTO %s (
798
                                    id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did
799
                                )
800
                                VALUES (
801
                                    NULL, '%s', '%s', %s, %s, %s
802
                                )";
803
                            $sql = sprintf(
804
                                $sql,
805
                                $tbl_se_ref,
806
                                $course_id,
807
                                TOOL_QUIZ,
808
                                array_shift($question_exercises),
809
                                $this->id,
810
                                $did
811
                            );
812
                            Database::query($sql);
813
                        }
814
                    } else {
815
                        $sql = "INSERT INTO %s (
816
                                id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did
817
                            )
818
                            VALUES (
819
                                NULL , '%s', '%s', %s, %s, %s
820
                            )";
821
                        $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id, $did);
822
                        Database::query($sql);
823
                    }
824
                }
825
            }
826
        }
827
    }
828
829
    /**
830
     * adds an exercise into the exercise list.
831
     *
832
     * @author Olivier Brouckaert
833
     *
834
     * @param int  $exerciseId - exercise ID
835
     * @param bool $fromSave   - from $this->save() or not
836
     */
837
    public function addToList($exerciseId, $fromSave = false)
838
    {
839
        $exerciseRelQuestionTable = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
840
        $id = (int) $this->id;
841
        $exerciseId = (int) $exerciseId;
842
843
        // checks if the exercise ID is not in the list
844
        if (!empty($exerciseId) && !in_array($exerciseId, $this->exerciseList)) {
845
            $this->exerciseList[] = $exerciseId;
846
            $courseId = isset($this->course['real_id']) ? $this->course['real_id'] : 0;
847
            $newExercise = new Exercise($courseId);
848
            $newExercise->read($exerciseId, false);
849
            $count = $newExercise->getQuestionCount();
850
            $count++;
851
            $sql = "INSERT INTO $exerciseRelQuestionTable (c_id, question_id, exercice_id, question_order)
852
                    VALUES ({$this->course['real_id']}, ".$id.', '.$exerciseId.", '$count')";
853
            Database::query($sql);
854
855
            // we do not want to reindex if we had just saved adnd indexed the question
856
            if (!$fromSave) {
857
                $this->search_engine_edit($exerciseId, true);
858
            }
859
        }
860
    }
861
862
    /**
863
     * removes an exercise from the exercise list.
864
     *
865
     * @author Olivier Brouckaert
866
     *
867
     * @param int $exerciseId - exercise ID
868
     * @param int $courseId
869
     *
870
     * @return bool - true if removed, otherwise false
871
     */
872
    public function removeFromList($exerciseId, $courseId = 0)
873
    {
874
        $table = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
875
        $id = (int) $this->id;
876
        $exerciseId = (int) $exerciseId;
877
878
        // searches the position of the exercise ID in the list
879
        $pos = array_search($exerciseId, $this->exerciseList);
880
        $courseId = empty($courseId) ? api_get_course_int_id() : (int) $courseId;
881
882
        // exercise not found
883
        if (false === $pos) {
884
            return false;
885
        } else {
886
            // deletes the position in the array containing the wanted exercise ID
887
            unset($this->exerciseList[$pos]);
888
            //update order of other elements
889
            $sql = "SELECT question_order
890
                    FROM $table
891
                    WHERE
892
                        c_id = $courseId AND
893
                        question_id = $id AND
894
                        exercice_id = $exerciseId";
895
            $res = Database::query($sql);
896
            if (Database::num_rows($res) > 0) {
897
                $row = Database::fetch_array($res);
898
                if (!empty($row['question_order'])) {
899
                    $sql = "UPDATE $table
900
                            SET question_order = question_order-1
901
                            WHERE
902
                                c_id = $courseId AND
903
                                exercice_id = $exerciseId AND
904
                                question_order > ".$row['question_order'];
905
                    Database::query($sql);
906
                }
907
            }
908
909
            $sql = "DELETE FROM $table
910
                    WHERE
911
                        c_id = $courseId AND
912
                        question_id = $id AND
913
                        exercice_id = $exerciseId";
914
            Database::query($sql);
915
916
            return true;
917
        }
918
    }
919
920
    /**
921
     * Deletes a question from the database
922
     * the parameter tells if the question is removed from all exercises (value = 0),
923
     * or just from one exercise (value = exercise ID).
924
     *
925
     * @author Olivier Brouckaert
926
     *
927
     * @param int $deleteFromEx - exercise ID if the question is only removed from one exercise
928
     *
929
     * @return bool
930
     */
931
    public function delete($deleteFromEx = 0)
932
    {
933
        if (empty($this->course)) {
934
            return false;
935
        }
936
937
        $courseId = $this->course['real_id'];
938
939
        if (empty($courseId)) {
940
            return false;
941
        }
942
943
        $TBL_EXERCISE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
944
        $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
945
        $TBL_REPONSES = Database::get_course_table(TABLE_QUIZ_ANSWER);
946
        $TBL_QUIZ_QUESTION_REL_CATEGORY = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
947
948
        $id = (int) $this->id;
949
950
        // if the question must be removed from all exercises
951
        if (!$deleteFromEx) {
952
            //update the question_order of each question to avoid inconsistencies
953
            $sql = "SELECT exercice_id, question_order
954
                    FROM $TBL_EXERCISE_QUESTION
955
                    WHERE c_id = $courseId AND question_id = ".$id;
956
957
            $res = Database::query($sql);
958
            if (Database::num_rows($res) > 0) {
959
                while ($row = Database::fetch_array($res)) {
960
                    if (!empty($row['question_order'])) {
961
                        $sql = "UPDATE $TBL_EXERCISE_QUESTION
962
                                SET question_order = question_order-1
963
                                WHERE
964
                                    c_id = $courseId AND
965
                                    exercice_id = ".(int) ($row['exercice_id']).' AND
966
                                    question_order > '.$row['question_order'];
967
                        Database::query($sql);
968
                    }
969
                }
970
            }
971
972
            $sql = "DELETE FROM $TBL_EXERCISE_QUESTION
973
                    WHERE c_id = $courseId AND question_id = ".$id;
974
            Database::query($sql);
975
976
            $sql = "DELETE FROM $TBL_QUESTIONS
977
                    WHERE c_id = $courseId AND iid = ".$id;
978
            Database::query($sql);
979
980
            $sql = "DELETE FROM $TBL_REPONSES
981
                    WHERE c_id = $courseId AND question_id = ".$id;
982
            Database::query($sql);
983
984
            // remove the category of this question in the question_rel_category table
985
            $sql = "DELETE FROM $TBL_QUIZ_QUESTION_REL_CATEGORY
986
                    WHERE
987
                        c_id = $courseId AND
988
                        question_id = ".$id;
989
            Database::query($sql);
990
991
            // Add extra fields.
992
            $extraField = new ExtraFieldValue('question');
993
            $extraField->deleteValuesByItem($this->iid);
994
995
            /*api_item_property_update(
996
                $this->course,
997
                TOOL_QUIZ,
998
                $id,
999
                'QuizQuestionDeleted',
1000
                api_get_user_id()
1001
            );*/
1002
            Event::addEvent(
1003
                LOG_QUESTION_DELETED,
1004
                LOG_QUESTION_ID,
1005
                $this->iid
1006
            );
1007
        //$this->removePicture();
1008
        } else {
1009
            // just removes the exercise from the list
1010
            $this->removeFromList($deleteFromEx, $courseId);
1011
            if ('true' == api_get_setting('search_enabled') && extension_loaded('xapian')) {
1012
                // disassociate question with this exercise
1013
                $this->search_engine_edit($deleteFromEx, false, true);
1014
            }
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_REMOVED_FROM_QUIZ,
1025
                LOG_QUESTION_ID,
1026
                $this->iid
1027
            );
1028
        }
1029
1030
        return true;
1031
    }
1032
1033
    /**
1034
     * Duplicates the question.
1035
     *
1036
     * @author Olivier Brouckaert
1037
     *
1038
     * @param array $courseInfo Course info of the destination course
1039
     *
1040
     * @return false|string ID of the new question
1041
     */
1042
    public function duplicate($courseInfo = [])
1043
    {
1044
        $courseInfo = empty($courseInfo) ? $this->course : $courseInfo;
1045
1046
        if (empty($courseInfo)) {
1047
            return false;
1048
        }
1049
        $TBL_QUESTION_OPTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
1050
1051
        $questionText = $this->question;
1052
        $description = $this->description;
1053
1054
        // Using the same method used in the course copy to transform URLs
1055
        if ($this->course['id'] != $courseInfo['id']) {
1056
            $description = DocumentManager::replaceUrlWithNewCourseCode(
1057
                $description,
1058
                $this->course['code'],
1059
                $courseInfo['id']
1060
            );
1061
            $questionText = DocumentManager::replaceUrlWithNewCourseCode(
1062
                $questionText,
1063
                $this->course['code'],
1064
                $courseInfo['id']
1065
            );
1066
        }
1067
1068
        $course_id = $courseInfo['real_id'];
1069
1070
        // Read the source options
1071
        $options = self::readQuestionOption($this->id, $this->course['real_id']);
1072
1073
        $em = Database::getManager();
1074
        $courseEntity = api_get_course_entity($course_id);
1075
1076
        $question = new CQuizQuestion();
1077
        $question
1078
            ->setCId($course_id)
1079
            ->setQuestion($questionText)
1080
            ->setDescription($description)
1081
            ->setPonderation($this->weighting)
1082
            ->setPosition($this->position)
1083
            ->setType($this->type)
1084
            ->setExtra($this->extra)
1085
            ->setLevel($this->level)
1086
            ->setFeedback($this->feedback)
1087
            ->setParent($courseEntity)
1088
            ->addCourseLink(
1089
                $courseEntity
1090
            )
1091
        ;
1092
1093
        $em->persist($question);
1094
        $em->flush();
1095
        $newQuestionId = $question->getIid();
1096
1097
        if ($newQuestionId) {
1098
            // Add extra fields.
1099
            $extraField = new ExtraFieldValue('question');
1100
            $extraField->copy($this->iid, $newQuestionId);
1101
1102
            if (!empty($options)) {
1103
                // Saving the quiz_options
1104
                foreach ($options as $item) {
1105
                    $item['question_id'] = $newQuestionId;
1106
                    $item['c_id'] = $course_id;
1107
                    unset($item['id']);
1108
                    unset($item['iid']);
1109
                    Database::insert($TBL_QUESTION_OPTIONS, $item);
1110
                }
1111
            }
1112
1113
            // Duplicates the picture of the hotspot
1114
            // @todo implement copy of hotspot question
1115
            if ($this->type == HOT_SPOT) {
1116
                throw new Exception('implement copy of hotspot question');
1117
            }
1118
        }
1119
1120
        return $newQuestionId;
1121
    }
1122
1123
    /**
1124
     * @return string
1125
     */
1126
    public function get_question_type_name()
1127
    {
1128
        $key = self::$questionTypes[$this->type];
1129
1130
        return get_lang($key[1]);
1131
    }
1132
1133
    /**
1134
     * @param string $type
1135
     */
1136
    public static function get_question_type($type)
1137
    {
1138
        if (ORAL_EXPRESSION == $type && 'true' !== api_get_setting('enable_record_audio')) {
1139
            return null;
1140
        }
1141
1142
        return self::$questionTypes[$type];
1143
    }
1144
1145
    /**
1146
     * @return array
1147
     */
1148
    public static function getQuestionTypeList()
1149
    {
1150
        if ('true' !== api_get_setting('enable_record_audio')) {
1151
            self::$questionTypes[ORAL_EXPRESSION] = null;
1152
            unset(self::$questionTypes[ORAL_EXPRESSION]);
1153
        }
1154
        if ('true' !== api_get_setting('enable_quiz_scenario')) {
1155
            self::$questionTypes[HOT_SPOT_DELINEATION] = null;
1156
            unset(self::$questionTypes[HOT_SPOT_DELINEATION]);
1157
        }
1158
1159
        return self::$questionTypes;
1160
    }
1161
1162
    /**
1163
     * Returns an instance of the class corresponding to the type.
1164
     *
1165
     * @param int $type the type of the question
1166
     *
1167
     * @return $this instance of a Question subclass (or of Questionc class by default)
1168
     */
1169
    public static function getInstance($type)
1170
    {
1171
        if (null !== $type) {
1172
            list($fileName, $className) = self::get_question_type($type);
1173
            if (!empty($fileName)) {
1174
                if (class_exists($className)) {
1175
                    return new $className();
1176
                } else {
1177
                    echo 'Can\'t instanciate class '.$className.' of type '.$type;
1178
                }
1179
            }
1180
        }
1181
1182
        return null;
1183
    }
1184
1185
    /**
1186
     * Creates the form to create / edit a question
1187
     * A subclass can redefine this function to add fields...
1188
     *
1189
     * @param FormValidator $form
1190
     * @param Exercise      $exercise
1191
     */
1192
    public function createForm(&$form, $exercise)
1193
    {
1194
        echo '<style>
1195
                .media { display:none;}
1196
            </style>';
1197
1198
        $zoomOptions = api_get_configuration_value('quiz_image_zoom');
1199
        if (isset($zoomOptions['options'])) {
1200
            $finderFolder = api_get_path(WEB_PATH).'vendor/studio-42/elfinder/';
1201
            echo '<!-- elFinder CSS (REQUIRED) -->';
1202
            echo '<link rel="stylesheet" type="text/css" media="screen" href="'.$finderFolder.'css/elfinder.full.css">';
1203
            echo '<link rel="stylesheet" type="text/css" media="screen" href="'.$finderFolder.'css/theme.css">';
1204
1205
            echo '<!-- elFinder JS (REQUIRED) -->';
1206
            echo '<script type="text/javascript" src="'.$finderFolder.'js/elfinder.full.js"></script>';
1207
1208
            echo '<!-- elFinder translation (OPTIONAL) -->';
1209
            $language = 'en';
1210
            $platformLanguage = api_get_interface_language();
1211
            $iso = api_get_language_isocode($platformLanguage);
1212
            $filePart = "vendor/studio-42/elfinder/js/i18n/elfinder.$iso.js";
1213
            $file = api_get_path(SYS_PATH).$filePart;
1214
            $includeFile = '';
1215
            if (file_exists($file)) {
1216
                $includeFile = '<script type="text/javascript" src="'.api_get_path(WEB_PATH).$filePart.'"></script>';
1217
                $language = $iso;
1218
            }
1219
            echo $includeFile;
1220
1221
            echo '<script type="text/javascript" charset="utf-8">
1222
            $(function() {
1223
                $(".create_img_link").click(function(e){
1224
                    e.preventDefault();
1225
                    e.stopPropagation();
1226
                    var imageZoom = $("input[name=\'imageZoom\']").val();
1227
                    var imageWidth = $("input[name=\'imageWidth\']").val();
1228
                    CKEDITOR.instances.questionDescription.insertHtml(\'<img id="zoom_picture" class="zoom_picture" src="\'+imageZoom+\'" data-zoom-image="\'+imageZoom+\'" width="\'+imageWidth+\'px" />\');
1229
                });
1230
1231
                $("input[name=\'imageZoom\']").on("click", function(){
1232
                    var elf = $("#elfinder").elfinder({
1233
                        url : "'.api_get_path(WEB_LIBRARY_PATH).'elfinder/connectorAction.php?'.api_get_cidreq().'",
1234
                        getFileCallback: function(file) {
1235
                            var filePath = file; //file contains the relative url.
1236
                            var imgPath = "<img src = \'"+filePath+"\'/>";
1237
                            $("input[name=\'imageZoom\']").val(filePath.url);
1238
                            $("#elfinder").remove(); //close the window after image is selected
1239
                        },
1240
                        startPathHash: "l2_Lw", // Sets the course driver as default
1241
                        resizable: false,
1242
                        lang: "'.$language.'"
1243
                    }).elfinder("instance");
1244
                });
1245
            });
1246
            </script>';
1247
            echo '<div id="elfinder"></div>';
1248
        }
1249
1250
        // question name
1251
        if (api_get_configuration_value('save_titles_as_html')) {
1252
            $editorConfig = ['ToolbarSet' => 'TitleAsHtml'];
1253
            $form->addHtmlEditor(
1254
                'questionName',
1255
                get_lang('Question'),
1256
                false,
1257
                false,
1258
                $editorConfig,
1259
                true
1260
            );
1261
        } else {
1262
            $form->addElement('text', 'questionName', get_lang('Question'));
1263
        }
1264
1265
        $form->addRule('questionName', get_lang('Please type the question'), 'required');
1266
1267
        // default content
1268
        $isContent = isset($_REQUEST['isContent']) ? (int) $_REQUEST['isContent'] : null;
1269
1270
        // Question type
1271
        $answerType = isset($_REQUEST['answerType']) ? (int) $_REQUEST['answerType'] : null;
1272
        $form->addElement('hidden', 'answerType', $answerType);
1273
1274
        // html editor
1275
        $editorConfig = [
1276
            'ToolbarSet' => 'TestQuestionDescription',
1277
            'Height' => '150',
1278
        ];
1279
1280
        if (!api_is_allowed_to_edit(null, true)) {
1281
            $editorConfig['UserStatus'] = 'student';
1282
        }
1283
1284
        $form->addButtonAdvancedSettings('advanced_params');
1285
        $form->addHtml('<div id="advanced_params_options" style="display:none">');
1286
1287
        if (isset($zoomOptions['options'])) {
1288
            $form->addElement('text', 'imageZoom', get_lang('ImageURL'));
1289
            $form->addElement('text', 'imageWidth', get_lang('PixelWidth'));
1290
1291
            $form->addButton('btn_create_img', get_lang('AddToEditor'), 'plus', 'info', 'small', 'create_img_link');
1292
        }
1293
1294
        $form->addHtmlEditor(
1295
            'questionDescription',
1296
            get_lang('Enrich question'),
1297
            false,
1298
            false,
1299
            $editorConfig
1300
        );
1301
1302
        if (MEDIA_QUESTION != $this->type) {
1303
            // Advanced parameters
1304
            $form->addElement(
1305
                'select',
1306
                'questionLevel',
1307
                get_lang('Difficulty'),
1308
                self::get_default_levels()
1309
            );
1310
1311
            // Categories
1312
1313
            $form->addElement(
1314
                'select',
1315
                'questionCategory',
1316
                get_lang('Category'),
1317
                TestCategory::getCategoriesIdAndName()
1318
            );
1319
            if (EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_RANDOM == $exercise->getQuestionSelectionType() &&
1320
                api_get_configuration_value('allow_mandatory_question_in_category')
1321
            ) {
1322
                $form->addCheckBox(
1323
                    'mandatory',
1324
                    get_lang('IsMandatory')
1325
                );
1326
            }
1327
1328
            global $text;
1329
1330
            switch ($this->type) {
1331
                case UNIQUE_ANSWER:
1332
                    $buttonGroup = [];
1333
                    $buttonGroup[] = $form->addButtonSave(
1334
                        $text,
1335
                        'submitQuestion',
1336
                        true
1337
                    );
1338
                    $buttonGroup[] = $form->addButton(
1339
                        'convertAnswer',
1340
                        get_lang('Convert to multiple answer'),
1341
                        'dot-circle-o',
1342
                        'default',
1343
                        null,
1344
                        null,
1345
                        null,
1346
                        true
1347
                    );
1348
                    $form->addGroup($buttonGroup);
1349
1350
                    break;
1351
                case MULTIPLE_ANSWER:
1352
                    $buttonGroup = [];
1353
                    $buttonGroup[] = $form->addButtonSave(
1354
                        $text,
1355
                        'submitQuestion',
1356
                        true
1357
                    );
1358
                    $buttonGroup[] = $form->addButton(
1359
                        'convertAnswer',
1360
                        get_lang('Convert to unique answer'),
1361
                        'check-square-o',
1362
                        'default',
1363
                        null,
1364
                        null,
1365
                        null,
1366
                        true
1367
                    );
1368
                    $form->addGroup($buttonGroup);
1369
1370
                    break;
1371
            }
1372
            //Medias
1373
            //$course_medias = self::prepare_course_media_select(api_get_course_int_id());
1374
            //$form->addElement('select', 'parent_id', get_lang('Attach to media'), $course_medias);
1375
        }
1376
1377
        $form->addElement('html', '</div>');
1378
1379
        if (!isset($_GET['fromExercise'])) {
1380
            switch ($answerType) {
1381
                case 1:
1382
                    $this->question = get_lang('Select the good reasoning');
1383
1384
                    break;
1385
                case 2:
1386
                    $this->question = get_lang('The marasmus is a consequence of');
1387
1388
                    break;
1389
                case 3:
1390
                    $this->question = get_lang('Calculate the Body Mass Index');
1391
1392
                    break;
1393
                case 4:
1394
                    $this->question = get_lang('Order the operations');
1395
1396
                    break;
1397
                case 5:
1398
                    $this->question = get_lang('List what you consider the 10 top qualities of a good project manager?');
1399
1400
                    break;
1401
                case 9:
1402
                    $this->question = get_lang('The marasmus is a consequence of');
1403
1404
                    break;
1405
            }
1406
        }
1407
1408
        if (null !== $exercise) {
1409
            if ($exercise->questionFeedbackEnabled && $this->showFeedback($exercise)) {
1410
                $form->addTextarea('feedback', get_lang('Feedback if not correct'));
1411
            }
1412
        }
1413
1414
        $extraField = new ExtraField('question');
1415
        $extraField->addElements($form, $this->iid);
1416
1417
        // default values
1418
        $defaults = [];
1419
        $defaults['questionName'] = $this->question;
1420
        $defaults['questionDescription'] = $this->description;
1421
        $defaults['questionLevel'] = $this->level;
1422
        $defaults['questionCategory'] = $this->category;
1423
        $defaults['feedback'] = $this->feedback;
1424
        $defaults['mandatory'] = $this->mandatory;
1425
1426
        // Came from he question pool
1427
        if (isset($_GET['fromExercise'])) {
1428
            $form->setDefaults($defaults);
1429
        }
1430
1431
        if (!isset($_GET['newQuestion']) || $isContent) {
1432
            $form->setDefaults($defaults);
1433
        }
1434
1435
        /*if (!empty($_REQUEST['myid'])) {
1436
            $form->setDefaults($defaults);
1437
        } else {
1438
            if ($isContent == 1) {
1439
                $form->setDefaults($defaults);
1440
            }
1441
        }*/
1442
    }
1443
1444
    /**
1445
     * Function which process the creation of questions.
1446
     */
1447
    public function processCreation(FormValidator $form, Exercise $exercise)
1448
    {
1449
        $this->updateTitle($form->getSubmitValue('questionName'));
1450
        $this->updateDescription($form->getSubmitValue('questionDescription'));
1451
        $this->updateLevel($form->getSubmitValue('questionLevel'));
1452
        $this->updateCategory($form->getSubmitValue('questionCategory'));
1453
        $this->setMandatory($form->getSubmitValue('mandatory'));
1454
        $this->setFeedback($form->getSubmitValue('feedback'));
1455
1456
        //Save normal question if NOT media
1457
        if (MEDIA_QUESTION != $this->type) {
1458
            $this->save($exercise);
1459
            // modify the exercise
1460
            $exercise->addToList($this->id);
1461
            $exercise->update_question_positions();
1462
1463
            $params = $form->exportValues();
1464
            $params['item_id'] = $this->id;
1465
1466
            $extraFieldValues = new ExtraFieldValue('question');
1467
            $extraFieldValues->saveFieldValues($params);
1468
        }
1469
    }
1470
1471
    /**
1472
     * abstract function which creates the form to create / edit the answers of the question.
1473
     */
1474
    abstract public function createAnswersForm(FormValidator $form);
1475
1476
    /**
1477
     * abstract function which process the creation of answers.
1478
     *
1479
     * @param FormValidator $form
1480
     * @param Exercise      $exercise
1481
     */
1482
    abstract public function processAnswersCreation($form, $exercise);
1483
1484
    /**
1485
     * Displays the menu of question types.
1486
     *
1487
     * @param Exercise $objExercise
1488
     */
1489
    public static function displayTypeMenu($objExercise)
1490
    {
1491
        if (empty($objExercise)) {
1492
            return '';
1493
        }
1494
1495
        $feedbackType = $objExercise->getFeedbackType();
1496
        $exerciseId = $objExercise->id;
1497
1498
        // 1. by default we show all the question types
1499
        $questionTypeList = self::getQuestionTypeList();
1500
1501
        if (!isset($feedbackType)) {
1502
            $feedbackType = 0;
1503
        }
1504
1505
        switch ($feedbackType) {
1506
            case EXERCISE_FEEDBACK_TYPE_DIRECT:
1507
                $questionTypeList = [
1508
                    UNIQUE_ANSWER => self::$questionTypes[UNIQUE_ANSWER],
1509
                    HOT_SPOT_DELINEATION => self::$questionTypes[HOT_SPOT_DELINEATION],
1510
                ];
1511
1512
                break;
1513
            case EXERCISE_FEEDBACK_TYPE_POPUP:
1514
                $questionTypeList = [
1515
                    UNIQUE_ANSWER => self::$questionTypes[UNIQUE_ANSWER],
1516
                    MULTIPLE_ANSWER => self::$questionTypes[MULTIPLE_ANSWER],
1517
                    DRAGGABLE => self::$questionTypes[DRAGGABLE],
1518
                    HOT_SPOT_DELINEATION => self::$questionTypes[HOT_SPOT_DELINEATION],
1519
                    CALCULATED_ANSWER => self::$questionTypes[CALCULATED_ANSWER],
1520
                ];
1521
1522
                break;
1523
            default:
1524
                unset($questionTypeList[HOT_SPOT_DELINEATION]);
1525
1526
                break;
1527
        }
1528
1529
        echo '<div class="card">';
1530
        echo '<div class="card-body">';
1531
        echo '<ul class="question_menu">';
1532
        foreach ($questionTypeList as $i => $type) {
1533
            /** @var Question $type */
1534
            $type = new $type[1]();
1535
            $img = $type->getTypePicture();
1536
            $explanation = $type->getExplanation();
1537
            echo '<li>';
1538
            echo '<div class="icon-image">';
1539
            $icon = '<a href="admin.php?'.api_get_cidreq().'&newQuestion=yes&answerType='.$i.'&exerciseId='.$exerciseId.'">'.
1540
                Display::return_icon($img, $explanation, null, ICON_SIZE_BIG).'</a>';
1541
1542
            if (false === $objExercise->force_edit_exercise_in_lp) {
1543
                if (true == $objExercise->exercise_was_added_in_lp) {
1544
                    $img = pathinfo($img);
1545
                    $img = $img['filename'].'_na.'.$img['extension'];
1546
                    $icon = Display::return_icon($img, $explanation, null, ICON_SIZE_BIG);
1547
                }
1548
            }
1549
            echo $icon;
1550
            echo '</div>';
1551
            echo '</li>';
1552
        }
1553
1554
        echo '<li>';
1555
        echo '<div class="icon_image_content">';
1556
        if (true == $objExercise->exercise_was_added_in_lp) {
1557
            echo Display::return_icon(
1558
                'database_na.png',
1559
                get_lang('Recycle existing questions'),
1560
                null,
1561
                ICON_SIZE_BIG
1562
            );
1563
        } else {
1564
            if (in_array($feedbackType, [EXERCISE_FEEDBACK_TYPE_DIRECT, EXERCISE_FEEDBACK_TYPE_POPUP])) {
1565
                echo $url = '<a href="question_pool.php?'.api_get_cidreq()."&type=1&fromExercise=$exerciseId\">";
1566
            } else {
1567
                echo $url = '<a href="question_pool.php?'.api_get_cidreq().'&fromExercise='.$exerciseId.'">';
1568
            }
1569
            echo Display::return_icon(
1570
                'database.png',
1571
                get_lang('Recycle existing questions'),
1572
                null,
1573
                ICON_SIZE_BIG
1574
            );
1575
        }
1576
        echo '</a>';
1577
        echo '</div></li>';
1578
        echo '</ul>';
1579
        echo '</div>';
1580
        echo '</div>';
1581
    }
1582
1583
    /**
1584
     * @param int    $question_id
1585
     * @param string $name
1586
     * @param int    $course_id
1587
     * @param int    $position
1588
     *
1589
     * @return false|string
1590
     */
1591
    public static function saveQuestionOption($question_id, $name, $course_id, $position = 0)
1592
    {
1593
        $table = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
1594
        $params['question_id'] = (int) $question_id;
1595
        $params['name'] = $name;
1596
        $params['position'] = $position;
1597
        $params['c_id'] = $course_id;
1598
1599
        return Database::insert($table, $params);
1600
    }
1601
1602
    /**
1603
     * @param int $question_id
1604
     * @param int $course_id
1605
     */
1606
    public static function deleteAllQuestionOptions($question_id, $course_id)
1607
    {
1608
        $table = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
1609
        Database::delete(
1610
            $table,
1611
            [
1612
                'c_id = ? AND question_id = ?' => [
1613
                    $course_id,
1614
                    $question_id,
1615
                ],
1616
            ]
1617
        );
1618
    }
1619
1620
    /**
1621
     * @param int   $id
1622
     * @param array $params
1623
     * @param int   $course_id
1624
     *
1625
     * @return bool|int
1626
     */
1627
    public static function updateQuestionOption($id, $params, $course_id)
1628
    {
1629
        $table = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
1630
1631
        return Database::update(
1632
            $table,
1633
            $params,
1634
            ['c_id = ? AND iid = ?' => [$course_id, $id]]
1635
        );
1636
    }
1637
1638
    /**
1639
     * @param int $question_id
1640
     * @param int $course_id
1641
     *
1642
     * @return array
1643
     */
1644
    public static function readQuestionOption($question_id, $course_id)
1645
    {
1646
        $table = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
1647
1648
        return Database::select(
1649
            '*',
1650
            $table,
1651
            [
1652
                'where' => [
1653
                    'c_id = ? AND question_id = ?' => [
1654
                        $course_id,
1655
                        $question_id,
1656
                    ],
1657
                ],
1658
                'order' => 'iid ASC',
1659
            ]
1660
        );
1661
    }
1662
1663
    /**
1664
     * Shows question title an description.
1665
     *
1666
     * @param int   $counter
1667
     * @param array $score
1668
     *
1669
     * @return string HTML string with the header of the question (before the answers table)
1670
     */
1671
    public function return_header(Exercise $exercise, $counter = null, $score = [])
1672
    {
1673
        $counterLabel = '';
1674
        if (!empty($counter)) {
1675
            $counterLabel = (int) $counter;
1676
        }
1677
1678
        $scoreLabel = get_lang('Wrong');
1679
        if (in_array($exercise->results_disabled, [
1680
            RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER,
1681
            RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING,
1682
        ])
1683
        ) {
1684
            $scoreLabel = get_lang('Wrong answer. The correct one was:');
1685
        }
1686
1687
        $class = 'error';
1688
        if (isset($score['pass']) && true == $score['pass']) {
1689
            $scoreLabel = get_lang('Correct');
1690
1691
            if (in_array($exercise->results_disabled, [
1692
                RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER,
1693
                RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING,
1694
            ])
1695
            ) {
1696
                $scoreLabel = get_lang('Correct answer');
1697
            }
1698
            $class = 'success';
1699
        }
1700
1701
        switch ($this->type) {
1702
            case FREE_ANSWER:
1703
            case ORAL_EXPRESSION:
1704
            case ANNOTATION:
1705
                $score['revised'] = isset($score['revised']) ? $score['revised'] : false;
1706
                if (true == $score['revised']) {
1707
                    $scoreLabel = get_lang('Revised');
1708
                    $class = '';
1709
                } else {
1710
                    $scoreLabel = get_lang('Not reviewed');
1711
                    $class = 'warning';
1712
                    if (isset($score['weight'])) {
1713
                        $weight = float_format($score['weight'], 1);
1714
                        $score['result'] = ' ? / '.$weight;
1715
                    }
1716
                    $model = ExerciseLib::getCourseScoreModel();
1717
                    if (!empty($model)) {
1718
                        $score['result'] = ' ? ';
1719
                    }
1720
1721
                    $hide = api_get_configuration_value('hide_free_question_score');
1722
                    if (true === $hide) {
1723
                        $score['result'] = '-';
1724
                    }
1725
                }
1726
1727
                break;
1728
            case UNIQUE_ANSWER:
1729
                if (in_array($exercise->results_disabled, [
1730
                    RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER,
1731
                    RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING,
1732
                ])
1733
                ) {
1734
                    if (isset($score['user_answered'])) {
1735
                        if (false === $score['user_answered']) {
1736
                            $scoreLabel = get_lang('Unanswered');
1737
                            $class = 'info';
1738
                        }
1739
                    }
1740
                }
1741
1742
                break;
1743
        }
1744
1745
        // display question category, if any
1746
        $header = '';
1747
        if ($exercise->display_category_name) {
1748
            $header = TestCategory::returnCategoryAndTitle($this->id);
1749
        }
1750
        $show_media = '';
1751
        if ($show_media) {
1752
            $header .= $this->show_media_content();
1753
        }
1754
1755
        $scoreCurrent = [
1756
            'used' => isset($score['score']) ? $score['score'] : '',
1757
            'missing' => isset($score['weight']) ? $score['weight'] : '',
1758
        ];
1759
        $header .= Display::page_subheader2($counterLabel.'. '.$this->question);
1760
1761
        $showRibbon = true;
1762
        // dont display score for certainty degree questions
1763
        if (MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY == $this->type) {
1764
            $showRibbon = false;
1765
            $ribbonResult = api_get_configuration_value('show_exercise_question_certainty_ribbon_result');
1766
            if (true === $ribbonResult) {
1767
                $showRibbon = true;
1768
            }
1769
        }
1770
1771
        if ($showRibbon && isset($score['result'])) {
1772
            if (in_array($exercise->results_disabled, [
1773
                RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER,
1774
                RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING,
1775
            ])
1776
            ) {
1777
                $score['result'] = null;
1778
            }
1779
            $header .= $exercise->getQuestionRibbon($class, $scoreLabel, $score['result'], $scoreCurrent);
1780
        }
1781
1782
        if (READING_COMPREHENSION != $this->type) {
1783
            // Do not show the description (the text to read) if the question is of type READING_COMPREHENSION
1784
            $header .= Display::div(
1785
                $this->description,
1786
                ['class' => 'question_description']
1787
            );
1788
        } else {
1789
            if (true == $score['pass']) {
1790
                $message = Display::div(
1791
                    sprintf(
1792
                        get_lang('Congratulations, you have reached and correctly understood, at a speed of %s words per minute, a text of a total %s words.'),
1793
                        ReadingComprehension::$speeds[$this->level],
1794
                        $this->getWordsCount()
1795
                    )
1796
                );
1797
            } else {
1798
                $message = Display::div(
1799
                    sprintf(
1800
                        get_lang('Sorry, it seems like a speed of %s words/minute was too fast for this text of %s words.'),
1801
                        ReadingComprehension::$speeds[$this->level],
1802
                        $this->getWordsCount()
1803
                    )
1804
                );
1805
            }
1806
            $header .= $message.'<br />';
1807
        }
1808
1809
        if ($exercise->hideComment && $this->type == HOT_SPOT) {
1810
            $header .= Display::return_message(get_lang('ResultsOnlyAvailableOnline'));
1811
1812
            return $header;
1813
        }
1814
1815
        if (isset($score['pass']) && $score['pass'] === false) {
1816
            if ($this->showFeedback($exercise)) {
1817
                $header .= $this->returnFormatFeedback();
1818
            }
1819
        }
1820
1821
        return $header;
1822
    }
1823
1824
    /**
1825
     * @deprecated
1826
     * Create a question from a set of parameters
1827
     *
1828
     * @param int    $question_name        Quiz ID
1829
     * @param string $question_description Question name
1830
     * @param int    $max_score            Maximum result for the question
1831
     * @param int    $type                 Type of question (see constants at beginning of question.class.php)
1832
     * @param int    $level                Question level/category
1833
     * @param string $quiz_id
1834
     */
1835
    public function create_question(
1836
        $quiz_id,
1837
        $question_name,
1838
        $question_description = '',
1839
        $max_score = 0,
1840
        $type = 1,
1841
        $level = 1
1842
    ) {
1843
        $course_id = api_get_course_int_id();
1844
        $tbl_quiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
1845
        $tbl_quiz_rel_question = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
1846
1847
        $quiz_id = (int) $quiz_id;
1848
        $max_score = (float) $max_score;
1849
        $type = (int) $type;
1850
        $level = (int) $level;
1851
1852
        // Get the max position
1853
        $sql = "SELECT max(position) as max_position
1854
                FROM $tbl_quiz_question q
1855
                INNER JOIN $tbl_quiz_rel_question r
1856
                ON
1857
                    q.id = r.question_id AND
1858
                    exercice_id = $quiz_id AND
1859
                    q.c_id = $course_id AND
1860
                    r.c_id = $course_id";
1861
        $rs_max = Database::query($sql);
1862
        $row_max = Database::fetch_object($rs_max);
1863
        $max_position = $row_max->max_position + 1;
1864
1865
        $params = [
1866
            'c_id' => $course_id,
1867
            'question' => $question_name,
1868
            'description' => $question_description,
1869
            'ponderation' => $max_score,
1870
            'position' => $max_position,
1871
            'type' => $type,
1872
            'level' => $level,
1873
        ];
1874
        $question_id = Database::insert($tbl_quiz_question, $params);
1875
1876
        if ($question_id) {
1877
            // Get the max question_order
1878
            $sql = "SELECT max(question_order) as max_order
1879
                    FROM $tbl_quiz_rel_question
1880
                    WHERE c_id = $course_id AND exercice_id = $quiz_id ";
1881
            $rs_max_order = Database::query($sql);
1882
            $row_max_order = Database::fetch_object($rs_max_order);
1883
            $max_order = $row_max_order->max_order + 1;
1884
            // Attach questions to quiz
1885
            $sql = "INSERT INTO $tbl_quiz_rel_question (c_id, question_id, exercice_id, question_order)
1886
                    VALUES($course_id, $question_id, $quiz_id, $max_order)";
1887
            Database::query($sql);
1888
        }
1889
1890
        return $question_id;
1891
    }
1892
1893
    /**
1894
     * @return string
1895
     */
1896
    public function getTypePicture()
1897
    {
1898
        return $this->typePicture;
1899
    }
1900
1901
    /**
1902
     * @return string
1903
     */
1904
    public function getExplanation()
1905
    {
1906
        return get_lang($this->explanationLangVar);
1907
    }
1908
1909
    /**
1910
     * Get course medias.
1911
     *
1912
     * @param int $course_id
1913
     *
1914
     * @return array
1915
     */
1916
    public static function get_course_medias(
1917
        $course_id,
1918
        $start = 0,
1919
        $limit = 100,
1920
        $sidx = 'question',
1921
        $sord = 'ASC',
1922
        $where_condition = []
1923
    ) {
1924
        $table_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
1925
        $default_where = [
1926
            'c_id = ? AND parent_id = 0 AND type = ?' => [
1927
                $course_id,
1928
                MEDIA_QUESTION,
1929
            ],
1930
        ];
1931
1932
        return Database::select(
1933
            '*',
1934
            $table_question,
1935
            [
1936
                'limit' => " $start, $limit",
1937
                'where' => $default_where,
1938
                'order' => "$sidx $sord",
1939
            ]
1940
        );
1941
    }
1942
1943
    /**
1944
     * Get count course medias.
1945
     *
1946
     * @param int $course_id course id
1947
     *
1948
     * @return int
1949
     */
1950
    public static function get_count_course_medias($course_id)
1951
    {
1952
        $table_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
1953
        $result = Database::select(
1954
            'count(*) as count',
1955
            $table_question,
1956
            [
1957
                'where' => [
1958
                    'c_id = ? AND parent_id = 0 AND type = ?' => [
1959
                        $course_id,
1960
                        MEDIA_QUESTION,
1961
                    ],
1962
                ],
1963
            ],
1964
            'first'
1965
        );
1966
1967
        if ($result && isset($result['count'])) {
1968
            return $result['count'];
1969
        }
1970
1971
        return 0;
1972
    }
1973
1974
    /**
1975
     * @param int $course_id
1976
     *
1977
     * @return array
1978
     */
1979
    public static function prepare_course_media_select($course_id)
1980
    {
1981
        $medias = self::get_course_medias($course_id);
1982
        $media_list = [];
1983
        $media_list[0] = get_lang('Not linked to media');
1984
1985
        if (!empty($medias)) {
1986
            foreach ($medias as $media) {
1987
                $media_list[$media['id']] = empty($media['question']) ? get_lang('Untitled') : $media['question'];
1988
            }
1989
        }
1990
1991
        return $media_list;
1992
    }
1993
1994
    /**
1995
     * @return array
1996
     */
1997
    public static function get_default_levels()
1998
    {
1999
        return [
2000
            1 => 1,
2001
            2 => 2,
2002
            3 => 3,
2003
            4 => 4,
2004
            5 => 5,
2005
        ];
2006
    }
2007
2008
    /**
2009
     * @return string
2010
     */
2011
    public function show_media_content()
2012
    {
2013
        $html = '';
2014
        if (0 != $this->parent_id) {
2015
            $parent_question = self::read($this->parent_id);
2016
            $html = $parent_question->show_media_content();
2017
        } else {
2018
            $html .= Display::page_subheader($this->selectTitle());
2019
            $html .= $this->selectDescription();
2020
        }
2021
2022
        return $html;
2023
    }
2024
2025
    /**
2026
     * Swap between unique and multiple type answers.
2027
     *
2028
     * @return UniqueAnswer|MultipleAnswer
2029
     */
2030
    public function swapSimpleAnswerTypes()
2031
    {
2032
        $oppositeAnswers = [
2033
            UNIQUE_ANSWER => MULTIPLE_ANSWER,
2034
            MULTIPLE_ANSWER => UNIQUE_ANSWER,
2035
        ];
2036
        $this->type = $oppositeAnswers[$this->type];
2037
        Database::update(
2038
            Database::get_course_table(TABLE_QUIZ_QUESTION),
2039
            ['type' => $this->type],
2040
            ['c_id = ? AND id = ?' => [$this->course['real_id'], $this->id]]
2041
        );
2042
        $answerClasses = [
2043
            UNIQUE_ANSWER => 'UniqueAnswer',
2044
            MULTIPLE_ANSWER => 'MultipleAnswer',
2045
        ];
2046
        $swappedAnswer = new $answerClasses[$this->type]();
2047
        foreach ($this as $key => $value) {
2048
            $swappedAnswer->$key = $value;
2049
        }
2050
2051
        return $swappedAnswer;
2052
    }
2053
2054
    /**
2055
     * @param array $score
2056
     *
2057
     * @return bool
2058
     */
2059
    public function isQuestionWaitingReview($score)
2060
    {
2061
        $isReview = false;
2062
        if (!empty($score)) {
2063
            if (!empty($score['comments']) || $score['score'] > 0) {
2064
                $isReview = true;
2065
            }
2066
        }
2067
2068
        return $isReview;
2069
    }
2070
2071
    /**
2072
     * @param string $value
2073
     */
2074
    public function setFeedback($value)
2075
    {
2076
        $this->feedback = $value;
2077
    }
2078
2079
    /**
2080
     * @param Exercise $exercise
2081
     *
2082
     * @return bool
2083
     */
2084
    public function showFeedback($exercise)
2085
    {
2086
        if (false === $exercise->hideComment) {
2087
            return false;
2088
        }
2089
        return
2090
            in_array($this->type, $this->questionTypeWithFeedback) &&
2091
            EXERCISE_FEEDBACK_TYPE_EXAM != $exercise->getFeedbackType();
2092
    }
2093
2094
    /**
2095
     * @return string
2096
     */
2097
    public function returnFormatFeedback()
2098
    {
2099
        return '<br />'.Display::return_message($this->feedback, 'normal', false);
2100
    }
2101
2102
    /**
2103
     * Check if this question exists in another exercise.
2104
     *
2105
     * @throws \Doctrine\ORM\Query\QueryException
2106
     *
2107
     * @return bool
2108
     */
2109
    public function existsInAnotherExercise()
2110
    {
2111
        $count = $this->getCountExercise();
2112
2113
        return $count > 1;
2114
    }
2115
2116
    /**
2117
     * @throws \Doctrine\ORM\Query\QueryException
2118
     *
2119
     * @return int
2120
     */
2121
    public function getCountExercise()
2122
    {
2123
        $em = Database::getManager();
2124
2125
        $count = $em
2126
            ->createQuery('
2127
                SELECT COUNT(qq.iid) FROM ChamiloCourseBundle:CQuizRelQuestion qq
2128
                WHERE qq.question = :id
2129
            ')
2130
            ->setParameters(['id' => (int) $this->id])
2131
            ->getSingleScalarResult();
2132
2133
        return (int) $count;
2134
    }
2135
2136
    /**
2137
     * Check if this question exists in another exercise.
2138
     *
2139
     * @throws \Doctrine\ORM\Query\QueryException
2140
     */
2141
    public function getExerciseListWhereQuestionExists()
2142
    {
2143
        $em = Database::getManager();
2144
2145
        return $em
2146
            ->createQuery('
2147
                SELECT e
2148
                FROM ChamiloCourseBundle:CQuizRelQuestion qq
2149
                JOIN ChamiloCourseBundle:CQuiz e
2150
                WHERE e.iid = qq.exerciceId AND qq.questionId = :id
2151
            ')
2152
            ->setParameters(['id' => (int) $this->id])
2153
            ->getResult();
2154
    }
2155
2156
    /**
2157
     * @return int
2158
     */
2159
    public function countAnswers()
2160
    {
2161
        $result = Database::select(
2162
            'COUNT(1) AS c',
2163
            Database::get_course_table(TABLE_QUIZ_ANSWER),
2164
            ['where' => ['question_id = ?' => [$this->id]]],
2165
            'first'
2166
        );
2167
2168
        return (int) $result['c'];
2169
    }
2170
}
2171