3198609b0ba4930330da5376cee8472f6eb16b9e
[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');
1401         // Start working -- this is necessary as soon as the niceties are over
1402         $table->setup();
1404         /// Construct the SQL
1405         list($where, $params) = $table->get_sql_where();
1406         if ($where) {
1407             $where .= ' AND ';
1408         }
1410         if ($filter == self::FILTER_SUBMITTED) {
1411            $where .= 's.timemodified > 0 AND ';
1412         } else if($filter == self::FILTER_REQUIRE_GRADING) {
1413             $where = '';
1414             if ($assignment->assignmenttype != 'offline') {
1415                $where .= 's.timemarked < s.timemodified AND ';
1416             }
1417         }
1419         if ($sort = $table->get_sql_sort()) {
1420             $sort = ' ORDER BY '.$sort;
1421         }
1423         $ufields = user_picture::fields('u', $extrafields);
1424         if (!empty($users)) {
1425             $select = "SELECT $ufields,
1426                               s.id AS submissionid, s.grade, s.submissioncomment,
1427                               s.timemodified, s.timemarked,
1428                               CASE WHEN s.timemarked > 0 AND s.timemarked >= s.timemodified THEN 1
1429                                    ELSE 0 END AS status ";
1431             $sql = 'FROM {user} u '.
1432                    'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1433                     AND s.assignment = '.$this->assignment->id.' '.
1434                    'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1436             $ausers = $DB->get_records_sql($select.$sql.$sort, $params, $table->get_page_start(), $table->get_page_size());
1438             $table->pagesize($perpage, count($users));
1440             ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1441             $offset = $page * $perpage;
1442             $strupdate = get_string('update');
1443             $strgrade  = get_string('grade');
1444             $strview  = get_string('view');
1445             $grademenu = make_grades_menu($this->assignment->grade);
1447             if ($ausers !== false) {
1448                 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
1449                 $endposition = $offset + $perpage;
1450                 $currentposition = 0;
1451                 foreach ($ausers as $auser) {
1452                     if ($currentposition == $offset && $offset < $endposition) {
1453                         $rowclass = null;
1454                         $final_grade = $grading_info->items[0]->grades[$auser->id];
1455                         $grademax = $grading_info->items[0]->grademax;
1456                         $final_grade->formatted_grade = round($final_grade->grade,2) .' / ' . round($grademax,2);
1457                         $locked_overridden = 'locked';
1458                         if ($final_grade->overridden) {
1459                             $locked_overridden = 'overridden';
1460                         }
1462                         // TODO add here code if advanced grading grade must be reviewed => $auser->status=0
1464                         $picture = $OUTPUT->user_picture($auser);
1466                         if (empty($auser->submissionid)) {
1467                             $auser->grade = -1; //no submission yet
1468                         }
1470                         if (!empty($auser->submissionid)) {
1471                             $hassubmission = true;
1472                         ///Prints student answer and student modified date
1473                         ///attach file or print link to student answer, depending on the type of the assignment.
1474                         ///Refer to print_student_answer in inherited classes.
1475                             if ($auser->timemodified > 0) {
1476                                 $studentmodifiedcontent = $this->print_student_answer($auser->id)
1477                                         . userdate($auser->timemodified);
1478                                 if ($assignment->timedue && $auser->timemodified > $assignment->timedue && $this->supports_lateness()) {
1479                                     $studentmodifiedcontent .= $this->display_lateness($auser->timemodified);
1480                                     $rowclass = 'late';
1481                                 }
1482                             } else {
1483                                 $studentmodifiedcontent = '&nbsp;';
1484                             }
1485                             $studentmodified = html_writer::tag('div', $studentmodifiedcontent, array('id' => 'ts' . $auser->id));
1486                         ///Print grade, dropdown or text
1487                             if ($auser->timemarked > 0) {
1488                                 $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
1490                                 if ($final_grade->locked or $final_grade->overridden) {
1491                                     $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1492                                 } else if ($quickgrade) {
1493                                     $attributes = array();
1494                                     $attributes['tabindex'] = $tabindex++;
1495                                     $menu = html_writer::label(get_string('assignment:grade', 'assignment'), 'menumenu'. $auser->id, false, array('class' => 'accesshide'));
1496                                     $menu .= html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1497                                     $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
1498                                 } else {
1499                                     $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1500                                 }
1502                             } else {
1503                                 $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1504                                 if ($final_grade->locked or $final_grade->overridden) {
1505                                     $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1506                                 } else if ($quickgrade) {
1507                                     $attributes = array();
1508                                     $attributes['tabindex'] = $tabindex++;
1509                                     $menu = html_writer::label(get_string('assignment:grade', 'assignment'), 'menumenu'. $auser->id, false, array('class' => 'accesshide'));
1510                                     $menu .= html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1511                                     $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1512                                 } else {
1513                                     $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1514                                 }
1515                             }
1516                         ///Print Comment
1517                             if ($final_grade->locked or $final_grade->overridden) {
1518                                 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';
1520                             } else if ($quickgrade) {
1521                                 $comment = '<div id="com'.$auser->id.'">'
1522                                          . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1523                                          . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1524                             } else {
1525                                 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
1526                             }
1527                         } else {
1528                             $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1529                             $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1530                             $status          = '<div id="st'.$auser->id.'">&nbsp;</div>';
1532                             if ($final_grade->locked or $final_grade->overridden) {
1533                                 $grade = '<div id="g'.$auser->id.'">'.$final_grade->formatted_grade . '</div>';
1534                                 $hassubmission = true;
1535                             } else if ($quickgrade) {   // allow editing
1536                                 $attributes = array();
1537                                 $attributes['tabindex'] = $tabindex++;
1538                                 $menu = html_writer::label(get_string('assignment:grade', 'assignment'), 'menumenu'. $auser->id, false, array('class' => 'accesshide'));
1539                                 $menu .= html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1540                                 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1541                                 $hassubmission = true;
1542                             } else {
1543                                 $grade = '<div id="g'.$auser->id.'">-</div>';
1544                             }
1546                             if ($final_grade->locked or $final_grade->overridden) {
1547                                 $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
1548                             } else if ($quickgrade) {
1549                                 $comment = '<div id="com'.$auser->id.'">'
1550                                          . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1551                                          . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1552                             } else {
1553                                 $comment = '<div id="com'.$auser->id.'">&nbsp;</div>';
1554                             }
1555                         }
1557                         if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
1558                             $auser->status = 0;
1559                         } else {
1560                             $auser->status = 1;
1561                         }
1563                         $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
1564                         if ($final_grade->locked or $final_grade->overridden) {
1565                             $buttontext = $strview;
1566                         }
1568                         ///No more buttons, we use popups ;-).
1569                         $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1570                                    . '&amp;userid='.$auser->id.'&amp;mode=single'.'&amp;filter='.$filter.'&amp;offset='.$offset++;
1572                         $button = $OUTPUT->action_link($popup_url, $buttontext);
1574                         $status  = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
1576                         $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';
1578                         $outcomes = '';
1580                         if ($uses_outcomes) {
1582                             foreach($grading_info->outcomes as $n=>$outcome) {
1583                                 $outcomes .= '<div class="outcome"><label for="'. 'outcome_'.$n.'_'.$auser->id .'">'.$outcome->name.'</label>';
1584                                 $options = make_grades_menu(-$outcome->scaleid);
1586                                 if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
1587                                     $options[0] = get_string('nooutcome', 'grades');
1588                                     $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
1589                                 } else {
1590                                     $attributes = array();
1591                                     $attributes['tabindex'] = $tabindex++;
1592                                     $attributes['id'] = 'outcome_'.$n.'_'.$auser->id;
1593                                     $outcomes .= ' '.html_writer::select($options, 'outcome_'.$n.'['.$auser->id.']', $outcome->grades[$auser->id]->grade, array(0=>get_string('nooutcome', 'grades')), $attributes);
1594                                 }
1595                                 $outcomes .= '</div>';
1596                             }
1597                         }
1599                         $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>';
1600                         $extradata = array();
1601                         foreach ($extrafields as $field) {
1602                             $extradata[] = $auser->{$field};
1603                         }
1604                         $row = array_merge(array($picture, $userlink), $extradata,
1605                                 array($grade, $comment, $studentmodified, $teachermodified,
1606                                 $status, $finalgrade));
1607                         if ($uses_outcomes) {
1608                             $row[] = $outcomes;
1609                         }
1610                         $table->add_data($row, $rowclass);
1611                     }
1612                     $currentposition++;
1613                 }
1614                 if ($hassubmission && method_exists($this, 'download_submissions')) {
1615                     echo html_writer::start_tag('div', array('class' => 'mod-assignment-download-link'));
1616                     echo html_writer::link(new moodle_url('/mod/assignment/submissions.php', array('id' => $this->cm->id, 'download' => 'zip')), get_string('downloadall', 'assignment'));
1617                     echo html_writer::end_tag('div');
1618                 }
1619                 $table->print_html();  /// Print the whole table
1620             } else {
1621                 if ($filter == self::FILTER_SUBMITTED) {
1622                     echo html_writer::tag('div', get_string('nosubmisson', 'assignment'), array('class'=>'nosubmisson'));
1623                 } else if ($filter == self::FILTER_REQUIRE_GRADING) {
1624                     echo html_writer::tag('div', get_string('norequiregrading', 'assignment'), array('class'=>'norequiregrading'));
1625                 }
1626             }
1627         }
1629         /// Print quickgrade form around the table
1630         if ($quickgrade && $table->started_output && !empty($users)){
1631             $mailinfopref = false;
1632             if (get_user_preferences('assignment_mailinfo', 1)) {
1633                 $mailinfopref = true;
1634             }
1635             $emailnotification =  html_writer::checkbox('mailinfo', 1, $mailinfopref, get_string('enablenotification','assignment'));
1637             $emailnotification .= $OUTPUT->help_icon('enablenotification', 'assignment');
1638             echo html_writer::tag('div', $emailnotification, array('class'=>'emailnotification'));
1640             $savefeedback = html_writer::empty_tag('input', array('type'=>'submit', 'name'=>'fastg', 'value'=>get_string('saveallfeedback', 'assignment')));
1641             echo html_writer::tag('div', $savefeedback, array('class'=>'fastgbutton'));
1643             echo html_writer::end_tag('form');
1644         } else if ($quickgrade) {
1645             echo html_writer::end_tag('form');
1646         }
1648         echo '</div>';
1649         /// End of fast grading form
1651         /// Mini form for setting user preference
1653         $formaction = new moodle_url('/mod/assignment/submissions.php', array('id'=>$this->cm->id));
1654         $mform = new MoodleQuickForm('optionspref', 'post', $formaction, '', array('class'=>'optionspref'));
1656         $mform->addElement('hidden', 'updatepref');
1657         $mform->setDefault('updatepref', 1);
1658         $mform->addElement('header', 'qgprefs', get_string('optionalsettings', 'assignment'));
1659         $mform->addElement('select', 'filter', get_string('show'),  $filters);
1661         $mform->setDefault('filter', $filter);
1663         $mform->addElement('text', 'perpage', get_string('pagesize', 'assignment'), array('size'=>1));
1664         $mform->setDefault('perpage', $perpage);
1666         if ($this->quickgrade_mode_allowed()) {
1667             $mform->addElement('checkbox', 'quickgrade', get_string('quickgrade','assignment'));
1668             $mform->setDefault('quickgrade', $quickgrade);
1669             $mform->addHelpButton('quickgrade', 'quickgrade', 'assignment');
1670         }
1672         $mform->addElement('submit', 'savepreferences', get_string('savepreferences'));
1674         $mform->display();
1676         echo $OUTPUT->footer();
1677     }
1679     /**
1680      * If the form was cancelled ('Cancel' or 'Next' was pressed), call cancel method
1681      * from advanced grading (if applicable) and returns true
1682      * If the form was submitted, validates it and returns false if validation did not pass.
1683      * If validation passes, preprocess advanced grading (if applicable) and returns true.
1684      *
1685      * Note to the developers: This is NOT the correct way to implement advanced grading
1686      * in grading form. The assignment grading was written long time ago and unfortunately
1687      * does not fully use the mforms. Usually function is_validated() is called to
1688      * validate the form and get_data() is called to get the data from the form.
1689      *
1690      * Here we have to push the calculated grade to $_POST['xgrade'] because further processing
1691      * of the form gets the data not from form->get_data(), but from $_POST (using statement
1692      * like  $feedback = data_submitted() )
1693      */
1694     protected function validate_and_preprocess_feedback() {
1695         global $USER, $CFG;
1696         require_once($CFG->libdir.'/gradelib.php');
1697         if (!($feedback = data_submitted()) || !isset($feedback->userid) || !isset($feedback->offset)) {
1698             return true;      // No incoming data, nothing to validate
1699         }
1700         $userid = required_param('userid', PARAM_INT);
1701         $offset = required_param('offset', PARAM_INT);
1702         $gradinginfo = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($userid));
1703         $gradingdisabled = $gradinginfo->items[0]->grades[$userid]->locked || $gradinginfo->items[0]->grades[$userid]->overridden;
1704         if ($gradingdisabled) {
1705             return true;
1706         }
1707         $submissiondata = $this->display_submission($offset, $userid, false);
1708         $mform = $submissiondata->mform;
1709         $gradinginstance = $mform->use_advanced_grading();
1710         if (optional_param('cancel', false, PARAM_BOOL) || optional_param('next', false, PARAM_BOOL)) {
1711             // form was cancelled
1712             if ($gradinginstance) {
1713                 $gradinginstance->cancel();
1714             }
1715         } else if ($mform->is_submitted()) {
1716             // form was submitted (= a submit button other than 'cancel' or 'next' has been clicked)
1717             if (!$mform->is_validated()) {
1718                 return false;
1719             }
1720             // preprocess advanced grading here
1721             if ($gradinginstance) {
1722                 $data = $mform->get_data();
1723                 // create submission if it did not exist yet because we need submission->id for storing the grading instance
1724                 $submission = $this->get_submission($userid, true);
1725                 $_POST['xgrade'] = $gradinginstance->submit_and_get_grade($data->advancedgrading, $submission->id);
1726             }
1727         }
1728         return true;
1729     }
1731     /**
1732      *  Process teacher feedback submission
1733      *
1734      * This is called by submissions() when a grading even has taken place.
1735      * It gets its data from the submitted form.
1736      *
1737      * @global object
1738      * @global object
1739      * @global object
1740      * @return object|bool The updated submission object or false
1741      */
1742     function process_feedback($formdata=null) {
1743         global $CFG, $USER, $DB;
1744         require_once($CFG->libdir.'/gradelib.php');
1746         if (!$feedback = data_submitted() or !confirm_sesskey()) {      // No incoming data?
1747             return false;
1748         }
1750         ///For save and next, we need to know the userid to save, and the userid to go
1751         ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1752         ///as the userid to store
1753         if ((int)$feedback->saveuserid !== -1){
1754             $feedback->userid = $feedback->saveuserid;
1755         }
1757         if (!empty($feedback->cancel)) {          // User hit cancel button
1758             return false;
1759         }
1761         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);
1763         // store outcomes if needed
1764         $this->process_outcomes($feedback->userid);
1766         $submission = $this->get_submission($feedback->userid, true);  // Get or make one
1768         if (!($grading_info->items[0]->grades[$feedback->userid]->locked ||
1769             $grading_info->items[0]->grades[$feedback->userid]->overridden) ) {
1771             $submission->grade      = $feedback->xgrade;
1772             $submission->submissioncomment    = $feedback->submissioncomment_editor['text'];
1773             $submission->teacher    = $USER->id;
1774             $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1775             if (!$mailinfo) {
1776                 $submission->mailed = 1;       // treat as already mailed
1777             } else {
1778                 $submission->mailed = 0;       // Make sure mail goes out (again, even)
1779             }
1780             $submission->timemarked = time();
1782             unset($submission->data1);  // Don't need to update this.
1783             unset($submission->data2);  // Don't need to update this.
1785             if (empty($submission->timemodified)) {   // eg for offline assignments
1786                 // $submission->timemodified = time();
1787             }
1789             $DB->update_record('assignment_submissions', $submission);
1791             // triger grade event
1792             $this->update_grade($submission);
1794             add_to_log($this->course->id, 'assignment', 'update grades',
1795                        'submissions.php?id='.$this->cm->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
1796              if (!is_null($formdata)) {
1797                     if ($this->type == 'upload' || $this->type == 'uploadsingle') {
1798                         $mformdata = $formdata->mform->get_data();
1799                         $mformdata = file_postupdate_standard_filemanager($mformdata, 'files', $formdata->fileui_options, $this->context, 'mod_assignment', 'response', $submission->id);
1800                     }
1801              }
1802         }
1804         return $submission;
1806     }
1808     function process_outcomes($userid) {
1809         global $CFG, $USER;
1811         if (empty($CFG->enableoutcomes)) {
1812             return;
1813         }
1815         require_once($CFG->libdir.'/gradelib.php');
1817         if (!$formdata = data_submitted() or !confirm_sesskey()) {
1818             return;
1819         }
1821         $data = array();
1822         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
1824         if (!empty($grading_info->outcomes)) {
1825             foreach($grading_info->outcomes as $n=>$old) {
1826                 $name = 'outcome_'.$n;
1827                 if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
1828                     $data[$n] = $formdata->{$name}[$userid];
1829                 }
1830             }
1831         }
1832         if (count($data) > 0) {
1833             grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1834         }
1836     }
1838     /**
1839      * Load the submission object for a particular user
1840      *
1841      * @global object
1842      * @global object
1843      * @param int $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1844      * @param bool $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1845      * @param bool $teachermodified student submission set if false
1846      * @return object|bool The submission or false (if $createnew is false and there is no existing submission).
1847      */
1848     function get_submission($userid=0, $createnew=false, $teachermodified=false) {
1849         global $USER, $DB;
1851         if (empty($userid)) {
1852             $userid = $USER->id;
1853         }
1855         $submission = $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1857         if ($submission) {
1858             return $submission;
1859         } else if (!$createnew) {
1860             return false;
1861         }
1862         $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
1863         $DB->insert_record("assignment_submissions", $newsubmission);
1865         return $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1866     }
1868     /**
1869      * Check the given submission is complete. Preliminary rows are often created in the assignment_submissions
1870      * table before a submission actually takes place. This function checks to see if the given submission has actually
1871      * been submitted.
1872      *
1873      * @param  stdClass $submission The submission we want to check for completion
1874      * @return bool                 Indicates if the submission was found to be complete
1875      */
1876     public function is_submitted_with_required_data($submission) {
1877         return $submission->timemodified;
1878     }
1880     /**
1881      * Instantiates a new submission object for a given user
1882      *
1883      * Sets the assignment, userid and times, everything else is set to default values.
1884      *
1885      * @param int $userid The userid for which we want a submission object
1886      * @param bool $teachermodified student submission set if false
1887      * @return object The submission
1888      */
1889     function prepare_new_submission($userid, $teachermodified=false) {
1890         $submission = new stdClass();
1891         $submission->assignment   = $this->assignment->id;
1892         $submission->userid       = $userid;
1893         $submission->timecreated = time();
1894         // teachers should not be modifying modified date, except offline assignments
1895         if ($teachermodified) {
1896             $submission->timemodified = 0;
1897         } else {
1898             $submission->timemodified = $submission->timecreated;
1899         }
1900         $submission->numfiles     = 0;
1901         $submission->data1        = '';
1902         $submission->data2        = '';
1903         $submission->grade        = -1;
1904         $submission->submissioncomment      = '';
1905         $submission->format       = 0;
1906         $submission->teacher      = 0;
1907         $submission->timemarked   = 0;
1908         $submission->mailed       = 0;
1909         return $submission;
1910     }
1912     /**
1913      * Return all assignment submissions by ENROLLED students (even empty)
1914      *
1915      * @param string $sort optional field names for the ORDER BY in the sql query
1916      * @param string $dir optional specifying the sort direction, defaults to DESC
1917      * @return array The submission objects indexed by id
1918      */
1919     function get_submissions($sort='', $dir='DESC') {
1920         return assignment_get_all_submissions($this->assignment, $sort, $dir);
1921     }
1923     /**
1924      * Counts all complete (real) assignment submissions by enrolled students
1925      *
1926      * @param  int $groupid (optional) If nonzero then count is restricted to this group
1927      * @return int          The number of submissions
1928      */
1929     function count_real_submissions($groupid=0) {
1930         global $CFG;
1931         global $DB;
1933         // Grab the context assocated with our course module
1934         $context = context_module::instance($this->cm->id);
1936         // Get ids of users enrolled in the given course.
1937         list($enroledsql, $params) = get_enrolled_sql($context, 'mod/assignment:view', $groupid);
1938         $params['assignmentid'] = $this->cm->instance;
1940         // Get ids of users enrolled in the given course.
1941         return $DB->count_records_sql("SELECT COUNT('x')
1942                                          FROM {assignment_submissions} s
1943                                     LEFT JOIN {assignment} a ON a.id = s.assignment
1944                                    INNER JOIN ($enroledsql) u ON u.id = s.userid
1945                                         WHERE s.assignment = :assignmentid AND
1946                                               s.timemodified > 0", $params);
1947     }
1949     /**
1950      * Alerts teachers by email of new or changed assignments that need grading
1951      *
1952      * First checks whether the option to email teachers is set for this assignment.
1953      * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1954      * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1955      *
1956      * @global object
1957      * @global object
1958      * @param $submission object The submission that has changed
1959      * @return void
1960      */
1961     function email_teachers($submission) {
1962         global $CFG, $DB;
1964         if (empty($this->assignment->emailteachers)) {          // No need to do anything
1965             return;
1966         }
1968         $user = $DB->get_record('user', array('id'=>$submission->userid));
1970         if ($teachers = $this->get_graders($user)) {
1972             $strassignments = get_string('modulenameplural', 'assignment');
1973             $strassignment  = get_string('modulename', 'assignment');
1974             $strsubmitted  = get_string('submitted', 'assignment');
1976             foreach ($teachers as $teacher) {
1977                 $info = new stdClass();
1978                 $info->username = fullname($user, true);
1979                 $info->assignment = format_string($this->assignment->name,true);
1980                 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
1981                 $info->timeupdated = userdate($submission->timemodified, '%c', $teacher->timezone);
1983                 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1984                 $posttext = $this->email_teachers_text($info);
1985                 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
1987                 $eventdata = new stdClass();
1988                 $eventdata->modulename       = 'assignment';
1989                 $eventdata->userfrom         = $user;
1990                 $eventdata->userto           = $teacher;
1991                 $eventdata->subject          = $postsubject;
1992                 $eventdata->fullmessage      = $posttext;
1993                 $eventdata->fullmessageformat = FORMAT_PLAIN;
1994                 $eventdata->fullmessagehtml  = $posthtml;
1995                 $eventdata->smallmessage     = $postsubject;
1997                 $eventdata->name            = 'assignment_updates';
1998                 $eventdata->component       = 'mod_assignment';
1999                 $eventdata->notification    = 1;
2000                 $eventdata->contexturl      = $info->url;
2001                 $eventdata->contexturlname  = $info->assignment;
2003                 message_send($eventdata);
2004             }
2005         }
2006     }
2008     /**
2009      * Sends a file
2010      *
2011      * @param string $filearea
2012      * @param array $args
2013      * @param bool $forcedownload whether or not force download
2014      * @param array $options additional options affecting the file serving
2015      * @return bool
2016      */
2017     function send_file($filearea, $args, $forcedownload, array $options=array()) {
2018         debugging('plugin does not implement file sending', DEBUG_DEVELOPER);
2019         return false;
2020     }
2022     /**
2023      * Returns a list of teachers that should be grading given submission
2024      *
2025      * @param object $user
2026      * @return array
2027      */
2028     function get_graders($user) {
2029         global $DB;
2031         //potential graders
2032         list($enrolledsql, $params) = get_enrolled_sql($this->context, 'mod/assignment:grade', 0, true);
2033         $sql = "SELECT u.*
2034                   FROM {user} u
2035                   JOIN ($enrolledsql) je ON je.id = u.id";
2036         $potgraders = $DB->get_records_sql($sql, $params);
2038         $graders = array();
2039         if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) {   // Separate groups are being used
2040             if ($groups = groups_get_all_groups($this->course->id, $user->id)) {  // Try to find all groups
2041                 foreach ($groups as $group) {
2042                     foreach ($potgraders as $t) {
2043                         if ($t->id == $user->id) {
2044                             continue; // do not send self
2045                         }
2046                         if (groups_is_member($group->id, $t->id)) {
2047                             $graders[$t->id] = $t;
2048                         }
2049                     }
2050                 }
2051             } else {
2052                 // user not in group, try to find graders without group
2053                 foreach ($potgraders as $t) {
2054                     if ($t->id == $user->id) {
2055                         continue; // do not send self
2056                     }
2057                     if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
2058                         $graders[$t->id] = $t;
2059                     }
2060                 }
2061             }
2062         } else {
2063             foreach ($potgraders as $t) {
2064                 if ($t->id == $user->id) {
2065                     continue; // do not send self
2066                 }
2067                 $graders[$t->id] = $t;
2068             }
2069         }
2070         return $graders;
2071     }
2073     /**
2074      * Creates the text content for emails to teachers
2075      *
2076      * @param $info object The info used by the 'emailteachermail' language string
2077      * @return string
2078      */
2079     function email_teachers_text($info) {
2080         $posttext  = format_string($this->course->shortname, true, array('context' => $this->coursecontext)).' -> '.
2081                      $this->strassignments.' -> '.
2082                      format_string($this->assignment->name, true, array('context' => $this->context))."\n";
2083         $posttext .= '---------------------------------------------------------------------'."\n";
2084         $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
2085         $posttext .= "\n---------------------------------------------------------------------\n";
2086         return $posttext;
2087     }
2089      /**
2090      * Creates the html content for emails to teachers
2091      *
2092      * @param $info object The info used by the 'emailteachermailhtml' language string
2093      * @return string
2094      */
2095     function email_teachers_html($info) {
2096         global $CFG;
2097         $posthtml  = '<p><font face="sans-serif">'.
2098                      '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname, true, array('context' => $this->coursecontext)).'</a> ->'.
2099                      '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
2100                      '<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>';
2101         $posthtml .= '<hr /><font face="sans-serif">';
2102         $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
2103         $posthtml .= '</font><hr />';
2104         return $posthtml;
2105     }
2107     /**
2108      * Produces a list of links to the files uploaded by a user
2109      *
2110      * @param $userid int optional id of the user. If 0 then $USER->id is used.
2111      * @param $return boolean optional defaults to false. If true the list is returned rather than printed
2112      * @return string optional
2113      */
2114     function print_user_files($userid=0, $return=false) {
2115         global $CFG, $USER, $OUTPUT;
2117         if (!$userid) {
2118             if (!isloggedin()) {
2119                 return '';
2120             }
2121             $userid = $USER->id;
2122         }
2124         $output = '';
2126         $submission = $this->get_submission($userid);
2127         if (!$submission) {
2128             return $output;
2129         }
2131         $fs = get_file_storage();
2132         $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false);
2133         if (!empty($files)) {
2134             require_once($CFG->dirroot . '/mod/assignment/locallib.php');
2135             if ($CFG->enableportfolios) {
2136                 require_once($CFG->libdir.'/portfoliolib.php');
2137                 $button = new portfolio_add_button();
2138             }
2139             foreach ($files as $file) {
2140                 $filename = $file->get_filename();
2141                 $mimetype = $file->get_mimetype();
2142                 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/mod_assignment/submission/'.$submission->id.'/'.$filename);
2143                 $output .= '<a href="'.$path.'" >'.$OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon')).s($filename).'</a>';
2144                 if ($CFG->enableportfolios && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
2145                     $button->set_callback_options('assignment_portfolio_caller',
2146                                                   array('id' => $this->cm->id, 'submissionid' => $submission->id, 'fileid' => $file->get_id()),
2147                                                   'mod_assignment');
2148                     $button->set_format_by_file($file);
2149                     $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
2150                 }
2152                 if ($CFG->enableplagiarism) {
2153                     require_once($CFG->libdir.'/plagiarismlib.php');
2154                     $output .= plagiarism_get_links(array('userid'=>$userid, 'file'=>$file, 'cmid'=>$this->cm->id, 'course'=>$this->course, 'assignment'=>$this->assignment));
2155                     $output .= '<br />';
2156                 }
2157             }
2158             if ($CFG->enableportfolios && count($files) > 1  && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
2159                 $button->set_callback_options('assignment_portfolio_caller',
2160                                               array('id' => $this->cm->id, 'submissionid' => $submission->id),
2161                                               'mod_assignment');
2162                 $output .= '<br />'  . $button->to_html(PORTFOLIO_ADD_TEXT_LINK);
2163             }
2164         }
2166         $output = '<div class="files">'.$output.'</div>';
2168         if ($return) {
2169             return $output;
2170         }
2171         echo $output;
2172     }
2174     /**
2175      * Count the files uploaded by a given user
2176      *
2177      * @param $itemid int The submission's id as the file's itemid.
2178      * @return int
2179      */
2180     function count_user_files($itemid) {
2181         $fs = get_file_storage();
2182         $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $itemid, "id", false);
2183         return count($files);
2184     }
2186     /**
2187      * Returns true if the student is allowed to submit
2188      *
2189      * Checks that the assignment has started and, if the option to prevent late
2190      * submissions is set, also checks that the assignment has not yet closed.
2191      * @return boolean
2192      */
2193     function isopen() {
2194         $time = time();
2195         if ($this->assignment->preventlate && $this->assignment->timedue) {
2196             return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
2197         } else {
2198             return ($this->assignment->timeavailable <= $time);
2199         }
2200     }
2203     /**
2204      * Return true if is set description is hidden till available date
2205      *
2206      * This is needed by calendar so that hidden descriptions do not
2207      * come up in upcoming events.
2208      *
2209      * Check that description is hidden till available date
2210      * By default return false
2211      * Assignments types should implement this method if needed
2212      * @return boolen
2213      */
2214     function description_is_hidden() {
2215         return false;
2216     }
2218     /**
2219      * Return an outline of the user's interaction with the assignment
2220      *
2221      * The default method prints the grade and timemodified
2222      * @param $grade object
2223      * @return object with properties ->info and ->time
2224      */
2225     function user_outline($grade) {
2227         $result = new stdClass();
2228         $result->info = get_string('grade').': '.$grade->str_long_grade;
2229         $result->time = $grade->dategraded;
2230         return $result;
2231     }
2233     /**
2234      * Print complete information about the user's interaction with the assignment
2235      *
2236      * @param $user object
2237      */
2238     function user_complete($user, $grade=null) {
2239         global $OUTPUT;
2241         if ($submission = $this->get_submission($user->id)) {
2243             $fs = get_file_storage();
2245             if ($files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false)) {
2246                 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
2247                 foreach ($files as $file) {
2248                     $countfiles .= "; ".$file->get_filename();
2249                 }
2250             }
2252             echo $OUTPUT->box_start();
2253             echo get_string("lastmodified").": ";
2254             echo userdate($submission->timemodified);
2255             echo $this->display_lateness($submission->timemodified);
2257             $this->print_user_files($user->id);
2259             echo '<br />';
2261             $this->view_feedback($submission);
2263             echo $OUTPUT->box_end();
2265         } else {
2266             if ($grade) {
2267                 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
2268                 if ($grade->str_feedback) {
2269                     echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
2270                 }
2271             }
2272             print_string("notsubmittedyet", "assignment");
2273         }
2274     }
2276     /**
2277      * Return a string indicating how late a submission is
2278      *
2279      * @param $timesubmitted int
2280      * @return string
2281      */
2282     function display_lateness($timesubmitted) {
2283         return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
2284     }
2286     /**
2287      * Empty method stub for all delete actions.
2288      */
2289     function delete() {
2290         //nothing by default
2291         redirect('view.php?id='.$this->cm->id);
2292     }
2294     /**
2295      * Empty custom feedback grading form.
2296      */
2297     function custom_feedbackform($submission, $return=false) {
2298         //nothing by default
2299         return '';
2300     }
2302     /**
2303      * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
2304      * for the course (see resource).
2305      *
2306      * Given a course_module object, this function returns any "extra" information that may be needed
2307      * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
2308      *
2309      * @param $coursemodule object The coursemodule object (record).
2310      * @return cached_cm_info Object used to customise appearance on course page
2311      */
2312     function get_coursemodule_info($coursemodule) {
2313         return null;
2314     }
2316     /**
2317      * Plugin cron method - do not use $this here, create new assignment instances if needed.
2318      * @return void
2319      */
2320     function cron() {
2321         //no plugin cron by default - override if needed
2322     }
2324     /**
2325      * Reset all submissions
2326      */
2327     function reset_userdata($data) {
2328         global $CFG, $DB;
2330         if (!$DB->count_records('assignment', array('course'=>$data->courseid, 'assignmenttype'=>$this->type))) {
2331             return array(); // no assignments of this type present
2332         }
2334         $componentstr = get_string('modulenameplural', 'assignment');
2335         $status = array();
2337         $typestr = get_string('type'.$this->type, 'assignment');
2338         // ugly hack to support pluggable assignment type titles...
2339         if($typestr === '[[type'.$this->type.']]'){
2340             $typestr = get_string('type'.$this->type, 'assignment_'.$this->type);
2341         }
2343         if (!empty($data->reset_assignment_submissions)) {
2344             $assignmentssql = "SELECT a.id
2345                                  FROM {assignment} a
2346                                 WHERE a.course=? AND a.assignmenttype=?";
2347             $params = array($data->courseid, $this->type);
2349             // now get rid of all submissions and responses
2350             $fs = get_file_storage();
2351             if ($assignments = $DB->get_records_sql($assignmentssql, $params)) {
2352                 foreach ($assignments as $assignmentid=>$unused) {
2353                     if (!$cm = get_coursemodule_from_instance('assignment', $assignmentid)) {
2354                         continue;
2355                     }
2356                     $context = context_module::instance($cm->id);
2357                     $fs->delete_area_files($context->id, 'mod_assignment', 'submission');
2358                     $fs->delete_area_files($context->id, 'mod_assignment', 'response');
2359                 }
2360             }
2362             $DB->delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)", $params);
2364             $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
2366             if (empty($data->reset_gradebook_grades)) {
2367                 // remove all grades from gradebook
2368                 assignment_reset_gradebook($data->courseid, $this->type);
2369             }
2370         }
2372         /// updating dates - shift may be negative too
2373         if ($data->timeshift) {
2374             shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
2375             $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
2376         }
2378         return $status;
2379     }
2382     function portfolio_exportable() {
2383         return false;
2384     }
2386     /**
2387      * base implementation for backing up subtype specific information
2388      * for one single module
2389      *
2390      * @param filehandle $bf file handle for xml file to write to
2391      * @param mixed $preferences the complete backup preference object
2392      *
2393      * @return boolean
2394      *
2395      * @static
2396      */
2397     static function backup_one_mod($bf, $preferences, $assignment) {
2398         return true;
2399     }
2401     /**
2402      * base implementation for backing up subtype specific information
2403      * for one single submission
2404      *
2405      * @param filehandle $bf file handle for xml file to write to
2406      * @param mixed $preferences the complete backup preference object
2407      * @param object $submission the assignment submission db record
2408      *
2409      * @return boolean
2410      *
2411      * @static
2412      */
2413     static function backup_one_submission($bf, $preferences, $assignment, $submission) {
2414         return true;
2415     }
2417     /**
2418      * base implementation for restoring subtype specific information
2419      * for one single module
2420      *
2421      * @param array  $info the array representing the xml
2422      * @param object $restore the restore preferences
2423      *
2424      * @return boolean
2425      *
2426      * @static
2427      */
2428     static function restore_one_mod($info, $restore, $assignment) {
2429         return true;
2430     }
2432     /**
2433      * base implementation for restoring subtype specific information
2434      * for one single submission
2435      *
2436      * @param object $submission the newly created submission
2437      * @param array  $info the array representing the xml
2438      * @param object $restore the restore preferences
2439      *
2440      * @return boolean
2441      *
2442      * @static
2443      */
2444     static function restore_one_submission($info, $restore, $assignment, $submission) {
2445         return true;
2446     }
2448 } ////// End of the assignment_base class
2451 class assignment_grading_form extends moodleform {
2452     /** @var stores the advaned grading instance (if used in grading) */
2453     private $advancegradinginstance;
2455     function definition() {
2456         global $OUTPUT;
2457         $mform =& $this->_form;
2459         if (isset($this->_customdata->advancedgradinginstance)) {
2460             $this->use_advanced_grading($this->_customdata->advancedgradinginstance);
2461         }
2463         $formattr = $mform->getAttributes();
2464         $formattr['id'] = 'submitform';
2465         $mform->setAttributes($formattr);
2466         // hidden params
2467         $mform->addElement('hidden', 'offset', ($this->_customdata->offset+1));
2468         $mform->setType('offset', PARAM_INT);
2469         $mform->addElement('hidden', 'userid', $this->_customdata->userid);
2470         $mform->setType('userid', PARAM_INT);
2471         $mform->addElement('hidden', 'nextid', $this->_customdata->nextid);
2472         $mform->setType('nextid', PARAM_INT);
2473         $mform->addElement('hidden', 'id', $this->_customdata->cm->id);
2474         $mform->setType('id', PARAM_INT);
2475         $mform->addElement('hidden', 'sesskey', sesskey());
2476         $mform->setType('sesskey', PARAM_ALPHANUM);
2477         $mform->addElement('hidden', 'mode', 'grade');
2478         $mform->setType('mode', PARAM_TEXT);
2479         $mform->addElement('hidden', 'menuindex', "0");
2480         $mform->setType('menuindex', PARAM_INT);
2481         $mform->addElement('hidden', 'saveuserid', "-1");
2482         $mform->setType('saveuserid', PARAM_INT);
2483         $mform->addElement('hidden', 'filter', "0");
2484         $mform->setType('filter', PARAM_INT);
2486         $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->user),
2487                                                 fullname($this->_customdata->user, true) . '<br/>' .
2488                                                 userdate($this->_customdata->submission->timemodified) .
2489                                                 $this->_customdata->lateness );
2491         $this->add_submission_content();
2492         $this->add_grades_section();
2494         $this->add_feedback_section();
2496         if ($this->_customdata->submission->timemarked) {
2497             $datestring = userdate($this->_customdata->submission->timemarked)."&nbsp; (".format_time(time() - $this->_customdata->submission->timemarked).")";
2498             $mform->addElement('header', 'Last Grade', get_string('lastgrade', 'assignment'));
2499             $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->teacher) ,
2500                                                     fullname($this->_customdata->teacher,true).
2501                                                     '<br/>'.$datestring);
2502         }
2503         // buttons
2504         $this->add_action_buttons();
2506     }
2508     /**
2509      * Gets or sets the instance for advanced grading
2510      *
2511      * @param gradingform_instance $gradinginstance
2512      */
2513     public function use_advanced_grading($gradinginstance = false) {
2514         if ($gradinginstance !== false) {
2515             $this->advancegradinginstance = $gradinginstance;
2516         }
2517         return $this->advancegradinginstance;
2518     }
2520     /**
2521      * Add the grades configuration section to the assignment configuration form
2522      */
2523     function add_grades_section() {
2524         global $CFG;
2525         $mform =& $this->_form;
2526         $attributes = array();
2527         if ($this->_customdata->gradingdisabled) {
2528             $attributes['disabled'] ='disabled';
2529         }
2531         $mform->addElement('header', 'Grades', get_string('grades', 'grades'));
2533         $grademenu = make_grades_menu($this->_customdata->assignment->grade);
2534         if ($gradinginstance = $this->use_advanced_grading()) {
2535             $gradinginstance->get_controller()->set_grade_range($grademenu);
2536             $gradingelement = $mform->addElement('grading', 'advancedgrading', get_string('grade').':', array('gradinginstance' => $gradinginstance));
2537             if ($this->_customdata->gradingdisabled) {
2538                 $gradingelement->freeze();
2539             } else {
2540                 $mform->addElement('hidden', 'advancedgradinginstanceid', $gradinginstance->get_id());
2541             }
2542         } else {
2543             // use simple direct grading
2544             $grademenu['-1'] = get_string('nograde');
2546             $mform->addElement('select', 'xgrade', get_string('grade').':', $grademenu, $attributes);
2547             $mform->setDefault('xgrade', $this->_customdata->submission->grade ); //@fixme some bug when element called 'grade' makes it break
2548             $mform->setType('xgrade', PARAM_INT);
2549         }
2551         if (!empty($this->_customdata->enableoutcomes)) {
2552             foreach($this->_customdata->grading_info->outcomes as $n=>$outcome) {
2553                 $options = make_grades_menu(-$outcome->scaleid);
2554                 if ($outcome->grades[$this->_customdata->submission->userid]->locked) {
2555                     $options[0] = get_string('nooutcome', 'grades');
2556                     $mform->addElement('static', 'outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->name.':',
2557                             $options[$outcome->grades[$this->_customdata->submission->userid]->grade]);
2558                 } else {
2559                     $options[''] = get_string('nooutcome', 'grades');
2560                     $attributes = array('id' => 'menuoutcome_'.$n );
2561                     $mform->addElement('select', 'outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->name.':', $options, $attributes );
2562                     $mform->setType('outcome_'.$n.'['.$this->_customdata->userid.']', PARAM_INT);
2563                     $mform->setDefault('outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->grades[$this->_customdata->submission->userid]->grade );
2564                 }
2565             }
2566         }
2567         $course_context = context_module::instance($this->_customdata->cm->id);
2568         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
2569             $grade = '<a href="'.$CFG->wwwroot.'/grade/report/grader/index.php?id='. $this->_customdata->courseid .'" >'.
2570                         $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade . '</a>';
2571         }else{
2572             $grade = $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade;
2573         }
2574         $mform->addElement('static', 'finalgrade', get_string('currentgrade', 'assignment').':' ,$grade);
2575         $mform->setType('finalgrade', PARAM_INT);
2576     }
2578     /**
2579      *
2580      * @global core_renderer $OUTPUT
2581      */
2582     function add_feedback_section() {
2583         global $OUTPUT;
2584         $mform =& $this->_form;
2585         $mform->addElement('header', 'Feed Back', get_string('feedback', 'grades'));
2587         if ($this->_customdata->gradingdisabled) {
2588             $mform->addElement('static', 'disabledfeedback', $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_feedback );
2589         } else {
2590             // visible elements
2592             $mform->addElement('editor', 'submissioncomment_editor', get_string('feedback', 'assignment').':', null, $this->get_editor_options() );
2593             $mform->setType('submissioncomment_editor', PARAM_RAW); // to be cleaned before display
2594             $mform->setDefault('submissioncomment_editor', $this->_customdata->submission->submissioncomment);
2595             //$mform->addRule('submissioncomment', get_string('required'), 'required', null, 'client');
2596             switch ($this->_customdata->assignment->assignmenttype) {
2597                 case 'upload' :
2598                 case 'uploadsingle' :
2599                     $mform->addElement('filemanager', 'files_filemanager', get_string('responsefiles', 'assignment'). ':', null, $this->_customdata->fileui_options);
2600                     break;
2601                 default :
2602                     break;
2603             }
2604             $mform->addElement('hidden', 'mailinfo_h', "0");
2605             $mform->setType('mailinfo_h', PARAM_INT);
2606             $mform->addElement('checkbox', 'mailinfo',get_string('enablenotification','assignment').
2607             $OUTPUT->help_icon('enablenotification', 'assignment') .':' );
2608             $mform->setType('mailinfo', PARAM_INT);
2609         }
2610     }
2612     function add_action_buttons($cancel = true, $submitlabel = NULL) {
2613         $mform =& $this->_form;
2614         //if there are more to be graded.
2615         if ($this->_customdata->nextid>0) {
2616             $buttonarray=array();
2617             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2618             //@todo: fix accessibility: javascript dependency not necessary
2619             $buttonarray[] = &$mform->createElement('submit', 'saveandnext', get_string('saveandnext'));
2620             $buttonarray[] = &$mform->createElement('submit', 'next', get_string('next'));
2621             $buttonarray[] = &$mform->createElement('cancel');
2622         } else {
2623             $buttonarray=array();
2624             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2625             $buttonarray[] = &$mform->createElement('cancel');
2626         }
2627         $mform->addGroup($buttonarray, 'grading_buttonar', '', array(' '), false);
2628         $mform->closeHeaderBefore('grading_buttonar');
2629         $mform->setType('grading_buttonar', PARAM_RAW);
2630     }
2632     function add_submission_content() {
2633         $mform =& $this->_form;
2634         $mform->addElement('header', 'Submission', get_string('submission', 'assignment'));
2635         $mform->addElement('static', '', '' , $this->_customdata->submission_content );
2636     }
2638     protected function get_editor_options() {
2639         $editoroptions = array();
2640         $editoroptions['component'] = 'mod_assignment';
2641         $editoroptions['filearea'] = 'feedback';
2642         $editoroptions['noclean'] = false;
2643         $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)
2644         $editoroptions['maxbytes'] = $this->_customdata->maxbytes;
2645         $editoroptions['context'] = $this->_customdata->context;
2646         return $editoroptions;
2647     }
2649     public function set_data($data) {
2650         $editoroptions = $this->get_editor_options();
2651         if (!isset($data->text)) {
2652             $data->text = '';
2653         }
2654         if (!isset($data->format)) {
2655             $data->textformat = FORMAT_HTML;
2656         } else {
2657             $data->textformat = $data->format;
2658         }
2660         if (!empty($this->_customdata->submission->id)) {
2661             $itemid = $this->_customdata->submission->id;
2662         } else {
2663             $itemid = null;
2664         }
2666         switch ($this->_customdata->assignment->assignmenttype) {
2667                 case 'upload' :
2668                 case 'uploadsingle' :
2669                     $data = file_prepare_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2670                     break;
2671                 default :
2672                     break;
2673         }
2675         $data = file_prepare_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2676         return parent::set_data($data);
2677     }
2679     public function get_data() {
2680         $data = parent::get_data();
2682         if (!empty($this->_customdata->submission->id)) {
2683             $itemid = $this->_customdata->submission->id;
2684         } else {
2685             $itemid = null; //TODO: this is wrong, itemid MUST be known when saving files!! (skodak)
2686         }
2688         if ($data) {
2689             $editoroptions = $this->get_editor_options();
2690             switch ($this->_customdata->assignment->assignmenttype) {
2691                 case 'upload' :
2692                 case 'uploadsingle' :
2693                     $data = file_postupdate_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2694                     break;
2695                 default :
2696                     break;
2697             }
2698             $data = file_postupdate_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2699         }
2701         if ($this->use_advanced_grading() && !isset($data->advancedgrading)) {
2702             $data->advancedgrading = null;
2703         }
2705         return $data;
2706     }
2709 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
2711 /**
2712  * Deletes an assignment instance
2713  *
2714  * This is done by calling the delete_instance() method of the assignment type class
2715  */
2716 function assignment_delete_instance($id){
2717     global $CFG, $DB;
2719     if (! $assignment = $DB->get_record('assignment', array('id'=>$id))) {
2720         return false;
2721     }
2723     // fall back to base class if plugin missing
2724     $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2725     if (file_exists($classfile)) {
2726         require_once($classfile);
2727         $assignmentclass = "assignment_$assignment->assignmenttype";
2729     } else {
2730         debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
2731         $assignmentclass = "assignment_base";
2732     }
2734     $ass = new $assignmentclass();
2735     return $ass->delete_instance($assignment);
2739 /**
2740  * Updates an assignment instance
2741  *
2742  * This is done by calling the update_instance() method of the assignment type class
2743  */
2744 function assignment_update_instance($assignment){
2745     global $CFG;
2747     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_PLUGIN);
2749     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2750     $assignmentclass = "assignment_$assignment->assignmenttype";
2751     $ass = new $assignmentclass();
2752     return $ass->update_instance($assignment);
2756 /**
2757  * Adds an assignment instance
2758  *
2759  * This is done by calling the add_instance() method of the assignment type class
2760  *
2761  * @param stdClass $assignment
2762  * @param mod_assignment_mod_form $mform
2763  * @return int intance id
2764  */
2765 function assignment_add_instance($assignment, $mform = null) {
2766     global $CFG;
2768     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_PLUGIN);
2770     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2771     $assignmentclass = "assignment_$assignment->assignmenttype";
2772     $ass = new $assignmentclass();
2773     return $ass->add_instance($assignment);
2777 /**
2778  * Returns an outline of a user interaction with an assignment
2779  *
2780  * This is done by calling the user_outline() method of the assignment type class
2781  */
2782 function assignment_user_outline($course, $user, $mod, $assignment) {
2783     global $CFG;
2785     require_once("$CFG->libdir/gradelib.php");
2786     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2787     $assignmentclass = "assignment_$assignment->assignmenttype";
2788     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2789     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2790     if (!empty($grades->items[0]->grades)) {
2791         return $ass->user_outline(reset($grades->items[0]->grades));
2792     } else {
2793         return null;
2794     }
2797 /**
2798  * Prints the complete info about a user's interaction with an assignment
2799  *
2800  * This is done by calling the user_complete() method of the assignment type class
2801  */
2802 function assignment_user_complete($course, $user, $mod, $assignment) {
2803     global $CFG;
2805     require_once("$CFG->libdir/gradelib.php");
2806     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2807     $assignmentclass = "assignment_$assignment->assignmenttype";
2808     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2809     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2810     if (empty($grades->items[0]->grades)) {
2811         $grade = false;
2812     } else {
2813         $grade = reset($grades->items[0]->grades);
2814     }
2815     return $ass->user_complete($user, $grade);
2818 /**
2819  * Function to be run periodically according to the moodle cron
2820  *
2821  * Finds all assignment notifications that have yet to be mailed out, and mails them
2822  */
2823 function assignment_cron () {
2824     global $CFG, $USER, $DB;
2826     /// first execute all crons in plugins
2827     if ($plugins = get_plugin_list('assignment')) {
2828         foreach ($plugins as $plugin=>$dir) {
2829             require_once("$dir/assignment.class.php");
2830             $assignmentclass = "assignment_$plugin";
2831             $ass = new $assignmentclass();
2832             $ass->cron();
2833         }
2834     }
2836     /// Notices older than 1 day will not be mailed.  This is to avoid the problem where
2837     /// cron has not been running for a long time, and then suddenly people are flooded
2838     /// with mail from the past few weeks or months
2840     $timenow   = time();
2841     $endtime   = $timenow - $CFG->maxeditingtime;
2842     $starttime = $endtime - 24 * 3600;   /// One day earlier
2844     if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2846         $realuser = clone($USER);
2848         foreach ($submissions as $key => $submission) {
2849             $DB->set_field("assignment_submissions", "mailed", "1", array("id"=>$submission->id));
2850         }
2852         $timenow = time();
2854         foreach ($submissions as $submission) {
2856             echo "Processing assignment submission $submission->id\n";
2858             if (! $user = $DB->get_record("user", array("id"=>$submission->userid))) {
2859                 echo "Could not find user $user->id\n";
2860                 continue;
2861             }
2863             if (! $course = $DB->get_record("course", array("id"=>$submission->course))) {
2864                 echo "Could not find course $submission->course\n";
2865                 continue;
2866             }
2868             /// Override the language and timezone of the "current" user, so that
2869             /// mail is customised for the receiver.
2870             cron_setup_user($user, $course);
2872             $coursecontext = context_course::instance($submission->course);
2873             $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
2874             if (!is_enrolled($coursecontext, $user->id)) {
2875                 echo fullname($user)." not an active participant in " . $courseshortname . "\n";
2876                 continue;
2877             }
2879             if (! $teacher = $DB->get_record("user", array("id"=>$submission->teacher))) {
2880                 echo "Could not find teacher $submission->teacher\n";
2881                 continue;
2882             }
2884             if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2885                 echo "Could not find course module for assignment id $submission->assignment\n";
2886                 continue;
2887             }
2889             if (! $mod->visible) {    /// Hold mail notification for hidden assignments until later
2890                 continue;
2891             }
2893             $strassignments = get_string("modulenameplural", "assignment");
2894             $strassignment  = get_string("modulename", "assignment");
2896             $assignmentinfo = new stdClass();
2897             $assignmentinfo->teacher = fullname($teacher);
2898             $assignmentinfo->assignment = format_string($submission->name,true);
2899             $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2901             $postsubject = "$courseshortname: $strassignments: ".format_string($submission->name,true);
2902             $posttext  = "$courseshortname -> $strassignments -> ".format_string($submission->name,true)."\n";
2903             $posttext .= "---------------------------------------------------------------------\n";
2904             $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2905             $posttext .= "---------------------------------------------------------------------\n";
2907             if ($user->mailformat == 1) {  // HTML
2908                 $posthtml = "<p><font face=\"sans-serif\">".
2909                 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$courseshortname</a> ->".
2910                 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2911                 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2912                 $posthtml .= "<hr /><font face=\"sans-serif\">";
2913                 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2914                 $posthtml .= "</font><hr />";
2915             } else {
2916                 $posthtml = "";
2917             }
2919             $eventdata = new stdClass();
2920             $eventdata->modulename       = 'assignment';
2921             $eventdata->userfrom         = $teacher;
2922             $eventdata->userto           = $user;
2923             $eventdata->subject          = $postsubject;
2924             $eventdata->fullmessage      = $posttext;
2925             $eventdata->fullmessageformat = FORMAT_PLAIN;
2926             $eventdata->fullmessagehtml  = $posthtml;
2927             $eventdata->smallmessage     = get_string('assignmentmailsmall', 'assignment', $assignmentinfo);
2929             $eventdata->name            = 'assignment_updates';
2930             $eventdata->component       = 'mod_assignment';
2931             $eventdata->notification    = 1;
2932             $eventdata->contexturl      = $assignmentinfo->url;
2933             $eventdata->contexturlname  = $assignmentinfo->assignment;
2935             message_send($eventdata);
2936         }
2938         cron_setup_user();
2939     }
2941     return true;
2944 /**
2945  * Return grade for given user or all users.
2946  *
2947  * @param stdClass $assignment An assignment instance
2948  * @param int $userid Optional user id, 0 means all users
2949  * @return array An array of grades, false if none
2950  */
2951 function assignment_get_user_grades($assignment, $userid=0) {
2952     global $CFG, $DB;
2954     if ($userid) {
2955         $user = "AND u.id = :userid";
2956         $params = array('userid'=>$userid);
2957     } else {
2958         $user = "";
2959     }
2960     $params['aid'] = $assignment->id;
2962     $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2963                    s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2964               FROM {user} u, {assignment_submissions} s
2965              WHERE u.id = s.userid AND s.assignment = :aid
2966                    $user";
2968     return $DB->get_records_sql($sql, $params);
2971 /**
2972  * Update activity grades
2973  *
2974  * @category grade
2975  * @param stdClass $assignment Assignment instance
2976  * @param int $userid specific user only, 0 means all
2977  * @param bool $nullifnone Not used
2978  */
2979 function assignment_update_grades($assignment, $userid=0, $nullifnone=true) {
2980     global $CFG, $DB;
2981     require_once($CFG->libdir.'/gradelib.php');
2983     if ($assignment->grade == 0) {
2984         assignment_grade_item_update($assignment);
2986     } else if ($grades = assignment_get_user_grades($assignment, $userid)) {
2987         foreach($grades as $k=>$v) {
2988             if ($v->rawgrade == -1) {
2989                 $grades[$k]->rawgrade = null;
2990             }
2991         }
2992         assignment_grade_item_update($assignment, $grades);
2994     } else {
2995         assignment_grade_item_update($assignment);
2996     }
2999 /**
3000  * Update all grades in gradebook.
3001  */
3002 function assignment_upgrade_grades() {
3003     global $DB;
3005     $sql = "SELECT COUNT('x')
3006               FROM {assignment} a, {course_modules} cm, {modules} m
3007              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
3008     $count = $DB->count_records_sql($sql);
3010     $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
3011               FROM {assignment} a, {course_modules} cm, {modules} m
3012              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
3013     $rs = $DB->get_recordset_sql($sql);
3014     if ($rs->valid()) {
3015         // too much debug output
3016         $pbar = new progress_bar('assignmentupgradegrades', 500, true);
3017         $i=0;
3018         foreach ($rs as $assignment) {
3019             $i++;
3020             upgrade_set_timeout(60*5); // set up timeout, may also abort execution
3021             assignment_update_grades($assignment);
3022             $pbar->update($i, $count, "Updating Assignment grades ($i/$count).");
3023         }
3024         upgrade_set_timeout(); // reset to default timeout
3025     }
3026     $rs->close();
3029 /**
3030  * Create grade item for given assignment
3031  *
3032  * @category grade
3033  * @param stdClass $assignment An assignment instance with extra cmidnumber property
3034  * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
3035  * @return int 0 if ok, error code otherwise
3036  */
3037 function assignment_grade_item_update($assignment, $grades=NULL) {
3038     global $CFG;
3039     require_once($CFG->libdir.'/gradelib.php');
3041     if (!isset($assignment->courseid)) {
3042         $assignment->courseid = $assignment->course;
3043     }
3045     $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
3047     if ($assignment->grade > 0) {
3048         $params['gradetype'] = GRADE_TYPE_VALUE;
3049         $params['grademax']  = $assignment->grade;
3050         $params['grademin']  = 0;
3052     } else if ($assignment->grade < 0) {
3053         $params['gradetype'] = GRADE_TYPE_SCALE;
3054         $params['scaleid']   = -$assignment->grade;
3056     } else {
3057         $params['gradetype'] = GRADE_TYPE_TEXT; // allow text comments only
3058     }
3060     if ($grades  === 'reset') {
3061         $params['reset'] = true;
3062         $grades = NULL;
3063     }
3065     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades, $params);
3068 /**
3069  * Delete grade item for given assignment
3070  *
3071  * @category grade
3072  * @param object $assignment object
3073  * @return object assignment
3074  */
3075 function assignment_grade_item_delete($assignment) {
3076     global $CFG;
3077     require_once($CFG->libdir.'/gradelib.php');
3079     if (!isset($assignment->courseid)) {
3080         $assignment->courseid = $assignment->course;
3081     }
3083     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
3087 /**
3088  * Serves assignment submissions and other files.
3089  *
3090  * @package  mod_assignment
3091  * @category files
3092  * @param stdClass $course course object
3093  * @param stdClass $cm course module object
3094  * @param stdClass $context context object
3095  * @param string $filearea file area
3096  * @param array $args extra arguments
3097  * @param bool $forcedownload whether or not force download
3098  * @param array $options additional options affecting the file serving
3099  * @return bool false if file not found, does not return if found - just send the file
3100  */
3101 function assignment_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
3102     global $CFG, $DB;
3104     if ($context->contextlevel != CONTEXT_MODULE) {
3105         return false;
3106     }
3108     require_login($course, false, $cm);
3110     if (!$assignment = $DB->get_record('assignment', array('id'=>$cm->instance))) {
3111         return false;
3112     }
3114     require_once($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
3115     $assignmentclass = 'assignment_'.$assignment->assignmenttype;
3116     $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm, $course);
3118     return $assignmentinstance->send_file($filearea, $args, $forcedownload, $options);
3120 /**
3121  * Checks if a scale is being used by an assignment
3122  *
3123  * This is used by the backup code to decide whether to back up a scale
3124  * @param $assignmentid int
3125  * @param $scaleid int
3126  * @return boolean True if the scale is used by the assignment
3127  */
3128 function assignment_scale_used($assignmentid, $scaleid) {
3129     global $DB;
3131     $return = false;
3133     $rec = $DB->get_record('assignment', array('id'=>$assignmentid,'grade'=>-$scaleid));
3135     if (!empty($rec) && !empty($scaleid)) {
3136         $return = true;
3137     }
3139     return $return;
3142 /**
3143  * Checks if scale is being used by any instance of assignment
3144  *
3145  * This is used to find out if scale used anywhere
3146  * @param $scaleid int
3147  * @return boolean True if the scale is used by any assignment
3148  */
3149 function assignment_scale_used_anywhere($scaleid) {
3150     global $DB;
3152     if ($scaleid and $DB->record_exists('assignment', array('grade'=>-$scaleid))) {
3153         return true;
3154     } else {
3155         return false;
3156     }
3159 /**
3160  * Make sure up-to-date events are created for all assignment instances
3161  *
3162  * This standard function will check all instances of this module
3163  * and make sure there are up-to-date events created for each of them.
3164  * If courseid = 0, then every assignment event in the site is checked, else
3165  * only assignment events belonging to the course specified are checked.
3166  * This function is used, in its new format, by restore_refresh_events()
3167  *
3168  * @param $courseid int optional If zero then all assignments for all courses are covered
3169  * @return boolean Always returns true
3170  */
3171 function assignment_refresh_events($courseid = 0) {
3172     global $DB;
3174     if ($courseid == 0) {
3175         if (! $assignments = $DB->get_records("assignment")) {
3176             return true;
3177         }
3178     } else {
3179         if (! $assignments = $DB->get_records("assignment", array("course"=>$courseid))) {
3180             return true;
3181         }
3182     }
3183     $moduleid = $DB->get_field('modules', 'id', array('name'=>'assignment'));
3185     foreach ($assignments as $assignment) {
3186         $cm = get_coursemodule_from_id('assignment', $assignment->id);
3187         $event = new stdClass();
3188         $event->name        = $assignment->name;
3189         $event->description = format_module_intro('assignment', $assignment, $cm->id);
3190         $event->timestart   = $assignment->timedue;
3192         if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
3193             update_event($event);
3195         } else {
3196             $event->courseid    = $assignment->course;
3197             $event->groupid     = 0;
3198             $event->userid      = 0;
3199             $event->modulename  = 'assignment';
3200             $event->instance    = $assignment->id;
3201             $event->eventtype   = 'due';
3202             $event->timeduration = 0;
3203             $event->visible     = $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$assignment->id));
3204             add_event($event);
3205         }
3207     }
3208     return true;
3211 /**
3212  * Print recent activity from all assignments in a given course
3213  *
3214  * This is used by the recent activity block
3215  */
3216 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
3217     global $CFG, $USER, $DB, $OUTPUT;
3219     // do not use log table if possible, it may be huge
3221     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
3222                                                      u.firstname, u.lastname, u.email, u.picture
3223                                                 FROM {assignment_submissions} asb
3224                                                      JOIN {assignment} a      ON a.id = asb.assignment
3225                                                      JOIN {course_modules} cm ON cm.instance = a.id
3226                                                      JOIN {modules} md        ON md.id = cm.module
3227                                                      JOIN {user} u            ON u.id = asb.userid
3228                                                WHERE asb.timemodified > ? AND
3229                                                      a.course = ? AND
3230                                                      md.name = 'assignment'
3231                                             ORDER BY asb.timemodified ASC", array($timestart, $course->id))) {
3232          return false;
3233     }
3235     $modinfo = get_fast_modinfo($course); // reference needed because we might load the groups
3236     $show    = array();
3237     $grader  = array();
3239     foreach($submissions as $submission) {
3240         if (!array_key_exists($submission->cmid, $modinfo->cms)) {
3241             continue;
3242         }
3243         $cm = $modinfo->cms[$submission->cmid];
3244         if (!$cm->uservisible) {
3245             continue;
3246         }
3247         if ($submission->userid == $USER->id) {
3248             $show[] = $submission;
3249             continue;
3250         }
3252         // the act of sumbitting of assignment may be considered private - only graders will see it if specified
3253         if (empty($CFG->assignment_showrecentsubmissions)) {
3254             if (!array_key_exists($cm->id, $grader)) {
3255                 $grader[$cm->id] = has_capability('moodle/grade:viewall', context_module::instance($cm->id));
3256             }
3257             if (!$grader[$cm->id]) {
3258                 continue;
3259             }
3260         }
3262         $groupmode = groups_get_activity_groupmode($cm, $course);
3264         if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', context_module::instance($cm->id))) {
3265             if (isguestuser()) {
3266                 // shortcut - guest user does not belong into any group
3267                 continue;
3268             }
3270             if (is_null($modinfo->groups)) {
3271                 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
3272             }
3274             // this will be slow - show only users that share group with me in this cm
3275             if (empty($modinfo->groups[$cm->id])) {
3276                 continue;
3277             }
3278             $usersgroups =  groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
3279             if (is_array($usersgroups)) {
3280                 $usersgroups = array_keys($usersgroups);
3281                 $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
3282                 if (empty($intersect)) {
3283                     continue;
3284                 }
3285             }
3286         }
3287         $show[] = $submission;
3288     }
3290     if (empty($show)) {
3291         return false;
3292     }
3294     echo $OUTPUT->heading(get_string('newsubmissions', 'assignment').':', 3);
3296     foreach ($show as $submission) {
3297         $cm = $modinfo->cms[$submission->cmid];
3298         $link = $CFG->wwwroot.'/mod/assignment/view.php?id='.$cm->id;
3299         print_recent_activity_note($submission->timemodified, $submission, $cm->name, $link, false, $viewfullnames);
3300     }
3302     return true;
3306 /**
3307  * Returns all assignments since a given time in specified forum.
3308  */
3309 function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0)  {
3310     global $CFG, $COURSE, $USER, $DB;
3312     if ($COURSE->id == $courseid) {
3313         $course = $COURSE;
3314     } else {
3315         $course = $DB->get_record('course', array('id'=>$courseid));
3316     }
3318     $modinfo = get_fast_modinfo($course);
3320     $cm = $modinfo->cms[$cmid];
3322     $params = array();
3323     if ($userid) {
3324         $userselect = "AND u.id = :userid";
3325         $params['userid'] = $userid;
3326     } else {
3327         $userselect = "";
3328     }
3330     if ($groupid) {
3331         $groupselect = "AND gm.groupid = :groupid";
3332         $groupjoin   = "JOIN {groups_members} gm ON  gm.userid=u.id";
3333         $params['groupid'] = $groupid;
3334     } else {
3335         $groupselect = "";
3336         $groupjoin   = "";
3337     }
3339     $params['cminstance'] = $cm->instance;
3340     $params['timestart'] = $timestart;
3342     $userfields = user_picture::fields('u', null, 'userid');
3344     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified,
3345                                                      $userfields
3346                                                 FROM {assignment_submissions} asb
3347                                                 JOIN {assignment} a      ON a.id = asb.assignment
3348                                                 JOIN {user} u            ON u.id = asb.userid
3349                                           $groupjoin
3350                                                WHERE asb.timemodified > :timestart AND a.id = :cminstance
3351                                                      $userselect $groupselect
3352                                             ORDER BY asb.timemodified ASC", $params)) {
3353          return;
3354     }
3356     $groupmode       = groups_get_activity_groupmode($cm, $course);
3357     $cm_context      = context_module::instance($cm->id);
3358     $grader          = has_capability('moodle/grade:viewall', $cm_context);
3359     $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
3360     $viewfullnames   = has_capability('moodle/site:viewfullnames', $cm_context);
3362     if (is_null($modinfo->groups)) {
3363         $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
3364     }
3366     $show = array();
3368     foreach($submissions as $submission) {
3369         if ($submission->userid == $USER->id) {
3370             $show[] = $submission;
3371             continue;
3372         }
3373         // the act of submitting of assignment may be considered private - only graders will see it if specified
3374         if (empty($CFG->assignment_showrecentsubmissions)) {
3375             if (!$grader) {
3376                 continue;
3377             }
3378         }
3380         if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
3381             if (isguestuser()) {
3382                 // shortcut - guest user does not belong into any group
3383                 continue;
3384             }
3386             // this will be slow - show only users that share group with me in this cm
3387             if (empty($modinfo->groups[$cm->id])) {
3388                 continue;
3389             }
3390             $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
3391             if (is_array($usersgroups)) {
3392                 $usersgroups = array_keys($usersgroups);
3393                 $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
3394                 if (empty($intersect)) {
3395                     continue;
3396                 }
3397             }
3398         }
3399         $show[] = $submission;
3400     }
3402     if (empty($show)) {
3403         return;
3404     }
3406     if ($grader) {
3407         require_once($CFG->libdir.'/gradelib.php');
3408         $userids = array();
3409         foreach ($show as $id=>$submission) {
3410             $userids[] = $submission->userid;
3412         }
3413         $grades = grade_get_grades($courseid, 'mod', 'assignment', $cm->instance, $userids);
3414     }
3416     $aname = format_string($cm->name,true);
3417     foreach ($show as $submission) {
3418         $tmpactivity = new stdClass();
3420         $tmpactivity->type         = 'assignment';
3421         $tmpactivity->cmid         = $cm->id;
3422         $tmpactivity->name         = $aname;
3423         $tmpactivity->sectionnum   = $cm->sectionnum;
3424         $tmpactivity->timestamp    = $submission->timemodified;
3426         if ($grader) {
3427             $tmpactivity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
3428         }
3430         $userfields = explode(',', user_picture::fields());
3431         foreach ($userfields as $userfield) {
3432             if ($userfield == 'id') {
3433                 $tmpactivity->user->{$userfield} = $submission->userid; // aliased in SQL above
3434             } else {
3435                 $tmpactivity->user->{$userfield} = $submission->{$userfield};
3436             }
3437         }
3438         $tmpactivity->user->fullname = fullname($submission, $viewfullnames);
3440         $activities[$index++] = $tmpactivity;
3441     }
3443     return;
3446 /**
3447  * Print recent activity from all assignments in a given course
3448  *
3449  * This is used by course/recent.php
3450  */
3451 function assignment_print_recent_mod_activity($activity, $courseid, $detail, $modnames)  {
3452     global $CFG, $OUTPUT;
3454     echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
3456     echo "<tr><td class=\"userpicture\" valign=\"top\">";
3457     echo $OUTPUT->user_picture($activity->user);
3458     echo "</td><td>";
3460     if ($detail) {
3461         $modname = $modnames[$activity->type];
3462         echo '<div class="title">';
3463         echo "<img src=\"" . $OUTPUT->pix_url('icon', 'assignment') . "\" ".
3464              "class=\"icon\" alt=\"$modname\">";
3465         echo "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id={$activity->cmid}\">{$activity->name}</a>";
3466         echo '</div>';
3467     }
3469     if (isset($activity->grade)) {
3470         echo '<div class="grade">';
3471         echo get_string('grade').': ';
3472         echo $activity->grade;
3473         echo '</div>';
3474     }
3476     echo '<div class="user">';
3477     echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->id}&amp;course=$courseid\">"
3478          ."{$activity->user->fullname}</a>  - ".userdate($activity->timestamp);
3479     echo '</div>';
3481     echo "</td></tr></table>";
3484 /// GENERIC SQL FUNCTIONS
3486 /**
3487  * Fetch info from logs
3488  *
3489  * @param $log object with properties ->info (the assignment id) and ->userid
3490  * @return array with assignment name and user firstname and lastname
3491  */
3492 function assignment_log_info($log) {
3493     global $CFG, $DB;
3495     return $DB->get_record_sql("SELECT a.name, u.firstname, u.lastname
3496                                   FROM {assignment} a, {user} u
3497                                  WHERE a.id = ? AND u.id = ?", array($log->info, $log->userid));
3500 /**
3501  * Return list of marked submissions that have not been mailed out for currently enrolled students
3502  *
3503  * @return array
3504  */
3505 function assignment_get_unmailed_submissions($starttime, $endtime) {
3506     global $CFG, $DB;
3508     return $DB->get_records_sql("SELECT s.*, a.course, a.name
3509                                    FROM {assignment_submissions} s,
3510                                         {assignment} a
3511                                   WHERE s.mailed = 0
3512                                         AND s.timemarked <= ?
3513                                         AND s.timemarked >= ?
3514                                         AND s.assignment = a.id", array($endtime, $starttime));
3517 /**
3518  * Counts all complete (real) assignment submissions by enrolled students for the given course modeule.
3519  *
3520  * @deprecated                         Since Moodle 2.2 MDL-abc - Please do not use this function any more.
3521  * @param  cm_info $cm                 The course module that we wish to perform the count on.
3522  * @param  int     $groupid (optional) If nonzero then count is restricted to this group
3523  * @return int                         The number of submissions
3524  */
3525 function assignment_count_real_submissions($cm, $groupid=0) {
3526     global $CFG, $DB;
3528     // Grab the assignment type for the given course module
3529     $assignmenttype = $DB->get_field($cm->modname, 'assignmenttype', array('id' => $cm->instance), MUST_EXIST);
3531     // Create the expected class file path and class name for the returned assignemnt type
3532     $filename = "{$CFG->dirroot}/mod/assignment/type/{$assignmenttype}/assignment.class.php";
3533     $classname = "assignment_{$assignmenttype}";
3535     // If the file exists and the class is not already loaded we require the class file
3536     if (file_exists($filename) && !class_exists($classname)) {
3537         require_once($filename);
3538     }
3539     // If the required class is still not loaded then we revert to assignment base
3540     if (!class_exists($classname)) {
3541         $classname = 'assignment_base';
3542     }
3543     $instance = new $classname;
3545     // Attach the course module to the assignment type instance and then call the method for counting submissions
3546     $instance->cm = $cm;
3547     return $instance->count_real_submissions($groupid);
3550 /**
3551  * Return all assignment submissions by ENROLLED students (even empty)
3552  *
3553  * There are also assignment type methods get_submissions() wich in the default
3554  * implementation simply call this function.
3555  * @param $sort string optional field names for the ORDER BY in the sql query
3556  * @param $dir string optional specifying the sort direction, defaults to DESC
3557  * @return array The submission objects indexed by id
3558  */
3559 function assignment_get_all_submissions($assignment, $sort="", $dir="DESC") {
3560 /// Return all assignment submissions by ENROLLED students (even empty)
3561     global $CFG, $DB;
3563     if ($sort == "lastname" or $sort == "firstname") {
3564         $sort = "u.$sort $dir";
3565     } else if (empty($sort)) {
3566         $sort = "a.timemodified DESC";
3567     } else {
3568         $sort = "a.$sort $dir";
3569     }
3571     /* not sure this is needed at all since assignment already has a course define, so this join?
3572     $select = "s.course = '$assignment->course' AND";
3573     if ($assignment->course == SITEID) {
3574         $select = '';
3575     }*/
3577     return $DB->get_records_sql("SELECT a.*
3578                                    FROM {assignment_submissions} a, {user} u
3579                                   WHERE u.id = a.userid
3580                                         AND a.assignment = ?
3581                                ORDER BY $sort", array($assignment->id));
3585 /**
3586  * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
3587  * for the course (see resource).
3588  *
3589  * Given a course_module object, this function returns any "extra" information that may be needed
3590  * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
3591  *
3592  * @param $coursemodule object The coursemodule object (record).
3593  * @return cached_cm_info An object on information that the courses will know about (most noticeably, an icon).
3594  */
3595 function assignment_get_coursemodule_info($coursemodule) {
3596     global $CFG, $DB;
3598     if (! $assignment = $DB->get_record('assignment', array('id'=>$coursemodule->instance),
3599             'id, assignmenttype, name, intro, introformat')) {
3600         return false;
3601     }
3603     $libfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
3605     if (file_exists($libfile)) {
3606         require_once($libfile);
3607         $assignmentclass = "assignment_$assignment->assignmenttype";
3608         $ass = new $assignmentclass('staticonly');
3609         if (!($result = $ass->get_coursemodule_info($coursemodule))) {
3610             $result = new cached_cm_info();
3611             $result->name = $assignment->name;
3612         }
3613         if ($coursemodule->showdescription) {
3614             // Convert intro to html. Do not filter cached version, filters run at display time.
3615             $result->content = format_module_intro('assignment', $assignment, $coursemodule->id, false);
3616         }
3617         return $result;
3618     } else {
3619         debugging('Incorrect assignment type: '.$assignment->assignmenttype);
3620         return false;
3621     }
3626 /// OTHER GENERAL FUNCTIONS FOR ASSIGNMENTS  ///////////////////////////////////////
3628 /**
3629  * Returns an array of installed assignment types indexed and sorted by name
3630  *
3631  * @return array The index is the name of the assignment type, the value its full name from the language strings
3632  */
3633 function assignment_types() {
3634     $types = array();
3635     $names = get_plugin_list('assignment');
3636     foreach ($names as $name=>$dir) {
3637         $types[$name] = get_string('type'.$name, 'assignment');
3639         // ugly hack to support pluggable assignment type titles..
3640         if ($types[$name] == '[[type'.$name.']]') {
3641             $types[$name] = get_string('type'.$name, 'assignment_'.$name);
3642         }
3643     }
3644     asort($types);
3645     return $types;
3648 function assignment_print_overview($courses, &$htmlarray) {
3649     global $USER, $CFG, $DB;
3650     require_once($CFG->libdir.'/gradelib.php');
3652     if (empty($courses) || !is_array($courses) || count($courses) == 0) {
3653         return array();
3654     }
3656     if (!$assignments = get_all_instances_in_courses('assignment',$courses)) {
3657         return;
3658     }
3660     $assignmentids = array();
3662     // Do assignment_base::isopen() here without loading the whole thing for speed
3663     foreach ($assignments as $key => $assignment) {
3664         $time = time();
3665         if ($assignment->timedue) {
3666             if ($assignment->preventlate) {
3667                 $isopen = ($assignment->timeavailable <= $time && $time <= $assignment->timedue);
3668             } else {
3669                 $isopen = ($assignment->timeavailable <= $time);
3670             }
3671         }
3672         if (empty($isopen) || empty($assignment->timedue)) {
3673             unset($assignments[$key]);
3674         } else {
3675             $assignmentids[] = $assignment->id;
3676         }
3677     }
3679     if (empty($assignmentids)){
3680         // no assignments to look at - we're done
3681         return true;
3682     }
3684     $strduedate = get_string('duedate', 'assignment');
3685     $strduedateno = get_string('duedateno', 'assignment');
3686     $strgraded = get_string('graded', 'assignment');
3687     $strnotgradedyet = get_string('notgradedyet', 'assignment');
3688     $strnotsubmittedyet = get_string('notsubmittedyet', 'assignment');
3689     $strsubmitted = get_string('submitted', 'assignment');
3690     $strassignment = get_string('modulename', 'assignment');
3691     $strreviewed = get_string('reviewed','assignment');
3694     // NOTE: we do all possible database work here *outside* of the loop to ensure this scales
3695     //
3696     list($sqlassignmentids, $assignmentidparams) = $DB->get_in_or_equal($assignmentids);
3698     // build up and array of unmarked submissions indexed by assignment id/ userid
3699     // for use where the user has grading rights on assignment
3700     $rs = $DB->get_recordset_sql("SELECT id, assignment, userid
3701                             FROM {assignment_submissions}
3702                             WHERE teacher = 0 AND timemarked = 0
3703                             AND assignment $sqlassignmentids", $assignmentidparams);
3705     $unmarkedsubmissions = array();
3706     foreach ($rs as $rd) {
3707         $unmarkedsubmissions[$rd->assignment][$rd->userid] = $rd->id;
3708     }
3709     $rs->close();
3712     // get all user submissions, indexed by assignment id
3713     $mysubmissions = $DB->get_records_sql("SELECT assignment, timemarked, teacher, grade
3714                                       FROM {assignment_submissions}
3715                                       WHERE userid = ? AND
3716                                       assignment $sqlassignmentids", array_merge(array($USER->id), $assignmentidparams));
3718     foreach ($assignments as $assignment) {
3719         $grading_info = grade_get_grades($assignment->course, 'mod', 'assignment', $assignment->id, $USER->id);
3720         $final_grade = $grading_info->items[0]->grades[$USER->id];
3722         $str = '<div class="assignment overview"><div class="name">'.$strassignment. ': '.
3723                '<a '.($assignment->visible ? '':' class="dimmed"').
3724                'title="'.$strassignment.'" href="'.$CFG->wwwroot.
3725                '/mod/assignment/view.php?id='.$assignment->coursemodule.'">'.
3726                $assignment->name.'</a></div>';
3727         if ($assignment->timedue) {
3728             $str .= '<div class="info">'.$strduedate.': '.userdate($assignment->timedue).'</div>';
3729         } else {
3730             $str .= '<div class="info">'.$strduedateno.'</div>';
3731         }
3732         $context = context_module::instance($assignment->coursemodule);
3733         if (has_capability('mod/assignment:grade', $context)) {
3735             // count how many people can submit
3736             $submissions = 0; // init
3737             if ($students = get_enrolled_users($context, 'mod/assignment:view', 0, 'u.id')) {
3738                 foreach ($students as $student) {
3739                     if (isset($unmarkedsubmissions[$assignment->id][$student->id])) {
3740                         $submissions++;
3741                     }
3742                 }
3743             }
3745             if ($submissions) {
3746                 $link = new moodle_url('/mod/assignment/submissions.php', array('id'=>$assignment->coursemodule));
3747                 $str .= '<div class="details"><a href="'.$link.'">'.get_string('submissionsnotgraded', 'assignment', $submissions).'</a></div>';
3748             }
3749         } else {
3750             $str .= '<div class="details">';
3751             if (isset($mysubmissions[$assignment->id])) {
3753                 $submission = $mysubmissions[$assignment->id];
3755                 if ($submission->teacher == 0 && $submission->timemarked == 0 && !$final_grade->grade) {
3756                     $str .= $strsubmitted . ', ' . $strnotgradedyet;
3757                 } else if ($submission->grade <= 0 && !$final_grade->grade) {
3758                     $str .= $strsubmitted . ', ' . $strreviewed;
3759                 } else {
3760                     $str .= $strsubmitted . ', ' . $strgraded;
3761                 }
3762             } else {
3763                 $str .= $strnotsubmittedyet . ' ' . assignment_display_lateness(time(), $assignment->timedue);
3764             }
3765             $str .= '</div>';
3766         }
3767         $str .= '</div>';
3768         if (empty($htmlarray[$assignment->course]['assignment'])) {
3769             $htmlarray[$assignment->course]['assignment'] = $str;
3770         } else {
3771             $htmlarray[$assignment->course]['assignment'] .= $str;
3772         }
3773     }
3776 function assignment_display_lateness($timesubmitted, $timedue) {
3777     if (!$timedue) {
3778         return '';
3779     }
3780     $time = $timedue - $timesubmitted;
3781     if ($time < 0) {
3782         $timetext = get_string('late', 'assignment', format_time($time));
3783         return ' (<span class="late">'.$timetext.'</span>)';
3784     } else {
3785         $timetext = get_string('early', 'assignment', format_time($time));
3786         return ' (<span class="early">'.$timetext.'</span>)';
3787     }
3790 function assignment_get_view_actions() {
3791     return array('view');
3794 function assignment_get_post_actions() {
3795     return array('upload');
3798 function assignment_get_types() {
3799     global $CFG;
3800     $types = array();
3802     $type = new stdClass();
3803     $type->modclass = MOD_CLASS_ACTIVITY;
3804     $type->type = "assignment_group_start";
3805     $type->typestr = '--'.get_string('modulenameplural', 'assignment');
3806     $types[] = $type;
3808     $standardassignments = array('upload','online','uploadsingle','offline');
3809     foreach ($standardassignments as $assignmenttype) {
3810         $type = new stdClass();
3811         $type->modclass = MOD_CLASS_ACTIVITY;
3812         $type->type = "assignment&amp;type=$assignmenttype";
3813         $type->typestr = get_string("type$assignmenttype", 'assignment');
3814         $types[] = $type;
3815     }
3817     /// Drop-in extra assignment types
3818     $assignmenttypes = get_list_of_plugins('mod/assignment/type');
3819     foreach ($assignmenttypes as $assignmenttype) {
3820         if (!empty($CFG->{'assignment_hide_'.$assignmenttype})) {  // Not wanted
3821             continue;
3822         }
3823         if (!in_array($assignmenttype, $standardassignments)) {
3824             $type = new stdClass();
3825             $type->modclass = MOD_CLASS_ACTIVITY;
3826             $type->type = "assignment&amp;type=$assignmenttype";
3827             $type->typestr = get_string("type$assignmenttype", 'assignment_'.$assignmenttype);
3828             $types[] = $type;
3829         }
3830     }
3832     $type = new stdClass();
3833     $type->modclass = MOD_CLASS_ACTIVITY;
3834     $type->type = "assignment_group_end";
3835     $type->typestr = '--';
3836     $types[] = $type;
3838     return $types;
3841 /**
3842  * Removes all grades from gradebook
3843  *
3844  * @param int $courseid The ID of the course to reset
3845  * @param string $type Optional type of assignment to limit the reset to a particular assignment type
3846  */
3847 function assignment_reset_gradebook($courseid, $type='') {
3848     global $CFG, $DB;
3850     $params = array('courseid'=>$courseid);
3851     if ($type) {
3852         $type = "AND a.assignmenttype= :type";
3853         $params['type'] = $type;
3854     }
3856     $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
3857               FROM {assignment} a, {course_modules} cm, {modules} m
3858              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id AND a.course=:courseid $type";
3860     if ($assignments = $DB->get_records_sql($sql, $params)) {
3861         foreach ($assignments as $assignment) {
3862             assignment_grade_item_update($assignment, 'reset');
3863         }
3864     }
3867 /**
3868  * This function is used by the reset_course_userdata function in moodlelib.
3869  * This function will remove all posts from the specified assignment
3870  * and clean up any related data.
3871  * @param $data the data submitted from the reset course.
3872  * @return array status array
3873  */
3874 function assignment_reset_userdata($data) {
3875     global $CFG;
3877     $status = array();
3878     foreach (get_plugin_list('assignment') as $type=>$dir) {
3879         require_once("$dir/assignment.class.php");
3880         $assignmentclass = "assignment_$type";
3881         $ass = new $assignmentclass();
3882         $status = array_merge($status, $ass->reset_userdata($data));
3883     }
3885     return $status;
3888 /**
3889  * Implementation of the function for printing the form elements that control