Revert "MDL-38254 Assignment Module: add avaialble message to all assignment types"
[moodle.git] / mod / assignment / lib.php
1 <?PHP
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
18 /**
19  * assignment_base is the base class for assignment types
20  *
21  * This class provides all the functionality for an assignment
22  *
23  * @package   mod-assignment
24  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
25  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26  */
28 /** Include eventslib.php */
29 require_once($CFG->libdir.'/eventslib.php');
30 /** Include formslib.php */
31 require_once($CFG->libdir.'/formslib.php');
32 /** Include calendar/lib.php */
33 require_once($CFG->dirroot.'/calendar/lib.php');
35 /** ASSIGNMENT_COUNT_WORDS = 1 */
36 define('ASSIGNMENT_COUNT_WORDS', 1);
37 /** ASSIGNMENT_COUNT_LETTERS = 2 */
38 define('ASSIGNMENT_COUNT_LETTERS', 2);
40 /**
41  * Standard base class for all assignment submodules (assignment types).
42  *
43  * @package   mod-assignment
44  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
45  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
46  */
47 class assignment_base {
49     const FILTER_ALL             = 0;
50     const FILTER_SUBMITTED       = 1;
51     const FILTER_REQUIRE_GRADING = 2;
53     /** @var object */
54     var $cm;
55     /** @var object */
56     var $course;
57     /** @var stdClass */
58     var $coursecontext;
59     /** @var object */
60     var $assignment;
61     /** @var string */
62     var $strassignment;
63     /** @var string */
64     var $strassignments;
65     /** @var string */
66     var $strsubmissions;
67     /** @var string */
68     var $strlastmodified;
69     /** @var string */
70     var $pagetitle;
71     /** @var bool */
72     var $usehtmleditor;
73     /**
74      * @todo document this var
75      */
76     var $defaultformat;
77     /**
78      * @todo document this var
79      */
80     var $context;
81     /** @var string */
82     var $type;
84     /**
85      * Constructor for the base assignment class
86      *
87      * Constructor for the base assignment class.
88      * If cmid is set create the cm, course, assignment objects.
89      * If the assignment is hidden and the user is not a teacher then
90      * this prints a page header and notice.
91      *
92      * @global object
93      * @global object
94      * @param int $cmid the current course module id - not set for new assignments
95      * @param object $assignment usually null, but if we have it we pass it to save db access
96      * @param object $cm usually null, but if we have it we pass it to save db access
97      * @param object $course usually null, but if we have it we pass it to save db access
98      */
99     function assignment_base($cmid='staticonly', $assignment=NULL, $cm=NULL, $course=NULL) {
100         global $COURSE, $DB;
102         if ($cmid == 'staticonly') {
103             //use static functions only!
104             return;
105         }
107         global $CFG;
109         if ($cm) {
110             $this->cm = $cm;
111         } else if (! $this->cm = get_coursemodule_from_id('assignment', $cmid)) {
112             print_error('invalidcoursemodule');
113         }
115         $this->context = context_module::instance($this->cm->id);
117         if ($course) {
118             $this->course = $course;
119         } else if ($this->cm->course == $COURSE->id) {
120             $this->course = $COURSE;
121         } else if (! $this->course = $DB->get_record('course', array('id'=>$this->cm->course))) {
122             print_error('invalidid', 'assignment');
123         }
124         $this->coursecontext = context_course::instance($this->course->id);
125         $courseshortname = format_text($this->course->shortname, true, array('context' => $this->coursecontext));
127         if ($assignment) {
128             $this->assignment = $assignment;
129         } else if (! $this->assignment = $DB->get_record('assignment', array('id'=>$this->cm->instance))) {
130             print_error('invalidid', 'assignment');
131         }
133         $this->assignment->cmidnumber = $this->cm->idnumber; // compatibility with modedit assignment obj
134         $this->assignment->courseid   = $this->course->id; // compatibility with modedit assignment obj
136         $this->strassignment = get_string('modulename', 'assignment');
137         $this->strassignments = get_string('modulenameplural', 'assignment');
138         $this->strsubmissions = get_string('submissions', 'assignment');
139         $this->strlastmodified = get_string('lastmodified');
140         $this->pagetitle = strip_tags($courseshortname.': '.$this->strassignment.': '.format_string($this->assignment->name, true, array('context' => $this->context)));
142         // visibility handled by require_login() with $cm parameter
143         // get current group only when really needed
145     /// Set up things for a HTML editor if it's needed
146         $this->defaultformat = editors_get_preferred_format();
147     }
149     /**
150      * Display the assignment, used by view.php
151      *
152      * This in turn calls the methods producing individual parts of the page
153      */
154     function view() {
156         $context = context_module::instance($this->cm->id);
157         require_capability('mod/assignment:view', $context);
159         add_to_log($this->course->id, "assignment", "view", "view.php?id={$this->cm->id}",
160                    $this->assignment->id, $this->cm->id);
162         $this->view_header();
164         $this->view_intro();
166         $this->view_dates();
168         $this->view_feedback();
170         $this->view_footer();
171     }
173     /**
174      * Display the header and top of a page
175      *
176      * (this doesn't change much for assignment types)
177      * This is used by the view() method to print the header of view.php but
178      * it can be used on other pages in which case the string to denote the
179      * page in the navigation trail should be passed as an argument
180      *
181      * @global object
182      * @param string $subpage Description of subpage to be used in navigation trail
183      */
184     function view_header($subpage='') {
185         global $CFG, $PAGE, $OUTPUT;
187         if ($subpage) {
188             $PAGE->navbar->add($subpage);
189         }
191         $PAGE->set_title($this->pagetitle);
192         $PAGE->set_heading($this->course->fullname);
194         echo $OUTPUT->header();
196         groups_print_activity_menu($this->cm, $CFG->wwwroot . '/mod/assignment/view.php?id=' . $this->cm->id);
198         echo '<div class="reportlink">'.$this->submittedlink().'</div>';
199         echo '<div class="clearer"></div>';
200         if (has_capability('moodle/site:config', context_system::instance())) {
201             echo $OUTPUT->notification(get_string('upgradenotification', 'assignment'));
202             $adminurl = new moodle_url('/admin/tool/assignmentupgrade/listnotupgraded.php');
203             echo $OUTPUT->single_button($adminurl, get_string('viewassignmentupgradetool', 'assignment'));
204         }
205     }
208     /**
209      * Display the assignment intro
210      *
211      * This will most likely be extended by assignment type plug-ins
212      * The default implementation prints the assignment description in a box
213      */
214     function view_intro() {
215         global $OUTPUT;
216         echo $OUTPUT->box_start('generalbox boxaligncenter', 'intro');
217         echo format_module_intro('assignment', $this->assignment, $this->cm->id);
218         echo $OUTPUT->box_end();
219         echo plagiarism_print_disclosure($this->cm->id);
220     }
222     /**
223      * Display the assignment dates
224      *
225      * Prints the assignment start and end dates in a box.
226      * This will be suitable for most assignment types
227      */
228     function view_dates() {
229         global $OUTPUT;
230         if (!$this->assignment->timeavailable && !$this->assignment->timedue) {
231             return;
232         }
234         echo $OUTPUT->box_start('generalbox boxaligncenter', 'dates');
235         echo '<table>';
236         if ($this->assignment->timeavailable) {
237             echo '<tr><td class="c0">'.get_string('availabledate','assignment').':</td>';
238             echo '    <td class="c1">'.userdate($this->assignment->timeavailable).'</td></tr>';
239         }
240         if ($this->assignment->timedue) {
241             echo '<tr><td class="c0">'.get_string('duedate','assignment').':</td>';
242             echo '    <td class="c1">'.userdate($this->assignment->timedue).'</td></tr>';
243         }
244         echo '</table>';
245         echo $OUTPUT->box_end();
246     }
249     /**
250      * Display the bottom and footer of a page
251      *
252      * This default method just prints the footer.
253      * This will be suitable for most assignment types
254      */
255     function view_footer() {
256         global $OUTPUT;
257         echo $OUTPUT->footer();
258     }
260     /**
261      * Display the feedback to the student
262      *
263      * This default method prints the teacher picture and name, date when marked,
264      * grade and teacher submissioncomment.
265      * If advanced grading is used the method render_grade from the
266      * advanced grading controller is called to display the grade.
267      *
268      * @global object
269      * @global object
270      * @global object
271      * @param object $submission The submission object or NULL in which case it will be loaded
272      * @return bool
273      */
274     function view_feedback($submission=NULL) {
275         global $USER, $CFG, $DB, $OUTPUT, $PAGE;
276         require_once($CFG->libdir.'/gradelib.php');
277         require_once("$CFG->dirroot/grade/grading/lib.php");
279         if (!$submission) { /// Get submission for this assignment
280             $userid = $USER->id;
281             $submission = $this->get_submission($userid);
282         } else {
283             $userid = $submission->userid;
284         }
285         // Check the user can submit
286         $canviewfeedback = ($userid == $USER->id && has_capability('mod/assignment:submit', $this->context, $USER->id, false));
287         // If not then check if the user still has the view cap and has a previous submission
288         $canviewfeedback = $canviewfeedback || (!empty($submission) && $submission->userid == $USER->id && has_capability('mod/assignment:view', $this->context));
289         // Or if user can grade (is a teacher or admin)
290         $canviewfeedback = $canviewfeedback || has_capability('mod/assignment:grade', $this->context);
292         if (!$canviewfeedback) {
293             // can not view or submit assignments -> no feedback
294             return false;
295         }
297         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
298         $item = $grading_info->items[0];
299         $grade = $item->grades[$userid];
301         if ($grade->hidden or $grade->grade === false) { // hidden or error
302             return false;
303         }
305         if ($grade->grade === null and empty($grade->str_feedback)) { // No grade to show yet
306             // If sumbission then check if feedback is avaiable to show else return.
307             if (!$submission) {
308                 return false;
309             }
311             $fs = get_file_storage();
312             $noresponsefiles = $fs->is_area_empty($this->context->id, 'mod_assignment', 'response', $submission->id);
313             if (empty($submission->submissioncomment) && $noresponsefiles) { // Nothing to show yet
314                 return false;
315             }
317             // We need the teacher info
318             if (!$teacher = $DB->get_record('user', array('id'=>$submission->teacher))) {
319                 print_error('cannotfindteacher');
320             }
322             $feedbackdate = $submission->timemarked;
323             $feedback = format_text($submission->submissioncomment, $submission->format);
324             $strlonggrade = '-';
325         }
326         else {
327             // We need the teacher info
328             if (!$teacher = $DB->get_record('user', array('id'=>$grade->usermodified))) {
329                 print_error('cannotfindteacher');
330             }
332             $feedbackdate = $grade->dategraded;
333             $feedback = $grade->str_feedback;
334             $strlonggrade = $grade->str_long_grade;
335         }
337         // Print the feedback
338         echo $OUTPUT->heading(get_string('submissionfeedback', 'assignment'), 3);
340         echo '<table cellspacing="0" class="feedback">';
342         echo '<tr>';
343         echo '<td class="left picture">';
344         if ($teacher) {
345             echo $OUTPUT->user_picture($teacher);
346         }
347         echo '</td>';
348         echo '<td class="topic">';
349         echo '<div class="from">';
350         if ($teacher) {
351             echo '<div class="fullname">'.fullname($teacher).'</div>';
352         }
353         echo '<div class="time">'.userdate($feedbackdate).'</div>';
354         echo '</div>';
355         echo '</td>';
356         echo '</tr>';
358         echo '<tr>';
359         echo '<td class="left side">&nbsp;</td>';
360         echo '<td class="content">';
362         if ($this->assignment->grade) {
363             $gradestr = '<div class="grade">'. get_string("grade").': '.$strlonggrade. '</div>';
364             if (!empty($submission) && $controller = get_grading_manager($this->context, 'mod_assignment', 'submission')->get_active_controller()) {
365                 $controller->set_grade_range(make_grades_menu($this->assignment->grade));
366                 echo $controller->render_grade($PAGE, $submission->id, $item, $gradestr, has_capability('mod/assignment:grade', $this->context));
367             } else {
368                 echo $gradestr;
369             }
370             echo '<div class="clearer"></div>';
371         }
373         echo '<div class="comment">';
374         echo $feedback;
375         echo '</div>';
376         echo '</tr>';
377         if (method_exists($this, 'view_responsefile')) {
378             $this->view_responsefile($submission);
379         }
380         echo '</table>';
382         return true;
383     }
385     /**
386      * Returns a link with info about the state of the assignment submissions
387      *
388      * This is used by view_header to put this link at the top right of the page.
389      * For teachers it gives the number of submitted assignments with a link
390      * For students it gives the time of their submission.
391      * This will be suitable for most assignment types.
392      *
393      * @global object
394      * @global object
395      * @param bool $allgroup print all groups info if user can access all groups, suitable for index.php
396      * @return string
397      */
398     function submittedlink($allgroups=false) {
399         global $USER;
400         global $CFG;
402         $submitted = '';
403         $urlbase = "{$CFG->wwwroot}/mod/assignment/";
405         $context = context_module::instance($this->cm->id);
406         if (has_capability('mod/assignment:grade', $context)) {
407             if ($allgroups and has_capability('moodle/site:accessallgroups', $context)) {
408                 $group = 0;
409             } else {
410                 $group = groups_get_activity_group($this->cm);
411             }
412             if ($this->type == 'offline') {
413                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
414                              get_string('viewfeedback', 'assignment').'</a>';
415             } else if ($count = $this->count_real_submissions($group)) {
416                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
417                              get_string('viewsubmissions', 'assignment', $count).'</a>';
418             } else {
419                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
420                              get_string('noattempts', 'assignment').'</a>';
421             }
422         } else {
423             if (isloggedin()) {
424                 if ($submission = $this->get_submission($USER->id)) {
425                     // If the submission has been completed
426                     if ($this->is_submitted_with_required_data($submission)) {
427                         if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
428                             $submitted = '<span class="early">'.userdate($submission->timemodified).'</span>';
429                         } else {
430                             $submitted = '<span class="late">'.userdate($submission->timemodified).'</span>';
431                         }
432                     }
433                 }
434             }
435         }
437         return $submitted;
438     }
440     /**
441      * Returns whether the assigment supports lateness information
442      *
443      * @return bool This assignment type supports lateness (true, default) or no (false)
444      */
445     function supports_lateness() {
446         return true;
447     }
449     /**
450      * @todo Document this function
451      */
452     function setup_elements(&$mform) {
454     }
456     /**
457      * Any preprocessing needed for the settings form for
458      * this assignment type
459      *
460      * @param array $default_values - array to fill in with the default values
461      *      in the form 'formelement' => 'value'
462      * @param object $form - the form that is to be displayed
463      * @return none
464      */
465     function form_data_preprocessing(&$default_values, $form) {
466     }
468     /**
469      * Any extra validation checks needed for the settings
470      * form for this assignment type
471      *
472      * See lib/formslib.php, 'validation' function for details
473      */
474     function form_validation($data, $files) {
475         return array();
476     }
478     /**
479      * Create a new assignment activity
480      *
481      * Given an object containing all the necessary data,
482      * (defined by the form in mod_form.php) this function
483      * will create a new instance and return the id number
484      * of the new instance.
485      * The due data is added to the calendar
486      * This is common to all assignment types.
487      *
488      * @global object
489      * @global object
490      * @param object $assignment The data from the form on mod_form.php
491      * @return int The id of the assignment
492      */
493     function add_instance($assignment) {
494         global $COURSE, $DB;
496         $assignment->timemodified = time();
497         $assignment->courseid = $assignment->course;
499         $returnid = $DB->insert_record("assignment", $assignment);
500         $assignment->id = $returnid;
502         if ($assignment->timedue) {
503             $event = new stdClass();
504             $event->name        = $assignment->name;
505             $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
506             $event->courseid    = $assignment->course;
507             $event->groupid     = 0;
508             $event->userid      = 0;
509             $event->modulename  = 'assignment';
510             $event->instance    = $returnid;
511             $event->eventtype   = 'due';
512             $event->timestart   = $assignment->timedue;
513             $event->timeduration = 0;
515             calendar_event::create($event);
516         }
518         assignment_grade_item_update($assignment);
520         return $returnid;
521     }
523     /**
524      * Deletes an assignment activity
525      *
526      * Deletes all database records, files and calendar events for this assignment.
527      *
528      * @global object
529      * @global object
530      * @param object $assignment The assignment to be deleted
531      * @return boolean False indicates error
532      */
533     function delete_instance($assignment) {
534         global $CFG, $DB;
536         $assignment->courseid = $assignment->course;
538         $result = true;
540         // now get rid of all files
541         $fs = get_file_storage();
542         if ($cm = get_coursemodule_from_instance('assignment', $assignment->id)) {
543             $context = context_module::instance($cm->id);
544             $fs->delete_area_files($context->id);
545         }
547         if (! $DB->delete_records('assignment_submissions', array('assignment'=>$assignment->id))) {
548             $result = false;
549         }
551         if (! $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
552             $result = false;
553         }
555         if (! $DB->delete_records('assignment', array('id'=>$assignment->id))) {
556             $result = false;
557         }
558         $mod = $DB->get_field('modules','id',array('name'=>'assignment'));
560         assignment_grade_item_delete($assignment);
562         return $result;
563     }
565     /**
566      * Updates a new assignment activity
567      *
568      * Given an object containing all the necessary data,
569      * (defined by the form in mod_form.php) this function
570      * will update the assignment instance and return the id number
571      * The due date is updated in the calendar
572      * This is common to all assignment types.
573      *
574      * @global object
575      * @global object
576      * @param object $assignment The data from the form on mod_form.php
577      * @return bool success
578      */
579     function update_instance($assignment) {
580         global $COURSE, $DB;
582         $assignment->timemodified = time();
584         $assignment->id = $assignment->instance;
585         $assignment->courseid = $assignment->course;
587         $DB->update_record('assignment', $assignment);
589         if ($assignment->timedue) {
590             $event = new stdClass();
592             if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
594                 $event->name        = $assignment->name;
595                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
596                 $event->timestart   = $assignment->timedue;
598                 $calendarevent = calendar_event::load($event->id);
599                 $calendarevent->update($event);
600             } else {
601                 $event = new stdClass();
602                 $event->name        = $assignment->name;
603                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
604                 $event->courseid    = $assignment->course;
605                 $event->groupid     = 0;
606                 $event->userid      = 0;
607                 $event->modulename  = 'assignment';
608                 $event->instance    = $assignment->id;
609                 $event->eventtype   = 'due';
610                 $event->timestart   = $assignment->timedue;
611                 $event->timeduration = 0;
613                 calendar_event::create($event);
614             }
615         } else {
616             $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id));
617         }
619         // get existing grade item
620         assignment_grade_item_update($assignment);
622         return true;
623     }
625     /**
626      * Update grade item for this submission.
627      *
628      * @param stdClass $submission The submission instance
629      */
630     function update_grade($submission) {
631         assignment_update_grades($this->assignment, $submission->userid);
632     }
634     /**
635      * Top-level function for handling of submissions called by submissions.php
636      *
637      * This is for handling the teacher interaction with the grading interface
638      * This should be suitable for most assignment types.
639      *
640      * @global object
641      * @param string $mode Specifies the kind of teacher interaction taking place
642      */
643     function submissions($mode) {
644         ///The main switch is changed to facilitate
645         ///1) Batch fast grading
646         ///2) Skip to the next one on the popup
647         ///3) Save and Skip to the next one on the popup
649         //make user global so we can use the id
650         global $USER, $OUTPUT, $DB, $PAGE;
652         $mailinfo = optional_param('mailinfo', null, PARAM_BOOL);
654         if (optional_param('next', null, PARAM_BOOL)) {
655             $mode='next';
656         }
657         if (optional_param('saveandnext', null, PARAM_BOOL)) {
658             $mode='saveandnext';
659         }
661         if (is_null($mailinfo)) {
662             if (optional_param('sesskey', null, PARAM_BOOL)) {
663                 set_user_preference('assignment_mailinfo', 0);
664             } else {
665                 $mailinfo = get_user_preferences('assignment_mailinfo', 0);
666             }
667         } else {
668             set_user_preference('assignment_mailinfo', $mailinfo);
669         }
671         if (!($this->validate_and_preprocess_feedback())) {
672             // form was submitted ('Save' or 'Save and next' was pressed, but validation failed)
673             $this->display_submission();
674             return;
675         }
677         switch ($mode) {
678             case 'grade':                         // We are in a main window grading
679                 if ($submission = $this->process_feedback()) {
680                     $this->display_submissions(get_string('changessaved'));
681                 } else {
682                     $this->display_submissions();
683                 }
684                 break;
686             case 'single':                        // We are in a main window displaying one submission
687                 if ($submission = $this->process_feedback()) {
688                     $this->display_submissions(get_string('changessaved'));
689                 } else {
690                     $this->display_submission();
691                 }
692                 break;
694             case 'all':                          // Main window, display everything
695                 $this->display_submissions();
696                 break;
698             case 'fastgrade':
699                 ///do the fast grading stuff  - this process should work for all 3 subclasses
700                 $grading    = false;
701                 $commenting = false;
702                 $col        = false;
703                 if (isset($_POST['submissioncomment'])) {
704                     $col = 'submissioncomment';
705                     $commenting = true;
706                 }
707                 if (isset($_POST['menu'])) {
708                     $col = 'menu';
709                     $grading = true;
710                 }
711                 if (!$col) {
712                     //both submissioncomment and grade columns collapsed..
713                     $this->display_submissions();
714                     break;
715                 }
717                 foreach ($_POST[$col] as $id => $unusedvalue){
719                     $id = (int)$id; //clean parameter name
721                     $this->process_outcomes($id);
723                     if (!$submission = $this->get_submission($id)) {
724                         $submission = $this->prepare_new_submission($id);
725                         $newsubmission = true;
726                     } else {
727                         $newsubmission = false;
728                     }
729                     unset($submission->data1);  // Don't need to update this.
730                     unset($submission->data2);  // Don't need to update this.
732                     //for fast grade, we need to check if any changes take place
733                     $updatedb = false;
735                     if ($grading) {
736                         $grade = $_POST['menu'][$id];
737                         $updatedb = $updatedb || ($submission->grade != $grade);
738                         $submission->grade = $grade;
739                     } else {
740                         if (!$newsubmission) {
741                             unset($submission->grade);  // Don't need to update this.
742                         }
743                     }
744                     if ($commenting) {
745                         $commentvalue = trim($_POST['submissioncomment'][$id]);
746                         $updatedb = $updatedb || ($submission->submissioncomment != $commentvalue);
747                         $submission->submissioncomment = $commentvalue;
748                     } else {
749                         unset($submission->submissioncomment);  // Don't need to update this.
750                     }
752                     $submission->teacher    = $USER->id;
753                     if ($updatedb) {
754                         $submission->mailed = (int)(!$mailinfo);
755                     }
757                     $submission->timemarked = time();
759                     //if it is not an update, we don't change the last modified time etc.
760                     //this will also not write into database if no submissioncomment and grade is entered.
762                     if ($updatedb){
763                         if ($newsubmission) {
764                             if (!isset($submission->submissioncomment)) {
765                                 $submission->submissioncomment = '';
766                             }
767                             $sid = $DB->insert_record('assignment_submissions', $submission);
768                             $submission->id = $sid;
769                         } else {
770                             $DB->update_record('assignment_submissions', $submission);
771                         }
773                         // trigger grade event
774                         $this->update_grade($submission);
776                         //add to log only if updating
777                         add_to_log($this->course->id, 'assignment', 'update grades',
778                                    'submissions.php?id='.$this->cm->id.'&user='.$submission->userid,
779                                    $submission->userid, $this->cm->id);
780                     }
782                 }
784                 $message = $OUTPUT->notification(get_string('changessaved'), 'notifysuccess');
786                 $this->display_submissions($message);
787                 break;
790             case 'saveandnext':
791                 ///We are in pop up. save the current one and go to the next one.
792                 //first we save the current changes
793                 if ($submission = $this->process_feedback()) {
794                     //print_heading(get_string('changessaved'));
795                     //$extra_javascript = $this->update_main_listing($submission);
796                 }
798             case 'next':
799                 /// We are currently in pop up, but we want to skip to next one without saving.
800                 ///    This turns out to be similar to a single case
801                 /// The URL used is for the next submission.
802                 $offset = required_param('offset', PARAM_INT);
803                 $nextid = required_param('nextid', PARAM_INT);
804                 $id = required_param('id', PARAM_INT);
805                 $filter = optional_param('filter', self::FILTER_ALL, PARAM_INT);
807                 if ($mode == 'next' || $filter !== self::FILTER_REQUIRE_GRADING) {
808                     $offset = (int)$offset+1;
809                 }
810                 $redirect = new moodle_url('submissions.php',
811                         array('id' => $id, 'offset' => $offset, 'userid' => $nextid,
812                         'mode' => 'single', 'filter' => $filter));
814                 redirect($redirect);
815                 break;
817             case 'singlenosave':
818                 $this->display_submission();
819                 break;
821             default:
822                 echo "something seriously is wrong!!";
823                 break;
824         }
825     }
827     /**
828      * Checks if grading method allows quickgrade mode. At the moment it is hardcoded
829      * that advanced grading methods do not allow quickgrade.
830      *
831      * Assignment type plugins are not allowed to override this method
832      *
833      * @return boolean
834      */
835     public final function quickgrade_mode_allowed() {
836         global $CFG;
837         require_once("$CFG->dirroot/grade/grading/lib.php");
838         if ($controller = get_grading_manager($this->context, 'mod_assignment', 'submission')->get_active_controller()) {
839             return false;
840         }
841         return true;
842     }
844     /**
845      * Helper method updating the listing on the main script from popup using javascript
846      *
847      * @global object
848      * @global object
849      * @param $submission object The submission whose data is to be updated on the main page
850      */
851     function update_main_listing($submission) {
852         global $SESSION, $CFG, $OUTPUT;
854         $output = '';
856         $perpage = get_user_preferences('assignment_perpage', 10);
858         $quickgrade = get_user_preferences('assignment_quickgrade', 0) && $this->quickgrade_mode_allowed();
860         /// Run some Javascript to try and update the parent page
861         $output .= '<script type="text/javascript">'."\n<!--\n";
862         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['submissioncomment'])) {
863             if ($quickgrade){
864                 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid.'").value="'
865                 .trim($submission->submissioncomment).'";'."\n";
866              } else {
867                 $output.= 'opener.document.getElementById("com'.$submission->userid.
868                 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment)), 15)."\";\n";
869             }
870         }
872         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['grade'])) {
873             //echo optional_param('menuindex');
874             if ($quickgrade){
875                 $output.= 'opener.document.getElementById("menumenu'.$submission->userid.
876                 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT).'";'."\n";
877             } else {
878                 $output.= 'opener.document.getElementById("g'.$submission->userid.'").innerHTML="'.
879                 $this->display_grade($submission->grade)."\";\n";
880             }
881         }
882         //need to add student's assignments in there too.
883         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemodified']) &&
884             $submission->timemodified) {
885             $output.= 'opener.document.getElementById("ts'.$submission->userid.
886                  '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid)).userdate($submission->timemodified)."\";\n";
887         }
889         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemarked']) &&
890             $submission->timemarked) {
891             $output.= 'opener.document.getElementById("tt'.$submission->userid.
892                  '").innerHTML="'.userdate($submission->timemarked)."\";\n";
893         }
895         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['status'])) {
896             $output.= 'opener.document.getElementById("up'.$submission->userid.'").className="s1";';
897             $buttontext = get_string('update');
898             $url = new moodle_url('/mod/assignment/submissions.php', array(
899                     'id' => $this->cm->id,
900                     'userid' => $submission->userid,
901                     'mode' => 'single',
902                     'offset' => (optional_param('offset', '', PARAM_INT)-1)));
903             $button = $OUTPUT->action_link($url, $buttontext, new popup_action('click', $url, 'grade'.$submission->userid, array('height' => 450, 'width' => 700)), array('ttile'=>$buttontext));
905             $output .= 'opener.document.getElementById("up'.$submission->userid.'").innerHTML="'.addslashes_js($button).'";';
906         }
908         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $submission->userid);
910         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['finalgrade'])) {
911             $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid.
912             '").innerHTML="'.$grading_info->items[0]->grades[$submission->userid]->str_grade.'";'."\n";
913         }
915         if (!empty($CFG->enableoutcomes) and empty($SESSION->flextable['mod-assignment-submissions']->collapse['outcome'])) {
917             if (!empty($grading_info->outcomes)) {
918                 foreach($grading_info->outcomes as $n=>$outcome) {
919                     if ($outcome->grades[$submission->userid]->locked) {
920                         continue;
921                     }
923                     if ($quickgrade){
924                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.
925                         '").selectedIndex="'.$outcome->grades[$submission->userid]->grade.'";'."\n";
927                     } else {
928                         $options = make_grades_menu(-$outcome->scaleid);
929                         $options[0] = get_string('nooutcome', 'grades');
930                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.'").innerHTML="'.$options[$outcome->grades[$submission->userid]->grade]."\";\n";
931                     }
933                 }
934             }
935         }
937         $output .= "\n-->\n</script>";
938         return $output;
939     }
941     /**
942      *  Return a grade in user-friendly form, whether it's a scale or not
943      *
944      * @global object
945      * @param mixed $grade
946      * @return string User-friendly representation of grade
947      */
948     function display_grade($grade) {
949         global $DB;
951         static $scalegrades = array();   // Cache scales for each assignment - they might have different scales!!
953         if ($this->assignment->grade >= 0) {    // Normal number
954             if ($grade == -1) {
955                 return '-';
956             } else {
957                 return $grade.' / '.$this->assignment->grade;
958             }
960         } else {                                // Scale
961             if (empty($scalegrades[$this->assignment->id])) {
962                 if ($scale = $DB->get_record('scale', array('id'=>-($this->assignment->grade)))) {
963                     $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
964                 } else {
965                     return '-';
966                 }
967             }
968             if (isset($scalegrades[$this->assignment->id][$grade])) {
969                 return $scalegrades[$this->assignment->id][$grade];
970             }
971             return '-';
972         }
973     }
975     /**
976      *  Display a single submission, ready for grading on a popup window
977      *
978      * This default method prints the teacher info and submissioncomment box at the top and
979      * the student info and submission at the bottom.
980      * This method also fetches the necessary data in order to be able to
981      * provide a "Next submission" button.
982      * Calls preprocess_submission() to give assignment type plug-ins a chance
983      * to process submissions before they are graded
984      * This method gets its arguments from the page parameters userid and offset
985      *
986      * @global object
987      * @global object
988      * @param string $extra_javascript
989      */
990     function display_submission($offset=-1,$userid =-1, $display=true) {
991         global $CFG, $DB, $PAGE, $OUTPUT, $USER;
992         require_once($CFG->libdir.'/gradelib.php');
993         require_once($CFG->libdir.'/tablelib.php');
994         require_once("$CFG->dirroot/repository/lib.php");
995         require_once("$CFG->dirroot/grade/grading/lib.php");
996         if ($userid==-1) {
997             $userid = required_param('userid', PARAM_INT);
998         }
999         if ($offset==-1) {
1000             $offset = required_param('offset', PARAM_INT);//offset for where to start looking for student.
1001         }
1002         $filter = optional_param('filter', 0, PARAM_INT);
1004         if (!$user = $DB->get_record('user', array('id'=>$userid))) {
1005             print_error('nousers');
1006         }
1008         if (!$submission = $this->get_submission($user->id)) {
1009             $submission = $this->prepare_new_submission($userid);
1010         }
1011         if ($submission->timemodified > $submission->timemarked) {
1012             $subtype = 'assignmentnew';
1013         } else {
1014             $subtype = 'assignmentold';
1015         }
1017         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
1018         $gradingdisabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
1020     /// construct SQL, using current offset to find the data of the next student
1021         $course     = $this->course;
1022         $assignment = $this->assignment;
1023         $cm         = $this->cm;
1024         $context    = context_module::instance($cm->id);
1026         //reset filter to all for offline assignment
1027         if ($assignment->assignmenttype == 'offline' && $filter == self::FILTER_SUBMITTED) {
1028             $filter = self::FILTER_ALL;
1029         }
1030         /// Get all ppl that can submit assignments
1032         $currentgroup = groups_get_activity_group($cm);
1033         $users = get_enrolled_users($context, 'mod/assignment:submit', $currentgroup, 'u.id');
1034         if ($users) {
1035             $users = array_keys($users);
1036             // if groupmembersonly used, remove users who are not in any group
1037             if (!empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
1038                 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1039                     $users = array_intersect($users, array_keys($groupingusers));
1040                 }
1041             }
1042         }
1044         $nextid = 0;
1045         $where = '';
1046         if($filter == self::FILTER_SUBMITTED) {
1047             $where .= 's.timemodified > 0 AND ';
1048         } else if($filter == self::FILTER_REQUIRE_GRADING) {
1049             $where .= 's.timemarked < s.timemodified AND ';
1050         }
1052         if ($users) {
1053             $userfields = user_picture::fields('u', array('lastaccess'));
1054             $select = "SELECT $userfields,
1055                               s.id AS submissionid, s.grade, s.submissioncomment,
1056                               s.timemodified, s.timemarked,
1057                               CASE WHEN s.timemarked > 0 AND s.timemarked >= s.timemodified THEN 1
1058                                    ELSE 0 END AS status ";
1060             $sql = 'FROM {user} u '.
1061                    'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1062                    AND s.assignment = '.$this->assignment->id.' '.
1063                    'WHERE '.$where.'u.id IN ('.implode(',', $users).') ';
1065             if ($sort = flexible_table::get_sort_for_table('mod-assignment-submissions')) {
1066                 $sort = 'ORDER BY '.$sort.' ';
1067             }
1068             $auser = $DB->get_records_sql($select.$sql.$sort, null, $offset, 2);
1070             if (is_array($auser) && count($auser)>1) {
1071                 $nextuser = next($auser);
1072                 $nextid = $nextuser->id;
1073             }
1074         }
1076         if ($submission->teacher) {
1077             $teacher = $DB->get_record('user', array('id'=>$submission->teacher));
1078         } else {
1079             global $USER;
1080             $teacher = $USER;
1081         }
1083         $this->preprocess_submission($submission);
1085         $mformdata = new stdClass();
1086         $mformdata->context = $this->context;
1087         $mformdata->maxbytes = $this->course->maxbytes;
1088         $mformdata->courseid = $this->course->id;
1089         $mformdata->teacher = $teacher;
1090         $mformdata->assignment = $assignment;
1091         $mformdata->submission = $submission;
1092         $mformdata->lateness = $this->display_lateness($submission->timemodified);
1093         $mformdata->auser = $auser;
1094         $mformdata->user = $user;
1095         $mformdata->offset = $offset;
1096         $mformdata->userid = $userid;
1097         $mformdata->cm = $this->cm;
1098         $mformdata->grading_info = $grading_info;
1099         $mformdata->enableoutcomes = $CFG->enableoutcomes;
1100         $mformdata->grade = $this->assignment->grade;
1101         $mformdata->gradingdisabled = $gradingdisabled;
1102         $mformdata->nextid = $nextid;
1103         $mformdata->submissioncomment= $submission->submissioncomment;
1104         $mformdata->submissioncommentformat= FORMAT_HTML;
1105         $mformdata->submission_content= $this->print_user_files($user->id,true);
1106         $mformdata->filter = $filter;
1107         $mformdata->mailinfo = get_user_preferences('assignment_mailinfo', 0);
1108          if ($assignment->assignmenttype == 'upload') {
1109             $mformdata->fileui_options = array('subdirs'=>1, 'maxbytes'=>$assignment->maxbytes, 'maxfiles'=>$assignment->var1, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL);
1110         } elseif ($assignment->assignmenttype == 'uploadsingle') {
1111             $mformdata->fileui_options = array('subdirs'=>0, 'maxbytes'=>$CFG->userquota, 'maxfiles'=>1, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL);
1112         }
1113         $advancedgradingwarning = false;
1114         $gradingmanager = get_grading_manager($this->context, 'mod_assignment', 'submission');
1115         if ($gradingmethod = $gradingmanager->get_active_method()) {
1116             $controller = $gradingmanager->get_controller($gradingmethod);
1117             if ($controller->is_form_available()) {
1118                 $itemid = null;
1119                 if (!empty($submission->id)) {
1120                     $itemid = $submission->id;
1121                 }
1122                 if ($gradingdisabled && $itemid) {
1123                     $mformdata->advancedgradinginstance = $controller->get_current_instance($USER->id, $itemid);
1124                 } else if (!$gradingdisabled) {
1125                     $instanceid = optional_param('advancedgradinginstanceid', 0, PARAM_INT);
1126                     $mformdata->advancedgradinginstance = $controller->get_or_create_instance($instanceid, $USER->id, $itemid);
1127                 }
1128             } else {
1129                 $advancedgradingwarning = $controller->form_unavailable_notification();
1130             }
1131         }
1133         $submitform = new assignment_grading_form( null, $mformdata );
1135          if (!$display) {
1136             $ret_data = new stdClass();
1137             $ret_data->mform = $submitform;
1138             if (isset($mformdata->fileui_options)) {
1139                 $ret_data->fileui_options = $mformdata->fileui_options;
1140             }
1141             return $ret_data;
1142         }
1144         if ($submitform->is_cancelled()) {
1145             redirect('submissions.php?id='.$this->cm->id);
1146         }
1148         $submitform->set_data($mformdata);
1150         $PAGE->set_title($this->course->fullname . ': ' .get_string('feedback', 'assignment').' - '.fullname($user, true));
1151         $PAGE->set_heading($this->course->fullname);
1152         $PAGE->navbar->add(get_string('submissions', 'assignment'), new moodle_url('/mod/assignment/submissions.php', array('id'=>$cm->id)));
1153         $PAGE->navbar->add(fullname($user, true));
1155         echo $OUTPUT->header();
1156         echo $OUTPUT->heading(get_string('feedback', 'assignment').': '.fullname($user, true));
1158         // display mform here...
1159         if ($advancedgradingwarning) {
1160             echo $OUTPUT->notification($advancedgradingwarning, 'error');
1161         }
1162         $submitform->display();
1164         $customfeedback = $this->custom_feedbackform($submission, true);
1165         if (!empty($customfeedback)) {
1166             echo $customfeedback;
1167         }
1169         echo $OUTPUT->footer();
1170     }
1172     /**
1173      *  Preprocess submission before grading
1174      *
1175      * Called by display_submission()
1176      * The default type does nothing here.
1177      *
1178      * @param object $submission The submission object
1179      */
1180     function preprocess_submission(&$submission) {
1181     }
1183     /**
1184      *  Display all the submissions ready for grading
1185      *
1186      * @global object
1187      * @global object
1188      * @global object
1189      * @global object
1190      * @param string $message
1191      * @return bool|void
1192      */
1193     function display_submissions($message='') {
1194         global $CFG, $DB, $USER, $DB, $OUTPUT, $PAGE;
1195         require_once($CFG->libdir.'/gradelib.php');
1197         /* first we check to see if the form has just been submitted
1198          * to request user_preference updates
1199          */
1201        $filters = array(self::FILTER_ALL             => get_string('all'),
1202                         self::FILTER_REQUIRE_GRADING => get_string('requiregrading', 'assignment'));
1204         $updatepref = optional_param('updatepref', 0, PARAM_BOOL);
1205         if ($updatepref) {
1206             $perpage = optional_param('perpage', 10, PARAM_INT);
1207             $perpage = ($perpage <= 0) ? 10 : $perpage ;
1208             $filter = optional_param('filter', 0, PARAM_INT);
1209             set_user_preference('assignment_perpage', $perpage);
1210             set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
1211             set_user_preference('assignment_filter', $filter);
1212         }
1214         /* next we get perpage and quickgrade (allow quick grade) params
1215          * from database
1216          */
1217         $perpage    = get_user_preferences('assignment_perpage', 10);
1218         $quickgrade = get_user_preferences('assignment_quickgrade', 0) && $this->quickgrade_mode_allowed();
1219         $filter = get_user_preferences('assignment_filter', 0);
1220         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);
1222         if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
1223             $uses_outcomes = true;
1224         } else {
1225             $uses_outcomes = false;
1226         }
1228         $page    = optional_param('page', 0, PARAM_INT);
1229         $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
1231     /// Some shortcuts to make the code read better
1233         $course     = $this->course;
1234         $assignment = $this->assignment;
1235         $cm         = $this->cm;
1236         $hassubmission = false;
1238         // reset filter to all for offline assignment only.
1239         if ($assignment->assignmenttype == 'offline') {
1240             if ($filter == self::FILTER_SUBMITTED) {
1241                 $filter = self::FILTER_ALL;
1242             }
1243         } else {
1244             $filters[self::FILTER_SUBMITTED] = get_string('submitted', 'assignment');
1245         }
1247         $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
1248         add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->cm->id, $this->assignment->id, $this->cm->id);
1250         $PAGE->set_title(format_string($this->assignment->name,true));
1251         $PAGE->set_heading($this->course->fullname);
1252         echo $OUTPUT->header();
1254         echo '<div class="usersubmissions">';
1256         //hook to allow plagiarism plugins to update status/print links.
1257         echo plagiarism_update_status($this->course, $this->cm);
1259         $course_context = context_course::instance($course->id);
1260         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
1261             echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">'
1262                 . get_string('seeallcoursegrades', 'grades') . '</a></div>';
1263         }
1265         if (!empty($message)) {
1266             echo $message;   // display messages here if any
1267         }
1269         $context = context_module::instance($cm->id);
1271     /// Check to see if groups are being used in this assignment
1273         /// find out current groups mode
1274         $groupmode = groups_get_activity_groupmode($cm);
1275         $currentgroup = groups_get_activity_group($cm, true);
1276         groups_print_activity_menu($cm, $CFG->wwwroot . '/mod/assignment/submissions.php?id=' . $this->cm->id);
1278         /// Print quickgrade form around the table
1279         if ($quickgrade) {
1280             $formattrs = array();
1281             $formattrs['action'] = new moodle_url('/mod/assignment/submissions.php');
1282             $formattrs['id'] = 'fastg';
1283             $formattrs['method'] = 'post';
1285             echo html_writer::start_tag('form', $formattrs);
1286             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'id',      'value'=> $this->cm->id));
1287             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'mode',    'value'=> 'fastgrade'));
1288             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'page',    'value'=> $page));
1289             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=> sesskey()));
1290         }
1292         /// Get all ppl that are allowed to submit assignments
1293         list($esql, $params) = get_enrolled_sql($context, 'mod/assignment:submit', $currentgroup);
1295         if ($filter == self::FILTER_ALL) {
1296             $sql = "SELECT u.id FROM {user} u ".
1297                    "LEFT JOIN ($esql) eu ON eu.id=u.id ".
1298                    "WHERE u.deleted = 0 AND eu.id=u.id ";
1299         } else {
1300             $wherefilter = ' AND s.assignment = '. $this->assignment->id;
1301             $assignmentsubmission = "LEFT JOIN {assignment_submissions} s ON (u.id = s.userid) ";
1302             if($filter == self::FILTER_SUBMITTED) {
1303                 $wherefilter .= ' AND s.timemodified > 0 ';
1304             } else if($filter == self::FILTER_REQUIRE_GRADING && $assignment->assignmenttype != 'offline') {
1305                 $wherefilter .= ' AND s.timemarked < s.timemodified ';
1306             } else { // require grading for offline assignment
1307                 $assignmentsubmission = "";
1308                 $wherefilter = "";
1309             }
1311             $sql = "SELECT u.id FROM {user} u ".
1312                    "LEFT JOIN ($esql) eu ON eu.id=u.id ".
1313                    $assignmentsubmission.
1314                    "WHERE u.deleted = 0 AND eu.id=u.id ".
1315                    $wherefilter;
1316         }
1318         $users = $DB->get_records_sql($sql, $params);
1319         if (!empty($users)) {
1320             if($assignment->assignmenttype == 'offline' && $filter == self::FILTER_REQUIRE_GRADING) {
1321                 //remove users who has submitted their assignment
1322                 foreach ($this->get_submissions() as $submission) {
1323                     if (array_key_exists($submission->userid, $users)) {
1324                         unset($users[$submission->userid]);
1325                     }
1326                 }
1327             }
1328             $users = array_keys($users);
1329         }
1331         // if groupmembersonly used, remove users who are not in any group
1332         if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
1333             if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1334                 $users = array_intersect($users, array_keys($groupingusers));
1335             }
1336         }
1338         $extrafields = get_extra_user_fields($context);
1339         $tablecolumns = array_merge(array('picture', 'fullname'), $extrafields,
1340                 array('grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade'));
1341         if ($uses_outcomes) {
1342             $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
1343         }
1345         $extrafieldnames = array();
1346         foreach ($extrafields as $field) {
1347             $extrafieldnames[] = get_user_field_name($field);
1348         }
1349         $tableheaders = array_merge(
1350                 array('', get_string('fullnameuser')),
1351                 $extrafieldnames,
1352                 array(
1353                     get_string('grade'),
1354                     get_string('comment', 'assignment'),
1355                     get_string('lastmodified').' ('.get_string('submission', 'assignment').')',
1356                     get_string('lastmodified').' ('.get_string('grade').')',
1357                     get_string('status'),
1358                     get_string('finalgrade', 'grades'),
1359                 ));
1360         if ($uses_outcomes) {
1361             $tableheaders[] = get_string('outcome', 'grades');
1362         }
1364         require_once($CFG->libdir.'/tablelib.php');
1365         $table = new flexible_table('mod-assignment-submissions');
1367         $table->define_columns($tablecolumns);
1368         $table->define_headers($tableheaders);
1369         $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;currentgroup='.$currentgroup);
1371         $table->sortable(true, 'lastname');//sorted by lastname by default
1372         $table->collapsible(true);
1373         $table->initialbars(true);
1375         $table->column_suppress('picture');
1376         $table->column_suppress('fullname');
1378         $table->column_class('picture', 'picture');
1379         $table->column_class('fullname', 'fullname');
1380         foreach ($extrafields as $field) {
1381             $table->column_class($field, $field);
1382         }
1383         $table->column_class('grade', 'grade');
1384         $table->column_class('submissioncomment', 'comment');
1385         $table->column_class('timemodified', 'timemodified');
1386         $table->column_class('timemarked', 'timemarked');
1387         $table->column_class('status', 'status');
1388         $table->column_class('finalgrade', 'finalgrade');
1389         if ($uses_outcomes) {
1390             $table->column_class('outcome', 'outcome');
1391         }
1393         $table->set_attribute('cellspacing', '0');
1394         $table->set_attribute('id', 'attempts');
1395         $table->set_attribute('class', 'submissions');
1396         $table->set_attribute('width', '100%');
1398         $table->no_sorting('finalgrade');
1399         $table->no_sorting('outcome');
1400         $table->text_sorting('submissioncomment');
1402         // Start working -- this is necessary as soon as the niceties are over
1403         $table->setup();
1405         /// Construct the SQL
1406         list($where, $params) = $table->get_sql_where();
1407         if ($where) {
1408             $where .= ' AND ';
1409         }
1411         if ($filter == self::FILTER_SUBMITTED) {
1412            $where .= 's.timemodified > 0 AND ';
1413         } else if($filter == self::FILTER_REQUIRE_GRADING) {
1414             $where = '';
1415             if ($assignment->assignmenttype != 'offline') {
1416                $where .= 's.timemarked < s.timemodified AND ';
1417             }
1418         }
1420         if ($sort = $table->get_sql_sort()) {
1421             $sort = ' ORDER BY '.$sort;
1422         }
1424         $ufields = user_picture::fields('u', $extrafields);
1425         if (!empty($users)) {
1426             $select = "SELECT $ufields,
1427                               s.id AS submissionid, s.grade, s.submissioncomment,
1428                               s.timemodified, s.timemarked,
1429                               CASE WHEN s.timemarked > 0 AND s.timemarked >= s.timemodified THEN 1
1430                                    ELSE 0 END AS status ";
1432             $sql = 'FROM {user} u '.
1433                    'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1434                     AND s.assignment = '.$this->assignment->id.' '.
1435                    'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1437             $ausers = $DB->get_records_sql($select.$sql.$sort, $params, $table->get_page_start(), $table->get_page_size());
1439             $table->pagesize($perpage, count($users));
1441             ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1442             $offset = $page * $perpage;
1443             $strupdate = get_string('update');
1444             $strgrade  = get_string('grade');
1445             $strview  = get_string('view');
1446             $grademenu = make_grades_menu($this->assignment->grade);
1448             if ($ausers !== false) {
1449                 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
1450                 $endposition = $offset + $perpage;
1451                 $currentposition = 0;
1452                 foreach ($ausers as $auser) {
1453                     if ($currentposition == $offset && $offset < $endposition) {
1454                         $rowclass = null;
1455                         $final_grade = $grading_info->items[0]->grades[$auser->id];
1456                         $grademax = $grading_info->items[0]->grademax;
1457                         $final_grade->formatted_grade = round($final_grade->grade,2) .' / ' . round($grademax,2);
1458                         $locked_overridden = 'locked';
1459                         if ($final_grade->overridden) {
1460                             $locked_overridden = 'overridden';
1461                         }
1463                         // TODO add here code if advanced grading grade must be reviewed => $auser->status=0
1465                         $picture = $OUTPUT->user_picture($auser);
1467                         if (empty($auser->submissionid)) {
1468                             $auser->grade = -1; //no submission yet
1469                         }
1471                         if (!empty($auser->submissionid)) {
1472                             $hassubmission = true;
1473                         ///Prints student answer and student modified date
1474                         ///attach file or print link to student answer, depending on the type of the assignment.
1475                         ///Refer to print_student_answer in inherited classes.
1476                             if ($auser->timemodified > 0) {
1477                                 $studentmodifiedcontent = $this->print_student_answer($auser->id)
1478                                         . userdate($auser->timemodified);
1479                                 if ($assignment->timedue && $auser->timemodified > $assignment->timedue && $this->supports_lateness()) {
1480                                     $studentmodifiedcontent .= $this->display_lateness($auser->timemodified);
1481                                     $rowclass = 'late';
1482                                 }
1483                             } else {
1484                                 $studentmodifiedcontent = '&nbsp;';
1485                             }
1486                             $studentmodified = html_writer::tag('div', $studentmodifiedcontent, array('id' => 'ts' . $auser->id));
1487                         ///Print grade, dropdown or text
1488                             if ($auser->timemarked > 0) {
1489                                 $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
1491                                 if ($final_grade->locked or $final_grade->overridden) {
1492                                     $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1493                                 } else if ($quickgrade) {
1494                                     $attributes = array();
1495                                     $attributes['tabindex'] = $tabindex++;
1496                                     $menu = html_writer::label(get_string('assignment:grade', 'assignment'), 'menumenu'. $auser->id, false, array('class' => 'accesshide'));
1497                                     $menu .= html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1498                                     $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
1499                                 } else {
1500                                     $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1501                                 }
1503                             } else {
1504                                 $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1505                                 if ($final_grade->locked or $final_grade->overridden) {
1506                                     $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1507                                 } else if ($quickgrade) {
1508                                     $attributes = array();
1509                                     $attributes['tabindex'] = $tabindex++;
1510                                     $menu = html_writer::label(get_string('assignment:grade', 'assignment'), 'menumenu'. $auser->id, false, array('class' => 'accesshide'));
1511                                     $menu .= html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1512                                     $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1513                                 } else {
1514                                     $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1515                                 }
1516                             }
1517                         ///Print Comment
1518                             if ($final_grade->locked or $final_grade->overridden) {
1519                                 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';
1521                             } else if ($quickgrade) {
1522                                 $comment = '<div id="com'.$auser->id.'">'
1523                                          . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1524                                          . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1525                             } else {
1526                                 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
1527                             }
1528                         } else {
1529                             $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1530                             $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1531                             $status          = '<div id="st'.$auser->id.'">&nbsp;</div>';
1533                             if ($final_grade->locked or $final_grade->overridden) {
1534                                 $grade = '<div id="g'.$auser->id.'">'.$final_grade->formatted_grade . '</div>';
1535                                 $hassubmission = true;
1536                             } else if ($quickgrade) {   // allow editing
1537                                 $attributes = array();
1538                                 $attributes['tabindex'] = $tabindex++;
1539                                 $menu = html_writer::label(get_string('assignment:grade', 'assignment'), 'menumenu'. $auser->id, false, array('class' => 'accesshide'));
1540                                 $menu .= html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1541                                 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1542                                 $hassubmission = true;
1543                             } else {
1544                                 $grade = '<div id="g'.$auser->id.'">-</div>';
1545                             }
1547                             if ($final_grade->locked or $final_grade->overridden) {
1548                                 $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
1549                             } else if ($quickgrade) {
1550                                 $comment = '<div id="com'.$auser->id.'">'
1551                                          . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1552                                          . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1553                             } else {
1554                                 $comment = '<div id="com'.$auser->id.'">&nbsp;</div>';
1555                             }
1556                         }
1558                         if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
1559                             $auser->status = 0;
1560                         } else {
1561                             $auser->status = 1;
1562                         }
1564                         $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
1565                         if ($final_grade->locked or $final_grade->overridden) {
1566                             $buttontext = $strview;
1567                         }
1569                         ///No more buttons, we use popups ;-).
1570                         $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1571                                    . '&amp;userid='.$auser->id.'&amp;mode=single'.'&amp;filter='.$filter.'&amp;offset='.$offset++;
1573                         $button = $OUTPUT->action_link($popup_url, $buttontext);
1575                         $status  = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
1577                         $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';
1579                         $outcomes = '';
1581                         if ($uses_outcomes) {
1583                             foreach($grading_info->outcomes as $n=>$outcome) {
1584                                 $outcomes .= '<div class="outcome"><label for="'. 'outcome_'.$n.'_'.$auser->id .'">'.$outcome->name.'</label>';
1585                                 $options = make_grades_menu(-$outcome->scaleid);
1587                                 if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
1588                                     $options[0] = get_string('nooutcome', 'grades');
1589                                     $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
1590                                 } else {
1591                                     $attributes = array();
1592                                     $attributes['tabindex'] = $tabindex++;
1593                                     $attributes['id'] = 'outcome_'.$n.'_'.$auser->id;
1594                                     $outcomes .= ' '.html_writer::select($options, 'outcome_'.$n.'['.$auser->id.']', $outcome->grades[$auser->id]->grade, array(0=>get_string('nooutcome', 'grades')), $attributes);
1595                                 }
1596                                 $outcomes .= '</div>';
1597                             }
1598                         }
1600                         $userlink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $auser->id . '&amp;course=' . $course->id . '">' . fullname($auser, has_capability('moodle/site:viewfullnames', $this->context)) . '</a>';
1601                         $extradata = array();
1602                         foreach ($extrafields as $field) {
1603                             $extradata[] = $auser->{$field};
1604                         }
1605                         $row = array_merge(array($picture, $userlink), $extradata,
1606                                 array($grade, $comment, $studentmodified, $teachermodified,
1607                                 $status, $finalgrade));
1608                         if ($uses_outcomes) {
1609                             $row[] = $outcomes;
1610                         }
1611                         $table->add_data($row, $rowclass);
1612                     }
1613                     $currentposition++;
1614                 }
1615                 if ($hassubmission && method_exists($this, 'download_submissions')) {
1616                     echo html_writer::start_tag('div', array('class' => 'mod-assignment-download-link'));
1617                     echo html_writer::link(new moodle_url('/mod/assignment/submissions.php', array('id' => $this->cm->id, 'download' => 'zip')), get_string('downloadall', 'assignment'));
1618                     echo html_writer::end_tag('div');
1619                 }
1620                 $table->print_html();  /// Print the whole table
1621             } else {
1622                 if ($filter == self::FILTER_SUBMITTED) {
1623                     echo html_writer::tag('div', get_string('nosubmisson', 'assignment'), array('class'=>'nosubmisson'));
1624                 } else if ($filter == self::FILTER_REQUIRE_GRADING) {
1625                     echo html_writer::tag('div', get_string('norequiregrading', 'assignment'), array('class'=>'norequiregrading'));
1626                 }
1627             }
1628         }
1630         /// Print quickgrade form around the table
1631         if ($quickgrade && $table->started_output && !empty($users)){
1632             $mailinfopref = false;
1633             if (get_user_preferences('assignment_mailinfo', 1)) {
1634                 $mailinfopref = true;
1635             }
1636             $emailnotification =  html_writer::checkbox('mailinfo', 1, $mailinfopref, get_string('enablenotification','assignment'));
1638             $emailnotification .= $OUTPUT->help_icon('enablenotification', 'assignment');
1639             echo html_writer::tag('div', $emailnotification, array('class'=>'emailnotification'));
1641             $savefeedback = html_writer::empty_tag('input', array('type'=>'submit', 'name'=>'fastg', 'value'=>get_string('saveallfeedback', 'assignment')));
1642             echo html_writer::tag('div', $savefeedback, array('class'=>'fastgbutton'));
1644             echo html_writer::end_tag('form');
1645         } else if ($quickgrade) {
1646             echo html_writer::end_tag('form');
1647         }
1649         echo '</div>';
1650         /// End of fast grading form
1652         /// Mini form for setting user preference
1654         $formaction = new moodle_url('/mod/assignment/submissions.php', array('id'=>$this->cm->id));
1655         $mform = new MoodleQuickForm('optionspref', 'post', $formaction, '', array('class'=>'optionspref'));
1657         $mform->addElement('hidden', 'updatepref');
1658         $mform->setDefault('updatepref', 1);
1659         $mform->addElement('header', 'qgprefs', get_string('optionalsettings', 'assignment'));
1660         $mform->addElement('select', 'filter', get_string('show'),  $filters);
1662         $mform->setDefault('filter', $filter);
1664         $mform->addElement('text', 'perpage', get_string('pagesize', 'assignment'), array('size'=>1));
1665         $mform->setDefault('perpage', $perpage);
1667         if ($this->quickgrade_mode_allowed()) {
1668             $mform->addElement('checkbox', 'quickgrade', get_string('quickgrade','assignment'));
1669             $mform->setDefault('quickgrade', $quickgrade);
1670             $mform->addHelpButton('quickgrade', 'quickgrade', 'assignment');
1671         }
1673         $mform->addElement('submit', 'savepreferences', get_string('savepreferences'));
1675         $mform->display();
1677         echo $OUTPUT->footer();
1678     }
1680     /**
1681      * If the form was cancelled ('Cancel' or 'Next' was pressed), call cancel method
1682      * from advanced grading (if applicable) and returns true
1683      * If the form was submitted, validates it and returns false if validation did not pass.
1684      * If validation passes, preprocess advanced grading (if applicable) and returns true.
1685      *
1686      * Note to the developers: This is NOT the correct way to implement advanced grading
1687      * in grading form. The assignment grading was written long time ago and unfortunately
1688      * does not fully use the mforms. Usually function is_validated() is called to
1689      * validate the form and get_data() is called to get the data from the form.
1690      *
1691      * Here we have to push the calculated grade to $_POST['xgrade'] because further processing
1692      * of the form gets the data not from form->get_data(), but from $_POST (using statement
1693      * like  $feedback = data_submitted() )
1694      */
1695     protected function validate_and_preprocess_feedback() {
1696         global $USER, $CFG;
1697         require_once($CFG->libdir.'/gradelib.php');
1698         if (!($feedback = data_submitted()) || !isset($feedback->userid) || !isset($feedback->offset)) {
1699             return true;      // No incoming data, nothing to validate
1700         }
1701         $userid = required_param('userid', PARAM_INT);
1702         $offset = required_param('offset', PARAM_INT);
1703         $gradinginfo = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($userid));
1704         $gradingdisabled = $gradinginfo->items[0]->grades[$userid]->locked || $gradinginfo->items[0]->grades[$userid]->overridden;
1705         if ($gradingdisabled) {
1706             return true;
1707         }
1708         $submissiondata = $this->display_submission($offset, $userid, false);
1709         $mform = $submissiondata->mform;
1710         $gradinginstance = $mform->use_advanced_grading();
1711         if (optional_param('cancel', false, PARAM_BOOL) || optional_param('next', false, PARAM_BOOL)) {
1712             // form was cancelled
1713             if ($gradinginstance) {
1714                 $gradinginstance->cancel();
1715             }
1716         } else if ($mform->is_submitted()) {
1717             // form was submitted (= a submit button other than 'cancel' or 'next' has been clicked)
1718             if (!$mform->is_validated()) {
1719                 return false;
1720             }
1721             // preprocess advanced grading here
1722             if ($gradinginstance) {
1723                 $data = $mform->get_data();
1724                 // create submission if it did not exist yet because we need submission->id for storing the grading instance
1725                 $submission = $this->get_submission($userid, true);
1726                 $_POST['xgrade'] = $gradinginstance->submit_and_get_grade($data->advancedgrading, $submission->id);
1727             }
1728         }
1729         return true;
1730     }
1732     /**
1733      *  Process teacher feedback submission
1734      *
1735      * This is called by submissions() when a grading even has taken place.
1736      * It gets its data from the submitted form.
1737      *
1738      * @global object
1739      * @global object
1740      * @global object
1741      * @return object|bool The updated submission object or false
1742      */
1743     function process_feedback($formdata=null) {
1744         global $CFG, $USER, $DB;
1745         require_once($CFG->libdir.'/gradelib.php');
1747         if (!$feedback = data_submitted() or !confirm_sesskey()) {      // No incoming data?
1748             return false;
1749         }
1751         ///For save and next, we need to know the userid to save, and the userid to go
1752         ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1753         ///as the userid to store
1754         if ((int)$feedback->saveuserid !== -1){
1755             $feedback->userid = $feedback->saveuserid;
1756         }
1758         if (!empty($feedback->cancel)) {          // User hit cancel button
1759             return false;
1760         }
1762         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);
1764         // store outcomes if needed
1765         $this->process_outcomes($feedback->userid);
1767         $submission = $this->get_submission($feedback->userid, true);  // Get or make one
1769         if (!($grading_info->items[0]->grades[$feedback->userid]->locked ||
1770             $grading_info->items[0]->grades[$feedback->userid]->overridden) ) {
1772             $submission->grade      = $feedback->xgrade;
1773             $submission->submissioncomment    = $feedback->submissioncomment_editor['text'];
1774             $submission->teacher    = $USER->id;
1775             $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1776             if (!$mailinfo) {
1777                 $submission->mailed = 1;       // treat as already mailed
1778             } else {
1779                 $submission->mailed = 0;       // Make sure mail goes out (again, even)
1780             }
1781             $submission->timemarked = time();
1783             unset($submission->data1);  // Don't need to update this.
1784             unset($submission->data2);  // Don't need to update this.
1786             if (empty($submission->timemodified)) {   // eg for offline assignments
1787                 // $submission->timemodified = time();
1788             }
1790             $DB->update_record('assignment_submissions', $submission);
1792             // triger grade event
1793             $this->update_grade($submission);
1795             add_to_log($this->course->id, 'assignment', 'update grades',
1796                        'submissions.php?id='.$this->cm->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
1797              if (!is_null($formdata)) {
1798                     if ($this->type == 'upload' || $this->type == 'uploadsingle') {
1799                         $mformdata = $formdata->mform->get_data();
1800                         $mformdata = file_postupdate_standard_filemanager($mformdata, 'files', $formdata->fileui_options, $this->context, 'mod_assignment', 'response', $submission->id);
1801                     }
1802              }
1803         }
1805         return $submission;
1807     }
1809     function process_outcomes($userid) {
1810         global $CFG, $USER;
1812         if (empty($CFG->enableoutcomes)) {
1813             return;
1814         }
1816         require_once($CFG->libdir.'/gradelib.php');
1818         if (!$formdata = data_submitted() or !confirm_sesskey()) {
1819             return;
1820         }
1822         $data = array();
1823         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
1825         if (!empty($grading_info->outcomes)) {
1826             foreach($grading_info->outcomes as $n=>$old) {
1827                 $name = 'outcome_'.$n;
1828                 if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
1829                     $data[$n] = $formdata->{$name}[$userid];
1830                 }
1831             }
1832         }
1833         if (count($data) > 0) {
1834             grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1835         }
1837     }
1839     /**
1840      * Load the submission object for a particular user
1841      *
1842      * @global object
1843      * @global object
1844      * @param int $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1845      * @param bool $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1846      * @param bool $teachermodified student submission set if false
1847      * @return object|bool The submission or false (if $createnew is false and there is no existing submission).
1848      */
1849     function get_submission($userid=0, $createnew=false, $teachermodified=false) {
1850         global $USER, $DB;
1852         if (empty($userid)) {
1853             $userid = $USER->id;
1854         }
1856         $submission = $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1858         if ($submission) {
1859             return $submission;
1860         } else if (!$createnew) {
1861             return false;
1862         }
1863         $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
1864         $DB->insert_record("assignment_submissions", $newsubmission);
1866         return $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1867     }
1869     /**
1870      * Check the given submission is complete. Preliminary rows are often created in the assignment_submissions
1871      * table before a submission actually takes place. This function checks to see if the given submission has actually
1872      * been submitted.
1873      *
1874      * @param  stdClass $submission The submission we want to check for completion
1875      * @return bool                 Indicates if the submission was found to be complete
1876      */
1877     public function is_submitted_with_required_data($submission) {
1878         return $submission->timemodified;
1879     }
1881     /**
1882      * Instantiates a new submission object for a given user
1883      *
1884      * Sets the assignment, userid and times, everything else is set to default values.
1885      *
1886      * @param int $userid The userid for which we want a submission object
1887      * @param bool $teachermodified student submission set if false
1888      * @return object The submission
1889      */
1890     function prepare_new_submission($userid, $teachermodified=false) {
1891         $submission = new stdClass();
1892         $submission->assignment   = $this->assignment->id;
1893         $submission->userid       = $userid;
1894         $submission->timecreated = time();
1895         // teachers should not be modifying modified date, except offline assignments
1896         if ($teachermodified) {
1897             $submission->timemodified = 0;
1898         } else {
1899             $submission->timemodified = $submission->timecreated;
1900         }
1901         $submission->numfiles     = 0;
1902         $submission->data1        = '';
1903         $submission->data2        = '';
1904         $submission->grade        = -1;
1905         $submission->submissioncomment      = '';
1906         $submission->format       = 0;
1907         $submission->teacher      = 0;
1908         $submission->timemarked   = 0;
1909         $submission->mailed       = 0;
1910         return $submission;
1911     }
1913     /**
1914      * Return all assignment submissions by ENROLLED students (even empty)
1915      *
1916      * @param string $sort optional field names for the ORDER BY in the sql query
1917      * @param string $dir optional specifying the sort direction, defaults to DESC
1918      * @return array The submission objects indexed by id
1919      */
1920     function get_submissions($sort='', $dir='DESC') {
1921         return assignment_get_all_submissions($this->assignment, $sort, $dir);
1922     }
1924     /**
1925      * Counts all complete (real) assignment submissions by enrolled students
1926      *
1927      * @param  int $groupid (optional) If nonzero then count is restricted to this group
1928      * @return int          The number of submissions
1929      */
1930     function count_real_submissions($groupid=0) {
1931         global $CFG;
1932         global $DB;
1934         // Grab the context assocated with our course module
1935         $context = context_module::instance($this->cm->id);
1937         // Get ids of users enrolled in the given course.
1938         list($enroledsql, $params) = get_enrolled_sql($context, 'mod/assignment:view', $groupid);
1939         $params['assignmentid'] = $this->cm->instance;
1941         // Get ids of users enrolled in the given course.
1942         return $DB->count_records_sql("SELECT COUNT('x')
1943                                          FROM {assignment_submissions} s
1944                                     LEFT JOIN {assignment} a ON a.id = s.assignment
1945                                    INNER JOIN ($enroledsql) u ON u.id = s.userid
1946                                         WHERE s.assignment = :assignmentid AND
1947                                               s.timemodified > 0", $params);
1948     }
1950     /**
1951      * Alerts teachers by email of new or changed assignments that need grading
1952      *
1953      * First checks whether the option to email teachers is set for this assignment.
1954      * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1955      * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1956      *
1957      * @global object
1958      * @global object
1959      * @param $submission object The submission that has changed
1960      * @return void
1961      */
1962     function email_teachers($submission) {
1963         global $CFG, $DB;
1965         if (empty($this->assignment->emailteachers)) {          // No need to do anything
1966             return;
1967         }
1969         $user = $DB->get_record('user', array('id'=>$submission->userid));
1971         if ($teachers = $this->get_graders($user)) {
1973             $strassignments = get_string('modulenameplural', 'assignment');
1974             $strassignment  = get_string('modulename', 'assignment');
1975             $strsubmitted  = get_string('submitted', 'assignment');
1977             foreach ($teachers as $teacher) {
1978                 $info = new stdClass();
1979                 $info->username = fullname($user, true);
1980                 $info->assignment = format_string($this->assignment->name,true);
1981                 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
1982                 $info->timeupdated = userdate($submission->timemodified, '%c', $teacher->timezone);
1984                 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1985                 $posttext = $this->email_teachers_text($info);
1986                 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
1988                 $eventdata = new stdClass();
1989                 $eventdata->modulename       = 'assignment';
1990                 $eventdata->userfrom         = $user;
1991                 $eventdata->userto           = $teacher;
1992                 $eventdata->subject          = $postsubject;
1993                 $eventdata->fullmessage      = $posttext;
1994                 $eventdata->fullmessageformat = FORMAT_PLAIN;
1995                 $eventdata->fullmessagehtml  = $posthtml;
1996                 $eventdata->smallmessage     = $postsubject;
1998                 $eventdata->name            = 'assignment_updates';
1999                 $eventdata->component       = 'mod_assignment';
2000                 $eventdata->notification    = 1;
2001                 $eventdata->contexturl      = $info->url;
2002                 $eventdata->contexturlname  = $info->assignment;
2004                 message_send($eventdata);
2005             }
2006         }
2007     }
2009     /**
2010      * Sends a file
2011      *
2012      * @param string $filearea
2013      * @param array $args
2014      * @param bool $forcedownload whether or not force download
2015      * @param array $options additional options affecting the file serving
2016      * @return bool
2017      */
2018     function send_file($filearea, $args, $forcedownload, array $options=array()) {
2019         debugging('plugin does not implement file sending', DEBUG_DEVELOPER);
2020         return false;
2021     }
2023     /**
2024      * Returns a list of teachers that should be grading given submission
2025      *
2026      * @param object $user
2027      * @return array
2028      */
2029     function get_graders($user) {
2030         global $DB;
2032         //potential graders
2033         list($enrolledsql, $params) = get_enrolled_sql($this->context, 'mod/assignment:grade', 0, true);
2034         $sql = "SELECT u.*
2035                   FROM {user} u
2036                   JOIN ($enrolledsql) je ON je.id = u.id";
2037         $potgraders = $DB->get_records_sql($sql, $params);
2039         $graders = array();
2040         if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) {   // Separate groups are being used
2041             if ($groups = groups_get_all_groups($this->course->id, $user->id)) {  // Try to find all groups
2042                 foreach ($groups as $group) {
2043                     foreach ($potgraders as $t) {
2044                         if ($t->id == $user->id) {
2045                             continue; // do not send self
2046                         }
2047                         if (groups_is_member($group->id, $t->id)) {
2048                             $graders[$t->id] = $t;
2049                         }
2050                     }
2051                 }
2052             } else {
2053                 // user not in group, try to find graders without group
2054                 foreach ($potgraders as $t) {
2055                     if ($t->id == $user->id) {
2056                         continue; // do not send self
2057                     }
2058                     if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
2059                         $graders[$t->id] = $t;
2060                     }
2061                 }
2062             }
2063         } else {
2064             foreach ($potgraders as $t) {
2065                 if ($t->id == $user->id) {
2066                     continue; // do not send self
2067                 }
2068                 $graders[$t->id] = $t;
2069             }
2070         }
2071         return $graders;
2072     }
2074     /**
2075      * Creates the text content for emails to teachers
2076      *
2077      * @param $info object The info used by the 'emailteachermail' language string
2078      * @return string
2079      */
2080     function email_teachers_text($info) {
2081         $posttext  = format_string($this->course->shortname, true, array('context' => $this->coursecontext)).' -> '.
2082                      $this->strassignments.' -> '.
2083                      format_string($this->assignment->name, true, array('context' => $this->context))."\n";
2084         $posttext .= '---------------------------------------------------------------------'."\n";
2085         $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
2086         $posttext .= "\n---------------------------------------------------------------------\n";
2087         return $posttext;
2088     }
2090      /**
2091      * Creates the html content for emails to teachers
2092      *
2093      * @param $info object The info used by the 'emailteachermailhtml' language string
2094      * @return string
2095      */
2096     function email_teachers_html($info) {
2097         global $CFG;
2098         $posthtml  = '<p><font face="sans-serif">'.
2099                      '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname, true, array('context' => $this->coursecontext)).'</a> ->'.
2100                      '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
2101                      '<a href="'.$CFG->wwwroot.'/mod/assignment/view.php?id='.$this->cm->id.'">'.format_string($this->assignment->name, true, array('context' => $this->context)).'</a></font></p>';
2102         $posthtml .= '<hr /><font face="sans-serif">';
2103         $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
2104         $posthtml .= '</font><hr />';
2105         return $posthtml;
2106     }
2108     /**
2109      * Produces a list of links to the files uploaded by a user
2110      *
2111      * @param $userid int optional id of the user. If 0 then $USER->id is used.
2112      * @param $return boolean optional defaults to false. If true the list is returned rather than printed
2113      * @return string optional
2114      */
2115     function print_user_files($userid=0, $return=false) {
2116         global $CFG, $USER, $OUTPUT;
2118         if (!$userid) {
2119             if (!isloggedin()) {
2120                 return '';
2121             }
2122             $userid = $USER->id;
2123         }
2125         $output = '';
2127         $submission = $this->get_submission($userid);
2128         if (!$submission) {
2129             return $output;
2130         }
2132         $fs = get_file_storage();
2133         $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false);
2134         if (!empty($files)) {
2135             require_once($CFG->dirroot . '/mod/assignment/locallib.php');
2136             if ($CFG->enableportfolios) {
2137                 require_once($CFG->libdir.'/portfoliolib.php');
2138                 $button = new portfolio_add_button();
2139             }
2140             foreach ($files as $file) {
2141                 $filename = $file->get_filename();
2142                 $mimetype = $file->get_mimetype();
2143                 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/mod_assignment/submission/'.$submission->id.'/'.$filename);
2144                 $output .= '<a href="'.$path.'" >'.$OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon')).s($filename).'</a>';
2145                 if ($CFG->enableportfolios && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
2146                     $button->set_callback_options('assignment_portfolio_caller',
2147                                                   array('id' => $this->cm->id, 'submissionid' => $submission->id, 'fileid' => $file->get_id()),
2148                                                   'mod_assignment');
2149                     $button->set_format_by_file($file);
2150                     $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
2151                 }
2153                 if ($CFG->enableplagiarism) {
2154                     require_once($CFG->libdir.'/plagiarismlib.php');
2155                     $output .= plagiarism_get_links(array('userid'=>$userid, 'file'=>$file, 'cmid'=>$this->cm->id, 'course'=>$this->course, 'assignment'=>$this->assignment));
2156                     $output .= '<br />';
2157                 }
2158             }
2159             if ($CFG->enableportfolios && count($files) > 1  && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
2160                 $button->set_callback_options('assignment_portfolio_caller',
2161                                               array('id' => $this->cm->id, 'submissionid' => $submission->id),
2162                                               'mod_assignment');
2163                 $output .= '<br />'  . $button->to_html(PORTFOLIO_ADD_TEXT_LINK);
2164             }
2165         }
2167         $output = '<div class="files">'.$output.'</div>';
2169         if ($return) {
2170             return $output;
2171         }
2172         echo $output;
2173     }
2175     /**
2176      * Count the files uploaded by a given user
2177      *
2178      * @param $itemid int The submission's id as the file's itemid.
2179      * @return int
2180      */
2181     function count_user_files($itemid) {
2182         $fs = get_file_storage();
2183         $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $itemid, "id", false);
2184         return count($files);
2185     }
2187     /**
2188      * Returns true if the student is allowed to submit
2189      *
2190      * Checks that the assignment has started and, if the option to prevent late
2191      * submissions is set, also checks that the assignment has not yet closed.
2192      * @return boolean
2193      */
2194     function isopen() {
2195         $time = time();
2196         if ($this->assignment->preventlate && $this->assignment->timedue) {
2197             return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
2198         } else {
2199             return ($this->assignment->timeavailable <= $time);
2200         }
2201     }
2204     /**
2205      * Return true if is set description is hidden till available date
2206      *
2207      * This is needed by calendar so that hidden descriptions do not
2208      * come up in upcoming events.
2209      *
2210      * Check that description is hidden till available date
2211      * By default return false
2212      * Assignments types should implement this method if needed
2213      * @return boolen
2214      */
2215     function description_is_hidden() {
2216         return false;
2217     }
2219     /**
2220      * Return an outline of the user's interaction with the assignment
2221      *
2222      * The default method prints the grade and timemodified
2223      * @param $grade object
2224      * @return object with properties ->info and ->time
2225      */
2226     function user_outline($grade) {
2228         $result = new stdClass();
2229         $result->info = get_string('grade').': '.$grade->str_long_grade;
2230         $result->time = $grade->dategraded;
2231         return $result;
2232     }
2234     /**
2235      * Print complete information about the user's interaction with the assignment
2236      *
2237      * @param $user object
2238      */
2239     function user_complete($user, $grade=null) {
2240         global $OUTPUT;
2242         if ($submission = $this->get_submission($user->id)) {
2244             $fs = get_file_storage();
2246             if ($files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false)) {
2247                 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
2248                 foreach ($files as $file) {
2249                     $countfiles .= "; ".$file->get_filename();
2250                 }
2251             }
2253             echo $OUTPUT->box_start();
2254             echo get_string("lastmodified").": ";
2255             echo userdate($submission->timemodified);
2256             echo $this->display_lateness($submission->timemodified);
2258             $this->print_user_files($user->id);
2260             echo '<br />';
2262             $this->view_feedback($submission);
2264             echo $OUTPUT->box_end();
2266         } else {
2267             if ($grade) {
2268                 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
2269                 if ($grade->str_feedback) {
2270                     echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
2271                 }
2272             }
2273             print_string("notsubmittedyet", "assignment");
2274         }
2275     }
2277     /**
2278      * Return a string indicating how late a submission is
2279      *
2280      * @param $timesubmitted int
2281      * @return string
2282      */
2283     function display_lateness($timesubmitted) {
2284         return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
2285     }
2287     /**
2288      * Empty method stub for all delete actions.
2289      */
2290     function delete() {
2291         //nothing by default
2292         redirect('view.php?id='.$this->cm->id);
2293     }
2295     /**
2296      * Empty custom feedback grading form.
2297      */
2298     function custom_feedbackform($submission, $return=false) {
2299         //nothing by default
2300         return '';
2301     }
2303     /**
2304      * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
2305      * for the course (see resource).
2306      *
2307      * Given a course_module object, this function returns any "extra" information that may be needed
2308      * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
2309      *
2310      * @param $coursemodule object The coursemodule object (record).
2311      * @return cached_cm_info Object used to customise appearance on course page
2312      */
2313     function get_coursemodule_info($coursemodule) {
2314         return null;
2315     }
2317     /**
2318      * Plugin cron method - do not use $this here, create new assignment instances if needed.
2319      * @return void
2320      */
2321     function cron() {
2322         //no plugin cron by default - override if needed
2323     }
2325     /**
2326      * Reset all submissions
2327      */
2328     function reset_userdata($data) {
2329         global $CFG, $DB;
2331         if (!$DB->count_records('assignment', array('course'=>$data->courseid, 'assignmenttype'=>$this->type))) {
2332             return array(); // no assignments of this type present
2333         }
2335         $componentstr = get_string('modulenameplural', 'assignment');
2336         $status = array();
2338         $typestr = get_string('type'.$this->type, 'assignment');
2339         // ugly hack to support pluggable assignment type titles...
2340         if($typestr === '[[type'.$this->type.']]'){
2341             $typestr = get_string('type'.$this->type, 'assignment_'.$this->type);
2342         }
2344         if (!empty($data->reset_assignment_submissions)) {
2345             $assignmentssql = "SELECT a.id
2346                                  FROM {assignment} a
2347                                 WHERE a.course=? AND a.assignmenttype=?";
2348             $params = array($data->courseid, $this->type);
2350             // now get rid of all submissions and responses
2351             $fs = get_file_storage();
2352             if ($assignments = $DB->get_records_sql($assignmentssql, $params)) {
2353                 foreach ($assignments as $assignmentid=>$unused) {
2354                     if (!$cm = get_coursemodule_from_instance('assignment', $assignmentid)) {
2355                         continue;
2356                     }
2357                     $context = context_module::instance($cm->id);
2358                     $fs->delete_area_files($context->id, 'mod_assignment', 'submission');
2359                     $fs->delete_area_files($context->id, 'mod_assignment', 'response');
2360                 }
2361             }
2363             $DB->delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)", $params);
2365             $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
2367             if (empty($data->reset_gradebook_grades)) {
2368                 // remove all grades from gradebook
2369                 assignment_reset_gradebook($data->courseid, $this->type);
2370             }
2371         }
2373         /// updating dates - shift may be negative too
2374         if ($data->timeshift) {
2375             shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
2376             $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
2377         }
2379         return $status;
2380     }
2383     function portfolio_exportable() {
2384         return false;
2385     }
2387     /**
2388      * base implementation for backing up subtype specific information
2389      * for one single module
2390      *
2391      * @param filehandle $bf file handle for xml file to write to
2392      * @param mixed $preferences the complete backup preference object
2393      *
2394      * @return boolean
2395      *
2396      * @static
2397      */
2398     static function backup_one_mod($bf, $preferences, $assignment) {
2399         return true;
2400     }
2402     /**
2403      * base implementation for backing up subtype specific information
2404      * for one single submission
2405      *
2406      * @param filehandle $bf file handle for xml file to write to
2407      * @param mixed $preferences the complete backup preference object
2408      * @param object $submission the assignment submission db record
2409      *
2410      * @return boolean
2411      *
2412      * @static
2413      */
2414     static function backup_one_submission($bf, $preferences, $assignment, $submission) {
2415         return true;
2416     }
2418     /**
2419      * base implementation for restoring subtype specific information
2420      * for one single module
2421      *
2422      * @param array  $info the array representing the xml
2423      * @param object $restore the restore preferences
2424      *
2425      * @return boolean
2426      *
2427      * @static
2428      */
2429     static function restore_one_mod($info, $restore, $assignment) {
2430         return true;
2431     }
2433     /**
2434      * base implementation for restoring subtype specific information
2435      * for one single submission
2436      *
2437      * @param object $submission the newly created submission
2438      * @param array  $info the array representing the xml
2439      * @param object $restore the restore preferences
2440      *
2441      * @return boolean
2442      *
2443      * @static
2444      */
2445     static function restore_one_submission($info, $restore, $assignment, $submission) {
2446         return true;
2447     }
2449 } ////// End of the assignment_base class
2452 class assignment_grading_form extends moodleform {
2453     /** @var stores the advaned grading instance (if used in grading) */
2454     private $advancegradinginstance;
2456     function definition() {
2457         global $OUTPUT;
2458         $mform =& $this->_form;
2460         if (isset($this->_customdata->advancedgradinginstance)) {
2461             $this->use_advanced_grading($this->_customdata->advancedgradinginstance);
2462         }
2464         $formattr = $mform->getAttributes();
2465         $formattr['id'] = 'submitform';
2466         $mform->setAttributes($formattr);
2467         // hidden params
2468         $mform->addElement('hidden', 'offset', ($this->_customdata->offset+1));
2469         $mform->setType('offset', PARAM_INT);
2470         $mform->addElement('hidden', 'userid', $this->_customdata->userid);
2471         $mform->setType('userid', PARAM_INT);
2472         $mform->addElement('hidden', 'nextid', $this->_customdata->nextid);
2473         $mform->setType('nextid', PARAM_INT);
2474         $mform->addElement('hidden', 'id', $this->_customdata->cm->id);
2475         $mform->setType('id', PARAM_INT);
2476         $mform->addElement('hidden', 'sesskey', sesskey());
2477         $mform->setType('sesskey', PARAM_ALPHANUM);
2478         $mform->addElement('hidden', 'mode', 'grade');
2479         $mform->setType('mode', PARAM_TEXT);
2480         $mform->addElement('hidden', 'menuindex', "0");
2481         $mform->setType('menuindex', PARAM_INT);
2482         $mform->addElement('hidden', 'saveuserid', "-1");
2483         $mform->setType('saveuserid', PARAM_INT);
2484         $mform->addElement('hidden', 'filter', "0");
2485         $mform->setType('filter', PARAM_INT);
2487         $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->user),
2488                                                 fullname($this->_customdata->user, true) . '<br/>' .
2489                                                 userdate($this->_customdata->submission->timemodified) .
2490                                                 $this->_customdata->lateness );
2492         $this->add_submission_content();
2493         $this->add_grades_section();
2495         $this->add_feedback_section();
2497         if ($this->_customdata->submission->timemarked) {
2498             $datestring = userdate($this->_customdata->submission->timemarked)."&nbsp; (".format_time(time() - $this->_customdata->submission->timemarked).")";
2499             $mform->addElement('header', 'Last Grade', get_string('lastgrade', 'assignment'));
2500             $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->teacher) ,
2501                                                     fullname($this->_customdata->teacher,true).
2502                                                     '<br/>'.$datestring);
2503         }
2504         // buttons
2505         $this->add_action_buttons();
2507     }
2509     /**
2510      * Gets or sets the instance for advanced grading
2511      *
2512      * @param gradingform_instance $gradinginstance
2513      */
2514     public function use_advanced_grading($gradinginstance = false) {
2515         if ($gradinginstance !== false) {
2516             $this->advancegradinginstance = $gradinginstance;
2517         }
2518         return $this->advancegradinginstance;
2519     }
2521     /**
2522      * Add the grades configuration section to the assignment configuration form
2523      */
2524     function add_grades_section() {
2525         global $CFG;
2526         $mform =& $this->_form;
2527         $attributes = array();
2528         if ($this->_customdata->gradingdisabled) {
2529             $attributes['disabled'] ='disabled';
2530         }
2532         $mform->addElement('header', 'Grades', get_string('grades', 'grades'));
2534         $grademenu = make_grades_menu($this->_customdata->assignment->grade);
2535         if ($gradinginstance = $this->use_advanced_grading()) {
2536             $gradinginstance->get_controller()->set_grade_range($grademenu);
2537             $gradingelement = $mform->addElement('grading', 'advancedgrading', get_string('grade').':', array('gradinginstance' => $gradinginstance));
2538             if ($this->_customdata->gradingdisabled) {
2539                 $gradingelement->freeze();
2540             } else {
2541                 $mform->addElement('hidden', 'advancedgradinginstanceid', $gradinginstance->get_id());
2542             }
2543         } else {
2544             // use simple direct grading
2545             $grademenu['-1'] = get_string('nograde');
2547             $mform->addElement('select', 'xgrade', get_string('grade').':', $grademenu, $attributes);
2548             $mform->setDefault('xgrade', $this->_customdata->submission->grade ); //@fixme some bug when element called 'grade' makes it break
2549             $mform->setType('xgrade', PARAM_INT);
2550         }
2552         if (!empty($this->_customdata->enableoutcomes)) {
2553             foreach($this->_customdata->grading_info->outcomes as $n=>$outcome) {
2554                 $options = make_grades_menu(-$outcome->scaleid);
2555                 if ($outcome->grades[$this->_customdata->submission->userid]->locked) {
2556                     $options[0] = get_string('nooutcome', 'grades');
2557                     $mform->addElement('static', 'outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->name.':',
2558                             $options[$outcome->grades[$this->_customdata->submission->userid]->grade]);
2559                 } else {
2560                     $options[''] = get_string('nooutcome', 'grades');
2561                     $attributes = array('id' => 'menuoutcome_'.$n );
2562                     $mform->addElement('select', 'outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->name.':', $options, $attributes );
2563                     $mform->setType('outcome_'.$n.'['.$this->_customdata->userid.']', PARAM_INT);
2564                     $mform->setDefault('outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->grades[$this->_customdata->submission->userid]->grade );
2565                 }
2566             }
2567         }
2568         $course_context = context_module::instance($this->_customdata->cm->id);
2569         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
2570             $grade = '<a href="'.$CFG->wwwroot.'/grade/report/grader/index.php?id='. $this->_customdata->courseid .'" >'.
2571                         $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade . '</a>';
2572         }else{
2573             $grade = $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade;
2574         }
2575         $mform->addElement('static', 'finalgrade', get_string('currentgrade', 'assignment').':' ,$grade);
2576         $mform->setType('finalgrade', PARAM_INT);
2577     }
2579     /**
2580      *
2581      * @global core_renderer $OUTPUT
2582      */
2583     function add_feedback_section() {
2584         global $OUTPUT;
2585         $mform =& $this->_form;
2586         $mform->addElement('header', 'Feed Back', get_string('feedback', 'grades'));
2588         if ($this->_customdata->gradingdisabled) {
2589             $mform->addElement('static', 'disabledfeedback', $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_feedback );
2590         } else {
2591             // visible elements
2593             $mform->addElement('editor', 'submissioncomment_editor', get_string('feedback', 'assignment').':', null, $this->get_editor_options() );
2594             $mform->setType('submissioncomment_editor', PARAM_RAW); // to be cleaned before display
2595             $mform->setDefault('submissioncomment_editor', $this->_customdata->submission->submissioncomment);
2596             //$mform->addRule('submissioncomment', get_string('required'), 'required', null, 'client');
2597             switch ($this->_customdata->assignment->assignmenttype) {
2598                 case 'upload' :
2599                 case 'uploadsingle' :
2600                     $mform->addElement('filemanager', 'files_filemanager', get_string('responsefiles', 'assignment'). ':', null, $this->_customdata->fileui_options);
2601                     break;
2602                 default :
2603                     break;
2604             }
2605             $mform->addElement('hidden', 'mailinfo_h', "0");
2606             $mform->setType('mailinfo_h', PARAM_INT);
2607             $mform->addElement('checkbox', 'mailinfo',get_string('enablenotification','assignment').
2608             $OUTPUT->help_icon('enablenotification', 'assignment') .':' );
2609             $mform->setType('mailinfo', PARAM_INT);
2610         }
2611     }
2613     function add_action_buttons($cancel = true, $submitlabel = NULL) {
2614         $mform =& $this->_form;
2615         //if there are more to be graded.
2616         if ($this->_customdata->nextid>0) {
2617             $buttonarray=array();
2618             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2619             //@todo: fix accessibility: javascript dependency not necessary
2620             $buttonarray[] = &$mform->createElement('submit', 'saveandnext', get_string('saveandnext'));
2621             $buttonarray[] = &$mform->createElement('submit', 'next', get_string('next'));
2622             $buttonarray[] = &$mform->createElement('cancel');
2623         } else {
2624             $buttonarray=array();
2625             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2626             $buttonarray[] = &$mform->createElement('cancel');
2627         }
2628         $mform->addGroup($buttonarray, 'grading_buttonar', '', array(' '), false);
2629         $mform->closeHeaderBefore('grading_buttonar');
2630         $mform->setType('grading_buttonar', PARAM_RAW);
2631     }
2633     function add_submission_content() {
2634         $mform =& $this->_form;
2635         $mform->addElement('header', 'Submission', get_string('submission', 'assignment'));
2636         $mform->addElement('static', '', '' , $this->_customdata->submission_content );
2637     }
2639     protected function get_editor_options() {
2640         $editoroptions = array();
2641         $editoroptions['component'] = 'mod_assignment';
2642         $editoroptions['filearea'] = 'feedback';
2643         $editoroptions['noclean'] = false;
2644         $editoroptions['maxfiles'] = 0; //TODO: no files for now, we need to first implement assignment_feedback area, integration with gradebook, files support in quickgrading, etc. (skodak)
2645         $editoroptions['maxbytes'] = $this->_customdata->maxbytes;
2646         $editoroptions['context'] = $this->_customdata->context;
2647         return $editoroptions;
2648     }
2650     public function set_data($data) {
2651         $editoroptions = $this->get_editor_options();
2652         if (!isset($data->text)) {
2653             $data->text = '';
2654         }
2655         if (!isset($data->format)) {
2656             $data->textformat = FORMAT_HTML;
2657         } else {
2658             $data->textformat = $data->format;
2659         }
2661         if (!empty($this->_customdata->submission->id)) {
2662             $itemid = $this->_customdata->submission->id;
2663         } else {
2664             $itemid = null;
2665         }
2667         switch ($this->_customdata->assignment->assignmenttype) {
2668                 case 'upload' :
2669                 case 'uploadsingle' :
2670                     $data = file_prepare_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2671                     break;
2672                 default :
2673                     break;
2674         }
2676         $data = file_prepare_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2677         return parent::set_data($data);
2678     }
2680     public function get_data() {
2681         $data = parent::get_data();
2683         if (!empty($this->_customdata->submission->id)) {
2684             $itemid = $this->_customdata->submission->id;
2685         } else {
2686             $itemid = null; //TODO: this is wrong, itemid MUST be known when saving files!! (skodak)
2687         }
2689         if ($data) {
2690             $editoroptions = $this->get_editor_options();
2691             switch ($this->_customdata->assignment->assignmenttype) {
2692                 case 'upload' :
2693                 case 'uploadsingle' :
2694                     $data = file_postupdate_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2695                     break;
2696                 default :
2697                     break;
2698             }
2699             $data = file_postupdate_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2700         }
2702         if ($this->use_advanced_grading() && !isset($data->advancedgrading)) {
2703             $data->advancedgrading = null;
2704         }
2706         return $data;
2707     }
2710 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
2712 /**
2713  * Deletes an assignment instance
2714  *
2715  * This is done by calling the delete_instance() method of the assignment type class
2716  */
2717 function assignment_delete_instance($id){
2718     global $CFG, $DB;
2720     if (! $assignment = $DB->get_record('assignment', array('id'=>$id))) {
2721         return false;
2722     }
2724     // fall back to base class if plugin missing
2725     $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2726     if (file_exists($classfile)) {
2727         require_once($classfile);
2728         $assignmentclass = "assignment_$assignment->assignmenttype";
2730     } else {
2731         debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
2732         $assignmentclass = "assignment_base";
2733     }
2735     $ass = new $assignmentclass();
2736     return $ass->delete_instance($assignment);
2740 /**
2741  * Updates an assignment instance
2742  *
2743  * This is done by calling the update_instance() method of the assignment type class
2744  */
2745 function assignment_update_instance($assignment){
2746     global $CFG;
2748     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_PLUGIN);
2750     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2751     $assignmentclass = "assignment_$assignment->assignmenttype";
2752     $ass = new $assignmentclass();
2753     return $ass->update_instance($assignment);
2757 /**
2758  * Adds an assignment instance
2759  *
2760  * This is done by calling the add_instance() method of the assignment type class
2761  *
2762  * @param stdClass $assignment
2763  * @param mod_assignment_mod_form $mform
2764  * @return int intance id
2765  */
2766 function assignment_add_instance($assignment, $mform = null) {
2767     global $CFG;
2769     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_PLUGIN);
2771     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2772     $assignmentclass = "assignment_$assignment->assignmenttype";
2773     $ass = new $assignmentclass();
2774     return $ass->add_instance($assignment);
2778 /**
2779  * Returns an outline of a user interaction with an assignment
2780  *
2781  * This is done by calling the user_outline() method of the assignment type class
2782  */
2783 function assignment_user_outline($course, $user, $mod, $assignment) {
2784     global $CFG;
2786     require_once("$CFG->libdir/gradelib.php");
2787     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2788     $assignmentclass = "assignment_$assignment->assignmenttype";
2789     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2790     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2791     if (!empty($grades->items[0]->grades)) {
2792         return $ass->user_outline(reset($grades->items[0]->grades));
2793     } else {
2794         return null;
2795     }
2798 /**
2799  * Prints the complete info about a user's interaction with an assignment
2800  *
2801  * This is done by calling the user_complete() method of the assignment type class
2802  */
2803 function assignment_user_complete($course, $user, $mod, $assignment) {
2804     global $CFG;
2806     require_once("$CFG->libdir/gradelib.php");
2807     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2808     $assignmentclass = "assignment_$assignment->assignmenttype";
2809     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2810     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2811     if (empty($grades->items[0]->grades)) {
2812         $grade = false;
2813     } else {
2814         $grade = reset($grades->items[0]->grades);
2815     }
2816     return $ass->user_complete($user, $grade);
2819 /**
2820  * Function to be run periodically according to the moodle cron
2821  *
2822  * Finds all assignment notifications that have yet to be mailed out, and mails them
2823  */
2824 function assignment_cron () {
2825     global $CFG, $USER, $DB;
2827     /// first execute all crons in plugins
2828     if ($plugins = get_plugin_list('assignment')) {
2829         foreach ($plugins as $plugin=>$dir) {
2830             require_once("$dir/assignment.class.php");
2831             $assignmentclass = "assignment_$plugin";
2832             $ass = new $assignmentclass();
2833             $ass->cron();
2834         }
2835     }
2837     /// Notices older than 1 day will not be mailed.  This is to avoid the problem where
2838     /// cron has not been running for a long time, and then suddenly people are flooded
2839     /// with mail from the past few weeks or months
2841     $timenow   = time();
2842     $endtime   = $timenow - $CFG->maxeditingtime;
2843     $starttime = $endtime - 24 * 3600;   /// One day earlier
2845     if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2847         $realuser = clone($USER);
2849         foreach ($submissions as $key => $submission) {
2850             $DB->set_field("assignment_submissions", "mailed", "1", array("id"=>$submission->id));
2851         }
2853         $timenow = time();
2855         foreach ($submissions as $submission) {
2857             echo "Processing assignment submission $submission->id\n";
2859             if (! $user = $DB->get_record("user", array("id"=>$submission->userid))) {
2860                 echo "Could not find user $user->id\n";
2861                 continue;
2862             }
2864             if (! $course = $DB->get_record("course", array("id"=>$submission->course))) {
2865                 echo "Could not find course $submission->course\n";
2866                 continue;
2867             }
2869             /// Override the language and timezone of the "current" user, so that
2870             /// mail is customised for the receiver.
2871             cron_setup_user($user, $course);
2873             $coursecontext = context_course::instance($submission->course);
2874             $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
2875             if (!is_enrolled($coursecontext, $user->id)) {
2876                 echo fullname($user)." not an active participant in " . $courseshortname . "\n";
2877                 continue;
2878             }
2880             if (! $teacher = $DB->get_record("user", array("id"=>$submission->teacher))) {
2881                 echo "Could not find teacher $submission->teacher\n";
2882                 continue;
2883             }
2885             if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2886                 echo "Could not find course module for assignment id $submission->assignment\n";
2887                 continue;
2888             }
2890             if (! $mod->visible) {    /// Hold mail notification for hidden assignments until later
2891                 continue;
2892             }
2894             $strassignments = get_string("modulenameplural", "assignment");
2895             $strassignment  = get_string("modulename", "assignment");
2897             $assignmentinfo = new stdClass();
2898             $assignmentinfo->teacher = fullname($teacher);
2899             $assignmentinfo->assignment = format_string($submission->name,true);
2900             $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2902             $postsubject = "$courseshortname: $strassignments: ".format_string($submission->name,true);
2903             $posttext  = "$courseshortname -> $strassignments -> ".format_string($submission->name,true)."\n";
2904             $posttext .= "---------------------------------------------------------------------\n";
2905             $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2906             $posttext .= "---------------------------------------------------------------------\n";
2908             if ($user->mailformat == 1) {  // HTML
2909                 $posthtml = "<p><font face=\"sans-serif\">".
2910                 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$courseshortname</a> ->".
2911                 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2912                 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2913                 $posthtml .= "<hr /><font face=\"sans-serif\">";
2914                 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2915                 $posthtml .= "</font><hr />";
2916             } else {
2917                 $posthtml = "";
2918             }
2920             $eventdata = new stdClass();
2921             $eventdata->modulename       = 'assignment';
2922             $eventdata->userfrom         = $teacher;
2923             $eventdata->userto           = $user;
2924             $eventdata->subject          = $postsubject;
2925             $eventdata->fullmessage      = $posttext;
2926             $eventdata->fullmessageformat = FORMAT_PLAIN;
2927             $eventdata->fullmessagehtml  = $posthtml;
2928             $eventdata->smallmessage     = get_string('assignmentmailsmall', 'assignment', $assignmentinfo);
2930             $eventdata->name            = 'assignment_updates';
2931             $eventdata->component       = 'mod_assignment';
2932             $eventdata->notification    = 1;
2933             $eventdata->contexturl      = $assignmentinfo->url;
2934             $eventdata->contexturlname  = $assignmentinfo->assignment;
2936             message_send($eventdata);
2937         }
2939         cron_setup_user();
2940     }
2942     return true;
2945 /**
2946  * Return grade for given user or all users.
2947  *
2948  * @param stdClass $assignment An assignment instance
2949  * @param int $userid Optional user id, 0 means all users
2950  * @return array An array of grades, false if none
2951  */
2952 function assignment_get_user_grades($assignment, $userid=0) {
2953     global $CFG, $DB;
2955     if ($userid) {
2956         $user = "AND u.id = :userid";
2957         $params = array('userid'=>$userid);
2958     } else {
2959         $user = "";
2960     }
2961     $params['aid'] = $assignment->id;
2963     $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2964                    s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2965               FROM {user} u, {assignment_submissions} s
2966              WHERE u.id = s.userid AND s.assignment = :aid
2967                    $user";
2969     return $DB->get_records_sql($sql, $params);
2972 /**
2973  * Update activity grades
2974  *
2975  * @category grade
2976  * @param stdClass $assignment Assignment instance
2977  * @param int $userid specific user only, 0 means all
2978  * @param bool $nullifnone Not used
2979  */
2980 function assignment_update_grades($assignment, $userid=0, $nullifnone=true) {
2981     global $CFG, $DB;
2982     require_once($CFG->libdir.'/gradelib.php');
2984     if ($assignment->grade == 0) {
2985         assignment_grade_item_update($assignment);
2987     } else if ($grades = assignment_get_user_grades($assignment, $userid)) {
2988         foreach($grades as $k=>$v) {
2989             if ($v->rawgrade == -1) {
2990                 $grades[$k]->rawgrade = null;
2991             }
2992         }
2993         assignment_grade_item_update($assignment, $grades);
2995     } else {
2996         assignment_grade_item_update($assignment);
2997     }
3000 /**
3001  * Update all grades in gradebook.
3002  */
3003 function assignment_upgrade_grades() {
3004     global $DB;
3006     $sql = "SELECT COUNT('x')
3007               FROM {assignment} a, {course_modules} cm, {modules} m
3008              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
3009     $count = $DB->count_records_sql($sql);
3011     $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
3012               FROM {assignment} a, {course_modules} cm, {modules} m
3013              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
3014     $rs = $DB->get_recordset_sql($sql);
3015     if ($rs->valid()) {
3016         // too much debug output
3017         $pbar = new progress_bar('assignmentupgradegrades', 500, true);
3018         $i=0;
3019         foreach ($rs as $assignment) {
3020             $i++;
3021             upgrade_set_timeout(60*5); // set up timeout, may also abort execution
3022             assignment_update_grades($assignment);
3023             $pbar->update($i, $count, "Updating Assignment grades ($i/$count).");
3024         }
3025         upgrade_set_timeout(); // reset to default timeout
3026     }
3027     $rs->close();
3030 /**
3031  * Create grade item for given assignment
3032  *
3033  * @category grade
3034  * @param stdClass $assignment An assignment instance with extra cmidnumber property
3035  * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
3036  * @return int 0 if ok, error code otherwise
3037  */
3038 function assignment_grade_item_update($assignment, $grades=NULL) {
3039     global $CFG;
3040     require_once($CFG->libdir.'/gradelib.php');
3042     if (!isset($assignment->courseid)) {
3043         $assignment->courseid = $assignment->course;
3044     }
3046     $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
3048     if ($assignment->grade > 0) {
3049         $params['gradetype'] = GRADE_TYPE_VALUE;
3050         $params['grademax']  = $assignment->grade;
3051         $params['grademin']  = 0;
3053     } else if ($assignment->grade < 0) {
3054         $params['gradetype'] = GRADE_TYPE_SCALE;
3055         $params['scaleid']   = -$assignment->grade;
3057     } else {
3058         $params['gradetype'] = GRADE_TYPE_TEXT; // allow text comments only
3059     }
3061     if ($grades  === 'reset') {
3062         $params['reset'] = true;
3063         $grades = NULL;
3064     }
3066     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades, $params);
3069 /**
3070  * Delete grade item for given assignment
3071  *
3072  * @category grade
3073  * @param object $assignment object
3074  * @return object assignment
3075  */
3076 function assignment_grade_item_delete($assignment) {
3077     global $CFG;
3078     require_once($CFG->libdir.'/gradelib.php');
3080     if (!isset($assignment->courseid)) {
3081         $assignment->courseid = $assignment->course;
3082     }
3084     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
3088 /**
3089  * Serves assignment submissions and other files.
3090  *
3091  * @package  mod_assignment
3092  * @category files
3093  * @param stdClass $course course object
3094  * @param stdClass $cm course module object
3095  * @param stdClass $context context object
3096  * @param string $filearea file area
3097  * @param array $args extra arguments
3098  * @param bool $forcedownload whether or not force download
3099  * @param array $options additional options affecting the file serving
3100  * @return bool false if file not found, does not return if found - just send the file
3101  */
3102 function assignment_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
3103     global $CFG, $DB;
3105     if ($context->contextlevel != CONTEXT_MODULE) {
3106         return false;
3107     }
3109     require_login($course, false, $cm);
3111     if (!$assignment = $DB->get_record('assignment', array('id'=>$cm->instance))) {
3112         return false;
3113     }
3115     require_once($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
3116     $assignmentclass = 'assignment_'.$assignment->assignmenttype;
3117     $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm, $course);
3119     return $assignmentinstance->send_file($filearea, $args, $forcedownload, $options);
3121 /**
3122  * Checks if a scale is being used by an assignment
3123  *
3124  * This is used by the backup code to decide whether to back up a scale
3125  * @param $assignmentid int
3126  * @param $scaleid int
3127  * @return boolean True if the scale is used by the assignment
3128  */
3129 function assignment_scale_used($assignmentid, $scaleid) {
3130     global $DB;
3132     $return = false;
3134     $rec = $DB->get_record('assignment', array('id'=>$assignmentid,'grade'=>-$scaleid));
3136     if (!empty($rec) && !empty($scaleid)) {
3137         $return = true;
3138     }
3140     return $return;
3143 /**
3144  * Checks if scale is being used by any instance of assignment
3145  *
3146  * This is used to find out if scale used anywhere
3147  * @param $scaleid int
3148  * @return boolean True if the scale is used by any assignment
3149  */
3150 function assignment_scale_used_anywhere($scaleid) {
3151     global $DB;
3153     if ($scaleid and $DB->record_exists('assignment', array('grade'=>-$scaleid))) {
3154         return true;
3155     } else {
3156         return false;
3157     }
3160 /**
3161  * Make sure up-to-date events are created for all assignment instances
3162  *
3163  * This standard function will check all instances of this module
3164  * and make sure there are up-to-date events created for each of them.
3165  * If courseid = 0, then every assignment event in the site is checked, else
3166  * only assignment events belonging to the course specified are checked.
3167  * This function is used, in its new format, by restore_refresh_events()
3168  *
3169  * @param $courseid int optional If zero then all assignments for all courses are covered
3170  * @return boolean Always returns true
3171  */
3172 function assignment_refresh_events($courseid = 0) {
3173     global $DB;
3175     if ($courseid == 0) {
3176         if (! $assignments = $DB->get_records("assignment")) {
3177             return true;
3178         }
3179     } else {
3180         if (! $assignments = $DB->get_records("assignment", array("course"=>$courseid))) {
3181             return true;
3182         }
3183     }
3184     $moduleid = $DB->get_field('modules', 'id', array('name'=>'assignment'));
3186     foreach ($assignments as $assignment) {
3187         $cm = get_coursemodule_from_id('assignment', $assignment->id);
3188         $event = new stdClass();
3189         $event->name        = $assignment->name;
3190         $event->description = format_module_intro('assignment', $assignment, $cm->id);
3191         $event->timestart   = $assignment->timedue;
3193         if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
3194             update_event($event);
3196         } else {
3197             $event->courseid    = $assignment->course;
3198             $event->groupid     = 0;
3199             $event->userid      = 0;
3200             $event->modulename  = 'assignment';
3201             $event->instance    = $assignment->id;
3202             $event->eventtype   = 'due';
3203             $event->timeduration = 0;
3204             $event->visible     = $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$assignment->id));
3205             add_event($event);
3206         }
3208     }
3209     return true;
3212 /**
3213  * Print recent activity from all assignments in a given course
3214  *
3215  * This is used by the recent activity block
3216  */
3217 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
3218     global $CFG, $USER, $DB, $OUTPUT;
3220     // do not use log table if possible, it may be huge
3222     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
3223                                                      u.firstname, u.lastname, u.email, u.picture
3224                                                 FROM {assignment_submissions} asb
3225                                                      JOIN {assignment} a      ON a.id = asb.assignment
3226                                                      JOIN {course_modules} cm ON cm.instance = a.id
3227                                                      JOIN {modules} md        ON md.id = cm.module
3228                                                      JOIN {user} u            ON u.id = asb.userid
3229                                                WHERE asb.timemodified > ? AND
3230                                                      a.course = ? AND
3231                                                      md.name = 'assignment'
3232                                             ORDER BY asb.timemodified ASC", array($timestart, $course->id))) {
3233          return false;
3234     }
3236     $modinfo = get_fast_modinfo($course); // reference needed because we might load the groups
3237     $show    = array();
3238     $grader  = array();
3240     foreach($submissions as $submission) {
3241         if (!array_key_exists($submission->cmid, $modinfo->cms)) {
3242             continue;
3243         }
3244         $cm = $modinfo->cms[$submission->cmid];
3245         if (!$cm->uservisible) {
3246             continue;
3247         }
3248         if ($submission->userid == $USER->id) {
3249             $show[] = $submission;
3250             continue;
3251         }
3253         // the act of sumbitting of assignment may be considered private - only graders will see it if specified
3254         if (empty($CFG->assignment_showrecentsubmissions)) {
3255             if (!array_key_exists($cm->id, $grader)) {
3256                 $grader[$cm->id] = has_capability('moodle/grade:viewall', context_module::instance($cm->id));
3257             }
3258             if (!$grader[$cm->id]) {
3259                 continue;
3260             }
3261         }
3263         $groupmode = groups_get_activity_groupmode($cm, $course);
3265         if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', context_module::instance($cm->id))) {
3266             if (isguestuser()) {
3267                 // shortcut - guest user does not belong into any group
3268                 continue;
3269             }
3271             if (is_null($modinfo->groups)) {
3272                 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
3273             }
3275             // this will be slow - show only users that share group with me in this cm
3276             if (empty($modinfo->groups[$cm->id])) {
3277                 continue;
3278             }
3279             $usersgroups =  groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
3280             if (is_array($usersgroups)) {
3281                 $usersgroups = array_keys($usersgroups);
3282                 $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
3283                 if (empty($intersect)) {
3284                     continue;
3285                 }
3286             }
3287         }
3288         $show[] = $submission;
3289     }
3291     if (empty($show)) {
3292         return false;
3293     }
3295     echo $OUTPUT->heading(get_string('newsubmissions', 'assignment').':', 3);
3297     foreach ($show as $submission) {
3298         $cm = $modinfo->cms[$submission->cmid];
3299         $link = $CFG->wwwroot.'/mod/assignment/view.php?id='.$cm->id;
3300         print_recent_activity_note($submission->timemodified, $submission, $cm->name, $link, false, $viewfullnames);
3301     }
3303     return true;
3307 /**
3308  * Returns all assignments since a given time in specified forum.
3309  */
3310 function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0)  {
3311     global $CFG, $COURSE, $USER, $DB;
3313     if ($COURSE->id == $courseid) {