3 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
19 * assignment_base is the base class for assignment types
21 * This class provides all the functionality for an assignment
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
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);
41 * Standard base class for all assignment submodules (assignment types).
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
47 class assignment_base {
50 const FILTER_SUBMITTED = 1;
51 const FILTER_REQUIRE_GRADING = 2;
74 * @todo document this var
78 * @todo document this var
85 * Constructor for the base assignment class
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.
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
99 function assignment_base($cmid='staticonly', $assignment=NULL, $cm=NULL, $course=NULL) {
102 if ($cmid == 'staticonly') {
103 //use static functions only!
111 } else if (! $this->cm = get_coursemodule_from_id('assignment', $cmid)) {
112 print_error('invalidcoursemodule');
115 $this->context = get_context_instance(CONTEXT_MODULE, $this->cm->id);
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');
124 $this->coursecontext = get_context_instance(CONTEXT_COURSE, $this->course->id);
125 $courseshortname = format_text($this->course->shortname, true, array('context' => $this->coursecontext));
128 $this->assignment = $assignment;
129 } else if (! $this->assignment = $DB->get_record('assignment', array('id'=>$this->cm->instance))) {
130 print_error('invalidid', 'assignment');
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();
150 * Display the assignment, used by view.php
152 * This in turn calls the methods producing individual parts of the page
156 $context = get_context_instance(CONTEXT_MODULE,$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();
168 $this->view_feedback();
170 $this->view_footer();
174 * Display the header and top of a page
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
182 * @param string $subpage Description of subpage to be used in navigation trail
184 function view_header($subpage='') {
185 global $CFG, $PAGE, $OUTPUT;
188 $PAGE->navbar->add($subpage);
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>';
204 * Display the assignment intro
206 * This will most likely be extended by assignment type plug-ins
207 * The default implementation prints the assignment description in a box
209 function view_intro() {
211 echo $OUTPUT->box_start('generalbox boxaligncenter', 'intro');
212 echo format_module_intro('assignment', $this->assignment, $this->cm->id);
213 echo $OUTPUT->box_end();
214 plagiarism_print_disclosure($this->cm->id);
218 * Display the assignment dates
220 * Prints the assignment start and end dates in a box.
221 * This will be suitable for most assignment types
223 function view_dates() {
225 if (!$this->assignment->timeavailable && !$this->assignment->timedue) {
229 echo $OUTPUT->box_start('generalbox boxaligncenter', 'dates');
231 if ($this->assignment->timeavailable) {
232 echo '<tr><td class="c0">'.get_string('availabledate','assignment').':</td>';
233 echo ' <td class="c1">'.userdate($this->assignment->timeavailable).'</td></tr>';
235 if ($this->assignment->timedue) {
236 echo '<tr><td class="c0">'.get_string('duedate','assignment').':</td>';
237 echo ' <td class="c1">'.userdate($this->assignment->timedue).'</td></tr>';
240 echo $OUTPUT->box_end();
245 * Display the bottom and footer of a page
247 * This default method just prints the footer.
248 * This will be suitable for most assignment types
250 function view_footer() {
252 echo $OUTPUT->footer();
256 * Display the feedback to the student
258 * This default method prints the teacher picture and name, date when marked,
259 * grade and teacher submissioncomment.
264 * @param object $submission The submission object or NULL in which case it will be loaded
266 function view_feedback($submission=NULL) {
267 global $USER, $CFG, $DB, $OUTPUT;
268 require_once($CFG->libdir.'/gradelib.php');
270 if (!is_enrolled($this->context, $USER, 'mod/assignment:view')) {
271 // can not submit assignments -> no feedback
275 if (!$submission) { /// Get submission for this assignment
276 $submission = $this->get_submission($USER->id);
278 // Check the user can submit
279 $cansubmit = has_capability('mod/assignment:submit', $this->context, $USER->id, false);
280 // If not then check if the user still has the view cap and has a previous submission
281 $cansubmit = $cansubmit || (!empty($submission) && has_capability('mod/assignment:view', $this->context, $USER->id, false));
284 // can not submit assignments -> no feedback
288 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $USER->id);
289 $item = $grading_info->items[0];
290 $grade = $item->grades[$USER->id];
292 if ($grade->hidden or $grade->grade === false) { // hidden or error
296 if ($grade->grade === null and empty($grade->str_feedback)) { /// Nothing to show yet
300 $graded_date = $grade->dategraded;
301 $graded_by = $grade->usermodified;
303 /// We need the teacher info
304 if (!$teacher = $DB->get_record('user', array('id'=>$graded_by))) {
305 print_error('cannotfindteacher');
308 /// Print the feedback
309 echo $OUTPUT->heading(get_string('feedbackfromteacher', 'assignment', fullname($teacher)));
311 echo '<table cellspacing="0" class="feedback">';
314 echo '<td class="left picture">';
316 echo $OUTPUT->user_picture($teacher);
319 echo '<td class="topic">';
320 echo '<div class="from">';
322 echo '<div class="fullname">'.fullname($teacher).'</div>';
324 echo '<div class="time">'.userdate($graded_date).'</div>';
330 echo '<td class="left side"> </td>';
331 echo '<td class="content">';
332 echo '<div class="grade">';
333 echo get_string("grade").': '.$grade->str_long_grade;
335 echo '<div class="clearer"></div>';
337 echo '<div class="comment">';
338 echo $grade->str_feedback;
342 if ($this->type == 'uploadsingle') { //@TODO: move to overload view_feedback method in the class or is uploadsingle merging into upload?
343 $responsefiles = $this->print_responsefiles($submission->userid, true);
344 if (!empty($responsefiles)) {
346 echo '<td class="left side"> </td>';
347 echo '<td class="content">';
357 * Returns a link with info about the state of the assignment submissions
359 * This is used by view_header to put this link at the top right of the page.
360 * For teachers it gives the number of submitted assignments with a link
361 * For students it gives the time of their submission.
362 * This will be suitable for most assignment types.
366 * @param bool $allgroup print all groups info if user can access all groups, suitable for index.php
369 function submittedlink($allgroups=false) {
374 $urlbase = "{$CFG->wwwroot}/mod/assignment/";
376 $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
377 if (has_capability('mod/assignment:grade', $context)) {
378 if ($allgroups and has_capability('moodle/site:accessallgroups', $context)) {
381 $group = groups_get_activity_group($this->cm);
383 if ($this->type == 'offline') {
384 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
385 get_string('viewfeedback', 'assignment').'</a>';
386 } else if ($count = $this->count_real_submissions($group)) {
387 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
388 get_string('viewsubmissions', 'assignment', $count).'</a>';
390 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
391 get_string('noattempts', 'assignment').'</a>';
395 if ($submission = $this->get_submission($USER->id)) {
396 if ($submission->timemodified) {
397 if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
398 $submitted = '<span class="early">'.userdate($submission->timemodified).'</span>';
400 $submitted = '<span class="late">'.userdate($submission->timemodified).'</span>';
412 * @todo Document this function
414 function setup_elements(&$mform) {
419 * Any preprocessing needed for the settings form for
420 * this assignment type
422 * @param array $default_values - array to fill in with the default values
423 * in the form 'formelement' => 'value'
424 * @param object $form - the form that is to be displayed
427 function form_data_preprocessing(&$default_values, $form) {
431 * Any extra validation checks needed for the settings
432 * form for this assignment type
434 * See lib/formslib.php, 'validation' function for details
436 function form_validation($data, $files) {
441 * Create a new assignment activity
443 * Given an object containing all the necessary data,
444 * (defined by the form in mod_form.php) this function
445 * will create a new instance and return the id number
446 * of the new instance.
447 * The due data is added to the calendar
448 * This is common to all assignment types.
452 * @param object $assignment The data from the form on mod_form.php
453 * @return int The id of the assignment
455 function add_instance($assignment) {
458 $assignment->timemodified = time();
459 $assignment->courseid = $assignment->course;
461 $returnid = $DB->insert_record("assignment", $assignment);
462 $assignment->id = $returnid;
464 if ($assignment->timedue) {
465 $event = new stdClass();
466 $event->name = $assignment->name;
467 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
468 $event->courseid = $assignment->course;
471 $event->modulename = 'assignment';
472 $event->instance = $returnid;
473 $event->eventtype = 'due';
474 $event->timestart = $assignment->timedue;
475 $event->timeduration = 0;
477 calendar_event::create($event);
480 assignment_grade_item_update($assignment);
486 * Deletes an assignment activity
488 * Deletes all database records, files and calendar events for this assignment.
492 * @param object $assignment The assignment to be deleted
493 * @return boolean False indicates error
495 function delete_instance($assignment) {
498 $assignment->courseid = $assignment->course;
502 // now get rid of all files
503 $fs = get_file_storage();
504 if ($cm = get_coursemodule_from_instance('assignment', $assignment->id)) {
505 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
506 $fs->delete_area_files($context->id);
509 if (! $DB->delete_records('assignment_submissions', array('assignment'=>$assignment->id))) {
513 if (! $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
517 if (! $DB->delete_records('assignment', array('id'=>$assignment->id))) {
520 $mod = $DB->get_field('modules','id',array('name'=>'assignment'));
522 assignment_grade_item_delete($assignment);
528 * Updates a new assignment activity
530 * Given an object containing all the necessary data,
531 * (defined by the form in mod_form.php) this function
532 * will update the assignment instance and return the id number
533 * The due date is updated in the calendar
534 * This is common to all assignment types.
538 * @param object $assignment The data from the form on mod_form.php
539 * @return bool success
541 function update_instance($assignment) {
544 $assignment->timemodified = time();
546 $assignment->id = $assignment->instance;
547 $assignment->courseid = $assignment->course;
549 $DB->update_record('assignment', $assignment);
551 if ($assignment->timedue) {
552 $event = new stdClass();
554 if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
556 $event->name = $assignment->name;
557 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
558 $event->timestart = $assignment->timedue;
560 $calendarevent = calendar_event::load($event->id);
561 $calendarevent->update($event);
563 $event = new stdClass();
564 $event->name = $assignment->name;
565 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
566 $event->courseid = $assignment->course;
569 $event->modulename = 'assignment';
570 $event->instance = $assignment->id;
571 $event->eventtype = 'due';
572 $event->timestart = $assignment->timedue;
573 $event->timeduration = 0;
575 calendar_event::create($event);
578 $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id));
581 // get existing grade item
582 assignment_grade_item_update($assignment);
588 * Update grade item for this submission.
590 function update_grade($submission) {
591 assignment_update_grades($this->assignment, $submission->userid);
595 * Top-level function for handling of submissions called by submissions.php
597 * This is for handling the teacher interaction with the grading interface
598 * This should be suitable for most assignment types.
601 * @param string $mode Specifies the kind of teacher interaction taking place
603 function submissions($mode) {
604 ///The main switch is changed to facilitate
605 ///1) Batch fast grading
606 ///2) Skip to the next one on the popup
607 ///3) Save and Skip to the next one on the popup
609 //make user global so we can use the id
610 global $USER, $OUTPUT, $DB, $PAGE;
612 $mailinfo = optional_param('mailinfo', null, PARAM_BOOL);
614 if (optional_param('next', null, PARAM_BOOL)) {
617 if (optional_param('saveandnext', null, PARAM_BOOL)) {
621 if (is_null($mailinfo)) {
622 if (optional_param('sesskey', null, PARAM_BOOL)) {
623 set_user_preference('assignment_mailinfo', $mailinfo);
625 $mailinfo = get_user_preferences('assignment_mailinfo', 0);
628 set_user_preference('assignment_mailinfo', $mailinfo);
632 case 'grade': // We are in a main window grading
633 if ($submission = $this->process_feedback()) {
634 $this->display_submissions(get_string('changessaved'));
636 $this->display_submissions();
640 case 'single': // We are in a main window displaying one submission
641 if ($submission = $this->process_feedback()) {
642 $this->display_submissions(get_string('changessaved'));
644 $this->display_submission();
648 case 'all': // Main window, display everything
649 $this->display_submissions();
653 ///do the fast grading stuff - this process should work for all 3 subclasses
657 if (isset($_POST['submissioncomment'])) {
658 $col = 'submissioncomment';
661 if (isset($_POST['menu'])) {
666 //both submissioncomment and grade columns collapsed..
667 $this->display_submissions();
671 foreach ($_POST[$col] as $id => $unusedvalue){
673 $id = (int)$id; //clean parameter name
675 $this->process_outcomes($id);
677 if (!$submission = $this->get_submission($id)) {
678 $submission = $this->prepare_new_submission($id);
679 $newsubmission = true;
681 $newsubmission = false;
683 unset($submission->data1); // Don't need to update this.
684 unset($submission->data2); // Don't need to update this.
686 //for fast grade, we need to check if any changes take place
690 $grade = $_POST['menu'][$id];
691 $updatedb = $updatedb || ($submission->grade != $grade);
692 $submission->grade = $grade;
694 if (!$newsubmission) {
695 unset($submission->grade); // Don't need to update this.
699 $commentvalue = trim($_POST['submissioncomment'][$id]);
700 $updatedb = $updatedb || ($submission->submissioncomment != $commentvalue);
701 $submission->submissioncomment = $commentvalue;
703 unset($submission->submissioncomment); // Don't need to update this.
706 $submission->teacher = $USER->id;
708 $submission->mailed = (int)(!$mailinfo);
711 $submission->timemarked = time();
713 //if it is not an update, we don't change the last modified time etc.
714 //this will also not write into database if no submissioncomment and grade is entered.
717 if ($newsubmission) {
718 if (!isset($submission->submissioncomment)) {
719 $submission->submissioncomment = '';
721 $sid = $DB->insert_record('assignment_submissions', $submission);
722 $submission->id = $sid;
724 $DB->update_record('assignment_submissions', $submission);
727 // trigger grade event
728 $this->update_grade($submission);
730 //add to log only if updating
731 add_to_log($this->course->id, 'assignment', 'update grades',
732 'submissions.php?id='.$this->cm->id.'&user='.$submission->userid,
733 $submission->userid, $this->cm->id);
738 $message = $OUTPUT->notification(get_string('changessaved'), 'notifysuccess');
740 $this->display_submissions($message);
745 ///We are in pop up. save the current one and go to the next one.
746 //first we save the current changes
747 if ($submission = $this->process_feedback()) {
748 //print_heading(get_string('changessaved'));
749 //$extra_javascript = $this->update_main_listing($submission);
753 /// We are currently in pop up, but we want to skip to next one without saving.
754 /// This turns out to be similar to a single case
755 /// The URL used is for the next submission.
756 $offset = required_param('offset', PARAM_INT);
757 $nextid = required_param('nextid', PARAM_INT);
758 $id = required_param('id', PARAM_INT);
759 $offset = (int)$offset+1;
760 //$this->display_submission($offset+1 , $nextid);
761 redirect('submissions.php?id='.$id.'&userid='. $nextid . '&mode=single&offset='.$offset);
765 $this->display_submission();
769 echo "something seriously is wrong!!";
775 * Helper method updating the listing on the main script from popup using javascript
779 * @param $submission object The submission whose data is to be updated on the main page
781 function update_main_listing($submission) {
782 global $SESSION, $CFG, $OUTPUT;
786 $perpage = get_user_preferences('assignment_perpage', 10);
788 $quickgrade = get_user_preferences('assignment_quickgrade', 0);
790 /// Run some Javascript to try and update the parent page
791 $output .= '<script type="text/javascript">'."\n<!--\n";
792 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['submissioncomment'])) {
794 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid.'").value="'
795 .trim($submission->submissioncomment).'";'."\n";
797 $output.= 'opener.document.getElementById("com'.$submission->userid.
798 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment)), 15)."\";\n";
802 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['grade'])) {
803 //echo optional_param('menuindex');
805 $output.= 'opener.document.getElementById("menumenu'.$submission->userid.
806 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT).'";'."\n";
808 $output.= 'opener.document.getElementById("g'.$submission->userid.'").innerHTML="'.
809 $this->display_grade($submission->grade)."\";\n";
812 //need to add student's assignments in there too.
813 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemodified']) &&
814 $submission->timemodified) {
815 $output.= 'opener.document.getElementById("ts'.$submission->userid.
816 '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid)).userdate($submission->timemodified)."\";\n";
819 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemarked']) &&
820 $submission->timemarked) {
821 $output.= 'opener.document.getElementById("tt'.$submission->userid.
822 '").innerHTML="'.userdate($submission->timemarked)."\";\n";
825 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['status'])) {
826 $output.= 'opener.document.getElementById("up'.$submission->userid.'").className="s1";';
827 $buttontext = get_string('update');
828 $url = new moodle_url('/mod/assignment/submissions.php', array(
829 'id' => $this->cm->id,
830 'userid' => $submission->userid,
832 'offset' => (optional_param('offset', '', PARAM_INT)-1)));
833 $button = $OUTPUT->action_link($url, $buttontext, new popup_action('click', $url, 'grade'.$submission->userid, array('height' => 450, 'width' => 700)), array('ttile'=>$buttontext));
835 $output .= 'opener.document.getElementById("up'.$submission->userid.'").innerHTML="'.addslashes_js($button).'";';
838 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $submission->userid);
840 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['finalgrade'])) {
841 $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid.
842 '").innerHTML="'.$grading_info->items[0]->grades[$submission->userid]->str_grade.'";'."\n";
845 if (!empty($CFG->enableoutcomes) and empty($SESSION->flextable['mod-assignment-submissions']->collapse['outcome'])) {
847 if (!empty($grading_info->outcomes)) {
848 foreach($grading_info->outcomes as $n=>$outcome) {
849 if ($outcome->grades[$submission->userid]->locked) {
854 $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.
855 '").selectedIndex="'.$outcome->grades[$submission->userid]->grade.'";'."\n";
858 $options = make_grades_menu(-$outcome->scaleid);
859 $options[0] = get_string('nooutcome', 'grades');
860 $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.'").innerHTML="'.$options[$outcome->grades[$submission->userid]->grade]."\";\n";
867 $output .= "\n-->\n</script>";
872 * Return a grade in user-friendly form, whether it's a scale or not
875 * @param mixed $grade
876 * @return string User-friendly representation of grade
878 function display_grade($grade) {
881 static $scalegrades = array(); // Cache scales for each assignment - they might have different scales!!
883 if ($this->assignment->grade >= 0) { // Normal number
887 return $grade.' / '.$this->assignment->grade;
891 if (empty($scalegrades[$this->assignment->id])) {
892 if ($scale = $DB->get_record('scale', array('id'=>-($this->assignment->grade)))) {
893 $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
898 if (isset($scalegrades[$this->assignment->id][$grade])) {
899 return $scalegrades[$this->assignment->id][$grade];
906 * Display a single submission, ready for grading on a popup window
908 * This default method prints the teacher info and submissioncomment box at the top and
909 * the student info and submission at the bottom.
910 * This method also fetches the necessary data in order to be able to
911 * provide a "Next submission" button.
912 * Calls preprocess_submission() to give assignment type plug-ins a chance
913 * to process submissions before they are graded
914 * This method gets its arguments from the page parameters userid and offset
918 * @param string $extra_javascript
920 function display_submission($offset=-1,$userid =-1, $display=true) {
921 global $CFG, $DB, $PAGE, $OUTPUT;
922 require_once($CFG->libdir.'/gradelib.php');
923 require_once($CFG->libdir.'/tablelib.php');
924 require_once("$CFG->dirroot/repository/lib.php");
926 $userid = required_param('userid', PARAM_INT);
929 $offset = required_param('offset', PARAM_INT);//offset for where to start looking for student.
931 $filter = optional_param('filter', 0, PARAM_INT);
933 if (!$user = $DB->get_record('user', array('id'=>$userid))) {
934 print_error('nousers');
937 if (!$submission = $this->get_submission($user->id)) {
938 $submission = $this->prepare_new_submission($userid);
940 if ($submission->timemodified > $submission->timemarked) {
941 $subtype = 'assignmentnew';
943 $subtype = 'assignmentold';
946 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
947 $gradingdisabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
949 /// construct SQL, using current offset to find the data of the next student
950 $course = $this->course;
951 $assignment = $this->assignment;
953 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
955 //reset filter to all for offline assignment
956 if ($assignment->assignmenttype == 'offline' && $filter == self::FILTER_SUBMITTED) {
957 $filter = self::FILTER_ALL;
959 /// Get all ppl that can submit assignments
961 $currentgroup = groups_get_activity_group($cm);
962 $users = get_enrolled_users($context, 'mod/assignment:view', $currentgroup, 'u.id');
964 $users = array_keys($users);
965 // if groupmembersonly used, remove users who are not in any group
966 if (!empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
967 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
968 $users = array_intersect($users, array_keys($groupingusers));
975 if($filter == self::FILTER_SUBMITTED) {
976 $where .= 's.timemodified > 0 AND ';
977 } else if($filter == self::FILTER_REQUIRE_GRADING) {
978 $where .= 's.timemarked < s.timemodified AND ';
982 $userfields = user_picture::fields('u', array('lastaccess'));
983 $select = "SELECT $userfields,
984 s.id AS submissionid, s.grade, s.submissioncomment,
985 s.timemodified, s.timemarked ";
986 $sql = 'FROM {user} u '.
987 'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
988 AND s.assignment = '.$this->assignment->id.' '.
989 'WHERE '.$where.'u.id IN ('.implode(',', $users).') ';
991 if ($sort = flexible_table::get_sort_for_table('mod-assignment-submissions')) {
992 $sort = 'ORDER BY '.$sort.' ';
994 $auser = $DB->get_records_sql($select.$sql.$sort, null, $offset, 2);
996 if (is_array($auser) && count($auser)>1) {
997 $nextuser = next($auser);
998 /// Calculate user status
999 $nextuser->status = ($nextuser->timemarked > 0) && ($nextuser->timemarked >= $nextuser->timemodified);
1000 $nextid = $nextuser->id;
1004 if ($submission->teacher) {
1005 $teacher = $DB->get_record('user', array('id'=>$submission->teacher));
1011 $this->preprocess_submission($submission);
1013 $mformdata = new stdClass();
1014 $mformdata->context = $this->context;
1015 $mformdata->maxbytes = $this->course->maxbytes;
1016 $mformdata->courseid = $this->course->id;
1017 $mformdata->teacher = $teacher;
1018 $mformdata->assignment = $assignment;
1019 $mformdata->submission = $submission;
1020 $mformdata->lateness = $this->display_lateness($submission->timemodified);
1021 $mformdata->auser = $auser;
1022 $mformdata->user = $user;
1023 $mformdata->offset = $offset;
1024 $mformdata->userid = $userid;
1025 $mformdata->cm = $this->cm;
1026 $mformdata->grading_info = $grading_info;
1027 $mformdata->enableoutcomes = $CFG->enableoutcomes;
1028 $mformdata->grade = $this->assignment->grade;
1029 $mformdata->gradingdisabled = $gradingdisabled;
1030 $mformdata->nextid = $nextid;
1031 $mformdata->submissioncomment= $submission->submissioncomment;
1032 $mformdata->submissioncommentformat= FORMAT_HTML;
1033 $mformdata->submission_content= $this->print_user_files($user->id,true);
1034 $mformdata->filter = $filter;
1035 $mformdata->mailinfo = get_user_preferences('assignment_mailinfo', 0);
1036 if ($assignment->assignmenttype == 'upload') {
1037 $mformdata->fileui_options = array('subdirs'=>1, 'maxbytes'=>$assignment->maxbytes, 'maxfiles'=>$assignment->var1, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL);
1038 } elseif ($assignment->assignmenttype == 'uploadsingle') {
1039 $mformdata->fileui_options = array('subdirs'=>0, 'maxbytes'=>$CFG->userquota, 'maxfiles'=>1, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL);
1042 $submitform = new mod_assignment_grading_form( null, $mformdata );
1045 $ret_data = new stdClass();
1046 $ret_data->mform = $submitform;
1047 $ret_data->fileui_options = $mformdata->fileui_options;
1051 if ($submitform->is_cancelled()) {
1052 redirect('submissions.php?id='.$this->cm->id);
1055 $submitform->set_data($mformdata);
1057 $PAGE->set_title($this->course->fullname . ': ' .get_string('feedback', 'assignment').' - '.fullname($user, true));
1058 $PAGE->set_heading($this->course->fullname);
1059 $PAGE->navbar->add(get_string('submissions', 'assignment'), new moodle_url('/mod/assignment/submissions.php', array('id'=>$cm->id)));
1060 $PAGE->navbar->add(fullname($user, true));
1062 echo $OUTPUT->header();
1063 echo $OUTPUT->heading(get_string('feedback', 'assignment').': '.fullname($user, true));
1065 // display mform here...
1066 $submitform->display();
1068 $customfeedback = $this->custom_feedbackform($submission, true);
1069 if (!empty($customfeedback)) {
1070 echo $customfeedback;
1073 echo $OUTPUT->footer();
1077 * Preprocess submission before grading
1079 * Called by display_submission()
1080 * The default type does nothing here.
1082 * @param object $submission The submission object
1084 function preprocess_submission(&$submission) {
1088 * Display all the submissions ready for grading
1094 * @param string $message
1097 function display_submissions($message='') {
1098 global $CFG, $DB, $USER, $DB, $OUTPUT, $PAGE;
1099 require_once($CFG->libdir.'/gradelib.php');
1101 /* first we check to see if the form has just been submitted
1102 * to request user_preference updates
1105 $filters = array(self::FILTER_ALL => get_string('all'),
1106 self::FILTER_REQUIRE_GRADING => get_string('requiregrading', 'assignment'));
1108 $updatepref = optional_param('updatepref', 0, PARAM_BOOL);
1110 $perpage = optional_param('perpage', 10, PARAM_INT);
1111 $perpage = ($perpage <= 0) ? 10 : $perpage ;
1112 $filter = optional_param('filter', 0, PARAM_INT);
1113 set_user_preference('assignment_perpage', $perpage);
1114 set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
1115 set_user_preference('assignment_filter', $filter);
1118 /* next we get perpage and quickgrade (allow quick grade) params
1121 $perpage = get_user_preferences('assignment_perpage', 10);
1122 $quickgrade = get_user_preferences('assignment_quickgrade', 0);
1123 $filter = get_user_preferences('assignment_filter', 0);
1124 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);
1126 if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
1127 $uses_outcomes = true;
1129 $uses_outcomes = false;
1132 $page = optional_param('page', 0, PARAM_INT);
1133 $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
1135 /// Some shortcuts to make the code read better
1137 $course = $this->course;
1138 $assignment = $this->assignment;
1140 $hassubmission = false;
1142 // reset filter to all for offline assignment only.
1143 if ($assignment->assignmenttype == 'offline') {
1144 if ($filter == self::FILTER_SUBMITTED) {
1145 $filter = self::FILTER_ALL;
1148 $filters[self::FILTER_SUBMITTED] = get_string('submitted', 'assignment');
1151 $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
1152 add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->cm->id, $this->assignment->id, $this->cm->id);
1154 $PAGE->set_title(format_string($this->assignment->name,true));
1155 $PAGE->set_heading($this->course->fullname);
1156 echo $OUTPUT->header();
1158 echo '<div class="usersubmissions">';
1160 //hook to allow plagiarism plugins to update status/print links.
1161 plagiarism_update_status($this->course, $this->cm);
1163 $course_context = get_context_instance(CONTEXT_COURSE, $course->id);
1164 if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
1165 echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">'
1166 . get_string('seeallcoursegrades', 'grades') . '</a></div>';
1169 if (!empty($message)) {
1170 echo $message; // display messages here if any
1173 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1175 /// Check to see if groups are being used in this assignment
1177 /// find out current groups mode
1178 $groupmode = groups_get_activity_groupmode($cm);
1179 $currentgroup = groups_get_activity_group($cm, true);
1180 groups_print_activity_menu($cm, $CFG->wwwroot . '/mod/assignment/submissions.php?id=' . $this->cm->id);
1182 /// Print quickgrade form around the table
1184 $formattrs = array();
1185 $formattrs['action'] = new moodle_url('/mod/assignment/submissions.php');
1186 $formattrs['id'] = 'fastg';
1187 $formattrs['method'] = 'post';
1189 echo html_writer::start_tag('form', $formattrs);
1190 echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'id', 'value'=> $this->cm->id));
1191 echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'mode', 'value'=> 'fastgrade'));
1192 echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'page', 'value'=> $page));
1193 echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=> sesskey()));
1196 /// Get all ppl that are allowed to submit assignments
1197 list($esql, $params) = get_enrolled_sql($context, 'mod/assignment:submit', $currentgroup);
1199 if ($filter == self::FILTER_ALL) {
1200 $sql = "SELECT u.id FROM {user} u ".
1201 "LEFT JOIN ($esql) eu ON eu.id=u.id ".
1202 "WHERE u.deleted = 0 AND eu.id=u.id ";
1204 $wherefilter = ' AND s.assignment = '. $this->assignment->id;
1205 $assignmentsubmission = "LEFT JOIN {assignment_submissions} s ON (u.id = s.userid) ";
1206 if($filter == self::FILTER_SUBMITTED) {
1207 $wherefilter .= ' AND s.timemodified > 0 ';
1208 } else if($filter == self::FILTER_REQUIRE_GRADING && $assignment->assignmenttype != 'offline') {
1209 $wherefilter .= ' AND s.timemarked < s.timemodified ';
1210 } else { // require grading for offline assignment
1211 $assignmentsubmission = "";
1215 $sql = "SELECT u.id FROM {user} u ".
1216 "LEFT JOIN ($esql) eu ON eu.id=u.id ".
1217 $assignmentsubmission.
1218 "WHERE u.deleted = 0 AND eu.id=u.id ".
1222 $users = $DB->get_records_sql($sql, $params);
1223 if (!empty($users)) {
1224 if($assignment->assignmenttype == 'offline' && $filter == self::FILTER_REQUIRE_GRADING) {
1225 //remove users who has submitted their assignment
1226 foreach ($this->get_submissions() as $submission) {
1227 if (array_key_exists($submission->userid, $users)) {
1228 unset($users[$submission->userid]);
1232 $users = array_keys($users);
1235 // if groupmembersonly used, remove users who are not in any group
1236 if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
1237 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1238 $users = array_intersect($users, array_keys($groupingusers));
1242 $tablecolumns = array('picture', 'fullname', 'grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade');
1243 if ($uses_outcomes) {
1244 $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
1247 $tableheaders = array('',
1248 get_string('fullnameuser'),
1249 get_string('grade'),
1250 get_string('comment', 'assignment'),
1251 get_string('lastmodified').' ('.get_string('submission', 'assignment').')',
1252 get_string('lastmodified').' ('.get_string('grade').')',
1253 get_string('status'),
1254 get_string('finalgrade', 'grades'));
1255 if ($uses_outcomes) {
1256 $tableheaders[] = get_string('outcome', 'grades');
1259 require_once($CFG->libdir.'/tablelib.php');
1260 $table = new flexible_table('mod-assignment-submissions');
1262 $table->define_columns($tablecolumns);
1263 $table->define_headers($tableheaders);
1264 $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&currentgroup='.$currentgroup);
1266 $table->sortable(true, 'lastname');//sorted by lastname by default
1267 $table->collapsible(true);
1268 $table->initialbars(true);
1270 $table->column_suppress('picture');
1271 $table->column_suppress('fullname');
1273 $table->column_class('picture', 'picture');
1274 $table->column_class('fullname', 'fullname');
1275 $table->column_class('grade', 'grade');
1276 $table->column_class('submissioncomment', 'comment');
1277 $table->column_class('timemodified', 'timemodified');
1278 $table->column_class('timemarked', 'timemarked');
1279 $table->column_class('status', 'status');
1280 $table->column_class('finalgrade', 'finalgrade');
1281 if ($uses_outcomes) {
1282 $table->column_class('outcome', 'outcome');
1285 $table->set_attribute('cellspacing', '0');
1286 $table->set_attribute('id', 'attempts');
1287 $table->set_attribute('class', 'submissions');
1288 $table->set_attribute('width', '100%');
1290 $table->no_sorting('finalgrade');
1291 $table->no_sorting('outcome');
1293 // Start working -- this is necessary as soon as the niceties are over
1296 /// Construct the SQL
1297 list($where, $params) = $table->get_sql_where();
1302 if ($filter == self::FILTER_SUBMITTED) {
1303 $where .= 's.timemodified > 0 AND ';
1304 } else if($filter == self::FILTER_REQUIRE_GRADING) {
1306 if ($assignment->assignmenttype != 'offline') {
1307 $where .= 's.timemarked < s.timemodified AND ';
1311 if ($sort = $table->get_sql_sort()) {
1312 $sort = ' ORDER BY '.$sort;
1315 $ufields = user_picture::fields('u');
1316 if (!empty($users)) {
1317 $select = "SELECT $ufields,
1318 s.id AS submissionid, s.grade, s.submissioncomment,
1319 s.timemodified, s.timemarked ";
1320 $sql = 'FROM {user} u '.
1321 'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1322 AND s.assignment = '.$this->assignment->id.' '.
1323 'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1325 $ausers = $DB->get_records_sql($select.$sql.$sort, $params, $table->get_page_start(), $table->get_page_size());
1327 $table->pagesize($perpage, count($users));
1329 ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1330 $offset = $page * $perpage;
1331 $strupdate = get_string('update');
1332 $strgrade = get_string('grade');
1333 $grademenu = make_grades_menu($this->assignment->grade);
1335 if ($ausers !== false) {
1336 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
1337 $endposition = $offset + $perpage;
1338 $currentposition = 0;
1339 foreach ($ausers as $auser) {
1340 if ($currentposition == $offset && $offset < $endposition) {
1341 $final_grade = $grading_info->items[0]->grades[$auser->id];
1342 $grademax = $grading_info->items[0]->grademax;
1343 $final_grade->formatted_grade = round($final_grade->grade,2) .' / ' . round($grademax,2);
1344 $locked_overridden = 'locked';
1345 if ($final_grade->overridden) {
1346 $locked_overridden = 'overridden';
1349 /// Calculate user status
1350 $auser->status = ($auser->timemarked > 0) && ($auser->timemarked >= $auser->timemodified);
1351 $picture = $OUTPUT->user_picture($auser);
1353 if (empty($auser->submissionid)) {
1354 $auser->grade = -1; //no submission yet
1357 if (!empty($auser->submissionid)) {
1358 $hassubmission = true;
1359 ///Prints student answer and student modified date
1360 ///attach file or print link to student answer, depending on the type of the assignment.
1361 ///Refer to print_student_answer in inherited classes.
1362 if ($auser->timemodified > 0) {
1363 $studentmodified = '<div id="ts'.$auser->id.'">'.$this->print_student_answer($auser->id)
1364 . userdate($auser->timemodified).'</div>';
1366 $studentmodified = '<div id="ts'.$auser->id.'"> </div>';
1368 ///Print grade, dropdown or text
1369 if ($auser->timemarked > 0) {
1370 $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
1372 if ($final_grade->locked or $final_grade->overridden) {
1373 $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1374 } else if ($quickgrade) {
1375 $attributes = array();
1376 $attributes['tabindex'] = $tabindex++;
1377 $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1378 $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
1380 $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1384 $teachermodified = '<div id="tt'.$auser->id.'"> </div>';
1385 if ($final_grade->locked or $final_grade->overridden) {
1386 $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1387 } else if ($quickgrade) {
1388 $attributes = array();
1389 $attributes['tabindex'] = $tabindex++;
1390 $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1391 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1393 $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1397 if ($final_grade->locked or $final_grade->overridden) {
1398 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';
1400 } else if ($quickgrade) {
1401 $comment = '<div id="com'.$auser->id.'">'
1402 . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1403 . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1405 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
1408 $studentmodified = '<div id="ts'.$auser->id.'"> </div>';
1409 $teachermodified = '<div id="tt'.$auser->id.'"> </div>';
1410 $status = '<div id="st'.$auser->id.'"> </div>';
1412 if ($final_grade->locked or $final_grade->overridden) {
1413 $grade = '<div id="g'.$auser->id.'">'.$final_grade->formatted_grade . '</div>';
1414 $hassubmission = true;
1415 } else if ($quickgrade) { // allow editing
1416 $attributes = array();
1417 $attributes['tabindex'] = $tabindex++;
1418 $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1419 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1420 $hassubmission = true;
1422 $grade = '<div id="g'.$auser->id.'">-</div>';
1425 if ($final_grade->locked or $final_grade->overridden) {
1426 $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
1427 } else if ($quickgrade) {
1428 $comment = '<div id="com'.$auser->id.'">'
1429 . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1430 . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1432 $comment = '<div id="com'.$auser->id.'"> </div>';
1436 if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
1442 $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
1444 ///No more buttons, we use popups ;-).
1445 $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1446 . '&userid='.$auser->id.'&mode=single'.'&filter='.$filter.'&offset='.$offset++;
1448 $button = $OUTPUT->action_link($popup_url, $buttontext);
1450 $status = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
1452 $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';
1456 if ($uses_outcomes) {
1458 foreach($grading_info->outcomes as $n=>$outcome) {
1459 $outcomes .= '<div class="outcome"><label>'.$outcome->name.'</label>';
1460 $options = make_grades_menu(-$outcome->scaleid);
1462 if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
1463 $options[0] = get_string('nooutcome', 'grades');
1464 $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
1466 $attributes = array();
1467 $attributes['tabindex'] = $tabindex++;
1468 $attributes['id'] = 'outcome_'.$n.'_'.$auser->id;
1469 $outcomes .= ' '.html_writer::select($options, 'outcome_'.$n.'['.$auser->id.']', $outcome->grades[$auser->id]->grade, array(0=>get_string('nooutcome', 'grades')), $attributes);
1471 $outcomes .= '</div>';
1475 $userlink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $auser->id . '&course=' . $course->id . '">' . fullname($auser, has_capability('moodle/site:viewfullnames', $this->context)) . '</a>';
1476 $row = array($picture, $userlink, $grade, $comment, $studentmodified, $teachermodified, $status, $finalgrade);
1477 if ($uses_outcomes) {
1480 $table->add_data($row);
1484 if ($hassubmission && ($this->assignment->assignmenttype=='upload' || $this->assignment->assignmenttype=='online' || $this->assignment->assignmenttype=='uploadsingle')) { //TODO: this is an ugly hack, where is the plugin spirit? (skodak)
1485 echo html_writer::start_tag('div', array('class' => 'mod-assignment-download-link'));
1486 echo html_writer::link(new moodle_url('/mod/assignment/submissions.php', array('id' => $this->cm->id, 'download' => 'zip')), get_string('downloadall', 'assignment'));
1487 echo html_writer::end_tag('div');
1489 $table->print_html(); /// Print the whole table
1491 if ($filter == self::FILTER_SUBMITTED) {
1492 echo html_writer::tag('div', get_string('nosubmisson', 'assignment'), array('class'=>'nosubmisson'));
1493 } else if ($filter == self::FILTER_REQUIRE_GRADING) {
1494 echo html_writer::tag('div', get_string('norequiregrading', 'assignment'), array('class'=>'norequiregrading'));
1499 /// Print quickgrade form around the table
1500 if ($quickgrade && $table->started_output && !empty($users)){
1501 $mailinfopref = false;
1502 if (get_user_preferences('assignment_mailinfo', 1)) {
1503 $mailinfopref = true;
1505 $emailnotification = html_writer::checkbox('mailinfo', 1, $mailinfopref, get_string('enablenotification','assignment'));
1507 $emailnotification .= $OUTPUT->help_icon('enablenotification', 'assignment');
1508 echo html_writer::tag('div', $emailnotification, array('class'=>'emailnotification'));
1510 $savefeedback = html_writer::empty_tag('input', array('type'=>'submit', 'name'=>'fastg', 'value'=>get_string('saveallfeedback', 'assignment')));
1511 echo html_writer::tag('div', $savefeedback, array('class'=>'fastgbutton'));
1513 echo html_writer::end_tag('form');
1514 } else if ($quickgrade) {
1515 echo html_writer::end_tag('form');
1519 /// End of fast grading form
1521 /// Mini form for setting user preference
1523 $formaction = new moodle_url('/mod/assignment/submissions.php', array('id'=>$this->cm->id));
1524 $mform = new MoodleQuickForm('optionspref', 'post', $formaction, '', array('class'=>'optionspref'));
1526 $mform->addElement('hidden', 'updatepref');
1527 $mform->setDefault('updatepref', 1);
1528 $mform->addElement('header', 'qgprefs', get_string('optionalsettings', 'assignment'));
1529 $mform->addElement('select', 'filter', get_string('show'), $filters);
1531 $mform->setDefault('filter', $filter);
1533 $mform->addElement('text', 'perpage', get_string('pagesize', 'assignment'), array('size'=>1));
1534 $mform->setDefault('perpage', $perpage);
1536 $mform->addElement('checkbox', 'quickgrade', get_string('quickgrade','assignment'));
1537 $mform->setDefault('quickgrade', $quickgrade);
1538 $mform->addHelpButton('quickgrade', 'quickgrade', 'assignment');
1540 $mform->addElement('submit', 'savepreferences', get_string('savepreferences'));
1544 echo $OUTPUT->footer();
1548 * Process teacher feedback submission
1550 * This is called by submissions() when a grading even has taken place.
1551 * It gets its data from the submitted form.
1556 * @return object|bool The updated submission object or false
1558 function process_feedback($formdata=null) {
1559 global $CFG, $USER, $DB;
1560 require_once($CFG->libdir.'/gradelib.php');
1562 if (!$feedback = data_submitted() or !confirm_sesskey()) { // No incoming data?
1566 ///For save and next, we need to know the userid to save, and the userid to go
1567 ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1568 ///as the userid to store
1569 if ((int)$feedback->saveuserid !== -1){
1570 $feedback->userid = $feedback->saveuserid;
1573 if (!empty($feedback->cancel)) { // User hit cancel button
1577 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);
1579 // store outcomes if needed
1580 $this->process_outcomes($feedback->userid);
1582 $submission = $this->get_submission($feedback->userid, true); // Get or make one
1584 if (!($grading_info->items[0]->grades[$feedback->userid]->locked ||
1585 $grading_info->items[0]->grades[$feedback->userid]->overridden) ) {
1587 $submission->grade = $feedback->xgrade;
1588 $submission->submissioncomment = $feedback->submissioncomment_editor['text'];
1589 $submission->teacher = $USER->id;
1590 $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1592 $submission->mailed = 1; // treat as already mailed
1594 $submission->mailed = 0; // Make sure mail goes out (again, even)
1596 $submission->timemarked = time();
1598 unset($submission->data1); // Don't need to update this.
1599 unset($submission->data2); // Don't need to update this.
1601 if (empty($submission->timemodified)) { // eg for offline assignments
1602 // $submission->timemodified = time();
1605 $DB->update_record('assignment_submissions', $submission);
1607 // triger grade event
1608 $this->update_grade($submission);
1610 add_to_log($this->course->id, 'assignment', 'update grades',
1611 'submissions.php?id='.$this->cm->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
1612 if (!is_null($formdata)) {
1613 if ($this->type == 'upload' || $this->type == 'uploadsingle') {
1614 $mformdata = $formdata->mform->get_data();
1615 $mformdata = file_postupdate_standard_filemanager($mformdata, 'files', $formdata->fileui_options, $this->context, 'mod_assignment', 'response', $submission->id);
1624 function process_outcomes($userid) {
1627 if (empty($CFG->enableoutcomes)) {
1631 require_once($CFG->libdir.'/gradelib.php');
1633 if (!$formdata = data_submitted() or !confirm_sesskey()) {
1638 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
1640 if (!empty($grading_info->outcomes)) {
1641 foreach($grading_info->outcomes as $n=>$old) {
1642 $name = 'outcome_'.$n;
1643 if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
1644 $data[$n] = $formdata->{$name}[$userid];
1648 if (count($data) > 0) {
1649 grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1655 * Load the submission object for a particular user
1659 * @param $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1660 * @param $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1661 * @param bool $teachermodified student submission set if false
1662 * @return object The submission
1664 function get_submission($userid=0, $createnew=false, $teachermodified=false) {
1667 if (empty($userid)) {
1668 $userid = $USER->id;
1671 $submission = $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1673 if ($submission || !$createnew) {
1676 $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
1677 $DB->insert_record("assignment_submissions", $newsubmission);
1679 return $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1683 * Instantiates a new submission object for a given user
1685 * Sets the assignment, userid and times, everything else is set to default values.
1687 * @param int $userid The userid for which we want a submission object
1688 * @param bool $teachermodified student submission set if false
1689 * @return object The submission
1691 function prepare_new_submission($userid, $teachermodified=false) {
1692 $submission = new stdClass();
1693 $submission->assignment = $this->assignment->id;
1694 $submission->userid = $userid;
1695 $submission->timecreated = time();
1696 // teachers should not be modifying modified date, except offline assignments
1697 if ($teachermodified) {
1698 $submission->timemodified = 0;
1700 $submission->timemodified = $submission->timecreated;
1702 $submission->numfiles = 0;
1703 $submission->data1 = '';
1704 $submission->data2 = '';
1705 $submission->grade = -1;
1706 $submission->submissioncomment = '';
1707 $submission->format = 0;
1708 $submission->teacher = 0;
1709 $submission->timemarked = 0;
1710 $submission->mailed = 0;
1715 * Return all assignment submissions by ENROLLED students (even empty)
1717 * @param string $sort optional field names for the ORDER BY in the sql query
1718 * @param string $dir optional specifying the sort direction, defaults to DESC
1719 * @return array The submission objects indexed by id
1721 function get_submissions($sort='', $dir='DESC') {
1722 return assignment_get_all_submissions($this->assignment, $sort, $dir);
1726 * Counts all real assignment submissions by ENROLLED students (not empty ones)
1728 * @param int $groupid optional If nonzero then count is restricted to this group
1729 * @return int The number of submissions
1731 function count_real_submissions($groupid=0) {
1732 return assignment_count_real_submissions($this->cm, $groupid);
1736 * Alerts teachers by email of new or changed assignments that need grading
1738 * First checks whether the option to email teachers is set for this assignment.
1739 * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1740 * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1744 * @param $submission object The submission that has changed
1747 function email_teachers($submission) {
1750 if (empty($this->assignment->emailteachers)) { // No need to do anything
1754 $user = $DB->get_record('user', array('id'=>$submission->userid));
1756 if ($teachers = $this->get_graders($user)) {
1758 $strassignments = get_string('modulenameplural', 'assignment');
1759 $strassignment = get_string('modulename', 'assignment');
1760 $strsubmitted = get_string('submitted', 'assignment');
1762 foreach ($teachers as $teacher) {
1763 $info = new stdClass();
1764 $info->username = fullname($user, true);
1765 $info->assignment = format_string($this->assignment->name,true);
1766 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
1767 $info->timeupdated = strftime('%c',$submission->timemodified);
1769 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1770 $posttext = $this->email_teachers_text($info);
1771 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
1773 $eventdata = new stdClass();
1774 $eventdata->modulename = 'assignment';
1775 $eventdata->userfrom = $user;
1776 $eventdata->userto = $teacher;
1777 $eventdata->subject = $postsubject;
1778 $eventdata->fullmessage = $posttext;
1779 $eventdata->fullmessageformat = FORMAT_PLAIN;
1780 $eventdata->fullmessagehtml = $posthtml;
1781 $eventdata->smallmessage = $postsubject;
1783 $eventdata->name = 'assignment_updates';
1784 $eventdata->component = 'mod_assignment';
1785 $eventdata->notification = 1;
1786 $eventdata->contexturl = $info->url;
1787 $eventdata->contexturlname = $info->assignment;
1789 message_send($eventdata);
1795 * @param string $filearea
1796 * @param array $args
1799 function send_file($filearea, $args) {
1800 debugging('plugin does not implement file sending', DEBUG_DEVELOPER);
1805 * Returns a list of teachers that should be grading given submission
1807 * @param object $user
1810 function get_graders($user) {
1812 $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false);
1815 if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) { // Separate groups are being used
1816 if ($groups = groups_get_all_groups($this->course->id, $user->id)) { // Try to find all groups
1817 foreach ($groups as $group) {
1818 foreach ($potgraders as $t) {
1819 if ($t->id == $user->id) {
1820 continue; // do not send self
1822 if (groups_is_member($group->id, $t->id)) {
1823 $graders[$t->id] = $t;
1828 // user not in group, try to find graders without group
1829 foreach ($potgraders as $t) {
1830 if ($t->id == $user->id) {
1831 continue; // do not send self
1833 if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
1834 $graders[$t->id] = $t;
1839 foreach ($potgraders as $t) {
1840 if ($t->id == $user->id) {
1841 continue; // do not send self
1843 $graders[$t->id] = $t;
1850 * Creates the text content for emails to teachers
1852 * @param $info object The info used by the 'emailteachermail' language string
1855 function email_teachers_text($info) {
1856 $posttext = format_string($this->course->shortname, true, array('context' => $this->coursecontext)).' -> '.
1857 $this->strassignments.' -> '.
1858 format_string($this->assignment->name, true, array('context' => $this->context))."\n";
1859 $posttext .= '---------------------------------------------------------------------'."\n";
1860 $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
1861 $posttext .= "\n---------------------------------------------------------------------\n";
1866 * Creates the html content for emails to teachers
1868 * @param $info object The info used by the 'emailteachermailhtml' language string
1871 function email_teachers_html($info) {
1873 $posthtml = '<p><font face="sans-serif">'.
1874 '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname, true, array('context' => $this->coursecontext)).'</a> ->'.
1875 '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
1876 '<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>';
1877 $posthtml .= '<hr /><font face="sans-serif">';
1878 $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
1879 $posthtml .= '</font><hr />';
1884 * Produces a list of links to the files uploaded by a user
1886 * @param $userid int optional id of the user. If 0 then $USER->id is used.
1887 * @param $return boolean optional defaults to false. If true the list is returned rather than printed
1888 * @return string optional
1890 function print_user_files($userid=0, $return=false) {
1891 global $CFG, $USER, $OUTPUT;
1894 if (!isloggedin()) {
1897 $userid = $USER->id;
1902 $submission = $this->get_submission($userid);
1907 $fs = get_file_storage();
1908 $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false);
1909 if (!empty($files)) {
1910 require_once($CFG->dirroot . '/mod/assignment/locallib.php');
1911 if ($CFG->enableportfolios) {
1912 require_once($CFG->libdir.'/portfoliolib.php');
1913 $button = new portfolio_add_button();
1915 foreach ($files as $file) {
1916 $filename = $file->get_filename();
1917 $mimetype = $file->get_mimetype();
1918 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/mod_assignment/submission/'.$submission->id.'/'.$filename);
1919 $output .= '<a href="'.$path.'" ><img src="'.$OUTPUT->pix_url(file_mimetype_icon($mimetype)).'" class="icon" alt="'.$mimetype.'" />'.s($filename).'</a>';
1920 if ($CFG->enableportfolios && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1921 $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id, 'fileid' => $file->get_id()), '/mod/assignment/locallib.php');
1922 $button->set_format_by_file($file);
1923 $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
1925 $output .= plagiarism_get_links(array('userid'=>$userid, 'file'=>$file, 'cmid'=>$this->cm->id, 'course'=>$this->course, 'assignment'=>$this->assignment));
1926 $output .= '<br />';
1928 if ($CFG->enableportfolios && count($files) > 1 && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1929 $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id), '/mod/assignment/locallib.php');
1930 $output .= '<br />' . $button->to_html();
1934 $output = '<div class="files">'.$output.'</div>';
1943 * Count the files uploaded by a given user
1945 * @param $itemid int The submission's id as the file's itemid.
1948 function count_user_files($itemid) {
1949 $fs = get_file_storage();
1950 $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $itemid, "id", false);
1951 return count($files);
1955 * Returns true if the student is allowed to submit
1957 * Checks that the assignment has started and, if the option to prevent late
1958 * submissions is set, also checks that the assignment has not yet closed.
1963 if ($this->assignment->preventlate && $this->assignment->timedue) {
1964 return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
1966 return ($this->assignment->timeavailable <= $time);
1972 * Return true if is set description is hidden till available date
1974 * This is needed by calendar so that hidden descriptions do not
1975 * come up in upcoming events.
1977 * Check that description is hidden till available date
1978 * By default return false
1979 * Assignments types should implement this method if needed
1982 function description_is_hidden() {
1987 * Return an outline of the user's interaction with the assignment
1989 * The default method prints the grade and timemodified
1990 * @param $grade object
1991 * @return object with properties ->info and ->time
1993 function user_outline($grade) {
1995 $result = new stdClass();
1996 $result->info = get_string('grade').': '.$grade->str_long_grade;
1997 $result->time = $grade->dategraded;
2002 * Print complete information about the user's interaction with the assignment
2004 * @param $user object
2006 function user_complete($user, $grade=null) {
2009 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
2010 if ($grade->str_feedback) {
2011 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
2015 if ($submission = $this->get_submission($user->id)) {
2017 $fs = get_file_storage();
2019 if ($files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false)) {
2020 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
2021 foreach ($files as $file) {
2022 $countfiles .= "; ".$file->get_filename();
2026 echo $OUTPUT->box_start();
2027 echo get_string("lastmodified").": ";
2028 echo userdate($submission->timemodified);
2029 echo $this->display_lateness($submission->timemodified);
2031 $this->print_user_files($user->id);
2035 $this->view_feedback($submission);
2037 echo $OUTPUT->box_end();
2040 print_string("notsubmittedyet", "assignment");
2045 * Return a string indicating how late a submission is
2047 * @param $timesubmitted int
2050 function display_lateness($timesubmitted) {
2051 return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
2055 * Empty method stub for all delete actions.
2058 //nothing by default
2059 redirect('view.php?id='.$this->cm->id);
2063 * Empty custom feedback grading form.
2065 function custom_feedbackform($submission, $return=false) {
2066 //nothing by default
2071 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
2072 * for the course (see resource).
2074 * Given a course_module object, this function returns any "extra" information that may be needed
2075 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
2077 * @param $coursemodule object The coursemodule object (record).
2078 * @return cached_cm_info Object used to customise appearance on course page
2080 function get_coursemodule_info($coursemodule) {
2085 * Plugin cron method - do not use $this here, create new assignment instances if needed.
2089 //no plugin cron by default - override if needed
2093 * Reset all submissions
2095 function reset_userdata($data) {
2098 if (!$DB->count_records('assignment', array('course'=>$data->courseid, 'assignmenttype'=>$this->type))) {
2099 return array(); // no assignments of this type present
2102 $componentstr = get_string('modulenameplural', 'assignment');
2105 $typestr = get_string('type'.$this->type, 'assignment');
2106 // ugly hack to support pluggable assignment type titles...
2107 if($typestr === '[[type'.$this->type.']]'){
2108 $typestr = get_string('type'.$this->type, 'assignment_'.$this->type);
2111 if (!empty($data->reset_assignment_submissions)) {
2112 $assignmentssql = "SELECT a.id
2114 WHERE a.course=? AND a.assignmenttype=?";
2115 $params = array($data->courseid, $this->type);
2117 // now get rid of all submissions and responses
2118 $fs = get_file_storage();
2119 if ($assignments = $DB->get_records_sql($assignmentssql, $params)) {
2120 foreach ($assignments as $assignmentid=>$unused) {
2121 if (!$cm = get_coursemodule_from_instance('assignment', $assignmentid)) {
2124 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2125 $fs->delete_area_files($context->id, 'mod_assignment', 'submission');
2126 $fs->delete_area_files($context->id, 'mod_assignment', 'response');
2130 $DB->delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)", $params);
2132 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
2134 if (empty($data->reset_gradebook_grades)) {
2135 // remove all grades from gradebook
2136 assignment_reset_gradebook($data->courseid, $this->type);
2140 /// updating dates - shift may be negative too
2141 if ($data->timeshift) {
2142 shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
2143 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
2150 function portfolio_exportable() {
2155 * base implementation for backing up subtype specific information
2156 * for one single module
2158 * @param filehandle $bf file handle for xml file to write to
2159 * @param mixed $preferences the complete backup preference object
2165 static function backup_one_mod($bf, $preferences, $assignment) {
2170 * base implementation for backing up subtype specific information
2171 * for one single submission
2173 * @param filehandle $bf file handle for xml file to write to
2174 * @param mixed $preferences the complete backup preference object
2175 * @param object $submission the assignment submission db record
2181 static function backup_one_submission($bf, $preferences, $assignment, $submission) {
2186 * base implementation for restoring subtype specific information
2187 * for one single module
2189 * @param array $info the array representing the xml
2190 * @param object $restore the restore preferences
2196 static function restore_one_mod($info, $restore, $assignment) {
2201 * base implementation for restoring subtype specific information
2202 * for one single submission
2204 * @param object $submission the newly created submission
2205 * @param array $info the array representing the xml
2206 * @param object $restore the restore preferences
2212 static function restore_one_submission($info, $restore, $assignment, $submission) {
2216 } ////// End of the assignment_base class
2219 class mod_assignment_grading_form extends moodleform {
2221 function definition() {
2223 $mform =& $this->_form;
2225 $formattr = $mform->getAttributes();
2226 $formattr['id'] = 'submitform';
2227 $mform->setAttributes($formattr);
2229 $mform->addElement('hidden', 'offset', ($this->_customdata->offset+1));
2230 $mform->setType('offset', PARAM_INT);
2231 $mform->addElement('hidden', 'userid', $this->_customdata->userid);
2232 $mform->setType('userid', PARAM_INT);
2233 $mform->addElement('hidden', 'nextid', $this->_customdata->nextid);
2234 $mform->setType('nextid', PARAM_INT);
2235 $mform->addElement('hidden', 'id', $this->_customdata->cm->id);
2236 $mform->setType('id', PARAM_INT);
2237 $mform->addElement('hidden', 'sesskey', sesskey());
2238 $mform->setType('sesskey', PARAM_ALPHANUM);
2239 $mform->addElement('hidden', 'mode', 'grade');
2240 $mform->setType('mode', PARAM_TEXT);
2241 $mform->addElement('hidden', 'menuindex', "0");
2242 $mform->setType('menuindex', PARAM_INT);
2243 $mform->addElement('hidden', 'saveuserid', "-1");
2244 $mform->setType('saveuserid', PARAM_INT);
2245 $mform->addElement('hidden', 'filter', "0");
2246 $mform->setType('filter', PARAM_INT);
2248 $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->user),
2249 fullname($this->_customdata->user, true) . '<br/>' .
2250 userdate($this->_customdata->submission->timemodified) .
2251 $this->_customdata->lateness );
2253 $this->add_submission_content();
2254 $this->add_grades_section();
2256 $this->add_feedback_section();
2258 if ($this->_customdata->submission->timemarked) {
2259 $datestring = userdate($this->_customdata->submission->timemarked)." (".format_time(time() - $this->_customdata->submission->timemarked).")";
2260 $mform->addElement('header', 'Last Grade', get_string('lastgrade', 'assignment'));
2261 $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->teacher) ,
2262 fullname($this->_customdata->teacher,true).
2263 '<br/>'.$datestring);
2266 $this->add_action_buttons();
2270 function add_grades_section() {
2272 $mform =& $this->_form;
2273 $attributes = array();
2274 if ($this->_customdata->gradingdisabled) {
2275 $attributes['disabled'] ='disabled';
2278 $grademenu = make_grades_menu($this->_customdata->assignment->grade);
2279 $grademenu['-1'] = get_string('nograde');
2281 $mform->addElement('header', 'Grades', get_string('grades', 'grades'));
2282 $mform->addElement('select', 'xgrade', get_string('grade').':', $grademenu, $attributes);
2283 $mform->setDefault('xgrade', $this->_customdata->submission->grade ); //@fixme some bug when element called 'grade' makes it break
2284 $mform->setType('xgrade', PARAM_INT);
2286 if (!empty($this->_customdata->enableoutcomes)) {
2287 foreach($this->_customdata->grading_info->outcomes as $n=>$outcome) {
2288 $options = make_grades_menu(-$outcome->scaleid);
2289 if ($outcome->grades[$this->_customdata->submission->userid]->locked) {
2290 $options[0] = get_string('nooutcome', 'grades');
2291 echo $options[$outcome->grades[$this->_customdata->submission->userid]->grade];
2293 $options[''] = get_string('nooutcome', 'grades');
2294 $attributes = array('id' => 'menuoutcome_'.$n );
2295 $mform->addElement('select', 'outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->name.':', $options, $attributes );
2296 $mform->setType('outcome_'.$n.'['.$this->_customdata->userid.']', PARAM_INT);
2297 $mform->setDefault('outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->grades[$this->_customdata->submission->userid]->grade );
2301 $course_context = get_context_instance(CONTEXT_MODULE , $this->_customdata->cm->id);
2302 if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
2303 $grade = '<a href="'.$CFG->wwwroot.'/grade/report/grader/index.php?id='. $this->_customdata->courseid .'" >'.
2304 $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade . '</a>';
2306 $grade = $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade;
2308 $mform->addElement('static', 'finalgrade', get_string('currentgrade', 'assignment').':' ,$grade);
2309 $mform->setType('finalgrade', PARAM_INT);
2314 * @global core_renderer $OUTPUT
2316 function add_feedback_section() {
2318 $mform =& $this->_form;
2319 $mform->addElement('header', 'Feed Back', get_string('feedback', 'grades'));
2321 if ($this->_customdata->gradingdisabled) {
2322 $mform->addElement('static', 'disabledfeedback', $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_feedback );
2326 $mform->addElement('editor', 'submissioncomment_editor', get_string('feedback', 'assignment').':', null, $this->get_editor_options() );
2327 $mform->setType('submissioncomment_editor', PARAM_RAW); // to be cleaned before display
2328 $mform->setDefault('submissioncomment_editor', $this->_customdata->submission->submissioncomment);
2329 //$mform->addRule('submissioncomment', get_string('required'), 'required', null, 'client');
2330 switch ($this->_customdata->assignment->assignmenttype) {
2332 case 'uploadsingle' :
2333 $mform->addElement('filemanager', 'files_filemanager', get_string('responsefiles', 'assignment'). ':', null, $this->_customdata->fileui_options);
2338 $mform->addElement('hidden', 'mailinfo_h', "0");
2339 $mform->setType('mailinfo_h', PARAM_INT);
2340 $mform->addElement('checkbox', 'mailinfo',get_string('enablenotification','assignment').
2341 $OUTPUT->help_icon('enablenotification', 'assignment') .':' );
2342 $mform->setType('mailinfo', PARAM_INT);
2346 function add_action_buttons() {
2347 $mform =& $this->_form;
2348 //if there are more to be graded.
2349 if ($this->_customdata->nextid>0) {
2350 $buttonarray=array();
2351 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2352 //@todo: fix accessibility: javascript dependency not necessary
2353 $buttonarray[] = &$mform->createElement('submit', 'saveandnext', get_string('saveandnext'));
2354 $buttonarray[] = &$mform->createElement('submit', 'next', get_string('next'));
2355 $buttonarray[] = &$mform->createElement('cancel');
2357 $buttonarray=array();
2358 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2359 $buttonarray[] = &$mform->createElement('cancel');
2361 $mform->addGroup($buttonarray, 'grading_buttonar', '', array(' '), false);
2362 $mform->closeHeaderBefore('grading_buttonar');
2363 $mform->setType('grading_buttonar', PARAM_RAW);
2366 function add_submission_content() {
2367 $mform =& $this->_form;
2368 $mform->addElement('header', 'Submission', get_string('submission', 'assignment'));
2369 $mform->addElement('static', '', '' , $this->_customdata->submission_content );
2372 protected function get_editor_options() {
2373 $editoroptions = array();
2374 $editoroptions['component'] = 'mod_assignment';
2375 $editoroptions['filearea'] = 'feedback';
2376 $editoroptions['noclean'] = false;
2377 $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)
2378 $editoroptions['maxbytes'] = $this->_customdata->maxbytes;
2379 $editoroptions['context'] = $this->_customdata->context;
2380 return $editoroptions;
2383 public function set_data($data) {
2384 $editoroptions = $this->get_editor_options();
2385 if (!isset($data->text)) {
2388 if (!isset($data->format)) {
2389 $data->textformat = FORMAT_HTML;
2391 $data->textformat = $data->format;
2394 if (!empty($this->_customdata->submission->id)) {
2395 $itemid = $this->_customdata->submission->id;
2400 switch ($this->_customdata->assignment->assignmenttype) {
2402 case 'uploadsingle' :
2403 $data = file_prepare_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2409 $data = file_prepare_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2410 return parent::set_data($data);
2413 public function get_data() {
2414 $data = parent::get_data();
2416 if (!empty($this->_customdata->submission->id)) {
2417 $itemid = $this->_customdata->submission->id;
2419 $itemid = null; //TODO: this is wrong, itemid MUST be known when saving files!! (skodak)
2423 $editoroptions = $this->get_editor_options();
2424 switch ($this->_customdata->assignment->assignmenttype) {
2426 case 'uploadsingle' :
2427 $data = file_postupdate_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2432 $data = file_postupdate_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2438 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
2441 * Deletes an assignment instance
2443 * This is done by calling the delete_instance() method of the assignment type class
2445 function assignment_delete_instance($id){
2448 if (! $assignment = $DB->get_record('assignment', array('id'=>$id))) {
2452 // fall back to base class if plugin missing
2453 $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2454 if (file_exists($classfile)) {
2455 require_once($classfile);
2456 $assignmentclass = "assignment_$assignment->assignmenttype";
2459 debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
2460 $assignmentclass = "assignment_base";
2463 $ass = new $assignmentclass();
2464 return $ass->delete_instance($assignment);
2469 * Updates an assignment instance
2471 * This is done by calling the update_instance() method of the assignment type class
2473 function assignment_update_instance($assignment){
2476 $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2478 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2479 $assignmentclass = "assignment_$assignment->assignmenttype";
2480 $ass = new $assignmentclass();
2481 return $ass->update_instance($assignment);
2486 * Adds an assignment instance
2488 * This is done by calling the add_instance() method of the assignment type class
2490 function assignment_add_instance($assignment) {
2493 $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2495 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2496 $assignmentclass = "assignment_$assignment->assignmenttype";
2497 $ass = new $assignmentclass();
2498 return $ass->add_instance($assignment);
2503 * Returns an outline of a user interaction with an assignment
2505 * This is done by calling the user_outline() method of the assignment type class
2507 function assignment_user_outline($course, $user, $mod, $assignment) {
2510 require_once("$CFG->libdir/gradelib.php");
2511 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2512 $assignmentclass = "assignment_$assignment->assignmenttype";
2513 $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2514 $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2515 if (!empty($grades->items[0]->grades)) {
2516 return $ass->user_outline(reset($grades->items[0]->grades));
2523 * Prints the complete info about a user's interaction with an assignment
2525 * This is done by calling the user_complete() method of the assignment type class
2527 function assignment_user_complete($course, $user, $mod, $assignment) {
2530 require_once("$CFG->libdir/gradelib.php");
2531 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2532 $assignmentclass = "assignment_$assignment->assignmenttype";
2533 $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2534 $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2535 if (empty($grades->items[0]->grades)) {
2538 $grade = reset($grades->items[0]->grades);
2540 return $ass->user_complete($user, $grade);
2544 * Function to be run periodically according to the moodle cron
2546 * Finds all assignment notifications that have yet to be mailed out, and mails them
2548 function assignment_cron () {
2549 global $CFG, $USER, $DB;
2551 /// first execute all crons in plugins
2552 if ($plugins = get_plugin_list('assignment')) {
2553 foreach ($plugins as $plugin=>$dir) {
2554 require_once("$dir/assignment.class.php");
2555 $assignmentclass = "assignment_$plugin";
2556 $ass = new $assignmentclass();
2561 /// Notices older than 1 day will not be mailed. This is to avoid the problem where
2562 /// cron has not been running for a long time, and then suddenly people are flooded
2563 /// with mail from the past few weeks or months
2566 $endtime = $timenow - $CFG->maxeditingtime;
2567 $starttime = $endtime - 24 * 3600; /// One day earlier
2569 if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2571 $realuser = clone($USER);
2573 foreach ($submissions as $key => $submission) {
2574 $DB->set_field("assignment_submissions", "mailed", "1", array("id"=>$submission->id));
2579 foreach ($submissions as $submission) {
2581 echo "Processing assignment submission $submission->id\n";
2583 if (! $user = $DB->get_record("user", array("id"=>$submission->userid))) {
2584 echo "Could not find user $user->id\n";
2588 if (! $course = $DB->get_record("course", array("id"=>$submission->course))) {
2589 echo "Could not find course $submission->course\n";
2593 /// Override the language and timezone of the "current" user, so that
2594 /// mail is customised for the receiver.
2595 cron_setup_user($user, $course);
2597 $coursecontext = get_context_instance(CONTEXT_COURSE, $submission->course);
2598 $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
2599 if (!is_enrolled($coursecontext, $user->id)) {
2600 echo fullname($user)." not an active participant in " . $courseshortname . "\n";
2604 if (! $teacher = $DB->get_record("user", array("id"=>$submission->teacher))) {
2605 echo "Could not find teacher $submission->teacher\n";
2609 if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2610 echo "Could not find course module for assignment id $submission->assignment\n";
2614 if (! $mod->visible) { /// Hold mail notification for hidden assignments until later
2618 $strassignments = get_string("modulenameplural", "assignment");
2619 $strassignment = get_string("modulename", "assignment");
2621 $assignmentinfo = new stdClass();
2622 $assignmentinfo->teacher = fullname($teacher);
2623 $assignmentinfo->assignment = format_string($submission->name,true);
2624 $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2626 $postsubject = "$courseshortname: $strassignments: ".format_string($submission->name,true);
2627 $posttext = "$courseshortname -> $strassignments -> ".format_string($submission->name,true)."\n";
2628 $posttext .= "---------------------------------------------------------------------\n";
2629 $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2630 $posttext .= "---------------------------------------------------------------------\n";
2632 if ($user->mailformat == 1) { // HTML
2633 $posthtml = "<p><font face=\"sans-serif\">".
2634 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$courseshortname</a> ->".
2635 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2636 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2637 $posthtml .= "<hr /><font face=\"sans-serif\">";
2638 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2639 $posthtml .= "</font><hr />";
2644 $eventdata = new stdClass();
2645 $eventdata->modulename = 'assignment';
2646 $eventdata->userfrom = $teacher;
2647 $eventdata->userto = $user;
2648 $eventdata->subject = $postsubject;
2649 $eventdata->fullmessage = $posttext;
2650 $eventdata->fullmessageformat = FORMAT_PLAIN;
2651 $eventdata->fullmessagehtml = $posthtml;
2652 $eventdata->smallmessage = get_string('assignmentmailsmall', 'assignment', $assignmentinfo);
2654 $eventdata->name = 'assignment_updates';
2655 $eventdata->component = 'mod_assignment';
2656 $eventdata->notification = 1;
2657 $eventdata->contexturl = $assignmentinfo->url;
2658 $eventdata->contexturlname = $assignmentinfo->assignment;
2660 message_send($eventdata);
2670 * Return grade for given user or all users.
2672 * @param int $assignmentid id of assignment
2673 * @param int $userid optional user id, 0 means all users
2674 * @return array array of grades, false if none
2676 function assignment_get_user_grades($assignment, $userid=0) {
2680 $user = "AND u.id = :userid";
2681 $params = array('userid'=>$userid);
2685 $params['aid'] = $assignment->id;
2687 $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2688 s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2689 FROM {user} u, {assignment_submissions} s
2690 WHERE u.id = s.userid AND s.assignment = :aid
2693 return $DB->get_records_sql($sql, $params);
2697 * Update activity grades
2699 * @param object $assignment
2700 * @param int $userid specific user only, 0 means all
2702 function assignment_update_grades($assignment, $userid=0, $nullifnone=true) {
2704 require_once($CFG->libdir.'/gradelib.php');
2706 if ($assignment->grade == 0) {
2707 assignment_grade_item_update($assignment);
2709 } else if ($grades = assignment_get_user_grades($assignment, $userid)) {
2710 foreach($grades as $k=>$v) {
2711 if ($v->rawgrade == -1) {
2712 $grades[$k]->rawgrade = null;
2715 assignment_grade_item_update($assignment, $grades);
2718 assignment_grade_item_update($assignment);
2723 * Update all grades in gradebook.
2725 function assignment_upgrade_grades() {
2728 $sql = "SELECT COUNT('x')
2729 FROM {assignment} a, {course_modules} cm, {modules} m
2730 WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2731 $count = $DB->count_records_sql($sql);
2733 $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
2734 FROM {assignment} a, {course_modules} cm, {modules} m
2735 WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2736 $rs = $DB->get_recordset_sql($sql);
2738 // too much debug output
2739 $pbar = new progress_bar('assignmentupgradegrades', 500, true);
2741 foreach ($rs as $assignment) {
2743 upgrade_set_timeout(60*5); // set up timeout, may also abort execution
2744 assignment_update_grades($assignment);
2745 $pbar->update($i, $count, "Updating Assignment grades ($i/$count).");
2747 upgrade_set_timeout(); // reset to default timeout
2753 * Create grade item for given assignment
2755 * @param object $assignment object with extra cmidnumber
2756 * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
2757 * @return int 0 if ok, error code otherwise
2759 function assignment_grade_item_update($assignment, $grades=NULL) {
2761 require_once($CFG->libdir.'/gradelib.php');
2763 if (!isset($assignment->courseid)) {
2764 $assignment->courseid = $assignment->course;
2767 $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
2769 if ($assignment->grade > 0) {
2770 $params['gradetype'] = GRADE_TYPE_VALUE;
2771 $params['grademax'] = $assignment->grade;
2772 $params['grademin'] = 0;
2774 } else if ($assignment->grade < 0) {
2775 $params['gradetype'] = GRADE_TYPE_SCALE;
2776 $params['scaleid'] = -$assignment->grade;
2779 $params['gradetype'] = GRADE_TYPE_TEXT; // allow text comments only
2782 if ($grades === 'reset') {
2783 $params['reset'] = true;
2787 return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades, $params);
2791 * Delete grade item for given assignment
2793 * @param object $assignment object
2794 * @return object assignment
2796 function assignment_grade_item_delete($assignment) {
2798 require_once($CFG->libdir.'/gradelib.php');
2800 if (!isset($assignment->courseid)) {
2801 $assignment->courseid = $assignment->course;
2804 return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
2808 * Returns the users with data in one assignment (students and teachers)
2810 * @todo: deprecated - to be deleted in 2.2
2812 * @param $assignmentid int
2813 * @return array of user objects
2815 function assignment_get_participants($assignmentid) {
2819 $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2821 {assignment_submissions} a
2822 WHERE a.assignment = ? and
2823 u.id = a.userid", array($assignmentid));
2825 $teachers = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2827 {assignment_submissions} a
2828 WHERE a.assignment = ? and
2829 u.id = a.teacher", array($assignmentid));
2831 //Add teachers to students
2833 foreach ($teachers as $teacher) {
2834 $students[$teacher->id] = $teacher;
2837 //Return students array (it contains an array of unique users)
2842 * Serves assignment submissions and other files.
2844 * @param object $course
2846 * @param object $context
2847 * @param string $filearea
2848 * @param array $args
2849 * @param bool $forcedownload
2850 * @return bool false if file not found, does not return if found - just send the file
2852 function assignment_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) {
2855 if ($context->contextlevel != CONTEXT_MODULE) {
2859 require_login($course, false, $cm);
2861 if (!$assignment = $DB->get_record('assignment', array('id'=>$cm->instance))) {
2865 require_once($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
2866 $assignmentclass = 'assignment_'.$assignment->assignmenttype;
2867 $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm, $course);
2869 return $assignmentinstance->send_file($filearea, $args);
2872 * Checks if a scale is being used by an assignment
2874 * This is used by the backup code to decide whether to back up a scale
2875 * @param $assignmentid int
2876 * @param $scaleid int
2877 * @return boolean True if the scale is used by the assignment
2879 function assignment_scale_used($assignmentid, $scaleid) {
2884 $rec = $DB->get_record('assignment', array('id'=>$assignmentid,'grade'=>-$scaleid));
2886 if (!empty($rec) && !empty($scaleid)) {
2894 * Checks if scale is being used by any instance of assignment
2896 * This is used to find out if scale used anywhere
2897 * @param $scaleid int
2898 * @return boolean True if the scale is used by any assignment
2900 function assignment_scale_used_anywhere($scaleid) {
2903 if ($scaleid and $DB->record_exists('assignment', array('grade'=>-$scaleid))) {
2911 * Make sure up-to-date events are created for all assignment instances
2913 * This standard function will check all instances of this module
2914 * and make sure there are up-to-date events created for each of them.
2915 * If courseid = 0, then every assignment event in the site is checked, else
2916 * only assignment events belonging to the course specified are checked.
2917 * This function is used, in its new format, by restore_refresh_events()
2919 * @param $courseid int optional If zero then all assignments for all courses are covered
2920 * @return boolean Always returns true
2922 function assignment_refresh_events($courseid = 0) {
2925 if ($courseid == 0) {
2926 if (! $assignments = $DB->get_records("assignment")) {
2930 if (! $assignments = $DB->get_records("assignment", array("course"=>$courseid))) {
2934 $moduleid = $DB->get_field('modules', 'id', array('name'=>'assignment'));
2936 foreach ($assignments as $assignment) {
2937 $cm = get_coursemodule_from_id('assignment', $assignment->id);
2938 $event = new stdClass();
2939 $event->name = $assignment->name;
2940 $event->description = format_module_intro('assignment', $assignment, $cm->id);
2941 $event->timestart = $assignment->timedue;
2943 if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
2944 update_event($event);
2947 $event->courseid = $assignment->course;
2948 $event->groupid = 0;
2950 $event->modulename = 'assignment';
2951 $event->instance = $assignment->id;
2952 $event->eventtype = 'due';
2953 $event->timeduration = 0;
2954 $event->visible = $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$assignment->id));
2963 * Print recent activity from all assignments in a given course
2965 * This is used by the recent activity block
2967 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
2968 global $CFG, $USER, $DB, $OUTPUT;
2970 // do not use log table if possible, it may be huge
2972 if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
2973 u.firstname, u.lastname, u.email, u.picture
2974 FROM {assignment_submissions} asb
2975 JOIN {assignment} a ON a.id = asb.assignment
2976 JOIN {course_modules} cm ON cm.instance = a.id
2977 JOIN {modules} md ON md.id = cm.module
2978 JOIN {user} u ON u.id = asb.userid
2979 WHERE asb.timemodified > ? AND
2981 md.name = 'assignment'
2982 ORDER BY asb.timemodified ASC", array($timestart, $course->id))) {
2986 $modinfo =& get_fast_modinfo($course); // reference needed because we might load the groups
2990 foreach($submissions as $submission) {
2991 if (!array_key_exists($submission->cmid, $modinfo->cms)) {
2994 $cm = $modinfo->cms[$submission->cmid];
2995 if (!$cm->uservisible) {
2998 if ($submission->userid == $USER->id) {
2999 $show[] = $submission;
3003 // the act of sumbitting of assignment may be considered private - only graders will see it if specified
3004 if (empty($CFG->assignment_showrecentsubmissions)) {
3005 if (!array_key_exists($cm->id, $grader)) {
3006 $grader[$cm->id] = has_capability('moodle/grade:viewall', get_context_instance(CONTEXT_MODULE, $cm->id));
3008 if (!$grader[$cm->id]) {
3013 $groupmode = groups_get_activity_groupmode($cm, $course);
3015 if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
3016 if (isguestuser()) {
3017 // shortcut - guest user does not belong into any group
3021 if (is_null($modinfo->groups)) {
3022 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
3025 // this will be slow - show only users that share group with me in this cm
3026 if (empty($modinfo->groups[$cm->id])) {
3029 $usersgroups = groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
3030 if (is_array($usersgroups)) {
3031 $usersgroups = array_keys($usersgroups);
3032 $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
3033 if (empty($intersect)) {
3038 $show[] = $submission;
3045 echo $OUTPUT->heading(get_string('newsubmissions', 'assignment').':', 3);
3047 foreach ($show as $submission) {
3048 $cm = $modinfo->cms[$submission->cmid];
3049 $link = $CFG->wwwroot.'/mod/assignment/view.php?id='.$cm->id;
3050 print_recent_activity_note($submission->timemodified, $submission, $cm->name, $link, false, $viewfullnames);
3058 * Returns all assignments since a given time in specified forum.
3060 function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0) {
3061 global $CFG, $COURSE, $USER, $DB;
3063 if ($COURSE->id == $courseid) {
3066 $course = $DB->get_record('course', array('id'=>$courseid));
3069 $modinfo =& get_fast_modinfo($course);
3071 $cm = $modinfo->cms[$cmid];
3075 $userselect = "AND u.id = :userid";
3076 $params['userid'] = $userid;
3082 $groupselect = "AND gm.groupid = :groupid";
3083 $groupjoin = "JOIN {groups_members} gm ON gm.userid=u.id";
3084 $params['groupid'] = $groupid;
3090 $params['cminstance'] = $cm->instance;
3091 $params['timestart'] = $timestart;
3093 $userfields = user_picture::fields('u', null, 'userid');
3095 if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified,
3097 FROM {assignment_submissions} asb
3098 JOIN {assignment} a ON a.id = asb.assignment
3099 JOIN {user} u ON u.id = asb.userid
3101 WHERE asb.timemodified > :timestart AND a.id = :cminstance
3102 $userselect $groupselect
3103 ORDER BY asb.timemodified ASC", $params)) {
3107 $groupmode = groups_get_activity_groupmode($cm, $course);
3108 $cm_context = get_context_instance(CONTEXT_MODULE, $cm->id);
3109 $grader = has_capability('moodle/grade:viewall', $cm_context);
3110 $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
3111 $viewfullnames = has_capability('moodle/site:viewfullnames', $cm_context);
3113 if (is_null($modinfo->groups)) {
3114 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
3119 foreach($submissions as $submission) {
3120 if ($submission->userid == $USER->id) {
3121 $show[] = $submission;
3124 // the act of submitting of assignment may be considered private - only graders will see it if specified
3125 if (empty($CFG->assignment_showrecentsubmissions)) {
3131 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
3132 if (isguestuser()) {
3133 // shortcut - guest user does not belong into any group
3137 // this will be slow - show only users that share group with me in this cm
3138 if (empty($modinfo->groups[$cm->id])) {
3141 $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
3142 if (is_array($usersgroups)) {
3143 $usersgroups = array_keys($usersgroups);
3144 $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
3145 if (empty($intersect)) {
3150 $show[] = $submission;
3158 require_once($CFG->libdir.'/gradelib.php');
3160 foreach ($show as $id=>$submission) {
3161 $userids[] = $submission->userid;
3164 $grades = grade_get_grades($courseid, 'mod', 'assignment', $cm->instance, $userids);
3167 $aname = format_string($cm->name,true);
3168 foreach ($show as $submission) {
3169 $tmpactivity = new stdClass();
3171 $tmpactivity->type = 'assignment';
3172 $tmpactivity->cmid = $cm->id;
3173 $tmpactivity->name = $aname;
3174 $tmpactivity->sectionnum = $cm->sectionnum;
3175 $tmpactivity->timestamp = $submission->timemodified;
3178 $tmpactivity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
3181 $userfields = explode(',', user_picture::fields());
3182 foreach ($userfields as $userfield) {
3183 if ($userfield == 'id') {
3184 $tmpactivity->user->{$userfield} = $submission->userid; // aliased in SQL above
3186 $tmpactivity->user->{$userfield} = $submission->{$userfield};
3189 $tmpactivity->user->fullname = fullname($submission, $viewfullnames);
3191 $activities[$index++] = $tmpactivity;
3198 * Print recent activity from all assignments in a given course
3200 * This is used by course/recent.php
3202 function assignment_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
3203 global $CFG, $OUTPUT;
3205 echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
3207 echo "<tr><td class=\"userpicture\" valign=\"top\">";
3208 echo $OUTPUT->user_picture($activity->user);
3212 $modname = $modnames[$activity->type];
3213 echo '<div class="title">';
3214 echo "<img src=\"" . $OUTPUT->pix_url('icon', 'assignment') . "\" ".
3215 "class=\"icon\" alt=\"$modname\">";
3216 echo "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id={$activity->cmid}\">{$activity->name}</a>";
3220 if (isset($activity->grade)) {
3221 echo '<div class="grade">';
3222 echo get_string('grade').': ';
3223 echo $activity->grade;
3227 echo '<div class="user">';
3228 echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->id}&course=$courseid\">"
3229 ."{$activity->user->fullname}</a> - ".userdate($activity->timestamp);
3232 echo "</td></tr></table>";
3235 /// GENERIC SQL FUNCTIONS
3238 * Fetch info from logs
3240 * @param $log object with properties ->info (the assignment id) and ->userid
3241 * @return array with assignment name and user firstname and lastname
3243 function assignment_log_info($log) {
3246 return $DB->get_record_sql("SELECT a.name, u.firstname, u.lastname
3247 FROM {assignment} a, {user} u
3248 WHERE a.id = ? AND u.id = ?", array($log->info, $log->userid));
3252 * Return list of marked submissions that have not been mailed out for currently enrolled students
3256 function assignment_get_unmailed_submissions($starttime, $endtime) {
3259 return $DB->get_records_sql("SELECT s.*, a.course, a.name
3260 FROM {assignment_submissions} s,
3263 AND s.timemarked <= ?
3264 AND s.timemarked >= ?
3265 AND s.assignment = a.id", array($endtime, $starttime));
3269 * Counts all real assignment submissions by ENROLLED students (not empty ones)
3271 * There are also assignment type methods count_real_submissions() which in the default
3272 * implementation simply call this function.
3273 * @param $groupid int optional If nonzero then count is restricted to this group
3274 * @return int The number of submissions
3276 function assignment_count_real_submissions($cm, $groupid=0) {
3279 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
3281 // this is all the users with this capability set, in this context or higher
3282 if ($users = get_enrolled_users($context, 'mod/assignment:view', $groupid, 'u.id')) {
3283 $users = array_keys($users);
3286 // if groupmembersonly used, remove users who are not in any group
3287 if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
3288 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
3289 $users = array_intersect($users, array_keys($groupingusers));
3293 if (empty($users)) {
3297 $userlists = implode(',', $users);
3299 return $DB->count_records_sql("SELECT COUNT('x')
3300 FROM {assignment_submissions}
3301 WHERE assignment = ? AND
3302 timemodified > 0 AND
3303 userid IN ($userlists)", array($cm->instance));
3308 * Return all assignment submissions by ENROLLED students (even empty)
3310 * There are also assignment type methods get_submissions() wich in the default
3311 * implementation simply call this function.
3312 * @param $sort string optional field names for the ORDER BY in the sql query
3313 * @param $dir string optional specifying the sort direction, defaults to DESC
3314 * @return array The submission objects indexed by id
3316 function assignment_get_all_submissions($assignment, $sort="", $dir="DESC") {
3317 /// Return all assignment submissions by ENROLLED students (even empty)
3320 if ($sort == "lastname" or $sort == "firstname") {
3321 $sort = "u.$sort $dir";
3322 } else if (empty($sort)) {
3323 $sort = "a.timemodified DESC";
3325 $sort = "a.$sort $dir";
3328 /* not sure this is needed at all since assignment already has a course define, so this join?
3329 $select = "s.course = '$assignment->course' AND";
3330 if ($assignment->course == SITEID) {
3334 return $DB->get_records_sql("SELECT a.*
3335 FROM {assignment_submissions} a, {user} u
3336 WHERE u.id = a.userid
3337 AND a.assignment = ?
3338 ORDER BY $sort", array($assignment->id));