vpl.class.php 68.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php
// This file is part of VPL for Moodle - http://vpl.dis.ulpgc.es/
//
// VPL for Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// VPL for Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with VPL for Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * VPL class definition
 *
 * @package mod_vpl
 * @copyright 2013 onwards Juan Carlos Rodríguez-del-Pino
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @author Juan Carlos Rodríguez-del-Pino <jcrodriguez@dis.ulpgc.es>
 */

/**
 * Module instance files
 * path= vpl_data/vpl_instance#
 * General info
 * path/required_files.lst
 * path/required_files/
 * path/execution_files.lst
 * path/execution_files/
 * path/execution_files/vpl_run.sh
 * path/execution_files/vpl_debug.sh
 * path/execution_files/vpl_evaluate.sh
 *  * Submission info
38
39
 * path/usersdata/userid#/submissionid#/submittedfiles/
 * path/usersdata/userid#/submissionid#/submittedfiles.lst
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
 * path/usersdata/userid#/submissionid#/grade_comments.txt
 * path/usersdata/userid#/submissionid#/teachertest.txt
 * path/usersdata/userid#/submissionid#/studenttest.txt
 */
defined('MOODLE_INTERNAL') || die();

require_once(dirname(__FILE__).'/filegroup.class.php');
require_once(dirname(__FILE__).'/lib.php');

class file_group_execution extends file_group_process {
    /**
     * Name of fixed file names
     *
     * @var string[]
     */
    protected static $basefiles = array (
            'vpl_run.sh',
            'vpl_debug.sh',
            'vpl_evaluate.sh',
            'vpl_evaluate.cases'
    );

    /**
     * Number of $basefiles elements
     *
     * @var int
     */
    protected static $numbasefiles;

    /**
     * Constructor
     *
     * @param string $filelistname
     * @param string $dir
     */
75
    public function __construct($dir) {
76
        self::$numbasefiles = count( self::$basefiles );
77
        parent::__construct( $dir, 1000, self::$numbasefiles );
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
    }

    /**
     * Get list of files
     *
     * @return string[]
     */
    public function getfilelist() {
        return array_values( array_unique( array_merge( self::$basefiles, parent::getfilelist() ) ) );
    }

    /**
     * Get the file comment by number
     *
     * @param int $num
     * @return string
     */
    public function getfilecomment($num) {
        if ($num < self::$numbasefiles) {
            return get_string( self::$basefiles [$num], VPL );
        } else {
            return get_string( 'file' ) . ' ' . ($num + 1 - self::$numbasefiles);
        }
    }

    /**
     * Get list of files to keep when running
     *
     * @return string[]
     */
    public function getfilekeeplist() {
        return file_group_process::read_list( $this->filelistname . '.keep' );
    }

    /**
     * Set the file list to keep when running
     *
     * @param string[] $filelist
     */
    public function setfilekeeplist($filelist) {
        file_group_process::write_list( $this->filelistname . '.keep', $filelist );
    }
}
121

122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
class mod_vpl {
    /**
     * Internal var for course_module
     *
     * @var object $cm
     */
    protected $cm;

    /**
     * Internal var for course
     *
     * @var object $course
     */
    protected $course;

    /**
     * Internal var for vpl
     *
     * @var object $instance
     */
    protected $instance;

    /**
145
     * Internal var array of object to  file group manager
146
     *
147
     * @var array of object of file group manager
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
     */
    protected $requiredfgm;

    /**
     * Internal var object to execution file group manager
     *
     * @var object of file group manager
     */
    protected $fgm;

    /**
     * Constructor
     *
     * @param $id int
     *            optional course_module id
     * @param $a int
     *            optional module instance id
     */
    public function __construct($id, $a = null) {
        global $DB;
        if ($id) {
            if (! $this->cm = get_coursemodule_from_id( VPL, $id )) {
                print_error( 'invalidcoursemodule');
            }
            if (! $this->course = $DB->get_record( "course", array (
                    "id" => $this->cm->course
            ) )) {
                print_error( 'unknowncourseidnumber', '', $this->cm->course );
            }
            if (! $this->instance = $DB->get_record( VPL, array (
                    "id" => $this->cm->instance
            ) )) {
                print_error( 'module instance id unknow' );
            }
            $this->instance->cmidnumber = $this->cm->id;
        } else {
            if (! $this->instance = $DB->get_record( VPL, array (
                    "id" => $a
            ) )) {
                print_error( 'module instance id unknow' );
            }
            if (! $this->course = $DB->get_record( "course",
                    array (
                            "id" => $this->instance->course
                    ) )) {
                print_error( 'unknowncourseidnumber', '', $this->instance->course );
            }
            if (! $this->cm = get_coursemodule_from_instance( VPL, $this->instance->id, $this->course->id )) {
                vpl_notice( get_string( 'invalidcoursemodule', 'error' ) . ' VPL id=' . $a );
                // Don't stop on error. This let delete a corrupted course.
            } else {
                $this->instance->cmidnumber = $this->cm->id;
            }
        }
202
        $this->fgm = array();
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
    }

    /**
     *
     * @return Object of module DB instance
     */
    public function get_instance() {
        return $this->instance;
    }

    /**
     *
     * @return Object of course DB instance
     *
     */
    public function get_course() {
        return $this->course;
    }

    /**
     *
     * @return Object of course_module DB instance
     *
     */
    public function get_course_module() {
        return $this->cm;
    }

    /**
     * Delete a vpl instance
     *
     * @return bool true if all OK
     */
    public function delete_all() {
237
        return vpl_delete_instance($this->instance->id);
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
    }

    /**
     * Update a VPL instance including timemodified field
     *
     * @return bool true if all OK
     */
    public function update() {
        global $DB;
        $this->instance->timemodified = time();
        return $DB->update_record( VPL, $this->instance );
    }

    /**
     * Get data directory path
     * @return string data directory path
     */
    public function get_data_directory() {
        global $CFG;
        return $CFG->dataroot . '/vpl_data/' . $this->instance->id;
    }

    /**
     * Get config data directory path
     * @return string config data directory path
     */
    public function get_users_data_directory() {
        return $this->get_data_directory() . '/usersdata';
    }

    /**
     *
270
271
     * @param $type string
     * @return directory to stored initial files
272
     */
273
274
275
    public function get_files_directory($type) {
        return $this->get_data_directory() . '/'.$type.'_files/';
    }
276
277
278
279
280

    /**
     * Get array of files required file names
     * @return array of strings
     */
281
    public function get_files($type) {
282
        return $this->get_fgm($type)->getfilelist();
283
    }
284
285
286
287
288
289

    /**
     *
     * @param $files array
     *            of required files
     */
290
    public function set_files($type, $files) {
291
        $this->get_fgm($type)->setfilelist($files);
292
    }
293
294
295

    /**
     *
296
     * @return file_group_process file group manager for specified files
297
     */
298
299
    public function get_fgm($type) {
        if (! isset($this->fgm[$type])) {
300
            if ($type == 'execution') {
301
                $this->fgm[$type] = new file_group_execution( $this->get_files_directory($type) );
302
            } else {
303
                $this->fgm[$type] = new file_group_process( $this->get_files_directory($type)
304
305
306
307
308
                                                       , $this->instance->maxfiles );
            }
        }
        return $this->fgm[$type];
    }
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323

    /**
     * get instance name with groupping name if available
     *
     * @return string with name+(grouping name)
     */
    public function get_printable_name() {
        global $CFG;
        $ret = $this->instance->name;
        if (! empty( $CFG->enablegroupings ) && ($this->cm->groupingid > 0)) {
            $grouping = groups_get_grouping( $this->cm->groupingid );
            if ($grouping !== false) {
                $ret .= ' (' . $grouping->name . ')';
            }
        }
324
        return format_string($ret);
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
    }

    /**
     * Get fulldescription
     *
     * @return string fulldescription
     *
     */
    public function get_fulldescription() {
        $instance = $this->get_instance();
        if ($instance->intro) {
            return format_module_intro( VPL, $this->get_instance(), $this->get_course_module()->id );
        } else {
            return '';
        }
    }

    /**
     * Get fulldescription adding basedon descriptions
     *
     * @return string fulldescription
     *
     */
    public function get_fulldescription_with_basedon() {
        $ret = '';
        if ($this->instance->basedon) { // Show recursive varaitions.
            $basevpl = new mod_vpl( false, $this->instance->basedon );
            $ret .= $basevpl->get_fulldescription_with_basedon();
        }
        return $ret . $this->get_fulldescription();
    }
    /**
     * Return maximum file size allowed
     *
     * @return int
     *
     */
    public function get_maxfilesize() {
        $plugincfg = get_config('mod_vpl');
        $max = vpl_get_max_post_size();
        if ($plugincfg->maxfilesize > 0 && $plugincfg->maxfilesize < $max) {
            $max = $plugincfg->maxfilesize;
        }
        if ($this->instance->maxfilesize > 0 && $this->instance->maxfilesize < $max) {
            $max = $this->instance->maxfilesize;
        }
        return $max;
    }

    /**
     * Get grading information help
     *
     * @return string grade comments summary in html format
     */
    public function get_grading_help() {
        $list = array ();
        $submissions = $this->all_last_user_submission();
        foreach ($submissions as $submission) {
            $sub = new mod_vpl_submission( $this, $submission );
            $sub->filter_feedback( $list );
        }
        // TODO show evaluation criteria with show hidde button.
        $all = array ();
        foreach ($list as $text => $info) {
            $astext = s( addslashes_js( $text ) );
            $html = '';
            $html .= s( $text );
392
            foreach ($info->grades as $grade => $dummy) {
393
394
395
396
397
398
399
400
                if ($grade >= 0) { // No grade.
                    $jscript = 'VPL.addComment(\'' . $astext . '\')';
                } else {
                    $jscript = 'VPL.addComment(\'' . $astext . ' (' . $grade . ')\')';
                }
                $link = '<a href="javascript:void(0)" onclick="' . $jscript . '">' . $grade . '</a>';
                $html .= ' (' . $link . ')';
            }
401
            $html .= '<br>';
402
403
404
405
406
407
408
409
410
            if (isset( $all [$info->count] )) {
                $all [$info->count] .= '(' . $info->count . ') ' . $html;
            } else {
                $all [$info->count] = '(' . $info->count . ') ' . $html;
            }
        }
        // Sort comments by number of occurrences.
        krsort( $all );
        $html = '';
411
        foreach ($all as $info) {
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
            $html .= $info;
        }
        // TODO show info about others review with show hidde button.
        return $html;
    }
    /**
     * Get password
     */
    protected function get_password() {
        return trim( $this->instance->password );
    }

    /**
     * Get password md5
     */
    protected function get_password_md5() {
        return md5( $this->instance->id . (sesskey()) );
    }
430

431
432
433
    /**
     * Get is use as base
     **/
434
435
    public function is_use_as_base() {
        return $this->instance->usableasbase == 1;
436
    }
437
438


439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
    /**
     * Check if pass password restriction
     */
    public function pass_password_check($passset = '') {
        $password = $this->get_password();
        if ($password > '') {
            global $SESSION;
            $passwordmd5 = $this->get_password_md5();
            $passvar = 'vpl_password_' . $this->instance->id;
            $passattempt = 'vpl_password_attempt' . $this->instance->id;
            if (isset( $SESSION->$passvar ) && $SESSION->$passvar == $passwordmd5) {
                return true;
            }
            if ($passset == '') {
                $passset = optional_param( 'password', '', PARAM_TEXT );
            }
            if ($passset > '') {
                if ($passset == $password) {
                    $SESSION->$passvar = $passwordmd5;
                    unset( $SESSION->$passattempt );
                    return true;
                }
                if (isset( $SESSION->$passattempt )) {
                    $SESSION->$passattempt ++;
                } else {
                    $SESSION->$passattempt = 1;
                }
                // Wait vpl_attempt_number seg to limit force brute crack.
                sleep( $SESSION->$passattempt );
            }
            return false;
        }
        return true;
    }

    /**
     * Check password restriction
     */
    public function password_check() {
        global $SESSION;
        if (! $this->pass_password_check()) {
            if ( constant( 'AJAX_SCRIPT' ) ) {
                throw new Exception( get_string( 'requiredpassword', VPL ) );
            }
            require_once('forms/password_form.php');
            $this->print_header();
            $mform = new mod_vpl_password_form( $_SERVER ['SCRIPT_NAME'], $this);
            $passattempt = 'vpl_password_attempt' . $this->get_instance()->id;
            if (isset( $SESSION->$passattempt)) {
                vpl_notice( get_string( 'attemptnumber', VPL, $SESSION->$passattempt),
                            'warning');
            }
            $mform->display();
            $this->print_footer();
            die();
        }
    }

    /**
     * Check network restriction and return true o false
     * @return boolean
     */
    public function pass_network_check() {
        return vpl_check_network( $this->instance->requirednet );
    }

    /**
     * Check netword restriction and show error if not passed
     * @return void
     */
    public function network_check() {
        if (! $this->pass_network_check()) {
            $str = get_string( 'opnotallowfromclient', VPL ) . ' ' . getremoteaddr();
            if ( constant( 'AJAX_SCRIPT') ) {
                throw new Exception( $str );
            }
            $this->print_header();
            vpl_notice( $str , 'warning');
            $this->print_footer();
            die();
        }
    }

    /**
     * Checks if SEB key is valid
     * @return void
     */
    protected function is_sebkey_valid() {
        global $FULLME;
        $keys = trim($this->get_instance()->sebkeys);
        if ( $keys == '') {
            return true;
        }
        if ( ! isset($_SERVER['HTTP_X_SAFEEXAMBROWSER_REQUESTHASH']) ) {
            return false;
        }
        $key = $_SERVER['HTTP_X_SAFEEXAMBROWSER_REQUESTHASH'];
        foreach (preg_split('/\s+/', $keys) as $testkey) {
            if (hash('sha256', $FULLME . $testkey) === $key) {
                return true;
            }
        }
        return false;
    }

    /**
     * Checks SEB restrictions and shows error if not passed
     * @return void
     */
    protected function seb_check() {
        $inst = $this->get_instance();
        $fail = $inst->sebrequired > 0;
        $fail = $fail && strpos($_SERVER['HTTP_USER_AGENT'], 'SEB') === false;
        $fail = $fail || ! $this->is_sebkey_valid();
        if ( $fail ) {
            $str = get_string( 'sebrequired_help', VPL );
            if ( constant( 'AJAX_SCRIPT') ) {
                throw new Exception( $str );
            }
            $this->print_header();
            vpl_notice( $str , 'warning');
            $this->print_footer();
            die();
        }
    }

    /**
     * Return true if is set to use SEB
     * @return void
     */
    protected function use_seb() {
        $inst = $this->get_instance();
        return $inst->sebrequired || $inst->sebkeys > '';
    }

    /**
     * Checks all restrictions and shows error if not passed
     * @return void
     */
    public function restrictions_check() {
        $this->network_check();
        $this->password_check();
        $this->seb_check();
    }

    /**
     * Check submission restriction
     *
     * @param $data Object
     *            with submitted data
     * @param & $error
     *            string
     * @return bool
     *
     */
    public function pass_submission_restriction(& $alldata, & $error) {
        $max = $this->get_maxfilesize();
596
        $rfn = $this->get_fgm('required');
597
598
599
600
601
602
603
604
605
        $list = $rfn->getFilelist();
        $error = '';
        if (count( $alldata ) > $this->instance->maxfiles) {
            $error .= get_string( 'maxfilesexceeded', VPL ) . "\n";
        }
        $lr = count( $list );
        $i = 0;
        foreach ($alldata as $name => $data) {
            if (strlen( $data ) > $max) {
606
                $error .= '"' . s( $name ) . '" ' . get_string( 'maxfilesizeexceeded', VPL ) . "<br>";
607
608
            }
            if (! vpl_is_valid_path_name( $name )) {
609
                $error .= '"' . s( $name ) . '" ' . get_string( 'incorrect_file_name', VPL ) . "<br>";
610
611
612
613
614
            }
            if ($i < $lr && $list [$i] != $name) {
                $a = new stdClass();
                $a->expected = $list [$i];
                $a->found = $name;
615
                $error .= s( get_string( 'unexpected_file_name', VPL, $a ) ) . "<br>";
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
            }
            $i++;
        }
        return strlen( $error ) == 0;
    }

    /**
     * Check and submission
     *
     * @param
     *            $userid
     * @param $data Object
     *            with submitted data
     * @param & $error
     *            string
     * @return false or submission id
     */
    public function add_submission($userid, & $files, $comments, & $error) {
        global $USER, $DB;
        if (! $this->pass_submission_restriction( $files, $error )) {
            return false;
        }
638
639
640
641
642
643
644
        $group = false;
        if ($this->is_group_activity()) {
            $group = $this->get_usergroup($userid);
            if ($group === false) {
                $error = get_string( 'notsaved', VPL ) . "\n" . get_string( 'inconsistentgroup', VPL );
                return false;
            }
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
        }
        $submittedby = '';
        if ($USER->id != $userid ) {
            if ($this->has_capability( VPL_MANAGE_CAPABILITY ) || ($this->has_capability(
                    VPL_GRADE_CAPABILITY ) )) {
                if (! $this->is_group_activity() ) {
                    $user = $DB->get_record( 'user', array (
                            'id' => $USER->id
                    ) );
                    $submittedby = get_string( 'submittedby', VPL, fullname( $user ) ) . "\n";
                    if (strpos($comments, $submittedby) === 0 ) {
                        $submittedby = '';
                    }
                }
            } else {
                $error = get_string( 'notsaved', VPL ) . "\n" . get_string( 'inconsistentgroup', VPL );
                return false;
            }
        }
        $saveduserid = $this->is_group_activity() ? $USER->id : $userid;
        $lastsub = false;
        $lock = new \mod_vpl\util\lock($this->get_users_data_directory() . '/' . $saveduserid);
        if (($lastsubins = $this->last_user_submission( $userid )) !== false) {
            $lastsub = new mod_vpl_submission( $this, $lastsubins );
            if ($lastsub->is_equal_to( $files, $submittedby . $comments )) {
670
                $lock->__destruct();
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
                return $lastsubins->id;
            }
        }
        ignore_user_abort( true );
        // Create submission record.
        $submissiondata = new stdClass();
        $submissiondata->vpl = $this->get_instance()->id;
        $submissiondata->userid = $saveduserid;
        $submissiondata->datesubmitted = time();
        $submissiondata->comments = $submittedby . $comments;
        if ( $lastsubins !== false ) {
            $submissiondata->nevaluations = $lastsubins->nevaluations;
        }
        if ( $group !== false ) {
            $submissiondata->groupid = $group->id;
        }
        $submissionid = $DB->insert_record( 'vpl_submissions', $submissiondata, true );
        if (! $submissionid) {
            $error = get_string( 'notsaved', VPL ) . "\ninserting vpl_submissions record";
690
            $lock->__destruct();
691
692
693
694
            return false;
        }
        // Save files.
        $submission = new mod_vpl_submission( $this, $submissionid );
695
696
697
698
699
700
701
702
        try {
            $submission->set_submitted_file( $files, $lastsub );
        } catch (file_exception $fe) {
            $DB->delete_records( VPL_SUBMISSIONS, array ('id' => $submissionid));
            $error = $fe->getMessage();
            $lock->__destruct();
            return false;
        }
703
704
705
706
707
        $submission->remove_grade();
        // If no submitted by grader and not group activity, remove near submmissions.
        if ($USER->id == $userid) {
            $this->delete_overflow_submissions( $userid );
        }
708
        $lock->__destruct();
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
        return $submissionid;
    }

    /**
     * Get user submissions, order reverse submission id
     *
     * @param $userid int the user id to retrieve submissions
     * @param $groupifga boolean if group activity get group submissions. default true
     * @return FALSE/array of objects
     */
    public function user_submissions($userid, $groupifga = true) {
        global $DB;

        if ($groupifga && $this->is_group_activity()) {
            $group = $this->get_usergroup($userid);
            if ($group) {
                $select = '(groupid = ?) AND (vpl = ?)';
                $parms = array (
                        $group->id,
                        $this->instance->id
                );
            } else {
                return array ();
            }
        } else {
            $select = '(userid = ?) AND (vpl = ?)';
            $parms = array (
                    $userid,
                    $this->instance->id
            );
        }
        return $DB->get_records_select( 'vpl_submissions', $select, $parms, 'id DESC' );
    }

    /**
     * Get the last submission of all users
     *
     * @param string $fields conma separeted
     *            to retrieve from submissions table, default s.*. userid is always retrieved
     * @return object array
     */
    public function all_last_user_submission($fields = 's.*') {
        // Get last submissions records for this vpl module.
        global $DB;
        $id = $this->get_instance()->id;
        if ($this->is_group_activity()) {
            $idfield = 'groupid';
        } else {
            $idfield = 'userid';
        }
        $query = "SELECT s.$idfield, $fields FROM {vpl_submissions} s";
        $query .= ' inner join ';
        $query .= ' (SELECT max(id) as maxid FROM {vpl_submissions} ';
        $query .= '  WHERE {vpl_submissions}.vpl=? ';
        $query .= "  GROUP BY {vpl_submissions}.$idfield) as ls";
        $query .= ' on s.id = ls.maxid';
        return $DB->get_records_sql( $query, array( $id ) );
    }

    /**
     * Get all saved submission of all users
     *
     * @param string $fields fields conma separeted
     *            to retrieve from submissions table, default s.*
     * @return object array
     */
    public function all_user_submission($fields = 's.*') {
        global $DB;
        $id = $this->get_instance()->id;
        $query = "SELECT s.id, $fields FROM {vpl_submissions} s WHERE vpl=?";
        return $DB->get_records_sql( $query, array ( $id ) );
    }
    /**
     * Get number of user submissions
     *
     * @return Array of objects with 'submissions' atribute as number of submissions saved
     */
    public function get_submissions_number() {
        global $DB;
        if ( $this->is_group_activity() ) {
            $field = 'groupid';
        } else {
            $field = 'userid';
        }
793
        $id = $this->get_instance()->id;
794
        $query = "SELECT $field, COUNT(*) as submissions FROM {vpl_submissions}";
795
        $query .= " WHERE {vpl_submissions}.vpl=$id";
796
        $query .= " GROUP BY {vpl_submissions}.$field";
797
        return $DB->get_records_sql( $query );
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
    }

    /**
     * This is for compatibility to old group scheme.
     * Update the submission groupid for VPL version <= 3.2
     *
     * Set the correct groupid when groupid = 0
     * @param int $groupid.
     *     If no $groupid => update $groupid of all groups of the activity
     * @return void
     */
    public function update_group_v32($groupid='') {
        global $DB;
        if ( ! $this->is_group_activity() ) {
            return;
        }
        // All groups.
        if ($groupid == '') {
            $cm = $this->get_course_module();
            $groups = groups_get_all_groups($this->get_course()->id, 0, $cm->groupingid);
            foreach ($groups as $cgroup) {
                $this->update_group_v32($cgroup->id);
            }
        }
        $students = $this->get_students($groupid);
        if (count($students) > 0) {
            $studentsids = array_keys($students);
            $insql = $DB->get_in_or_equal($studentsids);
            $vplid = $this->get_instance()->id;
            $select = 'userid ' . ($insql[0]) . ' and vpl = ? and groupid = 0';
            $params = $insql[1];
            $params[] = $vplid;
            $DB->set_field_select(VPL_SUBMISSIONS, 'groupid', $groupid, $select, $params);
        }
    }

    /**
     * Get last user submission
     *
     * @param int $userid
     * @return FALSE/object
     *
     */
    public function last_user_submission($userid) {
        global $DB;
        if ($this->is_group_activity()) {
            $group = $this->get_usergroup($userid);
            if ($group !== false) {
                $select = "(groupid = ?) AND (vpl = ?)";
                $params = array (
                        $group->id,
                        $this->instance->id
                );
                $res = $DB->get_records_select( 'vpl_submissions', $select, $params, 'id DESC', '*', 0, 1 );
                foreach ($res as $sub) {
                    return $sub;
                }
                $this->update_group_v32($group->id);
                $res = $DB->get_records_select( 'vpl_submissions', $select, $params, 'id DESC', '*', 0, 1 );
                foreach ($res as $sub) {
                    return $sub;
                }
            }
            return false;
        }
        $select = "(userid = ?) AND (vpl = ?)";
        $params = array (
                $userid,
                $this->instance->id
        );
        $res = $DB->get_records_select( 'vpl_submissions', $select, $params, 'id DESC', '*', 0, 1 );
        foreach ($res as $sub) {
            return $sub;
        }
        return false;
    }
    protected static $context = array ();
    /**
     * Return context object for this module instance
     *
     * @return object
     */
    public function get_context() {
        if (! isset( self::$context [$this->cm->id] )) {
            self::$context [$this->cm->id] = context_module::instance( $this->cm->id );
        }
        return self::$context [$this->cm->id];
    }

    /**
     * Requiere the current user has the capability of performing $capability in this module instance
     *
     * @param string $capability
     *            capability name
     * @param bool $alert
     *            if true show a JavaScript alert message
     * @return void
     */
    public function require_capability($capability, $alert = false) {
        if ($alert && ! ($this->has_capability( $capability ))) {
            global $OUTPUT;
            echo $OUTPUT->header();
            vpl_js_alert( get_string( 'notavailable' ) );
        }
        require_capability( $capability, $this->get_context() );
    }

    /**
     * Check if the user has the capability of performing $capability in this module instance
     *
     * @param string $capability
     *            capability name
     * @param int $userid
     *            default null => current user
     * @return bool
     */
    public function has_capability($capability, $userid = null) {
        return has_capability( $capability, $this->get_context(), $userid );
    }

    /**
     * Delete overflow submissions. If three submissions within the period central is delete
     *
     * @param
     *            $userid
     * @return void
     *
     */
    public function delete_overflow_submissions($userid) {
        global $DB;
        $plugincfg = get_config('mod_vpl');
        if (! isset( $plugincfg->discard_submission_period )) {
            return;
        }
        if ($plugincfg->discard_submission_period == 0) {
            // Keep all submissions.
            return;
        }
        if ($plugincfg->discard_submission_period > 0) {
            $select = "(userid = ?) AND (vpl = ?)";
            $params = array (
                    $userid,
                    $this->instance->id
            );
            $res = $DB->get_records_select( VPL_SUBMISSIONS, $select, $params, 'id DESC', '*', 0, 3 );
            if (count( $res ) == 3) {
                $i = 0;
                foreach ($res as $sub) {
                    switch ($i) {
                        case 0 :
                            $last = $sub;
                            break;
                        case 1 :
                            $second = $sub;
                            break;
                        case 2 :
                            $first = $sub;
                            break;
                    }
                    $i ++;
                }
                // Check time consistence.
                if (! ($last->datesubmitted > $second->datesubmitted && $second->datesubmitted > $first->datesubmitted)) {
                    return;
                }
                if (($last->datesubmitted - $first->datesubmitted) < $plugincfg->discard_submission_period) {
                    // Remove second submission.
                    $submission = new mod_vpl_submission( $this, $second );
                    $submission->delete();
                }
            }
        }
    }

    /**
     * Check if it is submission period
     *
     * @return bool
     *
     */
    public function is_submission_period() {
        $now = time();
        $ret = $this->instance->startdate <= $now;
        return $ret && ($this->instance->duedate == 0 || $this->instance->duedate >= $now);
    }

    /**
     * is visible this vpl instance
     *
     * @return bool
     */
    public function is_visible() {
        $cm = $this->get_course_module();
        $modinfo = get_fast_modinfo( $cm->course );
        $ret = true;
        $ret = $ret && $modinfo->get_cm( $cm->id )->uservisible;
        $ret = $ret && $this->has_capability( VPL_VIEW_CAPABILITY );
        // Grader and manager always view.
        $ret = $ret || $this->has_capability( VPL_GRADE_CAPABILITY );
        $ret = $ret || $this->has_capability( VPL_MANAGE_CAPABILITY );
        return $ret;
    }