Project

General

Profile

Feature #6813 » exercise.class.php

Miguel José Amez Riendas, 08/11/2013 10:33

 
1
<?php
2
/* For licensing terms, see /license.txt */
3
/**
4
 * Exercise class: This class allows to instantiate an object of type Exercise
5
 * @package chamilo.exercise
6
 * @author Olivier Brouckaert
7
 * @author Julio Montoya Cleaning exercises
8
 * Modified by Hubert Borderiou #294
9
 */
10
/**
11
 * Code
12
 */
13
define('ALL_ON_ONE_PAGE',                   1);
14
define('ONE_PER_PAGE',                      2);
15

    
16
define('EXERCISE_FEEDBACK_TYPE_END',        0); //Feedback 		 - show score and expected answers
17
define('EXERCISE_FEEDBACK_TYPE_DIRECT',     1); //DirectFeedback - Do not show score nor answers
18
define('EXERCISE_FEEDBACK_TYPE_EXAM',       2); //NoFeedback 	 - Show score only
19

    
20
define('RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS',        0); //show score and expected answers
21
define('RESULT_DISABLE_NO_SCORE_AND_EXPECTED_ANSWERS',     1); //Do not show score nor answers
22
define('RESULT_DISABLE_SHOW_SCORE_ONLY',       2); //Show score only
23
define('RESULT_DISABLE_SHOW_FINAL_SCORE_ONLY_WITH_CATEGORIES',       3); //Show final score only with categories
24

    
25
define('EXERCISE_MAX_NAME_SIZE',            80);
26

    
27
$debug = false; //All exercise scripts should depend in this debug variable
28

    
29
require_once dirname(__FILE__).'/../inc/lib/exercise_show_functions.lib.php';
30

    
31
class Exercise {
32

    
33
    public $id;
34
    public $name;
35
    public $title;
36
    public $exercise;
37
    public $description;
38
    public $sound;
39
    public $type; //ALL_ON_ONE_PAGE or ONE_PER_PAGE
40
    public $random;
41
    public $random_answers;
42
    public $active;
43
    public $timeLimit;
44
    public $attempts;
45
    public $feedback_type;
46
    public $end_time;
47
    public $start_time;
48
    public $questionList;  // array with the list of this exercise's questions
49
    public $results_disabled;
50
    public $expired_time;
51
    public $course;
52
    public $course_id;
53
    public $propagate_neg;
54
    public $review_answers;
55
    public $randomByCat;
56
    public $text_when_finished;
57
    public $display_category_name;
58
    public $pass_percentage;
59
    public $edit_exercise_in_lp = false;
60
    public $is_gradebook_locked = false;
61
    public $exercise_was_added_in_lp = false;
62
    public $force_edit_exercise_in_lp = false;
63

    
64
    /**
65
     * Constructor of the class
66
     *
67
     * @author - Olivier Brouckaert
68
     */
69
    function Exercise($course_id = null) {
70
        $this->id				= 0;
71
        $this->exercise			= '';
72
        $this->description		= '';
73
        $this->sound			= '';
74
        $this->type				= ALL_ON_ONE_PAGE;
75
        $this->random			= 0;
76
        $this->random_answers	= 0;
77
        $this->active			= 1;
78
        $this->questionList		= array();
79
        $this->timeLimit 		= 0;
80
        $this->end_time 		= '0000-00-00 00:00:00';
81
        $this->start_time 		= '0000-00-00 00:00:00';
82
        $this->results_disabled = 1;
83
        $this->expired_time 	= '0000-00-00 00:00:00';
84
        $this->propagate_neg    = 0;
85
        $this->review_answers	= false;
86
        $this->randomByCat      = 0;	//
87
        $this->text_when_finished = ""; //
88
        $this->display_category_name = 0;
89
        $this->pass_percentage  = null;
90

    
91
        if (!empty($course_id)) {
92
            $course_info        = api_get_course_info_by_id($course_id);
93
        } else {
94
            $course_info 		= api_get_course_info();
95
        }
96
        $this->course_id    = $course_info['real_id'];
97
        $this->course   	= $course_info;
98
    }
99

    
100
    /**
101
     * reads exercise informations from the data base
102
     *
103
     * @author - Olivier Brouckaert
104
     * @param - integer $id - exercise ID
105
     * @return - boolean - true if exercise exists, otherwise false
106
     */
107
    function read($id) {
108
        global $_configuration;
109
        $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
110
        $table_lp_item = Database::get_course_table(TABLE_LP_ITEM);
111

    
112
        $id  = intval($id);
113
        if (empty($this->course_id)) {
114
            return false;
115
        }
116
        $sql = "SELECT * FROM $TBL_EXERCICES WHERE c_id = ".$this->course_id." AND id = ".$id;
117
        $result = Database::query($sql);
118

    
119
        // if the exercise has been found
120
        if ($object = Database::fetch_object($result)) {
121
            $this->id                       = $id;
122
            $this->exercise                 = $object->title;
123
            $this->name                     = $object->title;
124
            $this->title                    = $object->title;
125
            $this->description              = $object->description;
126
            $this->sound                    = $object->sound;
127
            $this->type                     = $object->type;
128
            if (empty($this->type)) {
129
                $this->type = ONE_PER_PAGE;
130
            }
131
            $this->random                   = $object->random;
132
            $this->random_answers           = $object->random_answers;
133
            $this->active                   = $object->active;
134
            $this->results_disabled         = $object->results_disabled;
135
            $this->attempts                 = $object->max_attempt;
136
            $this->feedback_type            = $object->feedback_type;
137
            $this->propagate_neg            = $object->propagate_neg;
138
            $this->randomByCat              = $object->random_by_category;
139
            $this->text_when_finished       = $object->text_when_finished;
140
            $this->display_category_name    = $object->display_category_name;
141
            $this->pass_percentage          = $object->pass_percentage;
142

    
143
            $this->is_gradebook_locked      = api_resource_is_locked_by_gradebook($id, LINK_EXERCISE);
144

    
145
            $this->review_answers   = (isset($object->review_answers) && $object->review_answers == 1) ? true : false;
146

    
147
            $sql = "SELECT max_score FROM $table_lp_item
148
                    WHERE   c_id = {$this->course_id} AND
149
                            item_type = '".TOOL_QUIZ."' AND
150
                            path = '".$id."'";
151
            $result = Database::query($sql);
152

    
153
            if (Database::num_rows($result) > 0) {
154
                $this->exercise_was_added_in_lp = true;
155
            }
156

    
157
            $this->force_edit_exercise_in_lp = isset($_configuration['force_edit_exercise_in_lp']) ? $_configuration['force_edit_exercise_in_lp'] : false;
158

    
159
            if ($this->exercise_was_added_in_lp) {
160
                $this->edit_exercise_in_lp = $this->force_edit_exercise_in_lp == true;
161
            } else {
162
                $this->edit_exercise_in_lp = true;
163
            }
164

    
165
            if ($object->end_time != '0000-00-00 00:00:00') {
166
                $this->end_time 	= $object->end_time;
167
            }
168
            if ($object->start_time != '0000-00-00 00:00:00') {
169
                $this->start_time 	= $object->start_time;
170
            }
171

    
172
            //control time
173
            $this->expired_time 	= $object->expired_time;
174

    
175
            //Checking if question_order is correctly set
176
            $this->questionList     = $this->selectQuestionList(true);
177

    
178
            //overload questions list with recorded questions list
179
            //load questions only for exercises of type 'one question per page'
180
            //this is needed only is there is no questions
181
            /*
182
			// @todo not sure were in the code this is used somebody mess with the exercise tool
183
			// @todo don't know who add that config and why $_configuration['live_exercise_tracking']
184
			global $_configuration, $questionList;
185
			if ($this->type == ONE_PER_PAGE && $_SERVER['REQUEST_METHOD'] != 'POST' && defined('QUESTION_LIST_ALREADY_LOGGED') &&
186
			isset($_configuration['live_exercise_tracking']) && $_configuration['live_exercise_tracking']) {
187
				$this->questionList = $questionList;
188
			}*/
189
            return true;
190
        }
191
        // exercise not found
192
        return false;
193
    }
194

    
195
    function getCutTitle() {
196
        return cut($this->exercise, EXERCISE_MAX_NAME_SIZE);
197
    }
198

    
199
    /**
200
     * returns the exercise ID
201
     *
202
     * @author - Olivier Brouckaert
203
     * @return - integer - exercise ID
204
     */
205
    function selectId() {
206
        return $this->id;
207
    }
208

    
209
    /**
210
     * returns the exercise title
211
     *
212
     * @author - Olivier Brouckaert
213
     * @return - string - exercise title
214
     */
215
    function selectTitle() {
216
        return $this->exercise;
217
    }
218

    
219
    /**
220
     * returns the number of attempts setted
221
     *
222
     * @return - numeric - exercise attempts
223
     */
224
    function selectAttempts() {
225
        return $this->attempts;
226
    }
227

    
228
    /** returns the number of FeedbackType  *
229
     *  0=>Feedback , 1=>DirectFeedback, 2=>NoFeedback
230
     * @return - numeric - exercise attempts
231
     */
232
    function selectFeedbackType() {
233
        return $this->feedback_type;
234
    }
235

    
236
    /**
237
     * returns the time limit
238
     */
239
    function selectTimeLimit() {
240
        return $this->timeLimit;
241
    }
242

    
243
    /**
244
     * returns the exercise description
245
     *
246
     * @author - Olivier Brouckaert
247
     * @return - string - exercise description
248
     */
249
    function selectDescription() {
250
        return $this->description;
251
    }
252

    
253
    /**
254
     * returns the exercise sound file
255
     *
256
     * @author - Olivier Brouckaert
257
     * @return - string - exercise description
258
     */
259
    function selectSound() {
260
        return $this->sound;
261
    }
262

    
263
    /**
264
     * returns the exercise type
265
     *
266
     * @author - Olivier Brouckaert
267
     * @return - integer - exercise type
268
     */
269
    function selectType() {
270
        return $this->type;
271
    }
272

    
273
    /**
274
     * @author - hubert borderiou 30-11-11
275
     * @return - integer : do we display the question category name for students
276
     */
277
    function selectDisplayCategoryName() {
278
        return $this->display_category_name;
279
    }
280

    
281
    function selectPassPercentage() {
282
        return $this->pass_percentage;
283
    }
284

    
285
    /**
286
     * @author - hubert borderiou 30-11-11
287
     * @return - : modify object to update the switch display_category_name
288
     * $in_txt is an integer 0 or 1
289
     */
290
    function updateDisplayCategoryName($in_txt) {
291
        $this->display_category_name = $in_txt;
292
    }
293

    
294
    /**
295
     * @author - hubert borderiou 28-11-11
296
     * @return - html text : the text to display ay the end of the test.
297
     */
298
    function selectTextWhenFinished() {
299
        return $this->text_when_finished;
300
    }
301

    
302
    /**
303
     * @author - hubert borderiou 28-11-11
304
     * @return - html text : update the text to display ay the end of the test.
305
     */
306
    function updateTextWhenFinished($in_txt) {
307
        $this->text_when_finished = $in_txt;
308
    }
309

    
310
    /**
311
     * return 1 or 2 if randomByCat
312
     * @author - hubert borderiou
313
     * @return - integer - quiz random by category
314
     */
315
    function selectRandomByCat() {
316
        return $this->randomByCat;
317
    }
318

    
319
    /**
320
     * return 0 if no random by cat
321
     * return 1 if random by cat, categories shuffled
322
     * return 2 if random by cat, categories sorted by alphabetic order
323
     * @author - hubert borderiou
324
     * @return - integer - quiz random by category
325
     */
326
    function isRandomByCat() {
327
        $res = 0;
328
        if ($this->randomByCat == 1) {
329
            $res = 1;
330
        } else if ($this->randomByCat == 2) {
331
            $res = 2;
332
        }
333
        return $res;
334
    }
335

    
336
    /**
337
     * return nothing
338
     * update randomByCat value for object
339
     * @author - hubert borderiou
340
     */
341
    function updateRandomByCat($in_randombycat) {
342
        if ($in_randombycat == 1) {
343
            $this->randomByCat = 1;
344
        } else if ($in_randombycat == 2) {
345
            $this->randomByCat = 2;
346
        } else {
347
            $this->randomByCat = 0;
348
        }
349
    }
350

    
351

    
352
    /**
353
     * tells if questions are selected randomly, and if so returns the draws
354
     *
355
     * @author - Carlos Vargas
356
     * @return - integer - results disabled exercise
357
     */
358
    function selectResultsDisabled() {
359
        return $this->results_disabled;
360
    }
361

    
362
    /**
363
     * tells if questions are selected randomly, and if so returns the draws
364
     *
365
     * @author - Olivier Brouckaert
366
     * @return - integer - 0 if not random, otherwise the draws
367
     */
368
    function isRandom() {
369
        if($this->random > 0 || $this->random == -1) {
370
            return true;
371
        } else {
372
            return false;
373
        }
374
    }
375

    
376
    /**
377
     * returns random answers status.
378
     *
379
     * @author - Juan Carlos Ra�a
380
     */
381
    function selectRandomAnswers() {
382
        return $this->random_answers;
383
    }
384

    
385
    /**
386
     * Same as isRandom() but has a name applied to values different than 0 or 1
387
     */
388
    function getShuffle() {
389
        return $this->random;
390
    }
391

    
392
    /**
393
     * returns the exercise status (1 = enabled ; 0 = disabled)
394
     *
395
     * @author - Olivier Brouckaert
396
     * @return - boolean - true if enabled, otherwise false
397
     */
398
    function selectStatus() {
399
        return $this->active;
400
    }
401

    
402
    /**
403
     * returns the array with the question ID list
404
     *
405
     * @author - Olivier Brouckaert
406
     * @return - array - question ID list
407
     */
408
    function selectQuestionList($from_db = false) {
409
        if ($from_db && !empty($this->id)) {
410
            $TBL_EXERCICE_QUESTION  = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
411
            $TBL_QUESTIONS          = Database::get_course_table(TABLE_QUIZ_QUESTION);
412

    
413
            $sql = "SELECT DISTINCT e.question_order
414
                    FROM $TBL_EXERCICE_QUESTION e INNER JOIN $TBL_QUESTIONS  q
415
                        ON (e.question_id = q.id AND e.c_id = ".$this->course_id." AND q.c_id = ".$this->course_id.")
416
					WHERE e.exercice_id	= '".Database::escape_string($this->id)."'";
417
            $result = Database::query($sql);
418

    
419
            $count_question_orders = Database::num_rows($result);
420

    
421
            $sql = "SELECT e.question_id, e.question_order
422
                    FROM $TBL_EXERCICE_QUESTION e INNER JOIN $TBL_QUESTIONS  q
423
                        ON (e.question_id= q.id AND e.c_id = ".$this->course_id." AND q.c_id = ".$this->course_id.")
424
					WHERE e.exercice_id	= '".Database::escape_string($this->id)."'
425
					ORDER BY question_order";
426
            $result = Database::query($sql);
427

    
428
            // fills the array with the question ID for this exercise
429
            // the key of the array is the question position
430
            $temp_question_list = array();
431
            $counter = 1;
432
            $question_list = array();
433

    
434
            while ($new_object = Database::fetch_object($result)) {
435
                $question_list[$new_object->question_order]=  $new_object->question_id;
436
                $temp_question_list[$counter] = $new_object->question_id;
437
                $counter++;
438
            }
439

    
440
            if (!empty($temp_question_list)) {
441
                if (count($temp_question_list) != $count_question_orders) {
442
                    $question_list = $temp_question_list;
443
                }
444
            }
445
            return $question_list;
446
        }
447
        return $this->questionList;
448
    }
449

    
450
    /**
451
     * returns the number of questions in this exercise
452
     *
453
     * @author - Olivier Brouckaert
454
     * @return - integer - number of questions
455
     */
456
    function selectNbrQuestions() {
457
        return sizeof($this->questionList);
458
    }
459

    
460
    function selectPropagateNeg() {
461
        return $this->propagate_neg;
462
    }
463

    
464
    /**
465
     * Selects questions randomly in the question list
466
     *
467
     * @author - Olivier Brouckaert
468
     * @return - array - if the exercise is not set to take questions randomly, returns the question list
469
     *					 without randomizing, otherwise, returns the list with questions selected randomly
470
     * Modified by Hubert Borderiou 15 nov 2011
471
     */
472
    function selectRandomList() {
473
        $nbQuestions	= $this->selectNbrQuestions();
474
        $temp_list		= $this->questionList;
475

    
476
        //Not a random exercise, or if there are not at least 2 questions
477
        if($this->random == 0 || $nbQuestions < 2) {
478
            return $this->questionList;
479
        }
480
        if ($nbQuestions != 0) {
481
            shuffle($temp_list);
482
            $my_random_list = array_combine(range(1,$nbQuestions),$temp_list);
483
            $my_question_list = array();
484
            // $this->random == -1 if random with all questions
485
            if ($this->random > 0) {
486
                $i = 0;
487
                foreach ($my_random_list as $item) {
488
                    if ($i < $this->random) {
489
                        $my_question_list[$i] = $item;
490
                    } else {
491
                        break;
492
                    }
493
                    $i++;
494
                }
495
            } else {
496
                $my_question_list = $my_random_list;
497
            }
498
            return $my_question_list;
499
        }
500
    }
501

    
502
    /**
503
     * returns 'true' if the question ID is in the question list
504
     *
505
     * @author - Olivier Brouckaert
506
     * @param - integer $questionId - question ID
507
     * @return - boolean - true if in the list, otherwise false
508
     */
509
    function isInList($questionId) {
510
        if (is_array($this->questionList))
511
            return in_array($questionId,$this->questionList);
512
        else
513
            return false;
514
    }
515

    
516
    /**
517
     * changes the exercise title
518
     *
519
     * @author - Olivier Brouckaert
520
     * @param - string $title - exercise title
521
     */
522
    function updateTitle($title) {
523
        $this->exercise=$title;
524
    }
525

    
526
    /**
527
     * changes the exercise max attempts
528
     *
529
     * @param - numeric $attempts - exercise max attempts
530
     */
531
    function updateAttempts($attempts) {
532
        $this->attempts=$attempts;
533
    }
534

    
535

    
536
    /**
537
     * changes the exercise feedback type
538
     *
539
     * @param - numeric $attempts - exercise max attempts
540
     */
541
    function updateFeedbackType($feedback_type) {
542
        $this->feedback_type=$feedback_type;
543
    }
544

    
545
    /**
546
     * changes the exercise description
547
     *
548
     * @author - Olivier Brouckaert
549
     * @param - string $description - exercise description
550
     */
551
    function updateDescription($description) {
552
        $this->description=$description;
553
    }
554

    
555
    /**
556
     * changes the exercise expired_time
557
     *
558
     * @author - Isaac flores
559
     * @param - int The expired time of the quiz
560
     */
561
    function updateExpiredTime($expired_time) {
562
        $this->expired_time = $expired_time;
563
    }
564

    
565
    function updatePropagateNegative($value) {
566
        $this->propagate_neg = $value;
567
    }
568

    
569
    function updateReviewAnswers($value) {
570
        $this->review_answers = (isset($value) && $value) ? true : false;
571
    }
572

    
573
    function updatePassPercentage($value) {
574
        $this->pass_percentage = $value;
575
    }
576

    
577
    /**
578
     * changes the exercise sound file
579
     *
580
     * @author - Olivier Brouckaert
581
     * @param - string $sound - exercise sound file
582
     * @param - string $delete - ask to delete the file
583
     */
584
    function updateSound($sound,$delete) {
585
        global $audioPath, $documentPath;
586
        $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
587

    
588
        if ($sound['size'] && (strstr($sound['type'],'audio') || strstr($sound['type'],'video'))) {
589
            $this->sound=$sound['name'];
590

    
591
            if (@move_uploaded_file($sound['tmp_name'],$audioPath.'/'.$this->sound)) {
592
                $query="SELECT 1 FROM $TBL_DOCUMENT  WHERE c_id = ".$this->course_id." AND path='".str_replace($documentPath,'',$audioPath).'/'.$this->sound."'";
593
                $result=Database::query($query);
594

    
595
                if(!Database::num_rows($result)) {
596
                    /*$query="INSERT INTO $TBL_DOCUMENT(path,filetype) VALUES "
597
                     ." ('".str_replace($documentPath,'',$audioPath).'/'.$this->sound."','file')";
598
                    Database::query($query);*/
599
                    $id = add_document($this->course,str_replace($documentPath,'',$audioPath).'/'.$this->sound,'file',$sound['size'],$sound['name']);
600
                    api_item_property_update($this->course, TOOL_DOCUMENT, $id, 'DocumentAdded',api_get_user_id());
601
                    item_property_update_on_folder($this->course,str_replace($documentPath,'',$audioPath),api_get_user_id());
602
                }
603
            }
604
        } elseif($delete && is_file($audioPath.'/'.$this->sound)) {
605
            $this->sound='';
606
        }
607
    }
608

    
609
    /**
610
     * changes the exercise type
611
     *
612
     * @author - Olivier Brouckaert
613
     * @param - integer $type - exercise type
614
     */
615
    function updateType($type) {
616
        $this->type=$type;
617
    }
618

    
619
    /**
620
     * sets to 0 if questions are not selected randomly
621
     * if questions are selected randomly, sets the draws
622
     *
623
     * @author - Olivier Brouckaert
624
     * @param - integer $random - 0 if not random, otherwise the draws
625
     */
626
    function setRandom($random) {
627
        /*if ($random == 'all') {
628
            $random = $this->selectNbrQuestions();
629
        }*/
630
        $this->random = $random;
631
    }
632

    
633

    
634
    /**
635
     * sets to 0 if answers are not selected randomly
636
     * if answers are selected randomly
637
     * @author - Juan Carlos Ra�a
638
     * @param - integer $random_answers - random answers
639
     */
640
    function updateRandomAnswers($random_answers) {
641
        $this->random_answers = $random_answers;
642
    }
643

    
644
    /**
645
     * enables the exercise
646
     *
647
     * @author - Olivier Brouckaert
648
     */
649
    function enable() {
650
        $this->active=1;
651
    }
652

    
653
    /**
654
     * disables the exercise
655
     *
656
     * @author - Olivier Brouckaert
657
     */
658
    function disable() {
659
        $this->active=0;
660
    }
661

    
662
    function disable_results() {
663
        $this->results_disabled = true;
664
    }
665

    
666
    function enable_results() {
667
        $this->results_disabled = false;
668
    }
669

    
670
    function updateResultsDisabled($results_disabled) {
671
        $this->results_disabled = intval($results_disabled);
672
    }
673

    
674

    
675
    /**
676
     * updates the exercise in the data base
677
     *
678
     * @author - Olivier Brouckaert
679
     */
680
    function save($type_e = '') {
681
        global $_course;
682
        $TBL_EXERCICES      = Database::get_course_table(TABLE_QUIZ_TEST);
683

    
684
        $id                     = $this->id;
685
        $exercise               = $this->exercise;
686
        $description            = $this->description;
687
        $sound                  = $this->sound;
688
        $type                   = $this->type;
689
        $attempts               = $this->attempts;
690
        $feedback_type          = $this->feedback_type;
691
        $random                 = $this->random;
692
        $random_answers         = $this->random_answers;
693
        $active                 = $this->active;
694
        $propagate_neg          = $this->propagate_neg;
695
        $review_answers         = (isset($this->review_answers) && $this->review_answers) ? 1 : 0;
696
        $randomByCat            = $this->randomByCat;
697
        $text_when_finished     = $this->text_when_finished;
698
        $display_category_name  = intval($this->display_category_name);
699
        $pass_percentage        = intval($this->pass_percentage);
700

    
701
        $session_id             = api_get_session_id();
702

    
703
        //If direct we do not show results
704
        if ($feedback_type == EXERCISE_FEEDBACK_TYPE_DIRECT) {
705
            $results_disabled = 0;
706
        } else {
707
            $results_disabled = intval($this->results_disabled);
708
        }
709

    
710
        $expired_time = intval($this->expired_time);
711

    
712
        if (!empty($this->start_time) && $this->start_time != '0000-00-00 00:00:00') {
713
            $start_time = Database::escape_string(api_get_utc_datetime($this->start_time));
714
        } else {
715
            $start_time = '0000-00-00 00:00:00';
716
        }
717
        if (!empty($this->end_time) && $this->end_time != '0000-00-00 00:00:00') {
718
            $end_time 	= Database::escape_string(api_get_utc_datetime($this->end_time));
719
        } else {
720
            $end_time = '0000-00-00 00:00:00';
721
        }
722

    
723
        // Exercise already exists
724
        if ($id) {
725
            $sql="UPDATE $TBL_EXERCICES SET
726
				    title='".Database::escape_string($exercise)."',
727
					description='".Database::escape_string($description)."'";
728

    
729
            if ($type_e != 'simple') {
730
                $sql .= ",sound='".Database::escape_string($sound)."',
731
					type           ='".Database::escape_string($type)."',
732
					random         ='".Database::escape_string($random)."',
733
					random_answers ='".Database::escape_string($random_answers)."',
734
					active         ='".Database::escape_string($active)."',
735
					feedback_type  ='".Database::escape_string($feedback_type)."',
736
					start_time     = '$start_time',
737
					end_time       = '$end_time',
738
					max_attempt    ='".Database::escape_string($attempts)."',
739
     			    expired_time   ='".Database::escape_string($expired_time)."',
740
         			propagate_neg  ='".Database::escape_string($propagate_neg)."',
741
         			review_answers  ='".Database::escape_string($review_answers)."',
742
        	        random_by_category='".Database::escape_string($randomByCat)."',
743
        	        text_when_finished = '".Database::escape_string($text_when_finished)."',
744
        	        display_category_name = '".Database::escape_string($display_category_name)."',
745
                    pass_percentage = '".Database::escape_string($pass_percentage)."',
746
					results_disabled='".Database::escape_string($results_disabled)."'";
747
            }
748
            $sql .= " WHERE c_id = ".$this->course_id." AND id='".Database::escape_string($id)."'";
749
            Database::query($sql);
750

    
751
            // update into the item_property table
752
            api_item_property_update($_course, TOOL_QUIZ, $id,'QuizUpdated',api_get_user_id());
753

    
754
            if (api_get_setting('search_enabled')=='true') {
755
                $this->search_engine_edit();
756
            }
757
        } else {
758
            // creates a new exercise
759
            $sql = "INSERT INTO $TBL_EXERCICES (c_id, start_time, end_time, title, description, sound, type, random, random_answers, active,
760
                                                results_disabled, max_attempt, feedback_type, expired_time, session_id, review_answers, random_by_category,
761
                                                text_when_finished, display_category_name, pass_percentage)
762
					VALUES(
763
						".$this->course_id.",
764
						'$start_time','$end_time',
765
						'".Database::escape_string($exercise)."',
766
						'".Database::escape_string($description)."',
767
						'".Database::escape_string($sound)."',
768
						'".Database::escape_string($type)."',
769
						'".Database::escape_string($random)."',
770
						'".Database::escape_string($random_answers)."',
771
						'".Database::escape_string($active)."',
772
						'".Database::escape_string($results_disabled)."',
773
						'".Database::escape_string($attempts)."',
774
						'".Database::escape_string($feedback_type)."',
775
						'".Database::escape_string($expired_time)."',
776
						'".Database::escape_string($session_id)."',
777
						'".Database::escape_string($review_answers)."',
778
						'".Database::escape_string($randomByCat)."',
779
						'".Database::escape_string($text_when_finished)."',
780
						'".Database::escape_string($display_category_name)."',
781
                        '".Database::escape_string($pass_percentage)."'
782
						)";
783
            Database::query($sql);
784
            $this->id = Database::insert_id();
785

    
786
            // insert into the item_property table
787
            api_item_property_update($this->course, TOOL_QUIZ, $this->id, 'QuizAdded', api_get_user_id());
788
            api_set_default_visibility($this->id, TOOL_QUIZ);
789

    
790
            if (api_get_setting('search_enabled')=='true' && extension_loaded('xapian')) {
791
                $this->search_engine_save();
792
            }
793
        }
794

    
795
        // updates the question position
796
        $this->update_question_positions();
797
    }
798

    
799
    /* Updates question position */
800
    function update_question_positions() {
801
        $quiz_question_table = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
802
        //Fixes #3483 when updating order
803
        $question_list = $this->selectQuestionList(true);
804
        if (!empty($question_list)) {
805
            foreach ($question_list as $position => $questionId) {
806
                $sql="UPDATE $quiz_question_table SET question_order ='".intval($position)."'".
807
                    "WHERE c_id = ".$this->course_id." AND question_id = ".intval($questionId)." AND exercice_id=".intval($this->id);
808
                Database::query($sql);
809
            }
810
        }
811
    }
812

    
813
    /**
814
     * Adds a question into the question list
815
     *
816
     * @author - Olivier Brouckaert
817
     * @param - integer $questionId - question ID
818
     * @return - boolean - true if the question has been added, otherwise false
819
     */
820
    function addToList($questionId) {
821
        // checks if the question ID is not in the list
822
        if(!$this->isInList($questionId)) {
823
            // selects the max position
824
            if(!$this->selectNbrQuestions()) {
825
                $pos=1;
826
            } else {
827
                if (is_array($this->questionList))
828
                    $pos=max(array_keys($this->questionList))+1;
829
            }
830
            $this->questionList[$pos]=$questionId;
831
            return true;
832
        }
833
        return false;
834
    }
835

    
836
    /**
837
     * removes a question from the question list
838
     *
839
     * @author - Olivier Brouckaert
840
     * @param - integer $questionId - question ID
841
     * @return - boolean - true if the question has been removed, otherwise false
842
     */
843
    function removeFromList($questionId) {
844
        // searches the position of the question ID in the list
845
        $pos = array_search($questionId,$this->questionList);
846

    
847
        // question not found
848
        if ($pos === false) {
849
            return false;
850
        } else {
851
            // dont reduce the number of random question if we use random by category option, or if
852
            // random all questions
853
            if ($this->isRandom() && $this->isRandomByCat() == 0) {
854
                if (count($this->questionList) >= $this->random && $this->random > 0) {
855
                    $this->random -= 1;
856
                    $this->save();
857
                }
858
            }
859
            // deletes the position from the array containing the wanted question ID
860
            unset($this->questionList[$pos]);
861
            return true;
862
        }
863
    }
864

    
865
    /**
866
     * deletes the exercise from the database
867
     * Notice : leaves the question in the data base
868
     *
869
     * @author - Olivier Brouckaert
870
     */
871
    function delete() {
872
        $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
873
        $sql="UPDATE $TBL_EXERCICES SET active='-1' WHERE c_id = ".$this->course_id." AND id='".Database::escape_string($this->id)."'";
874
        Database::query($sql);
875
        api_item_property_update($this->course, TOOL_QUIZ, $this->id,'QuizDeleted',api_get_user_id());
876

    
877
        if (api_get_setting('search_enabled')=='true' && extension_loaded('xapian') ) {
878
            $this->search_engine_delete();
879
        }
880
    }
881

    
882
    /**
883
     * Creates the form to create / edit an exercise
884
     * @param FormValidator $form the formvalidator instance (by reference)
885
     */
886
    function createForm ($form, $type='full') {
887
        global $id;
888

    
889
        if (empty($type)){
890
            $type='full';
891
        }
892

    
893
        // form title
894
        if (!empty($_GET['exerciseId'])) {
895
            $form_title = get_lang('ModifyExercise');
896
        } else {
897
            $form_title = get_lang('NewEx');
898
        }
899

    
900
        $form->addElement('header', $form_title);
901

    
902
        // title
903
        $form->addElement('text', 'exerciseTitle', get_lang('ExerciseName'), array('class' => 'span6','id'=>'exercise_title'));
904
        //$form->applyFilter('exerciseTitle','html_filter');
905

    
906
        $form->addElement('advanced_settings','
907
			<a href="javascript://" onclick=" return show_media()">
908
				<span id="media_icon">
909
					<img style="vertical-align: middle;" src="../img/looknfeel.png" alt="" /> '.addslashes(api_htmlentities(get_lang('ExerciseDescription'))).'
910
					</span>
911
			</a>
912
		');
913

    
914
        $editor_config = array('ToolbarSet' => 'TestQuestionDescription', 'Width' => '100%', 'Height' => '150');
915
        if (is_array($type)){
916
            $editor_config = array_merge($editor_config, $type);
917
        }
918

    
919
        $form->addElement ('html','<div class="HideFCKEditor" id="HiddenFCKexerciseDescription" >');
920
        $form->add_html_editor('exerciseDescription', get_lang('ExerciseDescription'), false, false, $editor_config);
921
        $form->addElement ('html','</div>');
922

    
923
        $form->addElement('advanced_settings','<a href="javascript://" onclick=" return advanced_parameters()"><span id="img_plus_and_minus"><div style="vertical-align:top;" >
924
                            <img style="vertical-align:middle;" src="../img/div_show.gif" alt="" /> '.addslashes(api_htmlentities(get_lang('AdvancedParameters'))).'</div></span></a>');
925

    
926
        // Random questions
927
        // style="" and not "display:none" to avoid #4029 Random and number of attempt menu empty
928
        $form->addElement('html','<div id="options" style="">');
929

    
930
        if ($type=='full') {
931

    
932
            /*$feedback_option[0]=get_lang('ExerciseAtTheEndOfTheTest');
933
             $feedback_option[1]=get_lang('DirectFeedback');
934
            $feedback_option[2]=get_lang('NoFeedback');
935
            */
936
            //Can't modify a DirectFeedback question
937
            if ($this->selectFeedbackType() != EXERCISE_FEEDBACK_TYPE_DIRECT ) {
938
                // feedback type
939
                $radios_feedback = array();
940
                $radios_feedback[] = $form->createElement('radio', 'exerciseFeedbackType', null, get_lang('ExerciseAtTheEndOfTheTest'),'0',array('id' =>'exerciseType_0', 'onclick' => 'check_feedback()'));
941

    
942
                if (api_get_setting('enable_quiz_scenario') == 'true') {
943
                    //Can't convert a question from one feedback to another if there is more than 1 question already added
944
                    if ($this->selectNbrQuestions() == 0) {
945
                        $radios_feedback[] = $form->createElement('radio', 'exerciseFeedbackType', null, get_lang('DirectFeedback'),'1',array('id' =>'exerciseType_1' , 'onclick' => 'check_direct_feedback()'));
946
                    }
947
                }
948

    
949
                $radios_feedback[] = $form->createElement('radio', 'exerciseFeedbackType', null, get_lang('NoFeedback'),'2',array('id' =>'exerciseType_2'));
950
                $form->addGroup($radios_feedback, null, get_lang('FeedbackType'), '');
951

    
952
                // test type
953
                $radios = array();
954

    
955
                $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SimpleExercise'),    '1', array('onclick' => 'check_per_page_all()', 'id'=>'option_page_all'));
956
                $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SequentialExercise'),'2', array('onclick' => 'check_per_page_one()', 'id'=>'option_page_one'));
957

    
958
                $form->addGroup($radios, null, get_lang('QuestionsPerPage'), '');
959

    
960
                $radios_results_disabled = array();
961
                $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('ShowScoreAndRightAnswer'), '0', array('id'=>'result_disabled_0'));
962
                $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('DoNotShowScoreNorRightAnswer'),  '1',array('id'=>'result_disabled_1','onclick' => 'check_results_disabled()'));
963
                $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('OnlyShowScore'),  '2', array('id'=>'result_disabled_2','onclick' => 'check_results_disabled()'));
964
                //$radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('ExamModeWithFinalScoreShowOnlyFinalScoreWithCategoriesIfAvailable'),  '3', array('id'=>'result_disabled_3','onclick' => 'check_results_disabled()'));
965

    
966
                $form->addGroup($radios_results_disabled, null, get_lang('ShowResultsToStudents'), '');
967

    
968
            } else {
969
                // if is Directfeedback but has not questions we can allow to modify the question type
970
                if ($this->selectNbrQuestions() == 0) {
971

    
972
                    // feedback type
973
                    $radios_feedback = array();
974
                    $radios_feedback[] = $form->createElement('radio', 'exerciseFeedbackType', null, get_lang('ExerciseAtTheEndOfTheTest'),'0',array('id' =>'exerciseType_0', 'onclick' => 'check_feedback()'));
975

    
976
                    if (api_get_setting('enable_quiz_scenario') == 'true') {
977
                        $radios_feedback[] = $form->createElement('radio', 'exerciseFeedbackType', null, get_lang('DirectFeedback'), '1', array('id' =>'exerciseType_1' , 'onclick' => 'check_direct_feedback()'));
978
                    }
979
                    $radios_feedback[] = $form->createElement('radio', 'exerciseFeedbackType', null, get_lang('NoFeedback'),'2',array('id' =>'exerciseType_2'));
980
                    $form->addGroup($radios_feedback, null, get_lang('FeedbackType'));
981

    
982

    
983
                    //$form->addElement('select', 'exerciseFeedbackType',get_lang('FeedbackType'),$feedback_option,'onchange="javascript:feedbackselection()"');
984
                    // test type
985
                    $radios = array();
986
                    $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SimpleExercise'),    '1');
987
                    $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SequentialExercise'),'2');
988
                    $form->addGroup($radios, null, get_lang('ExerciseType'));
989

    
990
                    $radios_results_disabled = array();
991
                    $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('ShowScoreAndRightAnswer'), '0', array('id'=>'result_disabled_0'));
992
                    $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('DoNotShowScoreNorRightAnswer'),  '1',array('id'=>'result_disabled_1','onclick' => 'check_results_disabled()'));
993
                    $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('OnlyShowScore'),  '2',array('id'=>'result_disabled_2','onclick' => 'check_results_disabled()'));
994
                    $form->addGroup($radios_results_disabled, null, get_lang('ShowResultsToStudents'),'');
995
                } else {
996
                    //Show options freeze
997
                    $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('ShowScoreAndRightAnswer'), '0', array('id'=>'result_disabled_0'));
998
                    $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('DoNotShowScoreNorRightAnswer'),  '1',array('id'=>'result_disabled_1','onclick' => 'check_results_disabled()'));
999
                    $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('OnlyShowScore'),  '2',array('id'=>'result_disabled_2','onclick' => 'check_results_disabled()'));
1000
                    $result_disable_group = $form->addGroup($radios_results_disabled, null, get_lang('ShowResultsToStudents'),'');
1001
                    $result_disable_group->freeze();
1002

    
1003
                    $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SimpleExercise'),    '1', array('onclick' => 'check_per_page_all()', 'id'=>'option_page_all'));
1004
                    $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SequentialExercise'),'2', array('onclick' => 'check_per_page_one()', 'id'=>'option_page_one'));
1005

    
1006
                    $type_group = $form->addGroup($radios, null, get_lang('QuestionsPerPage'), '');
1007
                    $type_group->freeze();
1008

    
1009
                    //we force the options to the DirectFeedback exercisetype
1010
                    $form->addElement('hidden', 'exerciseFeedbackType', EXERCISE_FEEDBACK_TYPE_DIRECT);
1011
                    $form->addElement('hidden', 'exerciseType', ONE_PER_PAGE);
1012
                }
1013
            }
1014

    
1015
            // number of random question
1016

    
1017
            $max = ($this->id > 0) ? $this->selectNbrQuestions() : 10 ;
1018
            $option = range(0,$max);
1019
            $option[0] = get_lang('No');
1020
            $option[-1] = get_lang('AllQuestionsShort');
1021
            $form->addElement('select', 'randomQuestions',array(get_lang('RandomQuestions'), get_lang('RandomQuestionsHelp')), $option, array('id'=>'randomQuestions','class'=>'chzn-select'));
1022

    
1023
            //random answers
1024
            $radios_random_answers = array();
1025
            $radios_random_answers[] = $form->createElement('radio', 'randomAnswers', null, get_lang('Yes'),'1');
1026
            $radios_random_answers[] = $form->createElement('radio', 'randomAnswers', null, get_lang('No'),'0');
1027
            $form->addGroup($radios_random_answers, null, get_lang('RandomAnswers'), '');
1028

    
1029
            //randow by category
1030
            $form->addElement('html','<div class="clear">&nbsp;</div>');
1031
            $radiocat = array();
1032
            $radiocat[] = $form->createElement('radio', 'randomByCat', null, get_lang('YesWithCategoriesShuffled'),'1');
1033
            $radiocat[] = $form->createElement('radio', 'randomByCat', null, get_lang('YesWithCategoriesSorted'),'2');
1034
            $radiocat[] = $form->createElement('radio', 'randomByCat', null, get_lang('No'),'0');
1035
            $form->addGroup($radiocat, null, get_lang('RandomQuestionByCategory'), '');
1036
            $form->addElement('html','<div class="clear">&nbsp;</div>');
1037

    
1038
            // add the radio display the category name for student
1039
            $radio_display_cat_name = array();
1040
            $radio_display_cat_name[] = $form->createElement('radio', 'display_category_name', null, get_lang('Yes'),'1');
1041
            $radio_display_cat_name[] = $form->createElement('radio', 'display_category_name', null, get_lang('No'),'0');
1042
            $form->addGroup($radio_display_cat_name, null, get_lang('QuestionDisplayCategoryName'), '');
1043

    
1044
            //Attempts
1045
            $attempt_option=range(0,10);
1046
            $attempt_option[0]=get_lang('Infinite');
1047

    
1048
            $form->addElement('select', 'exerciseAttempts',get_lang('ExerciseAttempts'),$attempt_option, array('id'=>'exerciseAttempts','class'=>'chzn-select'));
1049

    
1050
            // Exercice time limit
1051
            $form->addElement('checkbox', 'activate_start_date_check',null, get_lang('EnableStartTime'), array('onclick' => 'activate_start_date()'));
1052

    
1053
            $var = Exercise::selectTimeLimit();
1054

    
1055
            if (($this->start_time != '0000-00-00 00:00:00'))
1056
                $form->addElement('html','<div id="start_date_div" style="display:block;">');
1057
            else
1058
                $form->addElement('html','<div id="start_date_div" style="display:none;">');
1059

    
1060
            $form->addElement('datepicker', 'start_time', '', array('form_name'=>'exercise_admin'), 5);
1061

    
1062
            $form->addElement('html','</div>');
1063

    
1064
            $form->addElement('checkbox', 'activate_end_date_check', null , get_lang('EnableEndTime'), array('onclick' => 'activate_end_date()'));
1065

    
1066
            if (($this->end_time != '0000-00-00 00:00:00'))
1067
                $form->addElement('html','<div id="end_date_div" style="display:block;">');
1068
            else
1069
                $form->addElement('html','<div id="end_date_div" style="display:none;">');
1070

    
1071
            $form->addElement('datepicker', 'end_time', '', array('form_name'=>'exercise_admin'), 5);
1072
            $form->addElement('html','</div>');
1073

    
1074
            //$check_option=$this->selectType();
1075
            $diplay = 'block';
1076
            $form->addElement('checkbox', 'propagate_neg', null, get_lang('PropagateNegativeResults'));
1077
            $form->addElement('html','<div class="clear">&nbsp;</div>');
1078
            $form->addElement('checkbox', 'review_answers', null, get_lang('ReviewAnswers'));
1079

    
1080
            $form->addElement('html','<div id="divtimecontrol"  style="display:'.$diplay.';">');
1081

    
1082
            //Timer control
1083
            //$time_hours_option = range(0,12);
1084
            //$time_minutes_option = range(0,59);
1085
            $form->addElement('checkbox', 'enabletimercontrol', null, get_lang('EnableTimerControl'), array('onclick' =>'option_time_expired()','id'=>'enabletimercontrol','onload'=>'check_load_time()'));
1086
            $expired_date = (int)$this->selectExpiredTime();
1087

    
1088
            if (($expired_date!='0')) {
1089
                $form->addElement('html','<div id="timercontrol" style="display:block;">');
1090
            } else {
1091
                $form->addElement('html','<div id="timercontrol" style="display:none;">');
1092
            }
1093
            $form->addElement('text', 'enabletimercontroltotalminutes',get_lang('ExerciseTotalDurationInMinutes'),array('style' => 'width : 35px','id' => 'enabletimercontroltotalminutes'));
1094
            $form->addElement('html','</div>');
1095

    
1096
            $form->addElement('text', 'pass_percentage', array(get_lang('PassPercentage'), null, '%'),  array('id' => 'pass_percentage'));
1097
            $form->addRule('pass_percentage', get_lang('Numeric'), 'numeric');
1098

    
1099
            // add the text_when_finished textbox
1100
            $form -> add_html_editor('text_when_finished', get_lang('TextWhenFinished'), false, false, $editor_config);
1101

    
1102
            $defaults = array();
1103

    
1104
            if (api_get_setting('search_enabled') === 'true') {
1105
                require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php';
1106

    
1107
                $form->addElement ('checkbox', 'index_document','', get_lang('SearchFeatureDoIndexDocument'));
1108
                $form->addElement ('select_language', 'language', get_lang('SearchFeatureDocumentLanguage'));
1109

    
1110
                $specific_fields = get_specific_field_list();
1111

    
1112
                foreach ($specific_fields as $specific_field) {
1113
                    $form->addElement ('text', $specific_field['code'], $specific_field['name']);
1114
                    $filter = array('c_id'=> "'". api_get_course_int_id() ."'", 'field_id' => $specific_field['id'], 'ref_id' => $this->id, 'tool_id' => '\''. TOOL_QUIZ .'\'');
1115
                    $values = get_specific_field_values_list($filter, array('value'));
1116
                    if ( !empty($values) ) {
1117
                        $arr_str_values = array();
1118
                        foreach ($values as $value) {
1119
                            $arr_str_values[] = $value['value'];
1120
                        }
1121
                        $defaults[$specific_field['code']] = implode(', ', $arr_str_values);
1122
                    }
1123
                }
1124
                //$form->addElement ('html','</div>');
1125
            }
1126

    
1127
            $form->addElement('html','</div>');  //End advanced setting
1128
            $form->addElement('html','</div>');
1129
        }
1130

    
1131
        // submit
1132
        $text = isset($_GET['exerciseId']) ? get_lang('ModifyExercise') : get_lang('ProcedToQuestions');
1133

    
1134
        $form->addElement('style_submit_button', 'submitExercise', $text, 'class="save"');
1135

    
1136
        $form->addRule('exerciseTitle', get_lang('GiveExerciseName'), 'required');
1137

    
1138
        if ($type == 'full') {
1139
            // rules
1140
            $form->addRule('exerciseAttempts', get_lang('Numeric'), 'numeric');
1141
            $form->addRule('start_time', get_lang('InvalidDate'), 'date');
1142
            $form->addRule('end_time', get_lang('InvalidDate'), 'date');
1143
        }
1144

    
1145
        // defaults
1146
        if ($type=='full') {
1147
            if ($this->id > 0) {
1148
                if ($this->random > $this->selectNbrQuestions()) {
1149
                    $defaults['randomQuestions'] =  $this->selectNbrQuestions();
1150
                } else {
1151
                    $defaults['randomQuestions'] = $this->random;
1152
                }
1153

    
1154
                $defaults['randomAnswers']          = $this->selectRandomAnswers();
1155
                $defaults['exerciseType']           = $this->selectType();
1156
                $defaults['exerciseTitle']          = $this->selectTitle();
1157
                $defaults['exerciseDescription']    = $this->selectDescription();
1158
                $defaults['exerciseAttempts']       = $this->selectAttempts();
1159
                $defaults['exerciseFeedbackType']   = $this->selectFeedbackType();
1160
                $defaults['results_disabled']       = $this->selectResultsDisabled();
1161
                $defaults['propagate_neg']          = $this->selectPropagateNeg();
1162
                $defaults['review_answers']         = $this->review_answers;
1163
                $defaults['randomByCat']            = $this->selectRandomByCat(); //
1164
                $defaults['text_when_finished']     = $this->selectTextWhenFinished(); //
1165
                $defaults['display_category_name']  = $this->selectDisplayCategoryName(); //
1166
                $defaults['pass_percentage']        = $this->selectPassPercentage();
1167

    
1168
                if (($this->start_time != '0000-00-00 00:00:00'))
1169
                    $defaults['activate_start_date_check'] = 1;
1170
                if ($this->end_time != '0000-00-00 00:00:00')
1171
                    $defaults['activate_end_date_check'] = 1;
1172

    
1173
                $defaults['start_time'] = ($this->start_time!='0000-00-00 00:00:00') ? api_get_local_time($this->start_time) : date('Y-m-d 12:00:00');
1174
                $defaults['end_time']   = ($this->end_time!='0000-00-00 00:00:00') ? api_get_local_time($this->end_time) : date('Y-m-d 12:00:00', time()+84600);
1175

    
1176
                //Get expired time
1177
                if($this->expired_time != '0') {
1178
                    $defaults['enabletimercontrol'] = 1;
1179
                    $defaults['enabletimercontroltotalminutes'] = $this->expired_time;
1180
                } else {
1181
                    $defaults['enabletimercontroltotalminutes'] = 0;
1182
                }
1183
            } else {
1184
                $defaults['exerciseType'] = 2;
1185
                $defaults['exerciseAttempts'] = 0;
1186
                $defaults['randomQuestions'] = 0;
1187
                $defaults['randomAnswers'] = 0;
1188
                $defaults['exerciseDescription'] = '';
1189
                $defaults['exerciseFeedbackType'] = 0;
1190
                $defaults['results_disabled'] = 0;
1191
                $defaults['randomByCat'] = 0;	//
1192
                $defaults['text_when_finished'] = ""; //
1193
                $defaults['start_time'] = date('Y-m-d 12:00:00');
1194
                $defaults['display_category_name'] = 1; //
1195
                $defaults['end_time']   = date('Y-m-d 12:00:00',time()+84600);
1196
                $defaults['pass_percentage'] = '';
1197
            }
1198
        } else {
1199
            $defaults['exerciseTitle'] = $this->selectTitle();
1200
            $defaults['exerciseDescription'] = $this->selectDescription();
1201
        }
1202
        if (api_get_setting('search_enabled') === 'true') {
1203
            $defaults['index_document'] = 'checked="checked"';
1204
        }
1205
        $form->setDefaults($defaults);
1206
    }
1207

    
1208
    /**
1209
     * function which process the creation of exercises
1210
     * @param FormValidator $form the formvalidator instance
1211
     */
1212
    function processCreation($form, $type='') {
1213

    
1214
        $this->updateTitle($form->getSubmitValue('exerciseTitle'));
1215
        $this->updateDescription($form->getSubmitValue('exerciseDescription'));
1216
        $this->updateAttempts($form->getSubmitValue('exerciseAttempts'));
1217
        $this->updateFeedbackType($form->getSubmitValue('exerciseFeedbackType'));
1218
        $this->updateType($form->getSubmitValue('exerciseType'));
1219
        $this->setRandom($form->getSubmitValue('randomQuestions'));
1220
        $this->updateRandomAnswers($form->getSubmitValue('randomAnswers'));
1221
        $this->updateResultsDisabled($form->getSubmitValue('results_disabled'));
1222
        $this->updateExpiredTime($form->getSubmitValue('enabletimercontroltotalminutes'));
1223
        $this->updatePropagateNegative($form->getSubmitValue('propagate_neg'));
1224
        $this->updateRandomByCat($form->getSubmitValue('randomByCat'));
1225
        $this->updateTextWhenFinished($form->getSubmitValue('text_when_finished'));
1226
        $this->updateDisplayCategoryName($form->getSubmitValue('display_category_name'));
1227
        $this->updateReviewAnswers($form->getSubmitValue('review_answers'));
1228
        $this->updatePassPercentage($form->getSubmitValue('pass_percentage'));
1229

    
1230
        if ($form->getSubmitValue('activate_start_date_check') == 1) {
1231
            $start_time = $form->getSubmitValue('start_time');
1232
            $start_time['F'] = sprintf('%02d', $start_time['F']);
1233
            $start_time['i'] = sprintf('%02d', $start_time['i']);
1234
            $start_time['d'] = sprintf('%02d', $start_time['d']);
1235

    
1236
            $this->start_time = $start_time['Y'].'-'.$start_time['F'].'-'.$start_time['d'].' '.$start_time['H'].':'.$start_time['i'].':00';
1237
        } else {
1238
            $this->start_time = '0000-00-00 00:00:00';
1239
        }
1240

    
1241
        if ($form->getSubmitValue('activate_end_date_check') == 1) {
1242
            $end_time = $form->getSubmitValue('end_time');
1243
            $end_time['F'] = sprintf('%02d', $end_time['F']);
1244
            $end_time['i'] = sprintf('%02d', $end_time['i']);
1245
            $end_time['d'] = sprintf('%02d', $end_time['d']);
1246

    
1247
            $this->end_time = $end_time['Y'].'-'.$end_time['F'].'-'.$end_time['d'].' '.$end_time['H'].':'.$end_time['i'].':00';
1248
        } else {
1249
            $this->end_time   = '0000-00-00 00:00:00';
1250
        }
1251

    
1252
        if ($form->getSubmitValue('enabletimercontrol') == 1) {
1253
            $expired_total_time = $form->getSubmitValue('enabletimercontroltotalminutes');
1254
            if ($this->expired_time == 0) {
1255
                $this->expired_time = $expired_total_time;
1256
            }
1257
        } else {
1258
            $this->expired_time = 0;
1259
        }
1260

    
1261
        if ($form->getSubmitValue('randomAnswers') == 1) {
1262
            $this->random_answers=1;
1263
        } else {
1264
            $this->random_answers=0;
1265
        }
1266
        $this->save($type);
1267
    }
1268

    
1269
    function search_engine_save() {
1270
        if ($_POST['index_document'] != 1) {
1271
            return;
1272
        }
1273
        $course_id = api_get_course_id();
1274

    
1275
        require_once api_get_path(LIBRARY_PATH) . 'search/ChamiloIndexer.class.php';
1276
        require_once api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php';
1277
        require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php';
1278

    
1279
        $specific_fields = get_specific_field_list();
1280
        $ic_slide = new IndexableChunk();
1281

    
1282
        $all_specific_terms = '';
1283
        foreach ($specific_fields as $specific_field) {
1284
            if (isset($_REQUEST[$specific_field['code']])) {
1285
                $sterms = trim($_REQUEST[$specific_field['code']]);
1286
                if (!empty($sterms)) {
1287
                    $all_specific_terms .= ' '. $sterms;
1288
                    $sterms = explode(',', $sterms);
1289
                    foreach ($sterms as $sterm) {
1290
                        $ic_slide->addTerm(trim($sterm), $specific_field['code']);
1291
                        add_specific_field_value($specific_field['id'], $course_id, TOOL_QUIZ, $this->id, $sterm);
1292
                    }
1293
                }
1294
            }
1295
        }
1296

    
1297
        // build the chunk to index
1298
        $ic_slide->addValue("title", $this->exercise);
1299
        $ic_slide->addCourseId($course_id);
1300
        $ic_slide->addToolId(TOOL_QUIZ);
1301
        $xapian_data = array(
1302
            SE_COURSE_ID => $course_id,
1303
            SE_TOOL_ID => TOOL_QUIZ,
1304
            SE_DATA => array('type' => SE_DOCTYPE_EXERCISE_EXERCISE, 'exercise_id' => (int)$this->id),
1305
            SE_USER => (int)api_get_user_id(),
1306
        );
1307
        $ic_slide->xapian_data = serialize($xapian_data);
1308
        $exercise_description = $all_specific_terms .' '. $this->description;
1309
        $ic_slide->addValue("content", $exercise_description);
1310

    
1311
        $di = new ChamiloIndexer();
1312
        isset($_POST['language'])? $lang=Database::escape_string($_POST['language']): $lang = 'english';
1313
        $di->connectDb(NULL, NULL, $lang);
1314
        $di->addChunk($ic_slide);
1315

    
1316
        //index and return search engine document id
1317
        $did = $di->index();
1318
        if ($did) {
1319
            // save it to db
1320
            $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
1321
            $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
1322
			    VALUES (NULL , \'%s\', \'%s\', %s, %s)';
1323
            $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id, $did);
1324
            Database::query($sql);
1325
        }
1326
    }
1327

    
1328
    function search_engine_edit() {
1329
        // update search enchine and its values table if enabled
1330
        if (api_get_setting('search_enabled')=='true' && extension_loaded('xapian')) {
1331
            $course_id = api_get_course_id();
1332

    
1333
            // actually, it consists on delete terms from db, insert new ones, create a new search engine document, and remove the old one
1334
            // get search_did
1335
            $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
1336
            $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
1337
            $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
1338
            $res = Database::query($sql);
1339

    
1340
            if (Database::num_rows($res) > 0) {
1341
                require_once(api_get_path(LIBRARY_PATH) . 'search/ChamiloIndexer.class.php');
1342
                require_once(api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php');
1343
                require_once(api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php');
1344

    
1345
                $se_ref = Database::fetch_array($res);
1346
                $specific_fields = get_specific_field_list();
1347
                $ic_slide = new IndexableChunk();
1348

    
1349
                $all_specific_terms = '';
1350
                foreach ($specific_fields as $specific_field) {
1351
                    delete_all_specific_field_value($course_id, $specific_field['id'], TOOL_QUIZ, $this->id);
1352
                    if (isset($_REQUEST[$specific_field['code']])) {
1353
                        $sterms = trim($_REQUEST[$specific_field['code']]);
1354
                        $all_specific_terms .= ' '. $sterms;
1355
                        $sterms = explode(',', $sterms);
1356
                        foreach ($sterms as $sterm) {
1357
                            $ic_slide->addTerm(trim($sterm), $specific_field['code']);
1358
                            add_specific_field_value($specific_field['id'], $course_id, TOOL_QUIZ, $this->id, $sterm);
1359
                        }
1360
                    }
1361
                }
1362

    
1363
                // build the chunk to index
1364
                $ic_slide->addValue("title", $this->exercise);
1365
                $ic_slide->addCourseId($course_id);
1366
                $ic_slide->addToolId(TOOL_QUIZ);
1367
                $xapian_data = array(
1368
                    SE_COURSE_ID => $course_id,
1369
                    SE_TOOL_ID => TOOL_QUIZ,
1370
                    SE_DATA => array('type' => SE_DOCTYPE_EXERCISE_EXERCISE, 'exercise_id' => (int)$this->id),
1371
                    SE_USER => (int)api_get_user_id(),
1372
                );
1373
                $ic_slide->xapian_data = serialize($xapian_data);
1374
                $exercise_description = $all_specific_terms .' '. $this->description;
1375
                $ic_slide->addValue("content", $exercise_description);
1376

    
1377
                $di = new ChamiloIndexer();
1378
                isset($_POST['language'])? $lang=Database::escape_string($_POST['language']): $lang = 'english';
1379
                $di->connectDb(NULL, NULL, $lang);
1380
                $di->remove_document((int)$se_ref['search_did']);
1381
                $di->addChunk($ic_slide);
1382

    
1383
                //index and return search engine document id
1384
                $did = $di->index();
1385
                if ($did) {
1386
                    // save it to db
1387
                    $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=\'%s\'';
1388
                    $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
1389
                    Database::query($sql);
1390
                    $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
1391
                        VALUES (NULL , \'%s\', \'%s\', %s, %s)';
1392
                    $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id, $did);
1393
                    Database::query($sql);
1394
                }
1395
            } else {
1396
                $this->search_engine_save();
1397
            }
1398
        }
1399

    
1400
    }
1401

    
1402
    function search_engine_delete() {
1403
        // remove from search engine if enabled
1404
        if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian') ) {
1405
            $course_id = api_get_course_id();
1406
            $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
1407
            $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level IS NULL LIMIT 1';
1408
            $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
1409
            $res = Database::query($sql);
1410
            if (Database::num_rows($res) > 0) {
1411
                $row = Database::fetch_array($res);
1412
                require_once(api_get_path(LIBRARY_PATH) .'search/ChamiloIndexer.class.php');
1413
                $di = new ChamiloIndexer();
1414
                $di->remove_document((int)$row['search_did']);
1415
                unset($di);
1416
                $tbl_quiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
1417
                foreach ( $this->questionList as $question_i) {
1418
                    $sql = 'SELECT type FROM %s WHERE id=%s';
1419
                    $sql = sprintf($sql, $tbl_quiz_question, $question_i);
1420
                    $qres = Database::query($sql);
1421
                    if (Database::num_rows($qres) > 0) {
1422
                        $qrow = Database::fetch_array($qres);
1423
                        $objQuestion = Question::getInstance($qrow['type']);
1424
                        $objQuestion = Question::read((int)$question_i);
1425
                        $objQuestion->search_engine_edit($this->id, FALSE, TRUE);
1426
                        unset($objQuestion);
1427
                    }
1428
                }
1429
            }
1430
            $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level IS NULL LIMIT 1';
1431
            $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
1432
            Database::query($sql);
1433

    
1434
            // remove terms from db
1435
            require_once(api_get_path(LIBRARY_PATH) .'specific_fields_manager.lib.php');
1436
            delete_all_values_for_item($course_id, TOOL_QUIZ, $this->id);
1437
        }
1438
    }
1439
    function selectExpiredTime() {
1440
        return $this->expired_time;
1441
    }
1442

    
1443
    /**
1444
     * Cleans the student's results only for the Exercise tool (Not from the LP)
1445
     * The LP results are NOT deleted
1446
     * Works with exercises in sessions
1447
     * @return int quantity of user's exercises deleted
1448
     */
1449
    function clean_results() {
1450
        $table_track_e_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
1451
        $table_track_e_attempt   = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
1452

    
1453
        $sql_select = "SELECT exe_id FROM $table_track_e_exercises
1454
					   WHERE 	exe_cours_id = '".api_get_course_id()."' AND
1455
								exe_exo_id = ".$this->id." AND
1456
								orig_lp_id = 0 AND
1457
								orig_lp_item_id = 0 AND
1458
								session_id = ".api_get_session_id()."";
1459

    
1460
        $result   = Database::query($sql_select);
1461
        $exe_list = Database::store_result($result);
1462

    
1463
        //deleting TRACK_E_ATTEMPT table
1464
        $i = 0;
1465
        if (is_array($exe_list) && count($exe_list) > 0) {
1466
            foreach($exe_list as $item) {
1467
                $sql = "DELETE FROM $table_track_e_attempt WHERE exe_id = '".$item['exe_id']."'";
1468
                Database::query($sql);
1469
                $i++;
1470
            }
1471
        }
1472

    
1473
        //delete TRACK_E_EXERCICES table
1474
        $sql = "DELETE FROM $table_track_e_exercises
1475
				WHERE exe_cours_id = '".api_get_course_id()."' AND exe_exo_id = ".$this->id." AND orig_lp_id = 0 AND orig_lp_item_id = 0 AND session_id = ".api_get_session_id()."";
1476
        Database::query($sql);
1477
        return $i;
1478
    }
1479

    
1480
    /**
1481
     * Copies an exercise (duplicate all questions and answers)
1482
     */
1483

    
1484
    public function copy_exercise() {
1485
        $exercise_obj= new Exercise();
1486
        $exercise_obj = $this;
1487

    
1488
        // force the creation of a new exercise
1489
        $exercise_obj->updateTitle($exercise_obj->selectTitle().' - '.get_lang('Copy'));
1490
        //Hides the new exercise
1491
        $exercise_obj->updateStatus(false);
1492
        $exercise_obj->updateId(0);
1493
        $exercise_obj->save();
1494

    
1495
        $new_exercise_id = $exercise_obj->selectId();
1496
        $question_list 	 = $exercise_obj->selectQuestionList();
1497

    
1498
        if (!empty($question_list)) {
1499
            //Question creation
1500

    
1501
            foreach ($question_list as $old_question_id) {
1502
                $old_question_obj = Question::read($old_question_id);
1503
                $new_id = $old_question_obj->duplicate();
1504
                if ($new_id) {
1505
                    $new_question_obj = Question::read($new_id);
1506

    
1507
                    if (isset($new_question_obj) && $new_question_obj) {
1508
                        $new_question_obj->addToList($new_exercise_id);
1509
                        // This should be moved to the duplicate function
1510
                        $new_answer_obj = new Answer($old_question_id);
1511
                        $new_answer_obj->read();
1512
                        $new_answer_obj->duplicate($new_id);
1513
                    }
1514
                }
1515
            }
1516
        }
1517
    }
1518

    
1519
    /**
1520
     * Changes the exercise id
1521
     *
1522
     * @param - in $id - exercise id
1523
     */
1524
    private function updateId($id) {
1525
        $this->id = $id;
1526
    }
1527

    
1528
    /**
1529
     * Changes the exercise status
1530
     *
1531
     * @param - string $status - exercise status
1532
     */
1533
    function updateStatus($status) {
1534
        $this->active = $status;
1535
    }
1536

    
1537
    public function get_stat_track_exercise_info($lp_id = 0, $lp_item_id = 0, $lp_item_view_id = 0, $status = 'incomplete') {
1538
		// If we are anonymous and we didn't take this exam already in this browser and computer:
1539
		if (!isset($_SESSION['attempts_anonymous']) && api_get_user_id()==0) {
1540
			return array();
1541
		}
1542
        $track_exercises = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
1543
        if (empty($lp_id)) {
1544
            $lp_id = 0;
1545
        }
1546
        if (empty($lp_item_id)) {
1547
            $lp_item_id = 0;
1548
        }
1549
        if (empty($lp_item_view_id)) {
1550
            $lp_item_view_id = 0;
1551
        }
1552
		
1553
		if (api_get_user_id()==0) {
1554
			$condition = ' WHERE exe_id = ' . $_SESSION['attempts_anonymous'] . " LIMIT 1";
1555
		} else {
1556
			$condition = ' WHERE exe_exo_id 	= ' . "'" . $this->id . "'" .' AND
1557
						   exe_user_id 			= ' . "'" . api_get_user_id() . "'" . ' AND
1558
						   exe_cours_id 		= ' . "'" . api_get_course_id() . "'" . ' AND
1559
						   status 				= ' . "'" . Database::escape_string($status). "'" . ' AND
1560
						   orig_lp_id 			= ' . "'" . $lp_id . "'" . ' AND
1561
						   orig_lp_item_id 		= ' . "'" . $lp_item_id . "'" . ' AND
1562
						   orig_lp_item_view_id = ' . "'" . $lp_item_view_id . "'" . ' AND
1563
						   session_id 			= ' . "'" . api_get_session_id() . "' LIMIT 1"; //Adding limit 1 just in case
1564
		}
1565

    
1566
        $sql_track = 'SELECT * FROM '.$track_exercises.$condition;
1567

    
1568
        $result = Database::query($sql_track);
1569
        $new_array = array();
1570
        if (Database::num_rows($result) > 0 ) {
1571
            $new_array = Database::fetch_array($result, 'ASSOC');
1572
        }
1573
        return $new_array;
1574
    }
1575

    
1576
    /**
1577
     * Saves a test attempt
1578
     *
1579
     * @param int  clock_expired_time
1580
     * @param int  lp id
1581
     * @param int  lp item id
1582
     * @param int  lp item_view id
1583
     * @param array question list
1584

    
1585
     */
1586
    public function save_stat_track_exercise_info($clock_expired_time = 0, $safe_lp_id = 0, $safe_lp_item_id = 0, $safe_lp_item_view_id = 0, $questionList = array(), $weight = 0) {
1587
        $track_exercises = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
1588
        $safe_lp_id 			= intval($safe_lp_id);
1589
        $safe_lp_item_id 		= intval($safe_lp_item_id);
1590
        $safe_lp_item_view_id 	= intval($safe_lp_item_view_id);
1591

    
1592
        if (empty($safe_lp_id)) {
1593
            $safe_lp_id = 0;
1594
        }
1595
        if (empty($safe_lp_item_id)) {
1596
            $safe_lp_item_id = 0;
1597
        }
1598
        if (empty($clock_expired_time)) {
1599
            $clock_expired_time = 0;
1600
        }
1601
        if ($this->expired_time != 0) {
1602
            $sql_fields = "expired_time_control, ";
1603
            $sql_fields_values = "'"."$clock_expired_time"."',";
1604
        } else {
1605
            $sql_fields = "";
1606
            $sql_fields_values = "";
1607
        }
1608
        $questionList = array_map('intval', $questionList);
1609

    
1610
        $weight = Database::escape_string($weight);
1611
        $sql = "INSERT INTO $track_exercises ($sql_fields exe_exo_id, exe_user_id, exe_cours_id, status,session_id, data_tracking, start_date, orig_lp_id, orig_lp_item_id, exe_weighting)
1612
                VALUES($sql_fields_values '".$this->id."','" . api_get_user_id() . "','" . api_get_course_id() . "','incomplete','" . api_get_session_id() . "','" . implode(',', $questionList) . "', '" . api_get_utc_datetime() . "', '$safe_lp_id', '$safe_lp_item_id', '$weight' )";
1613
        Database::query($sql);
1614
        $id = Database::insert_id();
1615
		if (api_get_user_id()==0) {
1616
			$_SESSION['attempts_anonymous'] = $id;
1617
		}
1618
        return $id;
1619
    }
1620

    
1621
    public function show_button($question_id, $questionNum, $questions_in_media = array()) {
1622
        global $origin, $safe_lp_id, $safe_lp_item_id, $safe_lp_item_view_id;
1623

    
1624
        $nbrQuestions = $this->get_count_question_list();
1625

    
1626
        $all_button = $html = $label = '';
1627
        $hotspot_get = isset($_POST['hotspot']) ? Security::remove_XSS($_POST['hotspot']):null;
1628

    
1629
        if ($this->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT && $this->type == ONE_PER_PAGE) {
1630
            $html .='<a href="exercise_submit_modal.php?learnpath_id='.$safe_lp_id.'&learnpath_item_id='.$safe_lp_item_id.'&learnpath_item_view_id='.$safe_lp_item_view_id.'&origin='.$origin.'&hotspot='.$hotspot_get.'&nbrQuestions='.$nbrQuestions.'&num='.$questionNum.'&exerciseType='.$this->type.'&exerciseId='.$this->id.'&placeValuesBeforeTB_=savedValues&TB_iframe=true&height=480&width=640&modal=true" title="" class="thickbox btn">';
1631
            if ($questionNum == count($this->questionList)) {
1632
                $html .= get_lang('EndTest').'</a>';
1633
            } else {
1634
                $html .= get_lang('ContinueTest').'</a>';
1635
            }
1636
            $html .='<br />';
1637
        } else {
1638
            //User
1639
            if (api_is_allowed_to_session_edit()) {
1640
                if ($this->type == ALL_ON_ONE_PAGE || $nbrQuestions == $questionNum) {
1641
                    if ($this->review_answers) {
1642
                        $label = get_lang('ReviewQuestions');
1643
                        $class = 'btn btn-success';
1644
                    } else {
1645
                        $label = get_lang('EndTest');
1646
                        $class = 'btn btn-warning';
1647
                    }
1648
                } else {
1649
                    $label = get_lang('NextQuestion');
1650
                    $class = 'btn btn-primary';
1651
                }
1652
                if ($this->type == ONE_PER_PAGE) {
1653
                    if ($questionNum != 1) {
1654
                        $prev_question = $questionNum - 2;
1655
                        $all_button .= '<a href="javascript://" class="btn" onclick="previous_question_and_save('.$prev_question.', '.$question_id.' ); ">'.get_lang('PreviousQuestion').'</a>';
1656
                    }
1657

    
1658
                    //Next question
1659
                    if (!empty($questions_in_media)) {
1660
                        $questions_in_media = "['".implode("','",$questions_in_media)."']";
1661
                        $all_button .= '&nbsp;<a href="javascript://" class="'.$class.'" onclick="save_question_list('.$questions_in_media.'); ">'.$label.'</a>';
1662
                    } else {
1663
                        $all_button .= '&nbsp;<a href="javascript://" class="'.$class.'" onclick="save_now('.$question_id.'); ">'.$label.'</a>';
1664
                    }
1665
                    $all_button .= '<span id="save_for_now_'.$question_id.'" class="exercise_save_mini_message"></span>&nbsp;';
1666

    
1667
                    $html .= $all_button;
1668
                } else {
1669
                    if ($this->review_answers) {
1670
                        $all_label = get_lang('ReviewQuestions');
1671
                        $class = 'btn btn-success';
1672
                    } else {
1673
                        $all_label = get_lang('EndTest');
1674
                        $class = 'btn btn-warning';
1675
                    }
1676
                    $all_button = '&nbsp;<a href="javascript://" class="'.$class.'" onclick="validate_all(); ">'.$all_label.'</a>';
1677
                    $all_button .= '&nbsp;<span id="save_all_reponse"></span>';
1678
                    $html .= $all_button;
1679
                }
1680
            }
1681
        }
1682
        return $html;
1683
    }
1684

    
1685
    /**
1686
     * So the time control will work
1687
     */
1688
    public function show_time_control_js($time_left) {
1689
        $time_left = intval($time_left);
1690
        return "<script>
1691

    
1692
            function get_expired_date_string(expired_time) {
1693
                var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
1694
                var day, month, year, hours, minutes, seconds, date_string;
1695
                var obj_date = new Date(expired_time);
1696
                day     = obj_date.getDate();
1697
                if (day < 10) day = '0' + day;
1698
                    month   = obj_date.getMonth();
1699
                    year    = obj_date.getFullYear();
1700
                    hours   = obj_date.getHours();
1701
                if (hours < 10) hours = '0' + hours;
1702
                minutes = obj_date.getMinutes();
1703
                if (minutes < 10) minutes = '0' + minutes;
1704
                seconds = obj_date.getSeconds();
1705
                if (seconds < 10) seconds = '0' + seconds;
1706
                date_string = months[month] +' ' + day + ', ' + year + ' ' + hours + ':' + minutes + ':' + seconds;
1707
                return date_string;
1708
            }
1709

    
1710
            function open_clock_warning() {
1711
                $('#clock_warning').dialog({
1712
                    modal:true,
1713
                    height:250,
1714
                    closeOnEscape: false,
1715
                    resizable: false,
1716
                    buttons: {
1717
                        '".addslashes(get_lang("EndTest"))."': function() {
1718
                            $('#clock_warning').dialog('close');
1719
                        },
1720
                    },
1721
                    close: function() {
1722
                        send_form();
1723
                    }
1724
                });
1725
                $('#clock_warning').dialog('open');
1726

    
1727
                $('#counter_to_redirect').epiclock({
1728
                    mode: $.epiclock.modes.countdown,
1729
                    offset: {seconds: 5},
1730
                    format: 's'
1731
                }).bind('timer', function () {
1732
                    send_form();
1733
                });
1734

    
1735
            }
1736

    
1737
            function send_form() {
1738
                if ($('#exercise_form').length) {
1739
                    $('#exercise_form').submit();
1740
                } else {
1741
                    //In reminder
1742
                    final_submit();
1743
                }
1744
            }
1745

    
1746
            function onExpiredTimeExercise() {
1747
                $('#wrapper-clock').hide();
1748
                $('#exercise_form').hide();
1749
                $('#expired-message-id').show();
1750

    
1751
                //Fixes bug #5263
1752
                $('#num_current_id').attr('value', '".$this->selectNbrQuestions()."');
1753
                open_clock_warning();
1754
            }
1755

    
1756
			$(document).ready(function() {
1757

    
1758
				var current_time = new Date().getTime();
1759
                var time_left    = parseInt(".$time_left."); // time in seconds when using minutes there are some seconds lost
1760
				var expired_time = current_time + (time_left*1000);
1761
				var expired_date = get_expired_date_string(expired_time);
1762

    
1763
                $('#exercise_clock_warning').epiclock({
1764
                    mode: $.epiclock.modes.countdown,
1765
                    offset: {seconds: time_left},
1766
                    format: 'x:i:s',
1767
                    renderer: 'minute'
1768
                }).bind('timer', function () {
1769
                    onExpiredTimeExercise();
1770
                });
1771
	       		$('#submit_save').click(function () {});
1772
	    });
1773
	    </script>";
1774
    }
1775

    
1776
    /**
1777
     * Lp javascript for hotspots
1778
     */
1779
    public function show_lp_javascript() {
1780

    
1781
        return "<script type=\"text/javascript\" src=\"../plugin/hotspot/JavaScriptFlashGateway.js\"></script>
1782
                    <script src=\"../plugin/hotspot/hotspot.js\" type=\"text/javascript\"></script>
1783
                    <script language=\"JavaScript\" type=\"text/javascript\">
1784
                    <!--
1785
                    // -----------------------------------------------------------------------------
1786
                    // Globals
1787
                    // Major version of Flash required
1788
                    var requiredMajorVersion = 7;
1789
                    // Minor version of Flash required
1790
                    var requiredMinorVersion = 0;
1791
                    // Minor version of Flash required
1792
                    var requiredRevision = 0;
1793
                    // the version of javascript supported
1794
                    var jsVersion = 1.0;
1795
                    // -----------------------------------------------------------------------------
1796
                    // -->
1797
                    </script>
1798
                    <script language=\"VBScript\" type=\"text/vbscript\">
1799
                    <!-- // Visual basic helper required to detect Flash Player ActiveX control version information
1800
                    Function VBGetSwfVer(i)
1801
                      on error resume next
1802
                      Dim swControl, swVersion
1803
                      swVersion = 0
1804

    
1805
                      set swControl = CreateObject(\"ShockwaveFlash.ShockwaveFlash.\" + CStr(i))
1806
                      if (IsObject(swControl)) then
1807
                        swVersion = swControl.GetVariable(\"\$version\")
1808
                      end if
1809
                      VBGetSwfVer = swVersion
1810
                    End Function
1811
                    // -->
1812
                    </script>
1813

    
1814
                    <script language=\"JavaScript1.1\" type=\"text/javascript\">
1815
                    <!-- // Detect Client Browser type
1816
                    var isIE  = (navigator.appVersion.indexOf(\"MSIE\") != -1) ? true : false;
1817
                    var isWin = (navigator.appVersion.toLowerCase().indexOf(\"win\") != -1) ? true : false;
1818
                    var isOpera = (navigator.userAgent.indexOf(\"Opera\") != -1) ? true : false;
1819
                    jsVersion = 1.1;
1820
                    // JavaScript helper required to detect Flash Player PlugIn version information
1821
                    function JSGetSwfVer(i){
1822
                        // NS/Opera version >= 3 check for Flash plugin in plugin array
1823
                        if (navigator.plugins != null && navigator.plugins.length > 0) {
1824
                            if (navigator.plugins[\"Shockwave Flash 2.0\"] || navigator.plugins[\"Shockwave Flash\"]) {
1825
                                var swVer2 = navigator.plugins[\"Shockwave Flash 2.0\"] ? \" 2.0\" : \"\";
1826
                                var flashDescription = navigator.plugins[\"Shockwave Flash\" + swVer2].description;
1827
                                descArray = flashDescription.split(\" \");
1828
                                tempArrayMajor = descArray[2].split(\".\");
1829
                                versionMajor = tempArrayMajor[0];
1830
                                versionMinor = tempArrayMajor[1];
1831
                                if ( descArray[3] != \"\" ) {
1832
                                    tempArrayMinor = descArray[3].split(\"r\");
1833
                                } else {
1834
                                    tempArrayMinor = descArray[4].split(\"r\");
1835
                                }
1836
                                versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
1837
                                flashVer = versionMajor + \".\" + versionMinor + \".\" + versionRevision;
1838
                            } else {
1839
                                flashVer = -1;
1840
                            }
1841
                        }
1842
                        // MSN/WebTV 2.6 supports Flash 4
1843
                        else if (navigator.userAgent.toLowerCase().indexOf(\"webtv/2.6\") != -1) flashVer = 4;
1844
                        // WebTV 2.5 supports Flash 3
1845
                        else if (navigator.userAgent.toLowerCase().indexOf(\"webtv/2.5\") != -1) flashVer = 3;
1846
                        // older WebTV supports Flash 2
1847
                        else if (navigator.userAgent.toLowerCase().indexOf(\"webtv\") != -1) flashVer = 2;
1848
                        // Can't detect in all other cases
1849
                        else {
1850

    
1851
                            flashVer = -1;
1852
                        }
1853
                        return flashVer;
1854
                    }
1855
                    // When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
1856
                    function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
1857
                    {
1858
                        reqVer = parseFloat(reqMajorVer + \".\" + reqRevision);
1859
                        // loop backwards through the versions until we find the newest version
1860
                        for (i=25;i>0;i--) {
1861
                            if (isIE && isWin && !isOpera) {
1862
                                versionStr = VBGetSwfVer(i);
1863
                            } else {
1864
                                versionStr = JSGetSwfVer(i);
1865
                            }
1866
                            if (versionStr == -1 ) {
1867
                                return false;
1868
                            } else if (versionStr != 0) {
1869
                                if(isIE && isWin && !isOpera) {
1870
                                    tempArray         = versionStr.split(\" \");
1871
                                    tempString        = tempArray[1];
1872
                                    versionArray      = tempString .split(\",\");
1873
                                } else {
1874
                                    versionArray      = versionStr.split(\".\");
1875
                                }
1876
                                versionMajor      = versionArray[0];
1877
                                versionMinor      = versionArray[1];
1878
                                versionRevision   = versionArray[2];
1879

    
1880
                                versionString     = versionMajor + \".\" + versionRevision;   // 7.0r24 == 7.24
1881
                                versionNum        = parseFloat(versionString);
1882
                                // is the major.revision >= requested major.revision AND the minor version >= requested minor
1883
                                if ( (versionMajor > reqMajorVer) && (versionNum >= reqVer) ) {
1884
                                    return true;
1885
                                } else {
1886
                                    return ((versionNum >= reqVer && versionMinor >= reqMinorVer) ? true : false );
1887
                                }
1888
                            }
1889
                        }
1890
                    }
1891
                    // -->
1892
                    </script>";
1893
    }
1894

    
1895
    /**
1896
     * This function was originally found in the exercise_show.php
1897
     * @param   int     exe id
1898
     * @param   int     question id
1899
     * @param   int     the choice the user selected
1900
     * @param   array   the hotspot coordinates $hotspot[$question_id] = coordinates
1901
     * @param   string  function is called from 'exercise_show' or 'exercise_result'
1902
     * @param   bool    save results in the DB or just show the reponse
1903
     * @param   bool    gets information from DB or from the current selection
1904
     * @param   bool    show results or not
1905
     * @todo    reduce parameters of this function
1906
     * @return  string  html code
1907
     */
1908
    public function manage_answer($exeId, $questionId, $choice, $from = 'exercise_show', $exerciseResultCoordinates = array(), $saved_results = true, $from_database = false, $show_result = true, $propagate_neg = 0, $hotspot_delineation_result = array()) {
1909
        global $debug;
1910
        global $learnpath_id, $learnpath_item_id; //needed in order to use in the exercise_attempt() for the time
1911

    
1912
        $feedback_type = $this->selectFeedbackType();
1913

    
1914
        /*
1915
        if ($from == 'exercise_show') {
1916
            if (api_is_allowed_to_edit()) {
1917
                //For teachers
1918
                $feedback_type = EXERCISE_FEEDBACK_TYPE_END;
1919
            }
1920
        }*/
1921

    
1922
        require_once api_get_path(LIBRARY_PATH).'geometry.lib.php';
1923

    
1924
        if ($debug) error_log("<------ manage_answer ------> ");
1925
        if ($debug) error_log('manage_answer called exe_id: '.$exeId);
1926
        if ($debug) error_log('manage_answer $from:  '.$from);
1927
        if ($debug) error_log('manage_answer $saved_results: '.$saved_results);
1928
        if ($debug) error_log('manage_answer $from_database: '.$from_database);
1929
        if ($debug) error_log('manage_answer $show_result: '.$show_result);
1930
        if ($debug) error_log('manage_answer $propagate_neg: '.$propagate_neg);
1931
        if ($debug) error_log('manage_answer $exerciseResultCoordinates: '.print_r($exerciseResultCoordinates, 1));
1932
        if ($debug) error_log('manage_answer $hotspot_delineation_result: '.print_r($hotspot_delineation_result, 1));
1933
        if ($debug) error_log('manage_answer $learnpath_id: '.$learnpath_id);
1934
        if ($debug) error_log('manage_answer $learnpath_item_id: '.$learnpath_item_id);
1935

    
1936
        $extra_data = array();
1937
        $final_overlap = 0;
1938
        $final_missing =0;
1939
        $final_excess =0;
1940
        $overlap_color =0;
1941
        $missing_color =0;
1942
        $excess_color =0;
1943
        $threadhold1 =0;
1944
        $threadhold2 =0;
1945
        $threadhold3 = 0;
1946

    
1947
        $arrques = null;
1948
        $arrans  = null;
1949

    
1950
        $questionId   = intval($questionId);
1951
        $exeId        = intval($exeId);
1952
        $TBL_TRACK_ATTEMPT      = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
1953
        $table_ans              = Database::get_course_table(TABLE_QUIZ_ANSWER);
1954

    
1955
        // Creates a temporary Question object
1956
        $course_id              = api_get_course_int_id();
1957
        $objQuestionTmp         = Question::read($questionId, $course_id);
1958

    
1959
        if ($objQuestionTmp === false) {
1960
            return false;
1961
        }
1962

    
1963
        $questionName 			= $objQuestionTmp->selectTitle();
1964
        $questionWeighting 		= $objQuestionTmp->selectWeighting();
1965
        $answerType 			= $objQuestionTmp->selectType();
1966
        $quesId 				= $objQuestionTmp->selectId();
1967
        $extra                  = $objQuestionTmp->extra;
1968

    
1969
        $next = 1; //not for now
1970

    
1971
        //Extra information of the question
1972
        if (!empty($extra)) {
1973
            $extra          = explode(':', $extra);
1974
            if ($debug) error_log(print_r($extra, 1));
1975
            //Fixes problems with negatives values using intval
1976
            $true_score     = intval($extra[0]);
1977
            $false_score    = intval($extra[1]);
1978
            $doubt_score    = intval($extra[2]);
1979
        }
1980

    
1981
        $totalWeighting 		= 0;
1982
        $totalScore				= 0;
1983

    
1984
        // Destruction of the Question object
1985
        unset ($objQuestionTmp);
1986

    
1987
        // Construction of the Answer object
1988
        $objAnswerTmp = new Answer($questionId);
1989
        $nbrAnswers = $objAnswerTmp->selectNbrAnswers();
1990

    
1991
        if ($debug) error_log('Count of answers: '.$nbrAnswers);
1992
        if ($debug) error_log('$answerType: '.$answerType);
1993

    
1994
        if ($answerType == FREE_ANSWER || $answerType == ORAL_EXPRESSION) {
1995
            $nbrAnswers = 1;
1996
        }
1997

    
1998
        $nano = null;
1999

    
2000
        if ($answerType == ORAL_EXPRESSION) {
2001
            require_once api_get_path(LIBRARY_PATH).'nanogong.lib.php';
2002
            $exe_info = get_exercise_results_by_attempt($exeId);
2003
            $exe_info = $exe_info[$exeId];
2004

    
2005
            $params = array();
2006
            $params['course_id'] 	= api_get_course_int_id();
2007
            $params['session_id'] 	= api_get_session_id();
2008
            $params['user_id'] 		= isset($exe_info['exe_user_id'])? $exe_info['exe_user_id'] : api_get_user_id();
2009
            $params['exercise_id']  = isset($exe_info['exe_exo_id'])? $exe_info['exe_exo_id'] : $this->id;
2010
            $params['question_id'] 	= $questionId;
2011
            $params['exe_id'] 		= isset($exe_info['exe_id']) ? $exe_info['exe_id'] : $exeId;
2012

    
2013
            $nano = new Nanogong($params);
2014

    
2015
            //probably this attempt came in an exercise all question by page
2016
            if ($feedback_type == 0) {
2017
                $nano->replace_with_real_exe($exeId);
2018
            }
2019
        }
2020

    
2021
        $user_answer = '';
2022

    
2023
        // Get answer list for matching
2024
        $sql_answer = 'SELECT id, answer FROM '.$table_ans.' WHERE c_id = '.$course_id.' AND question_id = "'.$questionId.'" ';
2025
        $res_answer = Database::query($sql_answer);
2026

    
2027
        $answer_matching =array();
2028
        while ($real_answer = Database::fetch_array($res_answer)) {
2029
            $answer_matching[$real_answer['id']]= $real_answer['answer'];
2030
        }
2031

    
2032
        $real_answers = array();
2033
        $quiz_question_options = Question::readQuestionOption($questionId, $course_id);
2034

    
2035
        $organs_at_risk_hit = 0;
2036

    
2037
        $questionScore = 0;
2038

    
2039
        if ($debug) error_log('Start answer loop ');
2040

    
2041
        $answer_correct_array = array();
2042

    
2043
        for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
2044
            $answer             = $objAnswerTmp->selectAnswer($answerId);
2045
            $answerComment      = $objAnswerTmp->selectComment($answerId);
2046
            $answerCorrect      = $objAnswerTmp->isCorrect($answerId);
2047
            $answerWeighting    = (float)$objAnswerTmp->selectWeighting($answerId);
2048

    
2049
            $numAnswer          = $objAnswerTmp->selectAutoId($answerId);
2050

    
2051
            $answer_correct_array[$answerId] = (bool)$answerCorrect;
2052

    
2053
            if ($debug) error_log("answer auto id: $numAnswer ");
2054
            if ($debug) error_log("answer correct : $answerCorrect ");
2055

    
2056
            //delineation
2057
            $delineation_cord   = $objAnswerTmp->selectHotspotCoordinates(1);
2058
            $answer_delineation_destination=$objAnswerTmp->selectDestination(1);
2059

    
2060
            switch ($answerType) {
2061
                // for unique answer
2062
                case UNIQUE_ANSWER :
2063
                case UNIQUE_ANSWER_NO_OPTION :
2064
                    if ($from_database) {
2065
                        $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".$exeId."' and question_id= '".$questionId."'";
2066
                        $resultans = Database::query($queryans);
2067
                        $choice = Database::result($resultans,0,"answer");
2068

    
2069
                        $studentChoice=($choice == $numAnswer)?1:0;
2070
                        if ($studentChoice) {
2071
                            $questionScore+=$answerWeighting;
2072
                            $totalScore+=$answerWeighting;
2073
                        }
2074
                    } else {
2075
                        $studentChoice=($choice == $numAnswer)?1:0;
2076
                        if ($studentChoice) {
2077
                            $questionScore+=$answerWeighting;
2078
                            $totalScore+=$answerWeighting;
2079
                        }
2080
                    }
2081
                    break;
2082
                // for multiple answers
2083
                case MULTIPLE_ANSWER_TRUE_FALSE :
2084
                    if ($from_database) {
2085
                        $choice = array();
2086
                        $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." where exe_id = ".$exeId." and question_id = ".$questionId;
2087
                        $resultans = Database::query($queryans);
2088
                        while ($row = Database::fetch_array($resultans)) {
2089
                            $ind          = $row['answer'];
2090
                            $result       = explode(':',$ind);
2091
                            $my_answer_id = $result[0];
2092
                            $option       = $result[1];
2093
                            $choice[$my_answer_id] = $option;
2094
                        }
2095
                        $studentChoice  =$choice[$numAnswer];
2096
                    } else {
2097
                        $studentChoice  =$choice[$numAnswer];
2098
                    }
2099

    
2100
                    if (!empty($studentChoice)) {
2101
                        if ($studentChoice == $answerCorrect ) {
2102
                            $questionScore  += $true_score;
2103
                        } else {
2104
                            if ($quiz_question_options[$studentChoice]['name'] != "Don't know") {
2105
                                $questionScore   +=  $false_score;
2106
                            } else {
2107
                                $questionScore  +=  $doubt_score;
2108
                            }
2109
                        }
2110
                    } else {
2111
                        //if no result then the user just hit don't know
2112
                        $studentChoice = 3;
2113
                        $questionScore  +=  $doubt_score;
2114
                    }
2115
                    $totalScore = $questionScore;
2116
                    break;
2117
                case MULTIPLE_ANSWER : //2
2118
                    if ($from_database) {
2119
                        $choice = array();
2120
                        $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
2121
                        $resultans = Database::query($queryans);
2122
                        while ($row = Database::fetch_array($resultans)) {
2123
                            $ind = $row['answer'];
2124
                            $choice[$ind] = 1;
2125
                        }
2126

    
2127
                        $studentChoice = $choice[$numAnswer];
2128
                        $real_answers[$answerId] = (bool)$studentChoice;
2129

    
2130
                        if ($studentChoice) {
2131
                            $questionScore  +=$answerWeighting;
2132
                        }
2133
                    } else {
2134
                        $studentChoice = $choice[$numAnswer];
2135
                        $real_answers[$answerId] = (bool)$studentChoice;
2136

    
2137
                        if (isset($studentChoice)) {
2138
                            $questionScore  += $answerWeighting;
2139
                        }
2140
                    }
2141
                    $totalScore     += $answerWeighting;
2142

    
2143
                    if ($debug) error_log("studentChoice: $studentChoice");
2144
                    break;
2145
                case GLOBAL_MULTIPLE_ANSWER :
2146
                    if ($from_database) {
2147
                        $choice = array();
2148
                        $queryans = "SELECT answer FROM $TBL_TRACK_ATTEMPT WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
2149
                        $resultans = Database::query($queryans);
2150
                        while ($row = Database::fetch_array($resultans)) {
2151
                            $ind = $row['answer'];
2152
                            $choice[$ind] = 1;
2153
                        }
2154
                        $studentChoice = $choice[$numAnswer];
2155
                        $real_answers[$answerId] = (bool)$studentChoice;
2156
                        if ($studentChoice) {
2157
                            $questionScore  +=$answerWeighting;
2158
                        }
2159
                    } else {
2160
                        $studentChoice = $choice[$numAnswer];
2161
                        if (isset($studentChoice)) {
2162
                            $questionScore  += $answerWeighting;
2163
                        }
2164
                        $real_answers[$answerId] = (bool)$studentChoice;
2165
                    }
2166
                    $totalScore     += $answerWeighting;
2167
                    if ($debug) error_log("studentChoice: $studentChoice");
2168
                    break;
2169
                case MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE:
2170
                    if ($from_database) {
2171
                        $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." where exe_id = ".$exeId." AND question_id= ".$questionId;
2172
                        $resultans = Database::query($queryans);
2173
                        while ($row = Database::fetch_array($resultans)) {
2174
                            $ind = $row['answer'];
2175
                            $result = explode(':',$ind);
2176
                            $my_answer_id = $result[0];
2177
                            $option       = $result[1];
2178
                            $choice[$my_answer_id] = $option;
2179
                        }
2180
                        $numAnswer = $objAnswerTmp->selectAutoId($answerId);
2181
                        $studentChoice = $choice[$numAnswer];
2182

    
2183
                        if ($answerCorrect == $studentChoice) {
2184
                            //$answerCorrect = 1;
2185
                            $real_answers[$answerId] = true;
2186
                        } else {
2187
                            //$answerCorrect = 0;
2188
                            $real_answers[$answerId] = false;
2189
                        }
2190
                    } else {
2191
                        $studentChoice = $choice[$numAnswer];
2192
                        if ($answerCorrect == $studentChoice) {
2193
                            //$answerCorrect = 1;
2194
                            $real_answers[$answerId] = true;
2195
                        } else {
2196
                            //$answerCorrect = 0;
2197
                            $real_answers[$answerId] = false;
2198
                        }
2199
                    }
2200
                    break;
2201
                case MULTIPLE_ANSWER_COMBINATION:
2202
                    if ($from_database) {
2203
                        $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." where exe_id = '".$exeId."' and question_id= '".$questionId."'";
2204
                        $resultans = Database::query($queryans);
2205
                        while ($row = Database::fetch_array($resultans)) {
2206
                            $ind = $row['answer'];
2207
                            $choice[$ind] = 1;
2208
                        }
2209
                        $numAnswer=$objAnswerTmp->selectAutoId($answerId);
2210
                        $studentChoice=$choice[$numAnswer];
2211

    
2212
                        if ($answerCorrect == 1) {
2213
                            if ($studentChoice) {
2214
                                $real_answers[$answerId] = true;
2215
                            } else {
2216
                                $real_answers[$answerId] = false;
2217
                            }
2218
                        } else {
2219
                            if ($studentChoice) {
2220
                                $real_answers[$answerId] = false;
2221
                            } else {
2222
                                $real_answers[$answerId] = true;
2223
                            }
2224
                        }
2225
                    } else {
2226
                        $studentChoice=$choice[$numAnswer];
2227
                        if ($answerCorrect == 1) {
2228
                            if ($studentChoice) {
2229
                                $real_answers[$answerId] = true;
2230
                            } else {
2231
                                $real_answers[$answerId] = false;
2232
                            }
2233
                        } else {
2234
                            if ($studentChoice) {
2235
                                $real_answers[$answerId] = false;
2236
                            } else {
2237
                                $real_answers[$answerId] = true;
2238
                            }
2239
                        }
2240
                    }
2241
                    break;
2242
                // for fill in the blanks
2243
                case FILL_IN_BLANKS :
2244
                    // the question is encoded like this
2245
                    // [A] B [C] D [E] F::10,10,10@1
2246
                    // number 1 before the "@" means that is a switchable fill in blank question
2247
                    // [A] B [C] D [E] F::10,10,10@ or  [A] B [C] D [E] F::10,10,10
2248
                    // means that is a normal fill blank question
2249
                    // first we explode the "::"
2250
                    $pre_array = explode('::', $answer);
2251
                    // is switchable fill blank or not
2252
                    $last = count($pre_array) - 1;
2253
                    $is_set_switchable = explode('@', $pre_array[$last]);
2254
                    $switchable_answer_set = false;
2255
                    /*if (isset ($is_set_switchable[1]) && $is_set_switchable[1] == 1) {
2256
                        $switchable_answer_set = true;
2257
                    }*/
2258
                    $answer = '';
2259
                    for ($k = 0; $k < $last; $k++) {
2260
                        $answer .= $pre_array[$k];
2261
                    }
2262
                    // splits weightings that are joined with a comma
2263
                    $answerWeighting = explode(',', $is_set_switchable[0]);
2264

    
2265
                    // we save the answer because it will be modified
2266
                    //$temp = $answer;
2267
                    $temp = $answer;
2268

    
2269
                    $answer = '';
2270
                    $j = 0;
2271
                    //initialise answer tags
2272
                    $user_tags = $correct_tags = $real_text = array ();
2273
                    // the loop will stop at the end of the text
2274
                    while (1) {
2275
                        // quits the loop if there are no more blanks (detect '[')
2276
                        if (($pos = api_strpos($temp, '[')) === false) {
2277
                            // adds the end of the text
2278
                            $answer = $temp;
2279
                            /* // Deprecated code
2280
                             // TeX parsing - replacement of texcode tags
2281
                            $texstring = api_parse_tex($texstring);
2282
                            $answer = str_replace("{texcode}", $texstring, $answer);
2283
                            */
2284
                            $real_text[] = $answer;
2285
                            break; //no more "blanks", quit the loop
2286
                        }
2287
                        // adds the piece of text that is before the blank
2288
                        //and ends with '[' into a general storage array
2289
                        $real_text[] = api_substr($temp, 0, $pos +1);
2290
                        $answer .= api_substr($temp, 0, $pos +1);
2291
                        //take the string remaining (after the last "[" we found)
2292
                        $temp = api_substr($temp, $pos +1);
2293
                        // quit the loop if there are no more blanks, and update $pos to the position of next ']'
2294
                        if (($pos = api_strpos($temp, ']')) === false) {
2295
                            // adds the end of the text
2296
                            $answer .= $temp;
2297
                            break;
2298
                        }
2299
                        if ($from_database) {
2300
                            $queryfill = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".$exeId."' AND question_id= '".Database::escape_string($questionId)."'";
2301
							
2302
                            $resfill = Database::query($queryfill);
2303
                            $str = Database::result($resfill,0,'answer');
2304

    
2305
                            api_preg_match_all('#\[([^[]*)\]#', $str, $arr);
2306
                            $str = str_replace('\r\n', '', $str);
2307
                            $choice = $arr[1];
2308

    
2309
                            $tmp = api_strrpos($choice[$j],' / ');
2310
                            $choice[$j] = api_substr($choice[$j],0,$tmp);
2311
                            $choice[$j] = trim($choice[$j]);
2312

    
2313
                            //Needed to let characters ' and " to work as part of an answer
2314
                            $choice[$j] = stripslashes($choice[$j]);
2315
                        } else {
2316
                            $choice[$j] = trim($choice[$j]);
2317
                        }
2318

    
2319
                        //No idea why we api_strtolower user reponses
2320
                        //$user_tags[] = api_strtolower($choice[$j]);
2321
                        $user_tags[] = $choice[$j];
2322
                        //put the contents of the [] answer tag into correct_tags[]
2323
                        //$correct_tags[] = api_strtolower(api_substr($temp, 0, $pos));
2324
                        $correct_tags[] = api_substr($temp, 0, $pos);
2325
                        $j++;
2326
                        $temp = api_substr($temp, $pos +1);
2327
                    }
2328
                    $answer = '';
2329
                    $real_correct_tags = $correct_tags;
2330
                    $chosen_list = array();
2331

    
2332
                    for ($i = 0; $i < count($real_correct_tags); $i++) {
2333
                        if ($i == 0) {
2334
                            $answer .= $real_text[0];
2335
                        }
2336
                        if (!$switchable_answer_set) {
2337
                            //needed to parse ' and " characters
2338
                            $user_tags[$i] = stripslashes($user_tags[$i]);
2339
                            if ($this->pass_fill_in_blanks_rules($correct_tags[$i],$user_tags[$i])) {
2340
                                // gives the related weighting to the student
2341
                                $questionScore += $answerWeighting[$i];
2342
                                // increments total score
2343
                                $totalScore += $answerWeighting[$i];
2344
                                // adds the word in green at the end of the string
2345
                                $answer .= strip_tags($user_tags[$i]);
2346
                            }
2347
							elseif (preg_match("#^\+@\+(.*)#",$user_tags[$i],$res)) {
2348
								$answer .= $res[1];
2349
								// gives the related weighting to the student
2350
                                $questionScore += $answerWeighting[$i];
2351
                                // increments total score
2352
                                $totalScore += $answerWeighting[$i];
2353
							}
2354
                            // else if the word entered by the student IS NOT the same as the one defined by the professor
2355
                            elseif (!empty ($user_tags[$i])) {
2356
                                // adds the word in red at the end of the string, and strikes it
2357
                                $answer .= '<font color="red"><s>' . $user_tags[$i] . '</s></font>';
2358
                            } else {
2359
                                // adds a tabulation if no word has been typed by the student
2360
                                $answer .= '&nbsp;&nbsp;&nbsp;';
2361
                            }
2362
                        } else {
2363
                            // switchable fill in the blanks
2364
                            if (in_array($user_tags[$i], $correct_tags)) {
2365
                                $chosen_list[] = $user_tags[$i];
2366
                                $correct_tags = array_diff($correct_tags, $chosen_list);
2367

    
2368
                                // gives the related weighting to the student
2369
                                $questionScore += $answerWeighting[$i];
2370
                                // increments total score
2371
                                $totalScore += $answerWeighting[$i];
2372
                                // adds the word in green at the end of the string
2373
                                $answer .= $user_tags[$i];
2374
                            }
2375
                            elseif (!empty ($user_tags[$i])) {
2376
                                // else if the word entered by the student IS NOT the same as the one defined by the professor
2377
                                // adds the word in red at the end of the string, and strikes it
2378
                                $answer .= '<font color="red"><s>' . $user_tags[$i] . '</s></font>';
2379
                            } else {
2380
                                // adds a tabulation if no word has been typed by the student
2381
                                $answer .= '&nbsp;&nbsp;&nbsp;';
2382
                            }
2383
                        }
2384
                        // adds the correct word, followed by ] to close the blank
2385
                        $answer .= ' / <font color="green"><b>' . $real_correct_tags[$i] . '</b></font>]';
2386
						if (!$this->pass_fill_in_blanks_rules($correct_tags[$i],$user_tags[$i]) && !preg_match("#^\+@\+(.*)#",$user_tags[$i],$res) && api_is_allowed_to_edit()) {
2387
							$answer .= '<input type="button" onclick="javascript:ChangeToCorrectGaps('.Database::escape_string($questionId).','.$i.')" value="Change to Correct" />';
2388
						}
2389
                        if (isset ($real_text[$i +1])) {
2390
                            $answer .= $real_text[$i +1];
2391
                        }
2392
                    }
2393
                    break;
2394
                // for free answer
2395
                case FREE_ANSWER :
2396
                    if ($from_database) {
2397
                        $query  = "SELECT answer, marks FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
2398
                        $resq   = Database::query($query);
2399
                        $choice = Database::result($resq,0,'answer');
2400
                        $choice = str_replace('\r\n', '', $choice);
2401
                        $choice = stripslashes($choice);
2402
                        $questionScore = Database::result($resq, 0, "marks");
2403
                        if ($questionScore == -1) {
2404
                            $totalScore+= 0;
2405
                        } else {
2406
                            $totalScore+= $questionScore;
2407
                        }
2408
                        if ($questionScore == '') {
2409
                            $questionScore = 0;
2410
                        }
2411
                        $arrques = $questionName;
2412
                        $arrans  = $choice;
2413
                    } else {
2414
                        $studentChoice = $choice;
2415
                        if ($studentChoice) {
2416
                            //Fixing negative puntation see #2193
2417
                            $questionScore = 0;
2418
                            $totalScore += 0;
2419
                        }
2420
                    }
2421
                    break;
2422
                case ORAL_EXPRESSION :
2423
                    if ($from_database) {
2424
                        $query  = "SELECT answer, marks FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
2425
                        $resq   = Database::query($query);
2426
                        $choice = Database::result($resq,0,'answer');
2427
                        $choice = str_replace('\r\n', '', $choice);
2428
                        $choice = stripslashes($choice);
2429
                        $questionScore = Database::result($resq,0,"marks");
2430
                        if ($questionScore==-1) {
2431
                            $totalScore+=0;
2432
                        } else {
2433
                            $totalScore+=$questionScore;
2434
                        }
2435
                        $arrques = $questionName;
2436
                        $arrans  = $choice;
2437
                    } else {
2438
                        $studentChoice = $choice;
2439
                        if ($studentChoice) {
2440
                            //Fixing negative puntation see #2193
2441
                            $questionScore = 0;
2442
                            $totalScore += 0;
2443
                        }
2444
                    }
2445
                    break;
2446
                // for matching
2447
                case MATCHING :
2448
                    if ($from_database) {
2449
                        $sql_answer = 'SELECT id, answer FROM '.$table_ans.' WHERE c_id = '.$course_id.' AND question_id="'.$questionId.'" AND correct=0';
2450
                        $res_answer = Database::query($sql_answer);
2451
                        // getting the real answer
2452
                        $real_list =array();
2453
                        while ($real_answer = Database::fetch_array($res_answer)) {
2454
                            $real_list[$real_answer['id']]= $real_answer['answer'];
2455
                        }
2456
                        $sql_select_answer = 'SELECT id, answer, correct, id_auto FROM '.$table_ans.'
2457
                                              WHERE c_id = '.$course_id.' AND question_id="'.$questionId.'" AND correct <> 0 ORDER BY id_auto';
2458
                        $res_answers = Database::query($sql_select_answer);
2459

    
2460
                        $questionScore = 0;
2461

    
2462
                        while ($a_answers = Database::fetch_array($res_answers)) {
2463
                            $i_answer_id    = $a_answers['id']; //3
2464
                            $s_answer_label = $a_answers['answer'];  // your daddy - your mother
2465
                            $i_answer_correct_answer = $a_answers['correct']; //1 - 2
2466
                            $i_answer_id_auto = $a_answers['id_auto']; // 3 - 4
2467

    
2468
                            $sql_user_answer = "SELECT answer FROM $TBL_TRACK_ATTEMPT
2469
                                                WHERE exe_id = '$exeId' AND question_id = '$questionId' AND position='$i_answer_id_auto'";
2470

    
2471
                            $res_user_answer = Database::query($sql_user_answer);
2472

    
2473
                            if (Database::num_rows($res_user_answer)>0 ) {
2474
                                $s_user_answer = Database::result($res_user_answer,0,0); //  rich - good looking
2475
                            } else {
2476
                                $s_user_answer = 0;
2477
                            }
2478
                            $i_answerWeighting=$objAnswerTmp->selectWeighting($i_answer_id);
2479
                            $user_answer = '';
2480
                            if (!empty($s_user_answer)) {
2481
                                if ($s_user_answer == $i_answer_correct_answer) {
2482
                                    $questionScore  += $i_answerWeighting;
2483
                                    $totalScore     += $i_answerWeighting;
2484
                                    $user_answer = '<span>'.$real_list[$i_answer_correct_answer].'</span>';
2485
                                } else {
2486
                                    $user_answer = '<span style="color: #FF0000; text-decoration: line-through;">'.$real_list[$s_user_answer].'</span>';
2487
                                }
2488
                            }
2489

    
2490
                            if ($show_result) {
2491
                                echo '<tr>';
2492
                                echo '<td>'.$s_answer_label.'</td>';
2493
                                echo '<td>'.$user_answer;
2494
                                echo ' <b><span style="color: #008000;">'.$real_list[$i_answer_correct_answer].'</span></b> ';
2495
                                echo '</td>';
2496
                                echo '</tr>';
2497
                            }
2498
                        }
2499
                        break(2); //break the switch and the "for" condition
2500
                    } else {
2501
                        $numAnswer=$objAnswerTmp->selectAutoId($answerId);
2502
                        if ($answerCorrect) {
2503
                            if ($answerCorrect == $choice[$numAnswer]) {
2504
                                $questionScore  += $answerWeighting;
2505
                                $totalScore     += $answerWeighting;
2506
                                $user_answer = '<span>'.$answer_matching[$choice[$numAnswer]].'</span>';
2507
                            } else {
2508
                                $user_answer = '<span style="color: #FF0000; text-decoration: line-through;">'.$answer_matching[$choice[$numAnswer]].'</span>';
2509
                            }
2510
                            $matching[$numAnswer] =  $choice[$numAnswer];
2511
                        }
2512
                        break;
2513
                    }
2514
                // for hotspot with no order
2515
                case HOT_SPOT :
2516
                    if ($from_database) {
2517
                        if ($show_result) {
2518
                            $TBL_TRACK_HOTSPOT = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
2519
                            $query = "SELECT hotspot_correct FROM ".$TBL_TRACK_HOTSPOT." WHERE hotspot_exe_id = '".$exeId."' and hotspot_question_id= '".$questionId."' AND hotspot_answer_id='".Database::escape_string($answerId)."'";
2520
                            $resq = Database::query($query);
2521
                            $studentChoice = Database::result($resq,0,"hotspot_correct");
2522

    
2523
                            if ($studentChoice) {
2524
                                $questionScore  += $answerWeighting;
2525
                                $totalScore     += $answerWeighting;
2526
                            }
2527
                        }
2528
                    }  else {
2529
                        $studentChoice = $choice[$answerId];
2530
                        if ($studentChoice) {
2531
                            $questionScore  += $answerWeighting;
2532
                            $totalScore     += $answerWeighting;
2533
                        }
2534
                    }
2535
                    break;
2536
                // @todo never added to chamilo
2537
                //for hotspot with fixed order
2538
                case HOT_SPOT_ORDER :
2539
                    $studentChoice = $choice['order'][$answerId];
2540
                    if ($studentChoice == $answerId) {
2541
                        $questionScore  += $answerWeighting;
2542
                        $totalScore     += $answerWeighting;
2543
                        $studentChoice = true;
2544
                    } else {
2545
                        $studentChoice = false;
2546
                    }
2547
                    break;
2548
                // for hotspot with delineation
2549
                case HOT_SPOT_DELINEATION :
2550
                    if ($from_database) {
2551
                        // getting the user answer
2552
                        $TBL_TRACK_HOTSPOT = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
2553
                        $query   = "SELECT hotspot_correct, hotspot_coordinate from ".$TBL_TRACK_HOTSPOT." where hotspot_exe_id = '".$exeId."' and hotspot_question_id= '".$questionId."' AND hotspot_answer_id='1'"; //by default we take 1 because it's a delineation
2554
                        $resq    = Database::query($query);
2555
                        $row     = Database::fetch_array($resq,'ASSOC');
2556

    
2557
                        $choice      = $row['hotspot_correct'];
2558
                        $user_answer = $row['hotspot_coordinate'];
2559

    
2560
                        // THIS is very important otherwise the poly_compile will throw an error!!
2561
                        // round-up the coordinates
2562
                        $coords = explode('/',$user_answer);
2563
                        $user_array = '';
2564
                        foreach ($coords as $coord) {
2565
                            list($x,$y) = explode(';',$coord);
2566
                            $user_array .= round($x).';'.round($y).'/';
2567
                        }
2568
                        $user_array = substr($user_array,0,-1);
2569
                    } else {
2570
                        if ($studentChoice) {
2571
                            $newquestionList[]=$questionId;
2572
                        }
2573

    
2574
                        if ($answerId===1) {
2575
                            $studentChoice	=$choice[$answerId];
2576
                            $questionScore	+=$answerWeighting;
2577

    
2578
                            if ($hotspot_delineation_result[1]==1) {
2579
                                $totalScore +=$answerWeighting; //adding the total
2580
                            }
2581
                        }
2582
                    }
2583
                    $_SESSION['hotspot_coord'][1]	= $delineation_cord;
2584
                    $_SESSION['hotspot_dest'][1]	= $answer_delineation_destination;
2585
                    break;
2586
            } // end switch Answertype
2587

    
2588
            global $origin;
2589

    
2590
            if ($show_result) {
2591

    
2592
                if ($debug) error_log('show result '.$show_result);
2593

    
2594
                if ($from == 'exercise_result') {
2595
                    if ($debug) error_log('Showing questions $from '.$from);
2596
                    //display answers (if not matching type, or if the answer is correct)
2597
                    if ($answerType != MATCHING || $answerCorrect) {
2598
                        if (in_array($answerType, array(UNIQUE_ANSWER, UNIQUE_ANSWER_NO_OPTION, MULTIPLE_ANSWER, MULTIPLE_ANSWER_COMBINATION, GLOBAL_MULTIPLE_ANSWER))) {
2599
                            //if ($origin != 'learnpath') {
2600
                            ExerciseShowFunctions::display_unique_or_multiple_answer($feedback_type, $answerType, $studentChoice, $answer, $answerComment, $answerCorrect, 0, 0, 0);
2601
                            //}
2602
                        } elseif($answerType == MULTIPLE_ANSWER_TRUE_FALSE) {
2603
                            //if ($origin!='learnpath') {
2604
                            ExerciseShowFunctions::display_multiple_answer_true_false($feedback_type, $answerType, $studentChoice, $answer, $answerComment, $answerCorrect,0,$questionId,0);
2605
                            //}
2606
                        } elseif($answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE ) {
2607
                            //	if ($origin!='learnpath') {
2608
                            ExerciseShowFunctions::display_multiple_answer_combination_true_false($feedback_type, $answerType, $studentChoice, $answer, $answerComment, $answerCorrect,0,0,0);
2609
                            //}
2610
                        } elseif($answerType == FILL_IN_BLANKS) {
2611
                            //if ($origin!='learnpath') {
2612
                            ExerciseShowFunctions::display_fill_in_blanks_answer($feedback_type, $answer,0,0);
2613
                            //	}
2614
                        } elseif($answerType == FREE_ANSWER) {
2615
                            //if($origin != 'learnpath') {
2616
                            ExerciseShowFunctions::display_free_answer($feedback_type, $choice, $exeId, $questionId, $questionScore);
2617
                            //}
2618
                        } elseif($answerType == ORAL_EXPRESSION) {
2619
                            // to store the details of open questions in an array to be used in mail
2620
                            //if ($origin != 'learnpath') {
2621
                            ExerciseShowFunctions::display_oral_expression_answer($feedback_type, $choice, 0, 0, $nano);
2622
                            //}
2623
                        } elseif($answerType == HOT_SPOT) {
2624
                            //if ($origin != 'learnpath') {
2625
                            ExerciseShowFunctions::display_hotspot_answer($feedback_type, $answerId, $answer, $studentChoice, $answerComment);
2626
                            //	}
2627
                        } elseif($answerType == HOT_SPOT_ORDER) {
2628
                            //if ($origin != 'learnpath') {
2629
                            ExerciseShowFunctions::display_hotspot_order_answer($feedback_type, $answerId, $answer, $studentChoice, $answerComment);
2630
                            //}
2631
                        } elseif ($answerType == HOT_SPOT_DELINEATION) {
2632
                            $user_answer = $_SESSION['exerciseResultCoordinates'][$questionId];
2633

    
2634
                            //round-up the coordinates
2635
                            $coords = explode('/',$user_answer);
2636
                            $user_array = '';
2637
                            foreach ($coords as $coord) {
2638
                                list($x,$y) = explode(';',$coord);
2639
                                $user_array .= round($x).';'.round($y).'/';
2640
                            }
2641
                            $user_array = substr($user_array,0,-1);
2642

    
2643
                            if ($next) {
2644
                                //$tbl_track_e_hotspot = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
2645
                                // Save into db
2646
                                /*	$sql = "INSERT INTO $tbl_track_e_hotspot (hotspot_user_id, hotspot_course_code, hotspot_exe_id, hotspot_question_id, hotspot_answer_id, hotspot_correct, hotspot_coordinate )
2647
                                VALUES ('".Database::escape_string($_user['user_id'])."', '".Database::escape_string($_course['id'])."', '".Database::escape_string($exeId)."', '".Database::escape_string($questionId)."', '".Database::escape_string($answerId)."', '".Database::escape_string($studentChoice)."', '".Database::escape_string($user_array)."')";
2648
                                $result = api_sql_query($sql,__FILE__,__LINE__);*/
2649
                                $user_answer = $user_array;
2650

    
2651
                                // we compare only the delineation not the other points
2652
                                $answer_question	= $_SESSION['hotspot_coord'][1];
2653
                                $answerDestination	= $_SESSION['hotspot_dest'][1];
2654

    
2655
                                //calculating the area
2656
                                $poly_user 			= convert_coordinates($user_answer,'/');
2657
                                $poly_answer		= convert_coordinates($answer_question,'|');
2658
                                $max_coord 			= poly_get_max($poly_user,$poly_answer);
2659
                                $poly_user_compiled = poly_compile($poly_user,$max_coord);
2660
                                $poly_answer_compiled = poly_compile($poly_answer,$max_coord);
2661
                                $poly_results 		= poly_result($poly_answer_compiled,$poly_user_compiled,$max_coord);
2662

    
2663
                                $overlap = $poly_results['both'];
2664
                                $poly_answer_area = $poly_results['s1'];
2665
                                $poly_user_area = $poly_results['s2'];
2666
                                $missing = $poly_results['s1Only'];
2667
                                $excess = $poly_results['s2Only'];
2668

    
2669
                                //$overlap = round(polygons_overlap($poly_answer,$poly_user)); //this is an area in pixels
2670
                                if ($debug>0)  error_log(__LINE__.' - Polygons results are '.print_r($poly_results,1),0);
2671

    
2672
                                if ($overlap < 1) {
2673
                                    //shortcut to avoid complicated calculations
2674
                                    $final_overlap = 0;
2675
                                    $final_missing = 100;
2676
                                    $final_excess = 100;
2677
                                } else {
2678
                                    // the final overlap is the percentage of the initial polygon that is overlapped by the user's polygon
2679
                                    $final_overlap = round(((float)$overlap / (float)$poly_answer_area)*100);
2680
                                    if ($debug>1) error_log(__LINE__.' - Final overlap is '.$final_overlap,0);
2681
                                    // the final missing area is the percentage of the initial polygon that is not overlapped by the user's polygon
2682
                                    $final_missing = 100 - $final_overlap;
2683
                                    if ($debug>1) {
2684
                                        error_log(__LINE__.' - Final missing is '.$final_missing,0);
2685
                                    }
2686
                                    // the final excess area is the percentage of the initial polygon's size that is covered by the user's polygon outside of the initial polygon
2687
                                    $final_excess = round((((float)$poly_user_area-(float)$overlap)/(float)$poly_answer_area)*100);
2688
                                    if ($debug>1) {
2689
                                        error_log(__LINE__.' - Final excess is '.$final_excess,0);
2690
                                    }
2691
                                }
2692

    
2693
                                //checking the destination parameters parsing the "@@"
2694
                                $destination_items= explode('@@', $answerDestination);
2695
                                $threadhold_total = $destination_items[0];
2696
                                $threadhold_items=explode(';',$threadhold_total);
2697
                                $threadhold1 = $threadhold_items[0]; // overlap
2698
                                $threadhold2 = $threadhold_items[1]; // excess
2699
                                $threadhold3 = $threadhold_items[2];	 //missing
2700

    
2701
                                // if is delineation
2702
                                if ($answerId===1) {
2703
                                    //setting colors
2704
                                    if ($final_overlap>=$threadhold1) {
2705
                                        $overlap_color=true; //echo 'a';
2706
                                    }
2707
                                    //echo $excess.'-'.$threadhold2;
2708
                                    if ($final_excess<=$threadhold2) {
2709
                                        $excess_color=true; //echo 'b';
2710
                                    }
2711
                                    //echo '--------'.$missing.'-'.$threadhold3;
2712
                                    if ($final_missing<=$threadhold3) {
2713
                                        $missing_color=true; //echo 'c';
2714
                                    }
2715

    
2716
                                    // if pass
2717
                                    if ($final_overlap>=$threadhold1 && $final_missing<=$threadhold3 && $final_excess<=$threadhold2) {
2718
                                        $next=1; //go to the oars
2719
                                        $result_comment=get_lang('Acceptable');
2720
                                        $final_answer = 1;	// do not update with  update_exercise_attempt
2721
                                    } else {
2722
                                        $next=0;
2723
                                        $result_comment=get_lang('Unacceptable');
2724
                                        $comment=$answerDestination=$objAnswerTmp->selectComment(1);
2725
                                        $answerDestination=$objAnswerTmp->selectDestination(1);
2726
                                        //checking the destination parameters parsing the "@@"
2727
                                        $destination_items= explode('@@', $answerDestination);
2728
                                    }
2729
                                } elseif($answerId>1) {
2730
                                    if ($objAnswerTmp->selectHotspotType($answerId) == 'noerror') {
2731
                                        if ($debug>0) {
2732
                                            error_log(__LINE__.' - answerId is of type noerror',0);
2733
                                        }
2734
                                        //type no error shouldn't be treated
2735
                                        $next = 1;
2736
                                        continue;
2737
                                    }
2738
                                    if ($debug>0) {
2739
                                        error_log(__LINE__.' - answerId is >1 so we\'re probably in OAR',0);
2740
                                    }
2741
                                    //check the intersection between the oar and the user
2742
                                    //echo 'user';	print_r($x_user_list);		print_r($y_user_list);
2743
                                    //echo 'official';print_r($x_list);print_r($y_list);
2744
                                    //$result = get_intersection_data($x_list,$y_list,$x_user_list,$y_user_list);
2745
                                    $inter= $result['success'];
2746

    
2747
                                    //$delineation_cord=$objAnswerTmp->selectHotspotCoordinates($answerId);
2748
                                    $delineation_cord=$objAnswerTmp->selectHotspotCoordinates($answerId);
2749

    
2750
                                    $poly_answer = convert_coordinates($delineation_cord,'|');
2751
                                    $max_coord = poly_get_max($poly_user,$poly_answer);
2752
                                    $poly_answer_compiled = poly_compile($poly_answer,$max_coord);
2753
                                    $overlap = poly_touch($poly_user_compiled, $poly_answer_compiled,$max_coord);
2754

    
2755
                                    if ($overlap == false) {
2756
                                        //all good, no overlap
2757
                                        $next = 1;
2758
                                        continue;
2759
                                    } else {
2760
                                        if ($debug>0) {
2761
                                            error_log(__LINE__.' - Overlap is '.$overlap.': OAR hit',0);
2762
                                        }
2763
                                        $organs_at_risk_hit++;
2764
                                        //show the feedback
2765
                                        $next=0;
2766
                                        $comment=$answerDestination=$objAnswerTmp->selectComment($answerId);
2767
                                        $answerDestination=$objAnswerTmp->selectDestination($answerId);
2768

    
2769
                                        $destination_items= explode('@@', $answerDestination);
2770
                                        $try_hotspot=$destination_items[1];
2771
                                        $lp_hotspot=$destination_items[2];
2772
                                        $select_question_hotspot=$destination_items[3];
2773
                                        $url_hotspot=$destination_items[4];
2774
                                    }
2775
                                }
2776
                            } else {	// the first delineation feedback
2777
                                if ($debug>0) {
2778
                                    error_log(__LINE__.' first',0);
2779
                                }
2780
                            }
2781
                        } elseif($answerType == MATCHING) {
2782
                            // if ($origin != 'learnpath') {
2783
                            echo '<tr>';
2784
                            echo '<td>'.$answer_matching[$answerId].'</td><td>'.$user_answer.' / <b><span style="color: #008000;">'.$answer_matching[$answerCorrect].'</span></b></td>';
2785
                            echo '</tr>';
2786
                            //}
2787
                        }
2788
                    }
2789
                } else {
2790
                    if ($debug) error_log('Showing questions $from '.$from);
2791

    
2792
                    switch ($answerType) {
2793
                        case UNIQUE_ANSWER :
2794
                        case UNIQUE_ANSWER_NO_OPTION:
2795
                        case MULTIPLE_ANSWER :
2796
                        case GLOBAL_MULTIPLE_ANSWER :
2797
                        case MULTIPLE_ANSWER_COMBINATION :
2798
                            if ($answerId==1) {
2799
                                ExerciseShowFunctions::display_unique_or_multiple_answer($feedback_type, $answerType, $studentChoice, $answer, $answerComment, $answerCorrect,$exeId,$questionId,$answerId);
2800
                            } else {
2801
                                ExerciseShowFunctions::display_unique_or_multiple_answer($feedback_type, $answerType, $studentChoice, $answer, $answerComment, $answerCorrect,$exeId,$questionId,"");
2802
                            }
2803
                            break;
2804
                        case MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE:
2805
                            if ($answerId==1) {
2806
                                ExerciseShowFunctions::display_multiple_answer_combination_true_false($feedback_type, $answerType, $studentChoice, $answer, $answerComment, $answerCorrect,$exeId,$questionId,$answerId);
2807
                            } else {
2808
                                ExerciseShowFunctions::display_multiple_answer_combination_true_false($feedback_type, $answerType, $studentChoice, $answer, $answerComment, $answerCorrect,$exeId,$questionId,"");
2809
                            }
2810
                            break;
2811
                        case MULTIPLE_ANSWER_TRUE_FALSE :
2812
                            if ($answerId==1) {
2813
                                ExerciseShowFunctions::display_multiple_answer_true_false($feedback_type, $answerType, $studentChoice, $answer, $answerComment, $answerCorrect,$exeId,$questionId,$answerId);
2814
                            } else {
2815
                                ExerciseShowFunctions::display_multiple_answer_true_false($feedback_type, $answerType, $studentChoice, $answer, $answerComment, $answerCorrect,$exeId,$questionId, "");
2816
                            }
2817
                            break;
2818
                        case FILL_IN_BLANKS:
2819
                            ExerciseShowFunctions::display_fill_in_blanks_answer($feedback_type, $answer,$exeId,$questionId);
2820
                            break;
2821
                        case FREE_ANSWER:
2822
                            echo ExerciseShowFunctions::display_free_answer($feedback_type, $choice, $exeId, $questionId, $questionScore);
2823
                            break;
2824
                        case ORAL_EXPRESSION:
2825
                            echo '<tr>
2826
		                            <td valign="top">'.ExerciseShowFunctions::display_oral_expression_answer($feedback_type, $choice, $exeId, $questionId, $nano).'</td>
2827
		                            </tr>
2828
		                            </table>';
2829
                            break;
2830
                        case HOT_SPOT:
2831
                            ExerciseShowFunctions::display_hotspot_answer($feedback_type, $answerId, $answer, $studentChoice, $answerComment);
2832
                            break;
2833
                        case HOT_SPOT_DELINEATION:
2834
                            $user_answer = $user_array;
2835
                            if ($next) {
2836
                                //$tbl_track_e_hotspot = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
2837
                                // Save into db
2838
                                /*	$sql = "INSERT INTO $tbl_track_e_hotspot (hotspot_user_id, hotspot_course_code, hotspot_exe_id, hotspot_question_id, hotspot_answer_id, hotspot_correct, hotspot_coordinate )
2839
                                VALUES ('".Database::escape_string($_user['user_id'])."', '".Database::escape_string($_course['id'])."', '".Database::escape_string($exeId)."', '".Database::escape_string($questionId)."', '".Database::escape_string($answerId)."', '".Database::escape_string($studentChoice)."', '".Database::escape_string($user_array)."')";
2840
                                $result = api_sql_query($sql,__FILE__,__LINE__);*/
2841
                                $user_answer = $user_array;
2842

    
2843
                                // we compare only the delineation not the other points
2844
                                $answer_question	= $_SESSION['hotspot_coord'][1];
2845
                                $answerDestination	= $_SESSION['hotspot_dest'][1];
2846

    
2847
                                //calculating the area
2848
                                $poly_user 			= convert_coordinates($user_answer,'/');
2849
                                $poly_answer		= convert_coordinates($answer_question,'|');
2850

    
2851
                                $max_coord 			= poly_get_max($poly_user,$poly_answer);
2852
                                $poly_user_compiled = poly_compile($poly_user,$max_coord);
2853
                                $poly_answer_compiled = poly_compile($poly_answer,$max_coord);
2854
                                $poly_results 		= poly_result($poly_answer_compiled,$poly_user_compiled,$max_coord);
2855

    
2856
                                $overlap = $poly_results['both'];
2857
                                $poly_answer_area = $poly_results['s1'];
2858
                                $poly_user_area = $poly_results['s2'];
2859
                                $missing = $poly_results['s1Only'];
2860
                                $excess = $poly_results['s2Only'];
2861

    
2862
                                //$overlap = round(polygons_overlap($poly_answer,$poly_user)); //this is an area in pixels
2863
                                if ($debug>0) {
2864
                                    error_log(__LINE__.' - Polygons results are '.print_r($poly_results,1),0);
2865
                                }
2866
                                if ($overlap < 1) {
2867
                                    //shortcut to avoid complicated calculations
2868
                                    $final_overlap = 0;
2869
                                    $final_missing = 100;
2870
                                    $final_excess = 100;
2871
                                } else {
2872
                                    // the final overlap is the percentage of the initial polygon that is overlapped by the user's polygon
2873
                                    $final_overlap = round(((float)$overlap / (float)$poly_answer_area)*100);
2874
                                    if ($debug>1) {
2875
                                        error_log(__LINE__.' - Final overlap is '.$final_overlap,0);
2876
                                    }
2877
                                    // the final missing area is the percentage of the initial polygon that is not overlapped by the user's polygon
2878
                                    $final_missing = 100 - $final_overlap;
2879
                                    if ($debug>1) {
2880
                                        error_log(__LINE__.' - Final missing is '.$final_missing,0);
2881
                                    }
2882
                                    // the final excess area is the percentage of the initial polygon's size that is covered by the user's polygon outside of the initial polygon
2883
                                    $final_excess = round((((float)$poly_user_area-(float)$overlap)/(float)$poly_answer_area)*100);
2884
                                    if ($debug>1) {
2885
                                        error_log(__LINE__.' - Final excess is '.$final_excess,0);
2886
                                    }
2887
                                }
2888

    
2889
                                //checking the destination parameters parsing the "@@"
2890
                                $destination_items= explode('@@', $answerDestination);
2891
                                $threadhold_total = $destination_items[0];
2892
                                $threadhold_items=explode(';',$threadhold_total);
2893
                                $threadhold1 = $threadhold_items[0]; // overlap
2894
                                $threadhold2 = $threadhold_items[1]; // excess
2895
                                $threadhold3 = $threadhold_items[2];	 //missing
2896

    
2897
                                // if is delineation
2898
                                if ($answerId===1) {
2899
                                    //setting colors
2900
                                    if ($final_overlap>=$threadhold1) {
2901
                                        $overlap_color=true; //echo 'a';
2902
                                    }
2903
                                    //echo $excess.'-'.$threadhold2;
2904
                                    if ($final_excess<=$threadhold2) {
2905
                                        $excess_color=true; //echo 'b';
2906
                                    }
2907
                                    //echo '--------'.$missing.'-'.$threadhold3;
2908
                                    if ($final_missing<=$threadhold3) {
2909
                                        $missing_color=true; //echo 'c';
2910
                                    }
2911

    
2912
                                    // if pass
2913
                                    if ($final_overlap>=$threadhold1 && $final_missing<=$threadhold3 && $final_excess<=$threadhold2) {
2914
                                        $next=1; //go to the oars
2915
                                        $result_comment=get_lang('Acceptable');
2916
                                        $final_answer = 1;	// do not update with  update_exercise_attempt
2917
                                    } else {
2918
                                        $next=0;
2919
                                        $result_comment=get_lang('Unacceptable');
2920
                                        $comment=$answerDestination=$objAnswerTmp->selectComment(1);
2921
                                        $answerDestination=$objAnswerTmp->selectDestination(1);
2922
                                        //checking the destination parameters parsing the "@@"
2923
                                        $destination_items= explode('@@', $answerDestination);
2924
                                    }
2925
                                } elseif($answerId>1) {
2926
                                    if ($objAnswerTmp->selectHotspotType($answerId) == 'noerror') {
2927
                                        if ($debug>0) {
2928
                                            error_log(__LINE__.' - answerId is of type noerror',0);
2929
                                        }
2930
                                        //type no error shouldn't be treated
2931
                                        $next = 1;
2932
                                        continue;
2933
                                    }
2934
                                    if ($debug>0) {
2935
                                        error_log(__LINE__.' - answerId is >1 so we\'re probably in OAR',0);
2936
                                    }
2937
                                    //check the intersection between the oar and the user
2938
                                    //echo 'user';	print_r($x_user_list);		print_r($y_user_list);
2939
                                    //echo 'official';print_r($x_list);print_r($y_list);
2940
                                    //$result = get_intersection_data($x_list,$y_list,$x_user_list,$y_user_list);
2941
                                    $inter= $result['success'];
2942

    
2943
                                    //$delineation_cord=$objAnswerTmp->selectHotspotCoordinates($answerId);
2944
                                    $delineation_cord=$objAnswerTmp->selectHotspotCoordinates($answerId);
2945

    
2946
                                    $poly_answer = convert_coordinates($delineation_cord,'|');
2947
                                    $max_coord = poly_get_max($poly_user,$poly_answer);
2948
                                    $poly_answer_compiled = poly_compile($poly_answer,$max_coord);
2949
                                    $overlap = poly_touch($poly_user_compiled, $poly_answer_compiled,$max_coord);
2950

    
2951
                                    if ($overlap == false) {
2952
                                        //all good, no overlap
2953
                                        $next = 1;
2954
                                        continue;
2955
                                    } else {
2956
                                        if ($debug>0) {
2957
                                            error_log(__LINE__.' - Overlap is '.$overlap.': OAR hit',0);
2958
                                        }
2959
                                        $organs_at_risk_hit++;
2960
                                        //show the feedback
2961
                                        $next=0;
2962
                                        $comment=$answerDestination=$objAnswerTmp->selectComment($answerId);
2963
                                        $answerDestination=$objAnswerTmp->selectDestination($answerId);
2964

    
2965
                                        $destination_items= explode('@@', $answerDestination);
2966
                                        $try_hotspot=$destination_items[1];
2967
                                        $lp_hotspot=$destination_items[2];
2968
                                        $select_question_hotspot=$destination_items[3];
2969
                                        $url_hotspot=$destination_items[4];
2970
                                    }
2971
                                }
2972
                            } else {	// the first delineation feedback
2973
                                if ($debug>0) {
2974
                                    error_log(__LINE__.' first',0);
2975
                                }
2976
                            }
2977
                            break;
2978
                        case HOT_SPOT_ORDER:
2979
                            ExerciseShowFunctions::display_hotspot_order_answer($feedback_type, $answerId, $answer, $studentChoice, $answerComment);
2980
                            break;
2981
                        case MATCHING:
2982
                            // if ($origin != 'learnpath') {
2983
                            echo '<tr>';
2984
                            echo '<td>'.$answer_matching[$answerId].'</td><td>'.$user_answer.' / <b><span style="color: #008000;">'.$answer_matching[$answerCorrect].'</span></b></td>';
2985
                            echo '</tr>';
2986
                            //}
2987
                            break;
2988
                    }
2989
                }
2990
            }
2991
            if ($debug) error_log(' ------ ');
2992
        } // end for that loops over all answers of the current question
2993

    
2994
        if ($debug) error_log('-- end answer loop --');
2995

    
2996
        $final_answer = true;
2997
        foreach ($real_answers as $my_answer) {
2998
            if (!$my_answer) {
2999
                $final_answer = false;
3000
            }
3001
        }
3002

    
3003
        //we add the total score after dealing with the answers
3004
        if ($answerType == MULTIPLE_ANSWER_COMBINATION || $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE ) {
3005
            if ($final_answer) {
3006
                //getting only the first score where we save the weight of all the question
3007
                $answerWeighting     = $objAnswerTmp->selectWeighting(1);
3008
                $questionScore      += $answerWeighting;
3009
                $totalScore         += $answerWeighting;
3010
            }
3011
        }
3012

    
3013
        //Fixes multiple answer question in order to be exact
3014
        if ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) {
3015
            //var_dump($answer_correct_array, $real_answers);
3016
            $diff = @array_diff($answer_correct_array, $real_answers);
3017
            //var_dump($diff);
3018
            /*
3019
             * All good answers or nothing works like exact
3020
            $counter = 1;
3021
            $correct_answer = true;
3022
            foreach ($real_answers as $my_answer) {
3023
                if ($debug) error_log(" my_answer: $my_answer answer_correct_array[counter]: ".$answer_correct_array[$counter]);
3024
                if ($my_answer != $answer_correct_array[$counter]) {
3025
                    $correct_answer = false;
3026
                    break;
3027
                }
3028
                $counter++;
3029
            }*/
3030
            if ($debug) error_log(" answer_correct_array: ".print_r($answer_correct_array, 1)."");
3031
            if ($debug) error_log(" real_answers: ".print_r($real_answers, 1)."");
3032
            //if ($debug) error_log(" correct_answer: ".$correct_answer);
3033

    
3034
            /*if ($correct_answer == false) {
3035
                $questionScore = 0;
3036
            }*/
3037

    
3038
            //This makes the result non exact
3039
            if (!empty($diff)) {
3040
                //$questionScore = 0;
3041
            }
3042
        }
3043

    
3044
        $extra_data = array(
3045
            'final_overlap' => $final_overlap,
3046
            'final_missing'=>$final_missing,
3047
            'final_excess'=> $final_excess,
3048
            'overlap_color' => $overlap_color,
3049
            'missing_color'=>$missing_color,
3050
            'excess_color'=> $excess_color,
3051
            'threadhold1'   => $threadhold1,
3052
            'threadhold2'=>$threadhold2,
3053
            'threadhold3'=> $threadhold3,
3054
        );
3055

    
3056
        if ($from == 'exercise_result') {
3057
            // if answer is hotspot. To the difference of exercise_show.php, we use the results from the session (from_db=0)
3058
            // TODO Change this, because it is wrong to show the user some results that haven't been stored in the database yet
3059
            if ($answerType == HOT_SPOT || $answerType == HOT_SPOT_ORDER || $answerType == HOT_SPOT_DELINEATION ) {
3060

    
3061
                if ($debug) error_log('$from AND this is a hotspot kind of question ');
3062

    
3063
                $my_exe_id = 0;
3064
                $from_database = 0;
3065
                if ($answerType == HOT_SPOT_DELINEATION) {
3066
                    if (0) {
3067
                        if ($overlap_color) {
3068
                            $overlap_color='green';
3069
                        } else {
3070
                            $overlap_color='red';
3071
                        }
3072
                        if ($missing_color) {
3073
                            $missing_color='green';
3074
                        } else {
3075
                            $missing_color='red';
3076
                        }
3077
                        if ($excess_color) {
3078
                            $excess_color='green';
3079
                        } else {
3080
                            $excess_color='red';
3081
                        }
3082
                        if (!is_numeric($final_overlap)) {
3083
                            $final_overlap = 0;
3084
                        }
3085
                        if (!is_numeric($final_missing)) {
3086
                            $final_missing = 0;
3087
                        }
3088
                        if (!is_numeric($final_excess)) {
3089
                            $final_excess = 0;
3090
                        }
3091

    
3092
                        if ($final_overlap>100) {
3093
                            $final_overlap = 100;
3094
                        }
3095

    
3096
                        $table_resume='<table class="data_table">
3097
        				<tr class="row_odd" >
3098
        					<td></td>
3099
        					<td ><b>'.get_lang('Requirements').'</b></td>
3100
        					<td><b>'.get_lang('YourAnswer').'</b></td>
3101
        				</tr>
3102
        				<tr class="row_even">
3103
        					<td><b>'.get_lang('Overlap').'</b></td>
3104
        					<td>'.get_lang('Min').' '.$threadhold1.'</td>
3105
        					<td><div style="color:'.$overlap_color.'">'.(($final_overlap < 0)?0:intval($final_overlap)).'</div></td>
3106
        				</tr>
3107
        				<tr>
3108
        					<td><b>'.get_lang('Excess').'</b></td>
3109
        					<td>'.get_lang('Max').' '.$threadhold2.'</td>
3110
        					<td><div style="color:'.$excess_color.'">'.(($final_excess < 0)?0:intval($final_excess)).'</div></td>
3111
        				</tr>
3112
        				<tr class="row_even">
3113
        					<td><b>'.get_lang('Missing').'</b></td>
3114
        					<td>'.get_lang('Max').' '.$threadhold3.'</td>
3115
        					<td><div style="color:'.$missing_color.'">'.(($final_missing < 0)?0:intval($final_missing)).'</div></td>
3116
        				</tr>
3117
        				</table>';
3118
                        if ($next==0) {
3119
                            $try = $try_hotspot;
3120
                            $lp = $lp_hotspot;
3121
                            $destinationid= $select_question_hotspot;
3122
                            $url=$url_hotspot;
3123
                        } else {
3124
                            //show if no error
3125
                            //echo 'no error';
3126
                            $comment=$answerComment=$objAnswerTmp->selectComment($nbrAnswers);
3127
                            $answerDestination=$objAnswerTmp->selectDestination($nbrAnswers);
3128
                        }
3129

    
3130
                        echo '<h1><div style="color:#333;">'.get_lang('Feedback').'</div></h1>
3131
        				<p style="text-align:center">';
3132

    
3133
                        $message='<p>'.get_lang('YourDelineation').'</p>';
3134
                        $message.=$table_resume;
3135
                        $message.='<br />'.get_lang('ResultIs').' '.$result_comment.'<br />';
3136
                        if ($organs_at_risk_hit>0) {
3137
                            $message.='<p><b>'.get_lang('OARHit').'</b></p>';
3138
                        }
3139
                        $message.='<p>'.$comment.'</p>';
3140
                        echo $message;
3141
                    } else {
3142
                        echo $hotspot_delineation_result[0]; //prints message
3143
                        $from_database = 1;	 // the hotspot_solution.swf needs this variable
3144
                    }
3145

    
3146
                    //save the score attempts
3147

    
3148
                    if (1) {
3149
                        $final_answer = $hotspot_delineation_result[1]; //getting the answer 1 or 0 comes from exercise_submit_modal.php
3150
                        if ($final_answer == 0) {
3151
                            $questionScore = 0;
3152
                        }
3153
                        exercise_attempt($questionScore, 1, $quesId, $exeId, 0); // we always insert the answer_id 1 = delineation
3154
                        //in delineation mode, get the answer from $hotspot_delineation_result[1]
3155
                        exercise_attempt_hotspot($exeId,$quesId,1, $hotspot_delineation_result[1], $exerciseResultCoordinates[$quesId]);
3156
                    } else {
3157
                        if ($final_answer==0) {
3158
                            $questionScore = 0;
3159
                            $answer=0;
3160
                            exercise_attempt($questionScore, $answer, $quesId, $exeId, 0);
3161
                            if (is_array($exerciseResultCoordinates[$quesId])) {
3162
                                foreach($exerciseResultCoordinates[$quesId] as $idx => $val) {
3163
                                    exercise_attempt_hotspot($exeId,$quesId,$idx,0,$val);
3164
                                }
3165
                            }
3166
                        } else {
3167
                            exercise_attempt($questionScore, $answer, $quesId, $exeId, 0);
3168
                            if (is_array($exerciseResultCoordinates[$quesId])) {
3169
                                foreach($exerciseResultCoordinates[$quesId] as $idx => $val) {
3170
                                    exercise_attempt_hotspot($exeId,$quesId,$idx,$choice[$idx],$val);
3171
                                }
3172
                            }
3173
                        }
3174
                    }
3175
                    $my_exe_id = $exeId;
3176
                }
3177
            }
3178

    
3179
            if ($answerType == HOT_SPOT || $answerType == HOT_SPOT_ORDER) {
3180
                // We made an extra table for the answers
3181

    
3182
                if ($show_result) {
3183
                    //	if ($origin != 'learnpath') {
3184
                    echo '</table></td></tr>';
3185
                    echo '<tr>
3186
                            <td colspan="2">';
3187
                    echo '<i>'.get_lang('HotSpot').'</i><br /><br />';
3188

    
3189
                    echo '<object type="application/x-shockwave-flash" data="'.api_get_path(WEB_CODE_PATH).'plugin/hotspot/hotspot_solution.swf?modifyAnswers='.Security::remove_XSS($questionId).'&exe_id='.$exeId.'&from_db=1" width="552" height="352">
3190
								<param name="movie" value="../plugin/hotspot/hotspot_solution.swf?modifyAnswers='.Security::remove_XSS($questionId).'&exe_id='.$exeId.'&from_db=1" />
3191
							</object>';
3192
                    echo '</td>
3193
                        </tr>';
3194
                    //	}
3195
                }
3196
            }
3197

    
3198
            //if ($origin != 'learnpath') {
3199
            if ($show_result) {
3200
                echo '</table>';
3201
            }
3202
            //	}
3203
        }
3204
        unset ($objAnswerTmp);
3205

    
3206

    
3207

    
3208
        $totalWeighting += $questionWeighting;
3209
        // Store results directly in the database
3210
        // For all in one page exercises, the results will be
3211
        // stored by exercise_results.php (using the session)
3212

    
3213
        if ($saved_results) {
3214
            if ($debug) error_log("Save question results $saved_results");
3215
            if ($debug) error_log(print_r($choice ,1 ));
3216

    
3217
            if (empty($choice)) {
3218
                $choice = 0;
3219
            }
3220
            if ($answerType ==  MULTIPLE_ANSWER_TRUE_FALSE || $answerType ==  MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE ) {
3221
                if ($choice != 0) {
3222
                    $reply = array_keys($choice);
3223
                    for ($i = 0; $i < sizeof($reply); $i++) {
3224
                        $ans = $reply[$i];
3225
                        exercise_attempt($questionScore, $ans.':'.$choice[$ans], $quesId, $exeId, $i, $this->id);
3226
                        if ($debug) error_log('result =>'.$questionScore.' '.$ans.':'.$choice[$ans]);
3227
                    }
3228
                } else {
3229
                    exercise_attempt($questionScore, 0, $quesId, $exeId, 0, $this->id);
3230
                }
3231
            } elseif ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) {
3232
                if ($choice != 0) {
3233
                    $reply = array_keys($choice);
3234

    
3235
                    if ($debug) error_log("reply ".print_r($reply, 1)."");
3236
                    for ($i = 0; $i < sizeof($reply); $i++) {
3237
                        $ans = $reply[$i];
3238
                        exercise_attempt($questionScore, $ans, $quesId, $exeId, $i, $this->id);
3239
                    }
3240
                } else {
3241
                    exercise_attempt($questionScore, 0, $quesId, $exeId, 0, $this->id);
3242
                }
3243
            } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION) {
3244
                if ($choice != 0) {
3245
                    $reply = array_keys($choice);
3246
                    for ($i = 0; $i < sizeof($reply); $i++) {
3247
                        $ans = $reply[$i];
3248
                        exercise_attempt($questionScore, $ans, $quesId, $exeId, $i, $this->id);
3249
                    }
3250
                } else {
3251
                    exercise_attempt($questionScore, 0, $quesId, $exeId, 0, $this->id);
3252
                }
3253
            } elseif ($answerType == MATCHING) {
3254
                if (isset($matching)) {
3255
                    foreach ($matching as $j => $val) {
3256
                        exercise_attempt($questionScore, $val, $quesId, $exeId, $j, $this->id);
3257
                    }
3258
                }
3259
            } elseif ($answerType == FREE_ANSWER) {
3260
                $answer = $choice;
3261
                exercise_attempt($questionScore, $answer, $quesId, $exeId, 0, $this->id);
3262
            } elseif ($answerType == ORAL_EXPRESSION) {
3263
                $answer = $choice;
3264
                exercise_attempt($questionScore, $answer, $quesId, $exeId, 0, $this->id, $nano);
3265

    
3266
            } elseif ($answerType == UNIQUE_ANSWER || $answerType == UNIQUE_ANSWER_NO_OPTION) {
3267
                $answer = $choice;
3268
                exercise_attempt($questionScore, $answer, $quesId, $exeId, 0, $this->id);
3269
                //            } elseif ($answerType == HOT_SPOT || $answerType == HOT_SPOT_DELINEATION) {
3270
            } elseif ($answerType == HOT_SPOT) {
3271
                exercise_attempt($questionScore, $answer, $quesId, $exeId, 0, $this->id);
3272
                if (isset($exerciseResultCoordinates[$questionId]) && !empty($exerciseResultCoordinates[$questionId])) {
3273
                    foreach ($exerciseResultCoordinates[$questionId] as $idx => $val) {
3274
                        exercise_attempt_hotspot($exeId,$quesId,$idx,$choice[$idx],$val,$this->id);
3275
                    }
3276
                }
3277
            } else {
3278
                exercise_attempt($questionScore, $answer, $quesId, $exeId, 0,$this->id);
3279
            }
3280
        }
3281

    
3282
        if ($propagate_neg == 0 && $questionScore < 0) {
3283
            $questionScore = 0;
3284
        }
3285

    
3286
        if ($saved_results) {
3287
            $stat_table = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
3288
            $sql_update = 'UPDATE ' . $stat_table . ' SET exe_result = exe_result + ' . floatval($questionScore) . ' WHERE exe_id = ' . $exeId;
3289
            if ($debug) error_log($sql_update);
3290
            Database::query($sql_update);
3291
        }
3292

    
3293
        $return_array = array(
3294
            'score'         => $questionScore,
3295
            'weight'        => $questionWeighting,
3296
            'extra'         => $extra_data,
3297
            'open_question' => $arrques,
3298
            'open_answer'   => $arrans,
3299
            'answer_type'   => $answerType
3300
        );
3301
        return $return_array;
3302
    }
3303

    
3304
    /**
3305
     * Sends a notification when a user ends an examn
3306
     *
3307
     */
3308
    function send_notification_for_open_questions($question_list_answers, $origin, $exe_id) {
3309
        if (api_get_course_setting('email_alert_manager_on_new_quiz') != 1 ) {
3310
            return null;
3311
        }
3312
        // Email configuration settings
3313
        $coursecode     = api_get_course_id();
3314
        $course_info    = api_get_course_info(api_get_course_id());
3315

    
3316
        $url_email = api_get_path(WEB_CODE_PATH).'exercice/exercise_show.php?'.api_get_cidreq().'&id_session='.api_get_session_id().'&id='.$exe_id.'&action=qualify';
3317
        $user_info = UserManager::get_user_info_by_id(api_get_user_id());
3318

    
3319
        $msg = '<p>'.get_lang('OpenQuestionsAttempted').' :</p>
3320
                    <p>'.get_lang('AttemptDetails').' : </p>
3321
                    <table class="data_table">
3322
                        <tr>
3323
                            <td><h3>'.get_lang('CourseName').'</h3></td>
3324
                            <td><h3>#course#</h3></td>
3325
                        </tr>
3326
                        <tr>
3327
                            <td>'.get_lang('TestAttempted').'</span></td>
3328
                            <td>#exercise#</td>
3329
                        </tr>
3330
                        <tr>
3331
                            <td>'.get_lang('StudentName').'</td>
3332
                            <td>#firstName# #lastName#</td>
3333
                        </tr>
3334
                        <tr>
3335
                            <td>'.get_lang('StudentEmail').'</td>
3336
                            <td>#mail#</td>
3337
                        </tr>
3338
                    </table>';
3339
        $open_question_list = null;
3340
        foreach ($question_list_answers as $item) {
3341
            $question    = $item['question'];
3342
            $answer      = $item['answer'];
3343
            $answer_type = $item['answer_type'];
3344

    
3345
            if (!empty($question) && !empty($answer) && $answer_type == FREE_ANSWER ) {
3346
                $open_question_list.='<tr>
3347
                            <td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;'.get_lang('Question').'</td>
3348
                            <td width="473" valign="top" bgcolor="#F3F3F3">'.$question.'</td>
3349
                        </tr>
3350
                        <tr>
3351
                            <td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;'.get_lang('Answer').'</td>
3352
                            <td valign="top" bgcolor="#F3F3F3">'.$answer.'</td>
3353
                        </tr>';
3354
            }
3355
        }
3356

    
3357
        if (!empty($open_question_list)) {
3358
            $msg .=  '<p><br />'.get_lang('OpenQuestionsAttemptedAre').' :</p>
3359
                    <table width="730" height="136" border="0" cellpadding="3" cellspacing="3">';
3360
            $msg .= $open_question_list;
3361
            $msg.='</table><br />';
3362

    
3363

    
3364
            $msg1   = str_replace("#exercise#",    $this->exercise, $msg);
3365
            $msg    = str_replace("#firstName#",   $user_info['firstname'],$msg1);
3366
            $msg1   = str_replace("#lastName#",    $user_info['lastname'],$msg);
3367
            $msg    = str_replace("#mail#",        $user_info['email'],$msg1);
3368
            $msg    = str_replace("#course#",      $course_info['name'],$msg1);
3369

    
3370
            if ($origin != 'learnpath') {
3371
                $msg.= get_lang('ClickToCommentAndGiveFeedback').', <br />
3372
                            <a href="#url#">#url#</a>';
3373
            }
3374
            $msg1 = str_replace("#url#", $url_email, $msg);
3375
            $mail_content = $msg1;
3376
            $subject = get_lang('OpenQuestionsAttempted');
3377

    
3378
            $teachers = array();
3379
            if (api_get_session_id()) {
3380
                $teachers = CourseManager::get_coach_list_from_course_code($coursecode, api_get_session_id());
3381
            } else {
3382
                $teachers = CourseManager::get_teacher_list_from_course_code($coursecode);
3383
            }
3384

    
3385
            if (!empty($teachers)) {
3386
                foreach ($teachers as $user_id => $teacher_data) {
3387
                    MessageManager::send_message_simple($user_id, $subject, $mail_content);
3388
                }
3389
            }
3390
        }
3391
    }
3392

    
3393
    function send_notification_for_oral_questions($question_list_answers, $origin, $exe_id) {
3394
        if (api_get_course_setting('email_alert_manager_on_new_quiz') != 1 ) {
3395
            return null;
3396
        }
3397
        // Email configuration settings
3398
        $coursecode     = api_get_course_id();
3399
        $course_info    = api_get_course_info(api_get_course_id());
3400

    
3401
        $url_email = api_get_path(WEB_CODE_PATH).'exercice/exercise_show.php?'.api_get_cidreq().'&id_session='.api_get_session_id().'&id='.$exe_id.'&action=qualify';
3402
        $user_info = UserManager::get_user_info_by_id(api_get_user_id());
3403

    
3404

    
3405
        $oral_question_list = null;
3406
        foreach ($question_list_answers as $item) {
3407
            $question    = $item['question'];
3408
            $answer      = $item['answer'];
3409
            $answer_type = $item['answer_type'];
3410

    
3411
            if (!empty($question) && !empty($answer) && $answer_type == ORAL_EXPRESSION) {
3412
                $oral_question_list.='<br /><table width="730" height="136" border="0" cellpadding="3" cellspacing="3"><tr>
3413
                            <td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;'.get_lang('Question').'</td>
3414
                            <td width="473" valign="top" bgcolor="#F3F3F3">'.$question.'</td>
3415
                        </tr>
3416
                        <tr>
3417
                            <td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;'.get_lang('Answer').'</td>
3418
                            <td valign="top" bgcolor="#F3F3F3">'.$answer.'</td>
3419
                        </tr></table>';
3420
            }
3421
        }
3422

    
3423
        if (!empty($oral_question_list)) {
3424
            $msg = '<p>'.get_lang('OralQuestionsAttempted').' :</p>
3425
                    <p>'.get_lang('AttemptDetails').' : </p>
3426
                    <table class="data_table">
3427
                        <tr>
3428
                            <td><h3>'.get_lang('CourseName').'</h3></td>
3429
                            <td><h3>#course#</h3></td>
3430
                        </tr>
3431
                        <tr>
3432
                            <td>'.get_lang('TestAttempted').'</span></td>
3433
                            <td>#exercise#</td>
3434
                        </tr>
3435
                        <tr>
3436
                            <td>'.get_lang('StudentName').'</td>
3437
                            <td>#firstName# #lastName#</td>
3438
                        </tr>
3439
                        <tr>
3440
                            <td>'.get_lang('StudentEmail').'</td>
3441
                            <td>#mail#</td>
3442
                        </tr>
3443
                    </table>';
3444
            $msg .=  '<br />'.sprintf(get_lang('OralQuestionsAttemptedAreX'),$oral_question_list).'<br />';
3445
            $msg1   = str_replace("#exercise#",    $this->exercise, $msg);
3446
            $msg    = str_replace("#firstName#",   $user_info['firstname'],$msg1);
3447
            $msg1   = str_replace("#lastName#",    $user_info['lastname'],$msg);
3448
            $msg    = str_replace("#mail#",        $user_info['email'],$msg1);
3449
            $msg    = str_replace("#course#",      $course_info['name'],$msg1);
3450

    
3451
            if ($origin != 'learnpath') {
3452
                $msg.= get_lang('ClickToCommentAndGiveFeedback').', <br />
3453
                            <a href="#url#">#url#</a>';
3454
            }
3455
            $msg1 = str_replace("#url#", $url_email, $msg);
3456
            $mail_content = $msg1;
3457
            $subject = get_lang('OralQuestionsAttempted');
3458

    
3459
            $teachers = array();
3460
            if (api_get_session_id()) {
3461
                $teachers = CourseManager::get_coach_list_from_course_code($coursecode, api_get_session_id());
3462
            } else {
3463
                $teachers = CourseManager::get_teacher_list_from_course_code($coursecode);
3464
            }
3465

    
3466
            if (!empty($teachers)) {
3467
                foreach ($teachers as $user_id => $teacher_data) {
3468
                    MessageManager::send_message_simple($user_id, $subject, $mail_content);
3469
                }
3470
            }
3471
        }
3472
    }
3473

    
3474
    function show_exercise_result_header($user_data, $start_date = null, $duration = null) {
3475
        $array = array();
3476

    
3477
        if (!empty($user_data)) {
3478
            $array[] = array('title' => get_lang("User"), 'content' => $user_data);
3479
        }
3480
        // Description can be very long and is generally meant to explain
3481
        //   rules *before* the exam. Leaving here to make display easier if
3482
        //   necessary
3483
        /*
3484
        if (!empty($this->description)) {
3485
            $array[] = array('title' => get_lang("Description"), 'content' => $this->description);
3486
        }
3487
        */
3488
        if (!empty($start_date)) {
3489
            $array[] = array('title' => get_lang("StartDate"), 'content' => $start_date);
3490
        }
3491

    
3492
        if (!empty($duration)) {
3493
            $array[] = array('title' => get_lang("Duration"), 'content' => $duration);
3494
        }
3495

    
3496
        $html  = Display::page_header(Display::return_icon('quiz_big.png', get_lang('Result')).' '.$this->exercise.' : '.get_lang('Result'));
3497
        $html .= Display::description($array);
3498
        return $html;
3499
    }
3500

    
3501
    /**
3502
     * Create a quiz from quiz data
3503
     * @param string  Title
3504
     * @param int     Time before it expires (in minutes)
3505
     * @param int     Type of exercise
3506
     * @param int     Whether it's randomly picked questions (1) or not (0)
3507
     * @param int     Whether the exercise is visible to the user (1) or not (0)
3508
     * @param int     Whether the results are show to the user (0) or not (1)
3509
     * @param int     Maximum number of attempts (0 if no limit)
3510
     * @param int     Feedback type
3511
     * @todo this was function was added due the import exercise via CSV
3512
     * @return    int New exercise ID
3513
     */
3514
    function create_quiz ($title, $expired_time = 0, $type = 2, $random = 0, $active = 1, $results_disabled = 0, $max_attempt = 0, $feedback = 3) {
3515
        $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
3516
        $expired_time = filter_var($expired_time,FILTER_SANITIZE_NUMBER_INT);
3517
        $type = filter_var($type,FILTER_SANITIZE_NUMBER_INT);
3518
        $random = filter_var($random,FILTER_SANITIZE_NUMBER_INT);
3519
        $active = filter_var($active,FILTER_SANITIZE_NUMBER_INT);
3520
        $results_disabled = filter_var($results_disabled,FILTER_SANITIZE_NUMBER_INT);
3521
        $max_attempt = filter_var($max_attempt,FILTER_SANITIZE_NUMBER_INT);
3522
        $feedback = filter_var($feedback,FILTER_SANITIZE_NUMBER_INT);
3523
        $sid = api_get_session_id();
3524
        $course_id = api_get_course_int_id();
3525
        // Save a new quiz
3526
        $sql = "INSERT INTO $tbl_quiz (c_id, title,type,random,active,results_disabled, max_attempt,start_time,end_time,feedback_type,expired_time, session_id) ".
3527
            " VALUES('$course_id', '".Database::escape_string($title)."',$type,$random,$active, $results_disabled,$max_attempt,'','',$feedback,$expired_time,$sid)";
3528
        $rs = Database::query($sql);
3529
        $quiz_id = Database::get_last_insert_id();
3530
        return $quiz_id;
3531
    }
3532

    
3533
    function process_geometry() {
3534

    
3535
    }
3536

    
3537
    /**
3538
     * Returns the exercise result
3539
     * @param 	int		attempt id
3540
     * @return 	float 	exercise result
3541
     */
3542

    
3543
    public function get_exercise_result($exe_id) {
3544
        $result = array();
3545
        $track_exercise_info = get_exercise_track_exercise_info($exe_id);
3546
        if (!empty($track_exercise_info)) {
3547
            $objExercise = new Exercise();
3548
            $objExercise->read($track_exercise_info['exe_exo_id']);
3549
            if (!empty($track_exercise_info['data_tracking'])) {
3550
                $question_list = explode(',', $track_exercise_info['data_tracking']);
3551
            }
3552
            foreach ($question_list as $questionId) {
3553
                $question_result = $objExercise->manage_answer($exe_id, $questionId, '','exercise_show', array(), false, true, false, $objExercise->selectPropagateNeg());
3554
                $questionScore   = $question_result['score'];
3555
                $totalScore      += $question_result['score'];
3556
            }
3557

    
3558
            if ($objExercise->selectPropagateNeg() == 0 && $totalScore < 0) {
3559
                $totalScore = 0;
3560
            }
3561
            $result = array(
3562
                'score' => $totalScore,
3563
                'weight' => $track_exercise_info['exe_weighting']
3564
            );
3565
        }
3566
        return $result;
3567
    }
3568

    
3569
    /**
3570
     *  Checks if the exercise is visible due a lot of conditions - visibility, time limits, student attempts
3571
     * @return bool true if is active
3572
     */
3573
    public function is_visible($lp_id = 0, $lp_item_id = 0 , $lp_item_view_id = 0, $filter_by_admin = true) {
3574
        //1. By default the exercise is visible
3575
        $is_visible = true;
3576
        $message = null;
3577

    
3578
        //1.1 Admins and teachers can access to the exercise
3579
        if ($filter_by_admin) {
3580
            if (api_is_platform_admin() || api_is_course_admin()) {
3581
                return array('value' => true, 'message' => '');
3582
            }
3583
        }
3584

    
3585
        //Checking visibility in the item_property table
3586
        $visibility = api_get_item_visibility(api_get_course_info(), TOOL_QUIZ, $this->id, api_get_session_id());
3587

    
3588
        if ($visibility == 0) {
3589
            $this->active = 0;
3590
        }
3591

    
3592
        //2. If the exercise is not active
3593
        if (empty($lp_id)) {
3594
            //2.1 LP is OFF
3595
            if ($this->active == 0) {
3596
                return array('value' => false, 'message' => Display::return_message(get_lang('ExerciseNotFound'), 'warning', false));
3597
            }
3598
        } else {
3599
            //2.1 LP is loaded
3600
            if ($this->active == 0 AND !learnpath::is_lp_visible_for_student($lp_id, api_get_user_id())) {
3601
                return array('value' => false, 'message' => Display::return_message(get_lang('ExerciseNotFound'), 'warning', false));
3602
            }
3603
        }
3604

    
3605
        //3. We check if the time limits are on
3606
        $limit_time_exists = ((!empty($this->start_time) && $this->start_time != '0000-00-00 00:00:00') || (!empty($this->end_time) && $this->end_time != '0000-00-00 00:00:00')) ? true : false;
3607

    
3608
        if ($limit_time_exists) {
3609
            $time_now = time();
3610

    
3611
            if (!empty($this->start_time) && $this->start_time != '0000-00-00 00:00:00') {
3612
                $is_visible = (($time_now - api_strtotime($this->start_time, 'UTC')) > 0) ? true : false;
3613
            }
3614

    
3615
            if ($is_visible == false) {
3616
                $message = sprintf(get_lang('ExerciseAvailableFromX'), api_convert_and_format_date($this->start_time));
3617
            }
3618

    
3619
            if ($is_visible == true) {
3620
                if ($this->end_time != '0000-00-00 00:00:00') {
3621
                    $is_visible = ((api_strtotime($this->end_time, 'UTC') > $time_now) > 0) ? true : false;
3622
                    if ($is_visible == false) {
3623
                        $message = sprintf(get_lang('ExerciseAvailableUntilX'), api_convert_and_format_date($this->end_time));
3624
                    }
3625
                }
3626
            }
3627
            if ($is_visible == false && $this->start_time != '0000-00-00 00:00:00' && $this->end_time != '0000-00-00 00:00:00') {
3628
                $message =  sprintf(get_lang('ExerciseWillBeActivatedFromXToY'), api_convert_and_format_date($this->start_time), api_convert_and_format_date($this->end_time));
3629
            }
3630
        }
3631

    
3632
        // 4. We check if the student have attempts
3633
        if ($is_visible) {
3634
            if ($this->selectAttempts() > 0) {
3635
                $attempt_count = get_attempt_count_not_finished(api_get_user_id(), $this->id, $lp_id, $lp_item_id, $lp_item_view_id);
3636

    
3637
                if ($attempt_count >= $this->selectAttempts()) {
3638
                    $message = sprintf(get_lang('ReachedMaxAttempts'), $this->name, $this->selectAttempts());
3639
                    $is_visible = false;
3640
                }
3641
            }
3642
        }
3643
        if (!empty($message)){
3644
            $message = Display :: return_message($message, 'warning', false);
3645
        }
3646
        return array('value' => $is_visible, 'message' => $message);
3647
    }
3648

    
3649
    function added_in_lp() {
3650
        $TBL_LP_ITEM	= Database::get_course_table(TABLE_LP_ITEM);
3651
        $sql = "SELECT max_score FROM $TBL_LP_ITEM WHERE c_id = ".$this->course_id." AND item_type = '".TOOL_QUIZ."' AND path = '".$this->id."'";
3652
        $result = Database::query($sql);
3653
        if (Database::num_rows($result) > 0) {
3654
            return true;
3655
        }
3656
        return false;
3657
    }
3658

    
3659
    function get_media_list() {
3660
        $media_questions = array();
3661
        $question_list = $this->get_validated_question_list();
3662
        if (!empty($question_list)) {
3663
            foreach ($question_list as $questionId) {
3664
                $objQuestionTmp = Question::read($questionId);
3665
                if (isset($objQuestionTmp->parent_id) && $objQuestionTmp->parent_id != 0) {
3666
                    $media_questions[$objQuestionTmp->parent_id][] = $objQuestionTmp->id;
3667
                } else {
3668
                    //Always the last item
3669
                    $media_questions[999][] = $objQuestionTmp->id;
3670
                }
3671
            }
3672
        }
3673
        return $media_questions;
3674
    }
3675

    
3676
    function media_is_activated($media_list) {
3677
        $active = false;
3678
        if (isset($media_list) && !empty($media_list)) {
3679
            $media_count = count($media_list);
3680
            if ($media_count > 1) {
3681
                return true;
3682
            } elseif ($media_count == 1) {
3683
                if (isset($media_list[999])) {
3684
                    return false;
3685
                } else {
3686
                    return true;
3687
                }
3688
            }
3689
        }
3690
        return $active;
3691
    }
3692

    
3693
    function get_validated_question_list() {
3694
        $tabres = array();
3695
        $isRandomByCategory = $this->isRandomByCat();
3696
        if ($isRandomByCategory == 0) {
3697
            if ($this->isRandom()) {
3698
                $tabres = $this->selectRandomList();
3699
            } else {
3700
                $tabres = $this->selectQuestionList();
3701
            }
3702
        } else {
3703
            if ($this->isRandom()) {
3704
                // USE question categories
3705
                // get questions by category for this exercice
3706
                // we have to choice $objExercise->random question in each array values of $tabCategoryQuestions
3707
                // key of $tabCategoryQuestions are the categopy id (0 for not in a category)
3708
                // value is the array of question id of this category
3709
                $questionList = array();
3710
                $tabCategoryQuestions = Testcategory::getQuestionsByCat($this->id);
3711
                $isRandomByCategory = $this->selectRandomByCat();
3712
                // on tri les categories en fonction du terme entre [] en tête de la description de la catégorie
3713
                /*
3714
                 * ex de catégories :
3715
                 * [biologie] Maîtriser les mécanismes de base de la génétique
3716
                 * [biologie] Relier les moyens de défenses et les agents infectieux
3717
                 * [biologie] Savoir où est produite l'énergie dans les cellules et sous quelle forme
3718
                 * [chimie] Classer les molécules suivant leur pouvoir oxydant ou réducteur
3719
                 * [chimie] Connaître la définition de la théorie acide/base selon Brönsted
3720
                 * [chimie] Connaître les charges des particules
3721
                 * On veut dans l'ordre des groupes définis par le terme entre crochet au début du titre de la catégorie
3722
                */
3723
                // If test option is Grouped By Categories
3724
                if ($isRandomByCategory == 2) {
3725
                    $tabCategoryQuestions = Testcategory::sortTabByBracketLabel($tabCategoryQuestions);
3726
                }
3727
                while (list($cat_id, $tabquestion) = each($tabCategoryQuestions)) {
3728
                    $number_of_random_question = $this->random;
3729
                    if ($this->random == -1) {
3730
                        $number_of_random_question = count($this->questionList);
3731
                    }
3732
                    $questionList = array_merge($questionList, Testcategory::getNElementsFromArray($tabquestion, $number_of_random_question));
3733
                }
3734
                // shuffle the question list if test is not grouped by categories
3735
                if ($isRandomByCategory == 1) {
3736
                    shuffle($questionList); // or not
3737
                }
3738
                $tabres = $questionList;
3739
            } else {
3740
                // Problem, random by category has been selected and we have no $this->isRandom nnumber of question selected
3741
                // Should not happened
3742
            }
3743
        }
3744
        return $tabres;
3745
    }
3746

    
3747
    function get_question_list($expand_media_questions = false) {
3748
        $question_list = $this->get_validated_question_list();
3749
        $question_list = $this->transform_question_list_with_medias($question_list, $expand_media_questions);
3750
        return $question_list;
3751
    }
3752

    
3753
    function transform_question_list_with_medias($question_list, $expand_media_questions = false) {
3754
        $new_question_list = array();
3755
        if (!empty($question_list)) {
3756
            $media_questions = $this->get_media_list();
3757
            $media_active = $this->media_is_activated($media_questions);
3758

    
3759
            if ($media_active) {
3760
                $counter = 1;
3761
                foreach ($question_list as $question_id) {
3762
                    $add_question = true;
3763
                    foreach ($media_questions as $media_id => $question_list_in_media) {
3764
                        if ($media_id != 999 && in_array($question_id, $question_list_in_media)) {
3765
                            $add_question = false;
3766
                            if (!in_array($media_id, $new_question_list)) {
3767
                                $new_question_list[$counter] = $media_id;
3768
                                $counter++;
3769
                            }
3770
                            break;
3771
                        }
3772
                    }
3773
                    if ($add_question) {
3774
                        $new_question_list[$counter] = $question_id;
3775
                        $counter++;
3776
                    }
3777
                }
3778
                if ($expand_media_questions) {
3779
                    $media_key_list = array_keys($media_questions);
3780
                    foreach ($new_question_list as &$question_id) {
3781
                        if (in_array($question_id, $media_key_list)) {
3782
                            $question_id = $media_questions[$question_id];
3783
                        }
3784
                    }
3785
                    $new_question_list = array_flatten($new_question_list);
3786
                }
3787
            } else {
3788
                $new_question_list = $question_list;
3789
            }
3790
        }
3791
        return $new_question_list;
3792
    }
3793

    
3794
    public function get_stat_track_exercise_info_by_exe_id($exe_id) {
3795
        $track_exercises = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
3796
        $exe_id = intval($exe_id);
3797
        $sql_track = "SELECT * FROM $track_exercises WHERE exe_id = $exe_id ";
3798
        $result = Database::query($sql_track);
3799
        $new_array = array();
3800
        if (Database::num_rows($result) > 0 ) {
3801
            $new_array = Database::fetch_array($result, 'ASSOC');
3802

    
3803
            $new_array['duration'] = null;
3804

    
3805
            $start_date = api_get_utc_datetime($new_array['start_date'], true);
3806
            $end_date = api_get_utc_datetime($new_array['exe_date'], true);
3807

    
3808
            if (!empty($start_date) && !empty($end_date)) {
3809
                $start_date = api_strtotime($start_date, 'UTC');
3810
                $end_date = api_strtotime($end_date, 'UTC');
3811
                if ($start_date && $end_date) {
3812
                    $mytime = $end_date- $start_date;
3813
                    $new_learnpath_item = new learnpathItem(null);
3814
                    $time_attemp = $new_learnpath_item->get_scorm_time('js', $mytime);
3815
                    $h = get_lang('h');
3816
                    $time_attemp = str_replace('NaN', '00' . $h . '00\'00"', $time_attemp);
3817
                    $new_array['duration'] = $time_attemp;
3818
                }
3819
            }
3820
        }
3821
        return $new_array;
3822
    }
3823

    
3824
    public function edit_question_to_remind($exe_id, $question_id, $action = 'add') {
3825
        $exercise_info = self::get_stat_track_exercise_info_by_exe_id($exe_id);
3826
        $question_id = intval($question_id);
3827
        $exe_id = intval($exe_id);
3828
        $track_exercises = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
3829
        if ($exercise_info) {
3830

    
3831
            if (empty($exercise_info['questions_to_check'])) {
3832
                if ($action == 'add') {
3833
                    $sql = "UPDATE $track_exercises SET questions_to_check = '$question_id' WHERE exe_id = $exe_id ";
3834
                    $result = Database::query($sql);
3835
                }
3836
            } else {
3837
                $remind_list = explode(',',$exercise_info['questions_to_check']);
3838

    
3839
                $remind_list_string = '';
3840
                if ($action == 'add') {
3841
                    if (!in_array($question_id, $remind_list)) {
3842
                        $remind_list[] = $question_id;
3843
                        if (!empty($remind_list)) {
3844
                            sort($remind_list);
3845
                            array_filter($remind_list);
3846
                        }
3847
                        $remind_list_string = implode(',', $remind_list);
3848
                    }
3849
                } elseif ($action == 'delete')  {
3850
                    if (!empty($remind_list)) {
3851
                        if (in_array($question_id, $remind_list)) {
3852
                            $remind_list = array_flip($remind_list);
3853
                            unset($remind_list[$question_id]);
3854
                            $remind_list = array_flip($remind_list);
3855

    
3856
                            if (!empty($remind_list)) {
3857
                                sort($remind_list);
3858
                                array_filter($remind_list);
3859
                                $remind_list_string = implode(',', $remind_list);
3860
                            }
3861
                        }
3862
                    }
3863
                }
3864
                $remind_list_string = Database::escape_string($remind_list_string);
3865
                $sql = "UPDATE $track_exercises SET questions_to_check = '$remind_list_string' WHERE exe_id = $exe_id ";
3866
                $result = Database::query($sql);
3867
            }
3868
        }
3869
    }
3870

    
3871
    public function fill_in_blank_answer_to_array($answer) {
3872
        api_preg_match_all('/\[[^]]+\]/', $answer, $teacher_answer_list);
3873
        $teacher_answer_list = $teacher_answer_list[0];
3874
        return $teacher_answer_list;
3875
    }
3876

    
3877
    public function fill_in_blank_answer_to_string($answer) {
3878
        $teacher_answer_list = $this->fill_in_blank_answer_to_array($answer);
3879
        $result = '';
3880
        if (!empty($teacher_answer_list)) {
3881
            $i = 0;
3882
            foreach ($teacher_answer_list as $teacher_item) {
3883
                $value = null;
3884
                //Cleaning student answer list
3885
                $value = strip_tags($teacher_item);
3886
                $value = api_substr($value,1, api_strlen($value)-2);
3887
                $value = explode('/', $value);
3888
                if (!empty($value[0])) {
3889
                    $value = trim($value[0]);
3890
                    $value = str_replace('&nbsp;', '',  $value);
3891
                    $result .= $value;
3892
                }
3893
            }
3894
        }
3895
        return $result;
3896
    }
3897

    
3898
    function return_time_left_div() {
3899
        $html  = '<div id="clock_warning" style="display:none">'.Display::return_message(get_lang('ReachedTimeLimit'), 'warning').' '.sprintf(get_lang('YouWillBeRedirectedInXSeconds'), '<span id="counter_to_redirect" class="red_alert"></span>').'</div>';
3900
        $html .= '<div id="exercise_clock_warning" class="well count_down"></div>';
3901
        return $html;
3902
    }
3903

    
3904
    function get_count_question_list() {
3905
        //Real question count
3906
        $question_count = 0;
3907
        $question_list = $this->get_question_list();
3908
        if (!empty($question_list)) {
3909
            $question_count = count($question_list);
3910
        }
3911
        return $question_count;
3912
    }
3913

    
3914
    function get_exercise_list_ordered() {
3915
        $table_exercise_order = Database::get_course_table(TABLE_QUIZ_ORDER);
3916
        $course_id = api_get_course_int_id();
3917
        $session_id = api_get_session_id();
3918
        $sql = "SELECT exercise_id, exercise_order FROM $table_exercise_order WHERE c_id = $course_id AND session_id = $session_id ORDER BY exercise_order";
3919
        $result = Database::query($sql);
3920
        $list = array();
3921
        if (Database::num_rows($result)) {
3922
            while($row = Database::fetch_array($result, 'ASSOC')) {
3923
                $list[$row['exercise_order']] = $row['exercise_id'];
3924
            }
3925
        }
3926
        return $list;
3927
    }
3928
	
3929
	private function pass_fill_in_blanks_rules($original,$user_answer) {
3930
		$result = false;
3931
		$original = preg_replace("/\.+|,+|;+/","",preg_replace('/\s+/', ' ',strtolower(strip_tags($original))));
3932
		$user_answer = preg_replace("/\.+|,+|;+/","",preg_replace('/\s+/', ' ',strtolower(strip_tags($user_answer))));
3933
		
3934
		$result = ($original==$user_answer)?true:false;
3935
		return $result;	
3936
	}
3937
}
(1-1/3)