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 = context_module::instance($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 = context_course::instance($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 = context_module::instance($this->cm->id);
157 require_capability('mod/assignment:view', $context);
159 add_to_log($this->course->id, "assignment", "view", "view.php?id={$this->cm->id}",
160 $this->assignment->id, $this->cm->id);
162 $this->view_header();
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>';
200 if (has_capability('moodle/site:config', context_system::instance())) {
201 echo $OUTPUT->notification(get_string('upgradenotification', 'assignment'));
202 $adminurl = new moodle_url('/admin/tool/assignmentupgrade/listnotupgraded.php');
203 echo $OUTPUT->single_button($adminurl, get_string('viewassignmentupgradetool', 'assignment'));
209 * Display the assignment intro
211 * This will most likely be extended by assignment type plug-ins
212 * The default implementation prints the assignment description in a box
214 function view_intro() {
216 echo $OUTPUT->box_start('generalbox boxaligncenter', 'intro');
217 echo format_module_intro('assignment', $this->assignment, $this->cm->id);
218 echo $OUTPUT->box_end();
219 echo plagiarism_print_disclosure($this->cm->id);
223 * Display the assignment dates
225 * Prints the assignment start and end dates in a box.
226 * This will be suitable for most assignment types
228 function view_dates() {
230 if (!$this->assignment->timeavailable && !$this->assignment->timedue) {
234 echo $OUTPUT->box_start('generalbox boxaligncenter', 'dates');
236 if ($this->assignment->timeavailable) {
237 echo '<tr><td class="c0">'.get_string('availabledate','assignment').':</td>';
238 echo ' <td class="c1">'.userdate($this->assignment->timeavailable).'</td></tr>';
240 if ($this->assignment->timedue) {
241 echo '<tr><td class="c0">'.get_string('duedate','assignment').':</td>';
242 echo ' <td class="c1">'.userdate($this->assignment->timedue).'</td></tr>';
245 echo $OUTPUT->box_end();
250 * Display the bottom and footer of a page
252 * This default method just prints the footer.
253 * This will be suitable for most assignment types
255 function view_footer() {
257 echo $OUTPUT->footer();
261 * Display the feedback to the student
263 * This default method prints the teacher picture and name, date when marked,
264 * grade and teacher submissioncomment.
265 * If advanced grading is used the method render_grade from the
266 * advanced grading controller is called to display the grade.
271 * @param object $submission The submission object or NULL in which case it will be loaded
274 function view_feedback($submission=NULL) {
275 global $USER, $CFG, $DB, $OUTPUT, $PAGE;
276 require_once($CFG->libdir.'/gradelib.php');
277 require_once("$CFG->dirroot/grade/grading/lib.php");
279 if (!$submission) { /// Get submission for this assignment
281 $submission = $this->get_submission($userid);
283 $userid = $submission->userid;
285 // Check the user can submit
286 $canviewfeedback = ($userid == $USER->id && has_capability('mod/assignment:submit', $this->context, $USER->id, false));
287 // If not then check if the user still has the view cap and has a previous submission
288 $canviewfeedback = $canviewfeedback || (!empty($submission) && $submission->userid == $USER->id && has_capability('mod/assignment:view', $this->context));
289 // Or if user can grade (is a teacher or admin)
290 $canviewfeedback = $canviewfeedback || has_capability('mod/assignment:grade', $this->context);
292 if (!$canviewfeedback) {
293 // can not view or submit assignments -> no feedback
297 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
298 $item = $grading_info->items[0];
299 $grade = $item->grades[$userid];
301 if ($grade->hidden or $grade->grade === false) { // hidden or error
305 if ($grade->grade === null and empty($grade->str_feedback)) { // No grade to show yet
306 // If sumbission then check if feedback is avaiable to show else return.
311 $fs = get_file_storage();
312 $noresponsefiles = $fs->is_area_empty($this->context->id, 'mod_assignment', 'response', $submission->id);
313 if (empty($submission->submissioncomment) && $noresponsefiles) { // Nothing to show yet
317 // We need the teacher info
318 if (!$teacher = $DB->get_record('user', array('id'=>$submission->teacher))) {
319 print_error('cannotfindteacher');
322 $feedbackdate = $submission->timemarked;
323 $feedback = format_text($submission->submissioncomment, $submission->format);
327 // We need the teacher info
328 if (!$teacher = $DB->get_record('user', array('id'=>$grade->usermodified))) {
329 print_error('cannotfindteacher');
332 $feedbackdate = $grade->dategraded;
333 $feedback = $grade->str_feedback;
334 $strlonggrade = $grade->str_long_grade;
337 // Print the feedback
338 echo $OUTPUT->heading(get_string('submissionfeedback', 'assignment'), 3);
340 echo '<table cellspacing="0" class="feedback">';
343 echo '<td class="left picture">';
345 echo $OUTPUT->user_picture($teacher);
348 echo '<td class="topic">';
349 echo '<div class="from">';
351 echo '<div class="fullname">'.fullname($teacher).'</div>';
353 echo '<div class="time">'.userdate($feedbackdate).'</div>';
359 echo '<td class="left side"> </td>';
360 echo '<td class="content">';
362 if ($this->assignment->grade) {
363 $gradestr = '<div class="grade">'. get_string("grade").': '.$strlonggrade. '</div>';
364 if (!empty($submission) && $controller = get_grading_manager($this->context, 'mod_assignment', 'submission')->get_active_controller()) {
365 $controller->set_grade_range(make_grades_menu($this->assignment->grade));
366 echo $controller->render_grade($PAGE, $submission->id, $item, $gradestr, has_capability('mod/assignment:grade', $this->context));
370 echo '<div class="clearer"></div>';
373 echo '<div class="comment">';
377 if (method_exists($this, 'view_responsefile')) {
378 $this->view_responsefile($submission);
386 * Returns a link with info about the state of the assignment submissions
388 * This is used by view_header to put this link at the top right of the page.
389 * For teachers it gives the number of submitted assignments with a link
390 * For students it gives the time of their submission.
391 * This will be suitable for most assignment types.
395 * @param bool $allgroup print all groups info if user can access all groups, suitable for index.php
398 function submittedlink($allgroups=false) {
403 $urlbase = "{$CFG->wwwroot}/mod/assignment/";
405 $context = context_module::instance($this->cm->id);
406 if (has_capability('mod/assignment:grade', $context)) {
407 if ($allgroups and has_capability('moodle/site:accessallgroups', $context)) {
410 $group = groups_get_activity_group($this->cm);
412 if ($this->type == 'offline') {
413 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
414 get_string('viewfeedback', 'assignment').'</a>';
415 } else if ($count = $this->count_real_submissions($group)) {
416 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
417 get_string('viewsubmissions', 'assignment', $count).'</a>';
419 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
420 get_string('noattempts', 'assignment').'</a>';
424 if ($submission = $this->get_submission($USER->id)) {
425 // If the submission has been completed
426 if ($this->is_submitted_with_required_data($submission)) {
427 if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
428 $submitted = '<span class="early">'.userdate($submission->timemodified).'</span>';
430 $submitted = '<span class="late">'.userdate($submission->timemodified).'</span>';
441 * Returns whether the assigment supports lateness information
443 * @return bool This assignment type supports lateness (true, default) or no (false)
445 function supports_lateness() {
450 * @todo Document this function
452 function setup_elements(&$mform) {
457 * Any preprocessing needed for the settings form for
458 * this assignment type
460 * @param array $default_values - array to fill in with the default values
461 * in the form 'formelement' => 'value'
462 * @param object $form - the form that is to be displayed
465 function form_data_preprocessing(&$default_values, $form) {
469 * Any extra validation checks needed for the settings
470 * form for this assignment type
472 * See lib/formslib.php, 'validation' function for details
474 function form_validation($data, $files) {
479 * Create a new assignment activity
481 * Given an object containing all the necessary data,
482 * (defined by the form in mod_form.php) this function
483 * will create a new instance and return the id number
484 * of the new instance.
485 * The due data is added to the calendar
486 * This is common to all assignment types.
490 * @param object $assignment The data from the form on mod_form.php
491 * @return int The id of the assignment
493 function add_instance($assignment) {
496 $assignment->timemodified = time();
497 $assignment->courseid = $assignment->course;
499 $returnid = $DB->insert_record("assignment", $assignment);
500 $assignment->id = $returnid;
502 if ($assignment->timedue) {
503 $event = new stdClass();
504 $event->name = $assignment->name;
505 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
506 $event->courseid = $assignment->course;
509 $event->modulename = 'assignment';
510 $event->instance = $returnid;
511 $event->eventtype = 'due';
512 $event->timestart = $assignment->timedue;
513 $event->timeduration = 0;
515 calendar_event::create($event);
518 assignment_grade_item_update($assignment);
524 * Deletes an assignment activity
526 * Deletes all database records, files and calendar events for this assignment.
530 * @param object $assignment The assignment to be deleted
531 * @return boolean False indicates error
533 function delete_instance($assignment) {
536 $assignment->courseid = $assignment->course;
540 // now get rid of all files
541 $fs = get_file_storage();
542 if ($cm = get_coursemodule_from_instance('assignment', $assignment->id)) {
543 $context = context_module::instance($cm->id);
544 $fs->delete_area_files($context->id);
547 if (! $DB->delete_records('assignment_submissions', array('assignment'=>$assignment->id))) {
551 if (! $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
555 if (! $DB->delete_records('assignment', array('id'=>$assignment->id))) {
558 $mod = $DB->get_field('modules','id',array('name'=>'assignment'));
560 assignment_grade_item_delete($assignment);
566 * Updates a new assignment activity
568 * Given an object containing all the necessary data,
569 * (defined by the form in mod_form.php) this function
570 * will update the assignment instance and return the id number
571 * The due date is updated in the calendar
572 * This is common to all assignment types.
576 * @param object $assignment The data from the form on mod_form.php
577 * @return bool success
579 function update_instance($assignment) {
582 $assignment->timemodified = time();
584 $assignment->id = $assignment->instance;
585 $assignment->courseid = $assignment->course;
587 $DB->update_record('assignment', $assignment);
589 if ($assignment->timedue) {
590 $event = new stdClass();
592 if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
594 $event->name = $assignment->name;
595 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
596 $event->timestart = $assignment->timedue;
598 $calendarevent = calendar_event::load($event->id);
599 $calendarevent->update($event);
601 $event = new stdClass();
602 $event->name = $assignment->name;
603 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
604 $event->courseid = $assignment->course;
607 $event->modulename = 'assignment';
608 $event->instance = $assignment->id;
609 $event->eventtype = 'due';
610 $event->timestart = $assignment->timedue;
611 $event->timeduration = 0;
613 calendar_event::create($event);
616 $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id));
619 // get existing grade item
620 assignment_grade_item_update($assignment);
626 * Update grade item for this submission.
628 * @param stdClass $submission The submission instance
630 function update_grade($submission) {
631 assignment_update_grades($this->assignment, $submission->userid);
635 * Top-level function for handling of submissions called by submissions.php
637 * This is for handling the teacher interaction with the grading interface
638 * This should be suitable for most assignment types.
641 * @param string $mode Specifies the kind of teacher interaction taking place
643 function submissions($mode) {
644 ///The main switch is changed to facilitate
645 ///1) Batch fast grading
646 ///2) Skip to the next one on the popup
647 ///3) Save and Skip to the next one on the popup
649 //make user global so we can use the id
650 global $USER, $OUTPUT, $DB, $PAGE;
652 $mailinfo = optional_param('mailinfo', null, PARAM_BOOL);
654 if (optional_param('next', null, PARAM_BOOL)) {
657 if (optional_param('saveandnext', null, PARAM_BOOL)) {
661 if (is_null($mailinfo)) {
662 if (optional_param('sesskey', null, PARAM_BOOL)) {
663 set_user_preference('assignment_mailinfo', 0);
665 $mailinfo = get_user_preferences('assignment_mailinfo', 0);
668 set_user_preference('assignment_mailinfo', $mailinfo);
671 if (!($this->validate_and_preprocess_feedback())) {
672 // form was submitted ('Save' or 'Save and next' was pressed, but validation failed)
673 $this->display_submission();
678 case 'grade': // We are in a main window grading
679 if ($submission = $this->process_feedback()) {
680 $this->display_submissions(get_string('changessaved'));
682 $this->display_submissions();
686 case 'single': // We are in a main window displaying one submission
687 if ($submission = $this->process_feedback()) {
688 $this->display_submissions(get_string('changessaved'));
690 $this->display_submission();
694 case 'all': // Main window, display everything
695 $this->display_submissions();
699 ///do the fast grading stuff - this process should work for all 3 subclasses
703 if (isset($_POST['submissioncomment'])) {
704 $col = 'submissioncomment';
707 if (isset($_POST['menu'])) {
712 //both submissioncomment and grade columns collapsed..
713 $this->display_submissions();
717 foreach ($_POST[$col] as $id => $unusedvalue){
719 $id = (int)$id; //clean parameter name
721 $this->process_outcomes($id);
723 if (!$submission = $this->get_submission($id)) {
724 $submission = $this->prepare_new_submission($id);
725 $newsubmission = true;
727 $newsubmission = false;
729 unset($submission->data1); // Don't need to update this.
730 unset($submission->data2); // Don't need to update this.
732 //for fast grade, we need to check if any changes take place
736 $grade = $_POST['menu'][$id];
737 $updatedb = $updatedb || ($submission->grade != $grade);
738 $submission->grade = $grade;
740 if (!$newsubmission) {
741 unset($submission->grade); // Don't need to update this.
745 $commentvalue = trim($_POST['submissioncomment'][$id]);
746 $updatedb = $updatedb || ($submission->submissioncomment != $commentvalue);
747 $submission->submissioncomment = $commentvalue;
749 unset($submission->submissioncomment); // Don't need to update this.
752 $submission->teacher = $USER->id;
754 $submission->mailed = (int)(!$mailinfo);
757 $submission->timemarked = time();
759 //if it is not an update, we don't change the last modified time etc.
760 //this will also not write into database if no submissioncomment and grade is entered.
763 if ($newsubmission) {
764 if (!isset($submission->submissioncomment)) {
765 $submission->submissioncomment = '';
767 $sid = $DB->insert_record('assignment_submissions', $submission);
768 $submission->id = $sid;
770 $DB->update_record('assignment_submissions', $submission);
773 // trigger grade event
774 $this->update_grade($submission);
776 //add to log only if updating
777 add_to_log($this->course->id, 'assignment', 'update grades',
778 'submissions.php?id='.$this->cm->id.'&user='.$submission->userid,
779 $submission->userid, $this->cm->id);
784 $message = $OUTPUT->notification(get_string('changessaved'), 'notifysuccess');
786 $this->display_submissions($message);
791 ///We are in pop up. save the current one and go to the next one.
792 //first we save the current changes
793 if ($submission = $this->process_feedback()) {
794 //print_heading(get_string('changessaved'));
795 //$extra_javascript = $this->update_main_listing($submission);
799 /// We are currently in pop up, but we want to skip to next one without saving.
800 /// This turns out to be similar to a single case
801 /// The URL used is for the next submission.
802 $offset = required_param('offset', PARAM_INT);
803 $nextid = required_param('nextid', PARAM_INT);
804 $id = required_param('id', PARAM_INT);
805 $filter = optional_param('filter', self::FILTER_ALL, PARAM_INT);
807 if ($mode == 'next' || $filter !== self::FILTER_REQUIRE_GRADING) {
808 $offset = (int)$offset+1;
810 $redirect = new moodle_url('submissions.php',
811 array('id' => $id, 'offset' => $offset, 'userid' => $nextid,
812 'mode' => 'single', 'filter' => $filter));
818 $this->display_submission();
822 echo "something seriously is wrong!!";
828 * Checks if grading method allows quickgrade mode. At the moment it is hardcoded
829 * that advanced grading methods do not allow quickgrade.
831 * Assignment type plugins are not allowed to override this method
835 public final function quickgrade_mode_allowed() {
837 require_once("$CFG->dirroot/grade/grading/lib.php");
838 if ($controller = get_grading_manager($this->context, 'mod_assignment', 'submission')->get_active_controller()) {
845 * Helper method updating the listing on the main script from popup using javascript
849 * @param $submission object The submission whose data is to be updated on the main page
851 function update_main_listing($submission) {
852 global $SESSION, $CFG, $OUTPUT;
856 $perpage = get_user_preferences('assignment_perpage', 10);
858 $quickgrade = get_user_preferences('assignment_quickgrade', 0) && $this->quickgrade_mode_allowed();
860 /// Run some Javascript to try and update the parent page
861 $output .= '<script type="text/javascript">'."\n<!--\n";
862 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['submissioncomment'])) {
864 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid.'").value="'
865 .trim($submission->submissioncomment).'";'."\n";
867 $output.= 'opener.document.getElementById("com'.$submission->userid.
868 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment)), 15)."\";\n";
872 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['grade'])) {
873 //echo optional_param('menuindex');
875 $output.= 'opener.document.getElementById("menumenu'.$submission->userid.
876 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT).'";'."\n";
878 $output.= 'opener.document.getElementById("g'.$submission->userid.'").innerHTML="'.
879 $this->display_grade($submission->grade)."\";\n";
882 //need to add student's assignments in there too.
883 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemodified']) &&
884 $submission->timemodified) {
885 $output.= 'opener.document.getElementById("ts'.$submission->userid.
886 '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid)).userdate($submission->timemodified)."\";\n";
889 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemarked']) &&
890 $submission->timemarked) {
891 $output.= 'opener.document.getElementById("tt'.$submission->userid.
892 '").innerHTML="'.userdate($submission->timemarked)."\";\n";
895 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['status'])) {
896 $output.= 'opener.document.getElementById("up'.$submission->userid.'").className="s1";';
897 $buttontext = get_string('update');
898 $url = new moodle_url('/mod/assignment/submissions.php', array(
899 'id' => $this->cm->id,
900 'userid' => $submission->userid,
902 'offset' => (optional_param('offset', '', PARAM_INT)-1)));
903 $button = $OUTPUT->action_link($url, $buttontext, new popup_action('click', $url, 'grade'.$submission->userid, array('height' => 450, 'width' => 700)), array('ttile'=>$buttontext));
905 $output .= 'opener.document.getElementById("up'.$submission->userid.'").innerHTML="'.addslashes_js($button).'";';
908 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $submission->userid);
910 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['finalgrade'])) {
911 $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid.
912 '").innerHTML="'.$grading_info->items[0]->grades[$submission->userid]->str_grade.'";'."\n";
915 if (!empty($CFG->enableoutcomes) and empty($SESSION->flextable['mod-assignment-submissions']->collapse['outcome'])) {
917 if (!empty($grading_info->outcomes)) {
918 foreach($grading_info->outcomes as $n=>$outcome) {
919 if ($outcome->grades[$submission->userid]->locked) {
924 $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.
925 '").selectedIndex="'.$outcome->grades[$submission->userid]->grade.'";'."\n";
928 $options = make_grades_menu(-$outcome->scaleid);
929 $options[0] = get_string('nooutcome', 'grades');
930 $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.'").innerHTML="'.$options[$outcome->grades[$submission->userid]->grade]."\";\n";
937 $output .= "\n-->\n</script>";
942 * Return a grade in user-friendly form, whether it's a scale or not
945 * @param mixed $grade
946 * @return string User-friendly representation of grade
948 function display_grade($grade) {
951 static $scalegrades = array(); // Cache scales for each assignment - they might have different scales!!
953 if ($this->assignment->grade >= 0) { // Normal number
957 return $grade.' / '.$this->assignment->grade;
961 if (empty($scalegrades[$this->assignment->id])) {
962 if ($scale = $DB->get_record('scale', array('id'=>-($this->assignment->grade)))) {
963 $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
968 if (isset($scalegrades[$this->assignment->id][$grade])) {
969 return $scalegrades[$this->assignment->id][$grade];
976 * Display a single submission, ready for grading on a popup window
978 * This default method prints the teacher info and submissioncomment box at the top and
979 * the student info and submission at the bottom.
980 * This method also fetches the necessary data in order to be able to
981 * provide a "Next submission" button.
982 * Calls preprocess_submission() to give assignment type plug-ins a chance
983 * to process submissions before they are graded
984 * This method gets its arguments from the page parameters userid and offset
988 * @param string $extra_javascript
990 function display_submission($offset=-1,$userid =-1, $display=true) {
991 global $CFG, $DB, $PAGE, $OUTPUT, $USER;
992 require_once($CFG->libdir.'/gradelib.php');
993 require_once($CFG->libdir.'/tablelib.php');
994 require_once("$CFG->dirroot/repository/lib.php");
995 require_once("$CFG->dirroot/grade/grading/lib.php");
997 $userid = required_param('userid', PARAM_INT);
1000 $offset = required_param('offset', PARAM_INT);//offset for where to start looking for student.
1002 $filter = optional_param('filter', 0, PARAM_INT);
1004 if (!$user = $DB->get_record('user', array('id'=>$userid))) {
1005 print_error('nousers');
1008 if (!$submission = $this->get_submission($user->id)) {
1009 $submission = $this->prepare_new_submission($userid);
1011 if ($submission->timemodified > $submission->timemarked) {
1012 $subtype = 'assignmentnew';
1014 $subtype = 'assignmentold';
1017 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
1018 $gradingdisabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
1020 /// construct SQL, using current offset to find the data of the next student
1021 $course = $this->course;
1022 $assignment = $this->assignment;
1024 $context = context_module::instance($cm->id);
1026 //reset filter to all for offline assignment
1027 if ($assignment->assignmenttype == 'offline' && $filter == self::FILTER_SUBMITTED) {
1028 $filter = self::FILTER_ALL;
1030 /// Get all ppl that can submit assignments
1032 $currentgroup = groups_get_activity_group($cm);
1033 $users = get_enrolled_users($context, 'mod/assignment:submit', $currentgroup, 'u.id');
1035 $users = array_keys($users);
1036 // if groupmembersonly used, remove users who are not in any group
1037 if (!empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
1038 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1039 $users = array_intersect($users, array_keys($groupingusers));
1046 if($filter == self::FILTER_SUBMITTED) {
1047 $where .= 's.timemodified > 0 AND ';
1048 } else if($filter == self::FILTER_REQUIRE_GRADING) {
1049 $where .= 's.timemarked < s.timemodified AND ';
1053 $userfields = user_picture::fields('u', array('lastaccess'));
1054 $select = "SELECT $userfields,
1055 s.id AS submissionid, s.grade, s.submissioncomment,
1056 s.timemodified, s.timemarked,
1057 CASE WHEN s.timemarked > 0 AND s.timemarked >= s.timemodified THEN 1
1058 ELSE 0 END AS status ";
1060 $sql = 'FROM {user} u '.
1061 'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1062 AND s.assignment = '.$this->assignment->id.' '.
1063 'WHERE '.$where.'u.id IN ('.implode(',', $users).') ';
1065 if ($sort = flexible_table::get_sort_for_table('mod-assignment-submissions')) {
1066 $sort = 'ORDER BY '.$sort.' ';
1068 $auser = $DB->get_records_sql($select.$sql.$sort, null, $offset, 2);
1070 if (is_array($auser) && count($auser)>1) {
1071 $nextuser = next($auser);
1072 $nextid = $nextuser->id;
1076 if ($submission->teacher) {
1077 $teacher = $DB->get_record('user', array('id'=>$submission->teacher));
1083 $this->preprocess_submission($submission);
1085 $mformdata = new stdClass();
1086 $mformdata->context = $this->context;
1087 $mformdata->maxbytes = $this->course->maxbytes;
1088 $mformdata->courseid = $this->course->id;
1089 $mformdata->teacher = $teacher;
1090 $mformdata->assignment = $assignment;
1091 $mformdata->submission = $submission;
1092 $mformdata->lateness = $this->display_lateness($submission->timemodified);
1093 $mformdata->auser = $auser;
1094 $mformdata->user = $user;
1095 $mformdata->offset = $offset;
1096 $mformdata->userid = $userid;
1097 $mformdata->cm = $this->cm;
1098 $mformdata->grading_info = $grading_info;
1099 $mformdata->enableoutcomes = $CFG->enableoutcomes;
1100 $mformdata->grade = $this->assignment->grade;
1101 $mformdata->gradingdisabled = $gradingdisabled;
1102 $mformdata->nextid = $nextid;
1103 $mformdata->submissioncomment= $submission->submissioncomment;
1104 $mformdata->submissioncommentformat= FORMAT_HTML;
1105 $mformdata->submission_content= $this->print_user_files($user->id,true);
1106 $mformdata->filter = $filter;
1107 $mformdata->mailinfo = get_user_preferences('assignment_mailinfo', 0);
1108 if ($assignment->assignmenttype == 'upload') {
1109 $mformdata->fileui_options = array('subdirs'=>1, 'maxbytes'=>$assignment->maxbytes, 'maxfiles'=>$assignment->var1, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL);
1110 } elseif ($assignment->assignmenttype == 'uploadsingle') {
1111 $mformdata->fileui_options = array('subdirs'=>0, 'maxbytes'=>$CFG->userquota, 'maxfiles'=>1, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL);
1113 $advancedgradingwarning = false;
1114 $gradingmanager = get_grading_manager($this->context, 'mod_assignment', 'submission');
1115 if ($gradingmethod = $gradingmanager->get_active_method()) {
1116 $controller = $gradingmanager->get_controller($gradingmethod);
1117 if ($controller->is_form_available()) {
1119 if (!empty($submission->id)) {
1120 $itemid = $submission->id;
1122 if ($gradingdisabled && $itemid) {
1123 $mformdata->advancedgradinginstance = $controller->get_current_instance($USER->id, $itemid);
1124 } else if (!$gradingdisabled) {
1125 $instanceid = optional_param('advancedgradinginstanceid', 0, PARAM_INT);
1126 $mformdata->advancedgradinginstance = $controller->get_or_create_instance($instanceid, $USER->id, $itemid);
1129 $advancedgradingwarning = $controller->form_unavailable_notification();
1133 $submitform = new assignment_grading_form( null, $mformdata );
1136 $ret_data = new stdClass();
1137 $ret_data->mform = $submitform;
1138 if (isset($mformdata->fileui_options)) {
1139 $ret_data->fileui_options = $mformdata->fileui_options;
1144 if ($submitform->is_cancelled()) {
1145 redirect('submissions.php?id='.$this->cm->id);
1148 $submitform->set_data($mformdata);
1150 $PAGE->set_title($this->course->fullname . ': ' .get_string('feedback', 'assignment').' - '.fullname($user, true));
1151 $PAGE->set_heading($this->course->fullname);
1152 $PAGE->navbar->add(get_string('submissions', 'assignment'), new moodle_url('/mod/assignment/submissions.php', array('id'=>$cm->id)));
1153 $PAGE->navbar->add(fullname($user, true));
1155 echo $OUTPUT->header();
1156 echo $OUTPUT->heading(get_string('feedback', 'assignment').': '.fullname($user, true));
1158 // display mform here...
1159 if ($advancedgradingwarning) {
1160 echo $OUTPUT->notification($advancedgradingwarning, 'error');
1162 $submitform->display();
1164 $customfeedback = $this->custom_feedbackform($submission, true);
1165 if (!empty($customfeedback)) {
1166 echo $customfeedback;
1169 echo $OUTPUT->footer();
1173 * Preprocess submission before grading
1175 * Called by display_submission()
1176 * The default type does nothing here.
1178 * @param object $submission The submission object
1180 function preprocess_submission(&$submission) {
1184 * Display all the submissions ready for grading
1190 * @param string $message
1193 function display_submissions($message='') {
1194 global $CFG, $DB, $USER, $DB, $OUTPUT, $PAGE;
1195 require_once($CFG->libdir.'/gradelib.php');
1197 /* first we check to see if the form has just been submitted
1198 * to request user_preference updates
1201 $filters = array(self::FILTER_ALL => get_string('all'),
1202 self::FILTER_REQUIRE_GRADING => get_string('requiregrading', 'assignment'));
1204 $updatepref = optional_param('updatepref', 0, PARAM_BOOL);
1206 $perpage = optional_param('perpage', 10, PARAM_INT);
1207 $perpage = ($perpage <= 0) ? 10 : $perpage ;
1208 $filter = optional_param('filter', 0, PARAM_INT);
1209 set_user_preference('assignment_perpage', $perpage);
1210 set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
1211 set_user_preference('assignment_filter', $filter);
1214 /* next we get perpage and quickgrade (allow quick grade) params
1217 $perpage = get_user_preferences('assignment_perpage', 10);
1218 $quickgrade = get_user_preferences('assignment_quickgrade', 0) && $this->quickgrade_mode_allowed();
1219 $filter = get_user_preferences('assignment_filter', 0);
1220 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);
1222 if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
1223 $uses_outcomes = true;
1225 $uses_outcomes = false;
1228 $page = optional_param('page', 0, PARAM_INT);
1229 $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
1231 /// Some shortcuts to make the code read better
1233 $course = $this->course;
1234 $assignment = $this->assignment;
1236 $hassubmission = false;
1238 // reset filter to all for offline assignment only.
1239 if ($assignment->assignmenttype == 'offline') {
1240 if ($filter == self::FILTER_SUBMITTED) {
1241 $filter = self::FILTER_ALL;
1244 $filters[self::FILTER_SUBMITTED] = get_string('submitted', 'assignment');
1247 $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
1248 add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->cm->id, $this->assignment->id, $this->cm->id);
1250 $PAGE->set_title(format_string($this->assignment->name,true));
1251 $PAGE->set_heading($this->course->fullname);
1252 echo $OUTPUT->header();
1254 echo '<div class="usersubmissions">';
1256 //hook to allow plagiarism plugins to update status/print links.
1257 echo plagiarism_update_status($this->course, $this->cm);
1259 $course_context = context_course::instance($course->id);
1260 if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
1261 echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">'
1262 . get_string('seeallcoursegrades', 'grades') . '</a></div>';
1265 if (!empty($message)) {
1266 echo $message; // display messages here if any
1269 $context = context_module::instance($cm->id);
1271 /// Check to see if groups are being used in this assignment
1273 /// find out current groups mode
1274 $groupmode = groups_get_activity_groupmode($cm);
1275 $currentgroup = groups_get_activity_group($cm, true);
1276 groups_print_activity_menu($cm, $CFG->wwwroot . '/mod/assignment/submissions.php?id=' . $this->cm->id);
1278 /// Print quickgrade form around the table
1280 $formattrs = array();
1281 $formattrs['action'] = new moodle_url('/mod/assignment/submissions.php');
1282 $formattrs['id'] = 'fastg';
1283 $formattrs['method'] = 'post';
1285 echo html_writer::start_tag('form', $formattrs);
1286 echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'id', 'value'=> $this->cm->id));
1287 echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'mode', 'value'=> 'fastgrade'));
1288 echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'page', 'value'=> $page));
1289 echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=> sesskey()));
1292 /// Get all ppl that are allowed to submit assignments
1293 list($esql, $params) = get_enrolled_sql($context, 'mod/assignment:submit', $currentgroup);
1295 if ($filter == self::FILTER_ALL) {
1296 $sql = "SELECT u.id FROM {user} u ".
1297 "LEFT JOIN ($esql) eu ON eu.id=u.id ".
1298 "WHERE u.deleted = 0 AND eu.id=u.id ";
1300 $wherefilter = ' AND s.assignment = '. $this->assignment->id;
1301 $assignmentsubmission = "LEFT JOIN {assignment_submissions} s ON (u.id = s.userid) ";
1302 if($filter == self::FILTER_SUBMITTED) {
1303 $wherefilter .= ' AND s.timemodified > 0 ';
1304 } else if($filter == self::FILTER_REQUIRE_GRADING && $assignment->assignmenttype != 'offline') {
1305 $wherefilter .= ' AND s.timemarked < s.timemodified ';
1306 } else { // require grading for offline assignment
1307 $assignmentsubmission = "";
1311 $sql = "SELECT u.id FROM {user} u ".
1312 "LEFT JOIN ($esql) eu ON eu.id=u.id ".
1313 $assignmentsubmission.
1314 "WHERE u.deleted = 0 AND eu.id=u.id ".
1318 $users = $DB->get_records_sql($sql, $params);
1319 if (!empty($users)) {
1320 if($assignment->assignmenttype == 'offline' && $filter == self::FILTER_REQUIRE_GRADING) {
1321 //remove users who has submitted their assignment
1322 foreach ($this->get_submissions() as $submission) {
1323 if (array_key_exists($submission->userid, $users)) {
1324 unset($users[$submission->userid]);
1328 $users = array_keys($users);
1331 // if groupmembersonly used, remove users who are not in any group
1332 if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
1333 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1334 $users = array_intersect($users, array_keys($groupingusers));
1338 $extrafields = get_extra_user_fields($context);
1339 $tablecolumns = array_merge(array('picture', 'fullname'), $extrafields,
1340 array('grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade'));
1341 if ($uses_outcomes) {
1342 $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
1345 $extrafieldnames = array();
1346 foreach ($extrafields as $field) {
1347 $extrafieldnames[] = get_user_field_name($field);
1349 $tableheaders = array_merge(
1350 array('', get_string('fullnameuser')),
1353 get_string('grade'),
1354 get_string('comment', 'assignment'),
1355 get_string('lastmodified').' ('.get_string('submission', 'assignment').')',
1356 get_string('lastmodified').' ('.get_string('grade').')',
1357 get_string('status'),
1358 get_string('finalgrade', 'grades'),
1360 if ($uses_outcomes) {
1361 $tableheaders[] = get_string('outcome', 'grades');
1364 require_once($CFG->libdir.'/tablelib.php');
1365 $table = new flexible_table('mod-assignment-submissions');
1367 $table->define_columns($tablecolumns);
1368 $table->define_headers($tableheaders);
1369 $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&currentgroup='.$currentgroup);
1371 $table->sortable(true, 'lastname');//sorted by lastname by default
1372 $table->collapsible(true);
1373 $table->initialbars(true);
1375 $table->column_suppress('picture');
1376 $table->column_suppress('fullname');
1378 $table->column_class('picture', 'picture');
1379 $table->column_class('fullname', 'fullname');
1380 foreach ($extrafields as $field) {
1381 $table->column_class($field, $field);
1383 $table->column_class('grade', 'grade');
1384 $table->column_class('submissioncomment', 'comment');
1385 $table->column_class('timemodified', 'timemodified');
1386 $table->column_class('timemarked', 'timemarked');
1387 $table->column_class('status', 'status');
1388 $table->column_class('finalgrade', 'finalgrade');
1389 if ($uses_outcomes) {
1390 $table->column_class('outcome', 'outcome');
1393 $table->set_attribute('cellspacing', '0');
1394 $table->set_attribute('id', 'attempts');
1395 $table->set_attribute('class', 'submissions');
1396 $table->set_attribute('width', '100%');
1398 $table->no_sorting('finalgrade');
1399 $table->no_sorting('outcome');
1400 $table->text_sorting('submissioncomment');
1402 // Start working -- this is necessary as soon as the niceties are over
1405 /// Construct the SQL
1406 list($where, $params) = $table->get_sql_where();
1411 if ($filter == self::FILTER_SUBMITTED) {
1412 $where .= 's.timemodified > 0 AND ';
1413 } else if($filter == self::FILTER_REQUIRE_GRADING) {
1415 if ($assignment->assignmenttype != 'offline') {
1416 $where .= 's.timemarked < s.timemodified AND ';
1420 if ($sort = $table->get_sql_sort()) {
1421 $sort = ' ORDER BY '.$sort;
1424 $ufields = user_picture::fields('u', $extrafields);
1425 if (!empty($users)) {
1426 $select = "SELECT $ufields,
1427 s.id AS submissionid, s.grade, s.submissioncomment,
1428 s.timemodified, s.timemarked,
1429 CASE WHEN s.timemarked > 0 AND s.timemarked >= s.timemodified THEN 1
1430 ELSE 0 END AS status ";
1432 $sql = 'FROM {user} u '.
1433 'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1434 AND s.assignment = '.$this->assignment->id.' '.
1435 'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1437 $ausers = $DB->get_records_sql($select.$sql.$sort, $params, $table->get_page_start(), $table->get_page_size());
1439 $table->pagesize($perpage, count($users));
1441 ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1442 $offset = $page * $perpage;
1443 $strupdate = get_string('update');
1444 $strgrade = get_string('grade');
1445 $strview = get_string('view');
1446 $grademenu = make_grades_menu($this->assignment->grade);
1448 if ($ausers !== false) {
1449 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
1450 $endposition = $offset + $perpage;
1451 $currentposition = 0;
1452 foreach ($ausers as $auser) {
1453 if ($currentposition == $offset && $offset < $endposition) {
1455 $final_grade = $grading_info->items[0]->grades[$auser->id];
1456 $grademax = $grading_info->items[0]->grademax;
1457 $final_grade->formatted_grade = round($final_grade->grade,2) .' / ' . round($grademax,2);
1458 $locked_overridden = 'locked';
1459 if ($final_grade->overridden) {
1460 $locked_overridden = 'overridden';
1463 // TODO add here code if advanced grading grade must be reviewed => $auser->status=0
1465 $picture = $OUTPUT->user_picture($auser);
1467 if (empty($auser->submissionid)) {
1468 $auser->grade = -1; //no submission yet
1471 if (!empty($auser->submissionid)) {
1472 $hassubmission = true;
1473 ///Prints student answer and student modified date
1474 ///attach file or print link to student answer, depending on the type of the assignment.
1475 ///Refer to print_student_answer in inherited classes.
1476 if ($auser->timemodified > 0) {
1477 $studentmodifiedcontent = $this->print_student_answer($auser->id)
1478 . userdate($auser->timemodified);
1479 if ($assignment->timedue && $auser->timemodified > $assignment->timedue && $this->supports_lateness()) {
1480 $studentmodifiedcontent .= $this->display_lateness($auser->timemodified);
1484 $studentmodifiedcontent = ' ';
1486 $studentmodified = html_writer::tag('div', $studentmodifiedcontent, array('id' => 'ts' . $auser->id));
1487 ///Print grade, dropdown or text
1488 if ($auser->timemarked > 0) {
1489 $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
1491 if ($final_grade->locked or $final_grade->overridden) {
1492 $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1493 } else if ($quickgrade) {
1494 $attributes = array();
1495 $attributes['tabindex'] = $tabindex++;
1496 $menu = html_writer::label(get_string('assignment:grade', 'assignment'), 'menumenu'. $auser->id, false, array('class' => 'accesshide'));
1497 $menu .= html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1498 $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
1500 $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1504 $teachermodified = '<div id="tt'.$auser->id.'"> </div>';
1505 if ($final_grade->locked or $final_grade->overridden) {
1506 $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1507 } else if ($quickgrade) {
1508 $attributes = array();
1509 $attributes['tabindex'] = $tabindex++;
1510 $menu = html_writer::label(get_string('assignment:grade', 'assignment'), 'menumenu'. $auser->id, false, array('class' => 'accesshide'));
1511 $menu .= html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1512 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1514 $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1518 if ($final_grade->locked or $final_grade->overridden) {
1519 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';
1521 } else if ($quickgrade) {
1522 $comment = '<div id="com'.$auser->id.'">'
1523 . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1524 . $auser->id.'" rows="2" cols="20" spellcheck="true">'.($auser->submissioncomment).'</textarea></div>';
1526 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
1529 $studentmodified = '<div id="ts'.$auser->id.'"> </div>';
1530 $teachermodified = '<div id="tt'.$auser->id.'"> </div>';
1531 $status = '<div id="st'.$auser->id.'"> </div>';
1533 if ($final_grade->locked or $final_grade->overridden) {
1534 $grade = '<div id="g'.$auser->id.'">'.$final_grade->formatted_grade . '</div>';
1535 $hassubmission = true;
1536 } else if ($quickgrade) { // allow editing
1537 $attributes = array();
1538 $attributes['tabindex'] = $tabindex++;
1539 $menu = html_writer::label(get_string('assignment:grade', 'assignment'), 'menumenu'. $auser->id, false, array('class' => 'accesshide'));
1540 $menu .= html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1541 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1542 $hassubmission = true;
1544 $grade = '<div id="g'.$auser->id.'">-</div>';
1547 if ($final_grade->locked or $final_grade->overridden) {
1548 $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
1549 } else if ($quickgrade) {
1550 $comment = '<div id="com'.$auser->id.'">'
1551 . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1552 . $auser->id.'" rows="2" cols="20" spellcheck="true">'.($auser->submissioncomment).'</textarea></div>';
1554 $comment = '<div id="com'.$auser->id.'"> </div>';
1558 if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
1564 $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
1565 if ($final_grade->locked or $final_grade->overridden) {
1566 $buttontext = $strview;
1569 ///No more buttons, we use popups ;-).
1570 $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1571 . '&userid='.$auser->id.'&mode=single'.'&filter='.$filter.'&offset='.$offset++;
1573 $button = $OUTPUT->action_link($popup_url, $buttontext);
1575 $status = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
1577 $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';
1581 if ($uses_outcomes) {
1583 foreach($grading_info->outcomes as $n=>$outcome) {
1584 $outcomes .= '<div class="outcome"><label for="'. 'outcome_'.$n.'_'.$auser->id .'">'.$outcome->name.'</label>';
1585 $options = make_grades_menu(-$outcome->scaleid);
1587 if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
1588 $options[0] = get_string('nooutcome', 'grades');
1589 $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
1591 $attributes = array();
1592 $attributes['tabindex'] = $tabindex++;
1593 $attributes['id'] = 'outcome_'.$n.'_'.$auser->id;
1594 $outcomes .= ' '.html_writer::select($options, 'outcome_'.$n.'['.$auser->id.']', $outcome->grades[$auser->id]->grade, array(0=>get_string('nooutcome', 'grades')), $attributes);
1596 $outcomes .= '</div>';
1600 $userlink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $auser->id . '&course=' . $course->id . '">' . fullname($auser, has_capability('moodle/site:viewfullnames', $this->context)) . '</a>';
1601 $extradata = array();
1602 foreach ($extrafields as $field) {
1603 $extradata[] = $auser->{$field};
1605 $row = array_merge(array($picture, $userlink), $extradata,
1606 array($grade, $comment, $studentmodified, $teachermodified,
1607 $status, $finalgrade));
1608 if ($uses_outcomes) {
1611 $table->add_data($row, $rowclass);
1615 if ($hassubmission && method_exists($this, 'download_submissions')) {
1616 echo html_writer::start_tag('div', array('class' => 'mod-assignment-download-link'));
1617 echo html_writer::link(new moodle_url('/mod/assignment/submissions.php', array('id' => $this->cm->id, 'download' => 'zip')), get_string('downloadall', 'assignment'));
1618 echo html_writer::end_tag('div');
1620 $table->print_html(); /// Print the whole table
1622 if ($filter == self::FILTER_SUBMITTED) {
1623 echo html_writer::tag('div', get_string('nosubmisson', 'assignment'), array('class'=>'nosubmisson'));
1624 } else if ($filter == self::FILTER_REQUIRE_GRADING) {
1625 echo html_writer::tag('div', get_string('norequiregrading', 'assignment'), array('class'=>'norequiregrading'));
1630 /// Print quickgrade form around the table
1631 if ($quickgrade && $table->started_output && !empty($users)){
1632 $mailinfopref = false;
1633 if (get_user_preferences('assignment_mailinfo', 1)) {
1634 $mailinfopref = true;
1636 $emailnotification = html_writer::checkbox('mailinfo', 1, $mailinfopref, get_string('enablenotification','assignment'));
1638 $emailnotification .= $OUTPUT->help_icon('enablenotification', 'assignment');
1639 echo html_writer::tag('div', $emailnotification, array('class'=>'emailnotification'));
1641 $savefeedback = html_writer::empty_tag('input', array('type'=>'submit', 'name'=>'fastg', 'value'=>get_string('saveallfeedback', 'assignment')));
1642 echo html_writer::tag('div', $savefeedback, array('class'=>'fastgbutton'));
1644 echo html_writer::end_tag('form');
1645 } else if ($quickgrade) {
1646 echo html_writer::end_tag('form');
1650 /// End of fast grading form
1652 /// Mini form for setting user preference
1654 $formaction = new moodle_url('/mod/assignment/submissions.php', array('id'=>$this->cm->id));
1655 $mform = new MoodleQuickForm('optionspref', 'post', $formaction, '', array('class'=>'optionspref'));
1657 $mform->addElement('hidden', 'updatepref');
1658 $mform->setDefault('updatepref', 1);
1659 $mform->addElement('header', 'qgprefs', get_string('optionalsettings', 'assignment'));
1660 $mform->addElement('select', 'filter', get_string('show'), $filters);
1662 $mform->setDefault('filter', $filter);
1664 $mform->addElement('text', 'perpage', get_string('pagesize', 'assignment'), array('size'=>1));
1665 $mform->setDefault('perpage', $perpage);
1667 if ($this->quickgrade_mode_allowed()) {
1668 $mform->addElement('checkbox', 'quickgrade', get_string('quickgrade','assignment'));
1669 $mform->setDefault('quickgrade', $quickgrade);
1670 $mform->addHelpButton('quickgrade', 'quickgrade', 'assignment');
1673 $mform->addElement('submit', 'savepreferences', get_string('savepreferences'));
1677 echo $OUTPUT->footer();
1681 * If the form was cancelled ('Cancel' or 'Next' was pressed), call cancel method
1682 * from advanced grading (if applicable) and returns true
1683 * If the form was submitted, validates it and returns false if validation did not pass.
1684 * If validation passes, preprocess advanced grading (if applicable) and returns true.
1686 * Note to the developers: This is NOT the correct way to implement advanced grading
1687 * in grading form. The assignment grading was written long time ago and unfortunately
1688 * does not fully use the mforms. Usually function is_validated() is called to
1689 * validate the form and get_data() is called to get the data from the form.
1691 * Here we have to push the calculated grade to $_POST['xgrade'] because further processing
1692 * of the form gets the data not from form->get_data(), but from $_POST (using statement
1693 * like $feedback = data_submitted() )
1695 protected function validate_and_preprocess_feedback() {
1697 require_once($CFG->libdir.'/gradelib.php');
1698 if (!($feedback = data_submitted()) || !isset($feedback->userid) || !isset($feedback->offset)) {
1699 return true; // No incoming data, nothing to validate
1701 $userid = required_param('userid', PARAM_INT);
1702 $offset = required_param('offset', PARAM_INT);
1703 $gradinginfo = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($userid));
1704 $gradingdisabled = $gradinginfo->items[0]->grades[$userid]->locked || $gradinginfo->items[0]->grades[$userid]->overridden;
1705 if ($gradingdisabled) {
1708 $submissiondata = $this->display_submission($offset, $userid, false);
1709 $mform = $submissiondata->mform;
1710 $gradinginstance = $mform->use_advanced_grading();
1711 if (optional_param('cancel', false, PARAM_BOOL) || optional_param('next', false, PARAM_BOOL)) {
1712 // form was cancelled
1713 if ($gradinginstance) {
1714 $gradinginstance->cancel();
1716 } else if ($mform->is_submitted()) {
1717 // form was submitted (= a submit button other than 'cancel' or 'next' has been clicked)
1718 if (!$mform->is_validated()) {
1721 // preprocess advanced grading here
1722 if ($gradinginstance) {
1723 $data = $mform->get_data();
1724 // create submission if it did not exist yet because we need submission->id for storing the grading instance
1725 $submission = $this->get_submission($userid, true);
1726 $_POST['xgrade'] = $gradinginstance->submit_and_get_grade($data->advancedgrading, $submission->id);
1733 * Process teacher feedback submission
1735 * This is called by submissions() when a grading even has taken place.
1736 * It gets its data from the submitted form.
1741 * @return object|bool The updated submission object or false
1743 function process_feedback($formdata=null) {
1744 global $CFG, $USER, $DB;
1745 require_once($CFG->libdir.'/gradelib.php');
1747 if (!$feedback = data_submitted() or !confirm_sesskey()) { // No incoming data?
1751 ///For save and next, we need to know the userid to save, and the userid to go
1752 ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1753 ///as the userid to store
1754 if ((int)$feedback->saveuserid !== -1){
1755 $feedback->userid = $feedback->saveuserid;
1758 if (!empty($feedback->cancel)) { // User hit cancel button
1762 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);
1764 // store outcomes if needed
1765 $this->process_outcomes($feedback->userid);
1767 $submission = $this->get_submission($feedback->userid, true); // Get or make one
1769 if (!($grading_info->items[0]->grades[$feedback->userid]->locked ||
1770 $grading_info->items[0]->grades[$feedback->userid]->overridden) ) {
1772 $submission->grade = $feedback->xgrade;
1773 $submission->submissioncomment = $feedback->submissioncomment_editor['text'];
1774 $submission->teacher = $USER->id;
1775 $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1777 $submission->mailed = 1; // treat as already mailed
1779 $submission->mailed = 0; // Make sure mail goes out (again, even)
1781 $submission->timemarked = time();
1783 unset($submission->data1); // Don't need to update this.
1784 unset($submission->data2); // Don't need to update this.
1786 if (empty($submission->timemodified)) { // eg for offline assignments
1787 // $submission->timemodified = time();
1790 $DB->update_record('assignment_submissions', $submission);
1792 // triger grade event
1793 $this->update_grade($submission);
1795 add_to_log($this->course->id, 'assignment', 'update grades',
1796 'submissions.php?id='.$this->cm->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
1797 if (!is_null($formdata)) {
1798 if ($this->type == 'upload' || $this->type == 'uploadsingle') {
1799 $mformdata = $formdata->mform->get_data();
1800 $mformdata = file_postupdate_standard_filemanager($mformdata, 'files', $formdata->fileui_options, $this->context, 'mod_assignment', 'response', $submission->id);
1809 function process_outcomes($userid) {
1812 if (empty($CFG->enableoutcomes)) {
1816 require_once($CFG->libdir.'/gradelib.php');
1818 if (!$formdata = data_submitted() or !confirm_sesskey()) {
1823 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
1825 if (!empty($grading_info->outcomes)) {
1826 foreach($grading_info->outcomes as $n=>$old) {
1827 $name = 'outcome_'.$n;
1828 if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
1829 $data[$n] = $formdata->{$name}[$userid];
1833 if (count($data) > 0) {
1834 grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1840 * Load the submission object for a particular user
1844 * @param int $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1845 * @param bool $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1846 * @param bool $teachermodified student submission set if false
1847 * @return object|bool The submission or false (if $createnew is false and there is no existing submission).
1849 function get_submission($userid=0, $createnew=false, $teachermodified=false) {
1852 if (empty($userid)) {
1853 $userid = $USER->id;
1856 $submission = $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1860 } else if (!$createnew) {
1863 $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
1864 $DB->insert_record("assignment_submissions", $newsubmission);
1866 return $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1870 * Check the given submission is complete. Preliminary rows are often created in the assignment_submissions
1871 * table before a submission actually takes place. This function checks to see if the given submission has actually
1874 * @param stdClass $submission The submission we want to check for completion
1875 * @return bool Indicates if the submission was found to be complete
1877 public function is_submitted_with_required_data($submission) {
1878 return $submission->timemodified;
1882 * Instantiates a new submission object for a given user
1884 * Sets the assignment, userid and times, everything else is set to default values.
1886 * @param int $userid The userid for which we want a submission object
1887 * @param bool $teachermodified student submission set if false
1888 * @return object The submission
1890 function prepare_new_submission($userid, $teachermodified=false) {
1891 $submission = new stdClass();
1892 $submission->assignment = $this->assignment->id;
1893 $submission->userid = $userid;
1894 $submission->timecreated = time();
1895 // teachers should not be modifying modified date, except offline assignments
1896 if ($teachermodified) {
1897 $submission->timemodified = 0;
1899 $submission->timemodified = $submission->timecreated;
1901 $submission->numfiles = 0;
1902 $submission->data1 = '';
1903 $submission->data2 = '';
1904 $submission->grade = -1;
1905 $submission->submissioncomment = '';
1906 $submission->format = 0;
1907 $submission->teacher = 0;
1908 $submission->timemarked = 0;
1909 $submission->mailed = 0;
1914 * Return all assignment submissions by ENROLLED students (even empty)
1916 * @param string $sort optional field names for the ORDER BY in the sql query
1917 * @param string $dir optional specifying the sort direction, defaults to DESC
1918 * @return array The submission objects indexed by id
1920 function get_submissions($sort='', $dir='DESC') {
1921 return assignment_get_all_submissions($this->assignment, $sort, $dir);
1925 * Counts all complete (real) assignment submissions by enrolled students
1927 * @param int $groupid (optional) If nonzero then count is restricted to this group
1928 * @return int The number of submissions
1930 function count_real_submissions($groupid=0) {
1934 // Grab the context assocated with our course module
1935 $context = context_module::instance($this->cm->id);
1937 // Get ids of users enrolled in the given course.
1938 list($enroledsql, $params) = get_enrolled_sql($context, 'mod/assignment:view', $groupid);
1939 $params['assignmentid'] = $this->cm->instance;
1941 // Get ids of users enrolled in the given course.
1942 return $DB->count_records_sql("SELECT COUNT('x')
1943 FROM {assignment_submissions} s
1944 LEFT JOIN {assignment} a ON a.id = s.assignment
1945 INNER JOIN ($enroledsql) u ON u.id = s.userid
1946 WHERE s.assignment = :assignmentid AND
1947 s.timemodified > 0", $params);
1951 * Alerts teachers by email of new or changed assignments that need grading
1953 * First checks whether the option to email teachers is set for this assignment.
1954 * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1955 * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1959 * @param $submission object The submission that has changed
1962 function email_teachers($submission) {
1965 if (empty($this->assignment->emailteachers)) { // No need to do anything
1969 $user = $DB->get_record('user', array('id'=>$submission->userid));
1971 if ($teachers = $this->get_graders($user)) {
1973 $strassignments = get_string('modulenameplural', 'assignment');
1974 $strassignment = get_string('modulename', 'assignment');
1975 $strsubmitted = get_string('submitted', 'assignment');
1977 foreach ($teachers as $teacher) {
1978 $info = new stdClass();
1979 $info->username = fullname($user, true);
1980 $info->assignment = format_string($this->assignment->name,true);
1981 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
1982 $info->timeupdated = userdate($submission->timemodified, '%c', $teacher->timezone);
1984 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1985 $posttext = $this->email_teachers_text($info);
1986 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
1988 $eventdata = new stdClass();
1989 $eventdata->modulename = 'assignment';
1990 $eventdata->userfrom = $user;
1991 $eventdata->userto = $teacher;
1992 $eventdata->subject = $postsubject;
1993 $eventdata->fullmessage = $posttext;
1994 $eventdata->fullmessageformat = FORMAT_PLAIN;
1995 $eventdata->fullmessagehtml = $posthtml;
1996 $eventdata->smallmessage = $postsubject;
1998 $eventdata->name = 'assignment_updates';
1999 $eventdata->component = 'mod_assignment';
2000 $eventdata->notification = 1;
2001 $eventdata->contexturl = $info->url;
2002 $eventdata->contexturlname = $info->assignment;
2004 message_send($eventdata);
2012 * @param string $filearea
2013 * @param array $args
2014 * @param bool $forcedownload whether or not force download
2015 * @param array $options additional options affecting the file serving
2018 function send_file($filearea, $args, $forcedownload, array $options=array()) {
2019 debugging('plugin does not implement file sending', DEBUG_DEVELOPER);
2024 * Returns a list of teachers that should be grading given submission
2026 * @param object $user
2029 function get_graders($user) {
2033 list($enrolledsql, $params) = get_enrolled_sql($this->context, 'mod/assignment:grade', 0, true);
2036 JOIN ($enrolledsql) je ON je.id = u.id";
2037 $potgraders = $DB->get_records_sql($sql, $params);
2040 if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) { // Separate groups are being used
2041 if ($groups = groups_get_all_groups($this->course->id, $user->id)) { // Try to find all groups
2042 foreach ($groups as $group) {
2043 foreach ($potgraders as $t) {
2044 if ($t->id == $user->id) {
2045 continue; // do not send self
2047 if (groups_is_member($group->id, $t->id)) {
2048 $graders[$t->id] = $t;
2053 // user not in group, try to find graders without group
2054 foreach ($potgraders as $t) {
2055 if ($t->id == $user->id) {
2056 continue; // do not send self
2058 if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
2059 $graders[$t->id] = $t;
2064 foreach ($potgraders as $t) {
2065 if ($t->id == $user->id) {
2066 continue; // do not send self
2068 $graders[$t->id] = $t;
2075 * Creates the text content for emails to teachers
2077 * @param $info object The info used by the 'emailteachermail' language string
2080 function email_teachers_text($info) {
2081 $posttext = format_string($this->course->shortname, true, array('context' => $this->coursecontext)).' -> '.
2082 $this->strassignments.' -> '.
2083 format_string($this->assignment->name, true, array('context' => $this->context))."\n";
2084 $posttext .= '---------------------------------------------------------------------'."\n";
2085 $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
2086 $posttext .= "\n---------------------------------------------------------------------\n";
2091 * Creates the html content for emails to teachers
2093 * @param $info object The info used by the 'emailteachermailhtml' language string
2096 function email_teachers_html($info) {
2098 $posthtml = '<p><font face="sans-serif">'.
2099 '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname, true, array('context' => $this->coursecontext)).'</a> ->'.
2100 '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
2101 '<a href="'.$CFG->wwwroot.'/mod/assignment/view.php?id='.$this->cm->id.'">'.format_string($this->assignment->name, true, array('context' => $this->context)).'</a></font></p>';
2102 $posthtml .= '<hr /><font face="sans-serif">';
2103 $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
2104 $posthtml .= '</font><hr />';
2109 * Produces a list of links to the files uploaded by a user
2111 * @param $userid int optional id of the user. If 0 then $USER->id is used.
2112 * @param $return boolean optional defaults to false. If true the list is returned rather than printed
2113 * @return string optional
2115 function print_user_files($userid=0, $return=false) {
2116 global $CFG, $USER, $OUTPUT;
2119 if (!isloggedin()) {
2122 $userid = $USER->id;
2127 $submission = $this->get_submission($userid);
2132 $fs = get_file_storage();
2133 $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false);
2134 if (!empty($files)) {
2135 require_once($CFG->dirroot . '/mod/assignment/locallib.php');
2136 if ($CFG->enableportfolios) {
2137 require_once($CFG->libdir.'/portfoliolib.php');
2138 $button = new portfolio_add_button();
2140 foreach ($files as $file) {
2141 $filename = $file->get_filename();
2142 $mimetype = $file->get_mimetype();
2143 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/mod_assignment/submission/'.$submission->id.'/'.$filename);
2144 $output .= '<a href="'.$path.'" >'.$OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon')).s($filename).'</a>';
2145 if ($CFG->enableportfolios && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
2146 $button->set_callback_options('assignment_portfolio_caller',
2147 array('id' => $this->cm->id, 'submissionid' => $submission->id, 'fileid' => $file->get_id()),
2149 $button->set_format_by_file($file);
2150 $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
2153 if ($CFG->enableplagiarism) {
2154 require_once($CFG->libdir.'/plagiarismlib.php');
2155 $output .= plagiarism_get_links(array('userid'=>$userid, 'file'=>$file, 'cmid'=>$this->cm->id, 'course'=>$this->course, 'assignment'=>$this->assignment));
2156 $output .= '<br />';
2159 if ($CFG->enableportfolios && count($files) > 1 && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
2160 $button->set_callback_options('assignment_portfolio_caller',
2161 array('id' => $this->cm->id, 'submissionid' => $submission->id),
2163 $output .= '<br />' . $button->to_html(PORTFOLIO_ADD_TEXT_LINK);
2167 $output = '<div class="files">'.$output.'</div>';
2176 * Count the files uploaded by a given user
2178 * @param $itemid int The submission's id as the file's itemid.
2181 function count_user_files($itemid) {
2182 $fs = get_file_storage();
2183 $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $itemid, "id", false);
2184 return count($files);
2188 * Returns true if the student is allowed to submit
2190 * Checks that the assignment has started and, if the option to prevent late
2191 * submissions is set, also checks that the assignment has not yet closed.
2196 if ($this->assignment->preventlate && $this->assignment->timedue) {
2197 return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
2199 return ($this->assignment->timeavailable <= $time);
2205 * Return true if is set description is hidden till available date
2207 * This is needed by calendar so that hidden descriptions do not
2208 * come up in upcoming events.
2210 * Check that description is hidden till available date
2211 * By default return false
2212 * Assignments types should implement this method if needed
2215 function description_is_hidden() {
2220 * Return an outline of the user's interaction with the assignment
2222 * The default method prints the grade and timemodified
2223 * @param $grade object
2224 * @return object with properties ->info and ->time
2226 function user_outline($grade) {
2228 $result = new stdClass();
2229 $result->info = get_string('grade').': '.$grade->str_long_grade;
2230 $result->time = $grade->dategraded;
2235 * Print complete information about the user's interaction with the assignment
2237 * @param $user object
2239 function user_complete($user, $grade=null) {
2242 if ($submission = $this->get_submission($user->id)) {
2244 $fs = get_file_storage();
2246 if ($files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false)) {
2247 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
2248 foreach ($files as $file) {
2249 $countfiles .= "; ".$file->get_filename();
2253 echo $OUTPUT->box_start();
2254 echo get_string("lastmodified").": ";
2255 echo userdate($submission->timemodified);
2256 echo $this->display_lateness($submission->timemodified);
2258 $this->print_user_files($user->id);
2262 $this->view_feedback($submission);
2264 echo $OUTPUT->box_end();
2268 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
2269 if ($grade->str_feedback) {
2270 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
2273 print_string("notsubmittedyet", "assignment");
2278 * Return a string indicating how late a submission is
2280 * @param $timesubmitted int
2283 function display_lateness($timesubmitted) {
2284 return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
2288 * Empty method stub for all delete actions.
2291 //nothing by default
2292 redirect('view.php?id='.$this->cm->id);
2296 * Empty custom feedback grading form.
2298 function custom_feedbackform($submission, $return=false) {
2299 //nothing by default
2304 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
2305 * for the course (see resource).
2307 * Given a course_module object, this function returns any "extra" information that may be needed
2308 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
2310 * @param $coursemodule object The coursemodule object (record).
2311 * @return cached_cm_info Object used to customise appearance on course page
2313 function get_coursemodule_info($coursemodule) {
2318 * Plugin cron method - do not use $this here, create new assignment instances if needed.
2322 //no plugin cron by default - override if needed
2326 * Reset all submissions
2328 function reset_userdata($data) {
2331 if (!$DB->count_records('assignment', array('course'=>$data->courseid, 'assignmenttype'=>$this->type))) {
2332 return array(); // no assignments of this type present
2335 $componentstr = get_string('modulenameplural', 'assignment');
2338 $typestr = get_string('type'.$this->type, 'assignment');
2339 // ugly hack to support pluggable assignment type titles...
2340 if($typestr === '[[type'.$this->type.']]'){
2341 $typestr = get_string('type'.$this->type, 'assignment_'.$this->type);
2344 if (!empty($data->reset_assignment_submissions)) {
2345 $assignmentssql = "SELECT a.id
2347 WHERE a.course=? AND a.assignmenttype=?";
2348 $params = array($data->courseid, $this->type);
2350 // now get rid of all submissions and responses
2351 $fs = get_file_storage();
2352 if ($assignments = $DB->get_records_sql($assignmentssql, $params)) {
2353 foreach ($assignments as $assignmentid=>$unused) {
2354 if (!$cm = get_coursemodule_from_instance('assignment', $assignmentid)) {
2357 $context = context_module::instance($cm->id);
2358 $fs->delete_area_files($context->id, 'mod_assignment', 'submission');
2359 $fs->delete_area_files($context->id, 'mod_assignment', 'response');
2363 $DB->delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)", $params);
2365 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
2367 if (empty($data->reset_gradebook_grades)) {
2368 // remove all grades from gradebook
2369 assignment_reset_gradebook($data->courseid, $this->type);
2373 /// updating dates - shift may be negative too
2374 if ($data->timeshift) {
2375 shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
2376 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
2383 function portfolio_exportable() {
2388 * base implementation for backing up subtype specific information
2389 * for one single module
2391 * @param filehandle $bf file handle for xml file to write to
2392 * @param mixed $preferences the complete backup preference object
2398 static function backup_one_mod($bf, $preferences, $assignment) {
2403 * base implementation for backing up subtype specific information
2404 * for one single submission
2406 * @param filehandle $bf file handle for xml file to write to
2407 * @param mixed $preferences the complete backup preference object
2408 * @param object $submission the assignment submission db record
2414 static function backup_one_submission($bf, $preferences, $assignment, $submission) {
2419 * base implementation for restoring subtype specific information
2420 * for one single module
2422 * @param array $info the array representing the xml
2423 * @param object $restore the restore preferences
2429 static function restore_one_mod($info, $restore, $assignment) {
2434 * base implementation for restoring subtype specific information
2435 * for one single submission
2437 * @param object $submission the newly created submission
2438 * @param array $info the array representing the xml
2439 * @param object $restore the restore preferences
2445 static function restore_one_submission($info, $restore, $assignment, $submission) {
2449 } ////// End of the assignment_base class
2452 class assignment_grading_form extends moodleform {
2453 /** @var stores the advaned grading instance (if used in grading) */
2454 private $advancegradinginstance;
2456 function definition() {
2458 $mform =& $this->_form;
2460 if (isset($this->_customdata->advancedgradinginstance)) {
2461 $this->use_advanced_grading($this->_customdata->advancedgradinginstance);
2464 $formattr = $mform->getAttributes();
2465 $formattr['id'] = 'submitform';
2466 $mform->setAttributes($formattr);
2468 $mform->addElement('hidden', 'offset', ($this->_customdata->offset+1));
2469 $mform->setType('offset', PARAM_INT);
2470 $mform->addElement('hidden', 'userid', $this->_customdata->userid);
2471 $mform->setType('userid', PARAM_INT);
2472 $mform->addElement('hidden', 'nextid', $this->_customdata->nextid);
2473 $mform->setType('nextid', PARAM_INT);
2474 $mform->addElement('hidden', 'id', $this->_customdata->cm->id);
2475 $mform->setType('id', PARAM_INT);
2476 $mform->addElement('hidden', 'sesskey', sesskey());
2477 $mform->setType('sesskey', PARAM_ALPHANUM);
2478 $mform->addElement('hidden', 'mode', 'grade');
2479 $mform->setType('mode', PARAM_TEXT);
2480 $mform->addElement('hidden', 'menuindex', "0");
2481 $mform->setType('menuindex', PARAM_INT);
2482 $mform->addElement('hidden', 'saveuserid', "-1");
2483 $mform->setType('saveuserid', PARAM_INT);
2484 $mform->addElement('hidden', 'filter', "0");
2485 $mform->setType('filter', PARAM_INT);
2487 $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->user),
2488 fullname($this->_customdata->user, true) . '<br/>' .
2489 userdate($this->_customdata->submission->timemodified) .
2490 $this->_customdata->lateness );
2492 $this->add_submission_content();
2493 $this->add_grades_section();
2495 $this->add_feedback_section();
2497 if ($this->_customdata->submission->timemarked) {
2498 $datestring = userdate($this->_customdata->submission->timemarked)." (".format_time(time() - $this->_customdata->submission->timemarked).")";
2499 $mform->addElement('header', 'Last Grade', get_string('lastgrade', 'assignment'));
2500 $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->teacher) ,
2501 fullname($this->_customdata->teacher,true).
2502 '<br/>'.$datestring);
2505 $this->add_action_buttons();
2510 * Gets or sets the instance for advanced grading
2512 * @param gradingform_instance $gradinginstance
2514 public function use_advanced_grading($gradinginstance = false) {
2515 if ($gradinginstance !== false) {
2516 $this->advancegradinginstance = $gradinginstance;
2518 return $this->advancegradinginstance;
2522 * Add the grades configuration section to the assignment configuration form
2524 function add_grades_section() {
2526 $mform =& $this->_form;
2527 $attributes = array();
2528 if ($this->_customdata->gradingdisabled) {
2529 $attributes['disabled'] ='disabled';
2532 $mform->addElement('header', 'Grades', get_string('grades', 'grades'));
2534 $grademenu = make_grades_menu($this->_customdata->assignment->grade);
2535 if ($gradinginstance = $this->use_advanced_grading()) {
2536 $gradinginstance->get_controller()->set_grade_range($grademenu);
2537 $gradingelement = $mform->addElement('grading', 'advancedgrading', get_string('grade').':', array('gradinginstance' => $gradinginstance));
2538 if ($this->_customdata->gradingdisabled) {
2539 $gradingelement->freeze();
2541 $mform->addElement('hidden', 'advancedgradinginstanceid', $gradinginstance->get_id());
2544 // use simple direct grading
2545 $grademenu['-1'] = get_string('nograde');
2547 $mform->addElement('select', 'xgrade', get_string('grade').':', $grademenu, $attributes);
2548 $mform->setDefault('xgrade', $this->_customdata->submission->grade ); //@fixme some bug when element called 'grade' makes it break
2549 $mform->setType('xgrade', PARAM_INT);
2552 if (!empty($this->_customdata->enableoutcomes)) {
2553 foreach($this->_customdata->grading_info->outcomes as $n=>$outcome) {
2554 $options = make_grades_menu(-$outcome->scaleid);
2555 if ($outcome->grades[$this->_customdata->submission->userid]->locked) {
2556 $options[0] = get_string('nooutcome', 'grades');
2557 $mform->addElement('static', 'outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->name.':',
2558 $options[$outcome->grades[$this->_customdata->submission->userid]->grade]);
2560 $options[''] = get_string('nooutcome', 'grades');
2561 $attributes = array('id' => 'menuoutcome_'.$n );
2562 $mform->addElement('select', 'outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->name.':', $options, $attributes );
2563 $mform->setType('outcome_'.$n.'['.$this->_customdata->userid.']', PARAM_INT);
2564 $mform->setDefault('outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->grades[$this->_customdata->submission->userid]->grade );
2568 $course_context = context_module::instance($this->_customdata->cm->id);
2569 if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
2570 $grade = '<a href="'.$CFG->wwwroot.'/grade/report/grader/index.php?id='. $this->_customdata->courseid .'" >'.
2571 $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade . '</a>';
2573 $grade = $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade;
2575 $mform->addElement('static', 'finalgrade', get_string('currentgrade', 'assignment').':' ,$grade);
2576 $mform->setType('finalgrade', PARAM_INT);
2581 * @global core_renderer $OUTPUT
2583 function add_feedback_section() {
2585 $mform =& $this->_form;
2586 $mform->addElement('header', 'Feed Back', get_string('feedback', 'grades'));
2588 if ($this->_customdata->gradingdisabled) {
2589 $mform->addElement('static', 'disabledfeedback', $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_feedback );
2593 $mform->addElement('editor', 'submissioncomment_editor', get_string('feedback', 'assignment').':', null, $this->get_editor_options() );
2594 $mform->setType('submissioncomment_editor', PARAM_RAW); // to be cleaned before display
2595 $mform->setDefault('submissioncomment_editor', $this->_customdata->submission->submissioncomment);
2596 //$mform->addRule('submissioncomment', get_string('required'), 'required', null, 'client');
2597 switch ($this->_customdata->assignment->assignmenttype) {
2599 case 'uploadsingle' :
2600 $mform->addElement('filemanager', 'files_filemanager', get_string('responsefiles', 'assignment'). ':', null, $this->_customdata->fileui_options);
2605 $mform->addElement('hidden', 'mailinfo_h', "0");
2606 $mform->setType('mailinfo_h', PARAM_INT);
2607 $mform->addElement('checkbox', 'mailinfo',get_string('enablenotification','assignment').
2608 $OUTPUT->help_icon('enablenotification', 'assignment') .':' );
2609 $mform->setType('mailinfo', PARAM_INT);
2613 function add_action_buttons($cancel = true, $submitlabel = NULL) {
2614 $mform =& $this->_form;
2615 //if there are more to be graded.
2616 if ($this->_customdata->nextid>0) {
2617 $buttonarray=array();
2618 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2619 //@todo: fix accessibility: javascript dependency not necessary
2620 $buttonarray[] = &$mform->createElement('submit', 'saveandnext', get_string('saveandnext'));
2621 $buttonarray[] = &$mform->createElement('submit', 'next', get_string('next'));
2622 $buttonarray[] = &$mform->createElement('cancel');
2624 $buttonarray=array();
2625 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2626 $buttonarray[] = &$mform->createElement('cancel');
2628 $mform->addGroup($buttonarray, 'grading_buttonar', '', array(' '), false);
2629 $mform->closeHeaderBefore('grading_buttonar');
2630 $mform->setType('grading_buttonar', PARAM_RAW);
2633 function add_submission_content() {
2634 $mform =& $this->_form;
2635 $mform->addElement('header', 'Submission', get_string('submission', 'assignment'));
2636 $mform->addElement('static', '', '' , $this->_customdata->submission_content );
2639 protected function get_editor_options() {
2640 $editoroptions = array();
2641 $editoroptions['component'] = 'mod_assignment';
2642 $editoroptions['filearea'] = 'feedback';
2643 $editoroptions['noclean'] = false;
2644 $editoroptions['maxfiles'] = 0; //TODO: no files for now, we need to first implement assignment_feedback area, integration with gradebook, files support in quickgrading, etc. (skodak)
2645 $editoroptions['maxbytes'] = $this->_customdata->maxbytes;
2646 $editoroptions['context'] = $this->_customdata->context;
2647 return $editoroptions;
2650 public function set_data($data) {
2651 $editoroptions = $this->get_editor_options();
2652 if (!isset($data->text)) {
2655 if (!isset($data->format)) {
2656 $data->textformat = FORMAT_HTML;
2658 $data->textformat = $data->format;
2661 if (!empty($this->_customdata->submission->id)) {
2662 $itemid = $this->_customdata->submission->id;
2667 switch ($this->_customdata->assignment->assignmenttype) {
2669 case 'uploadsingle' :
2670 $data = file_prepare_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2676 $data = file_prepare_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2677 return parent::set_data($data);
2680 public function get_data() {
2681 $data = parent::get_data();
2683 if (!empty($this->_customdata->submission->id)) {
2684 $itemid = $this->_customdata->submission->id;
2686 $itemid = null; //TODO: this is wrong, itemid MUST be known when saving files!! (skodak)
2690 $editoroptions = $this->get_editor_options();
2691 switch ($this->_customdata->assignment->assignmenttype) {
2693 case 'uploadsingle' :
2694 $data = file_postupdate_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2699 $data = file_postupdate_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2702 if ($this->use_advanced_grading() && !isset($data->advancedgrading)) {
2703 $data->advancedgrading = null;
2710 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
2713 * Deletes an assignment instance
2715 * This is done by calling the delete_instance() method of the assignment type class
2717 function assignment_delete_instance($id){
2720 if (! $assignment = $DB->get_record('assignment', array('id'=>$id))) {
2724 // fall back to base class if plugin missing
2725 $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2726 if (file_exists($classfile)) {
2727 require_once($classfile);
2728 $assignmentclass = "assignment_$assignment->assignmenttype";
2731 debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
2732 $assignmentclass = "assignment_base";
2735 $ass = new $assignmentclass();
2736 return $ass->delete_instance($assignment);
2741 * Updates an assignment instance
2743 * This is done by calling the update_instance() method of the assignment type class
2745 function assignment_update_instance($assignment){
2748 $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_PLUGIN);
2750 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2751 $assignmentclass = "assignment_$assignment->assignmenttype";
2752 $ass = new $assignmentclass();
2753 return $ass->update_instance($assignment);
2758 * Adds an assignment instance
2760 * This is done by calling the add_instance() method of the assignment type class
2762 * @param stdClass $assignment
2763 * @param mod_assignment_mod_form $mform
2764 * @return int intance id
2766 function assignment_add_instance($assignment, $mform = null) {
2769 $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_PLUGIN);
2771 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2772 $assignmentclass = "assignment_$assignment->assignmenttype";
2773 $ass = new $assignmentclass();
2774 return $ass->add_instance($assignment);
2779 * Returns an outline of a user interaction with an assignment
2781 * This is done by calling the user_outline() method of the assignment type class
2783 function assignment_user_outline($course, $user, $mod, $assignment) {
2786 require_once("$CFG->libdir/gradelib.php");
2787 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2788 $assignmentclass = "assignment_$assignment->assignmenttype";
2789 $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2790 $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2791 if (!empty($grades->items[0]->grades)) {
2792 return $ass->user_outline(reset($grades->items[0]->grades));
2799 * Prints the complete info about a user's interaction with an assignment
2801 * This is done by calling the user_complete() method of the assignment type class
2803 function assignment_user_complete($course, $user, $mod, $assignment) {
2806 require_once("$CFG->libdir/gradelib.php");
2807 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2808 $assignmentclass = "assignment_$assignment->assignmenttype";
2809 $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2810 $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2811 if (empty($grades->items[0]->grades)) {
2814 $grade = reset($grades->items[0]->grades);
2816 return $ass->user_complete($user, $grade);
2820 * Function to be run periodically according to the moodle cron
2822 * Finds all assignment notifications that have yet to be mailed out, and mails them
2824 function assignment_cron () {
2825 global $CFG, $USER, $DB;
2827 /// first execute all crons in plugins
2828 if ($plugins = get_plugin_list('assignment')) {
2829 foreach ($plugins as $plugin=>$dir) {
2830 require_once("$dir/assignment.class.php");
2831 $assignmentclass = "assignment_$plugin";
2832 $ass = new $assignmentclass();
2837 /// Notices older than 1 day will not be mailed. This is to avoid the problem where
2838 /// cron has not been running for a long time, and then suddenly people are flooded
2839 /// with mail from the past few weeks or months
2842 $endtime = $timenow - $CFG->maxeditingtime;
2843 $starttime = $endtime - 24 * 3600; /// One day earlier
2845 if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2847 $realuser = clone($USER);
2849 foreach ($submissions as $key => $submission) {
2850 $DB->set_field("assignment_submissions", "mailed", "1", array("id"=>$submission->id));
2855 foreach ($submissions as $submission) {
2857 echo "Processing assignment submission $submission->id\n";
2859 if (! $user = $DB->get_record("user", array("id"=>$submission->userid))) {
2860 echo "Could not find user $user->id\n";
2864 if (! $course = $DB->get_record("course", array("id"=>$submission->course))) {
2865 echo "Could not find course $submission->course\n";
2869 /// Override the language and timezone of the "current" user, so that
2870 /// mail is customised for the receiver.
2871 cron_setup_user($user, $course);
2873 $coursecontext = context_course::instance($submission->course);
2874 $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
2875 if (!is_enrolled($coursecontext, $user->id)) {
2876 echo fullname($user)." not an active participant in " . $courseshortname . "\n";
2880 if (! $teacher = $DB->get_record("user", array("id"=>$submission->teacher))) {
2881 echo "Could not find teacher $submission->teacher\n";
2885 if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2886 echo "Could not find course module for assignment id $submission->assignment\n";
2890 if (! $mod->visible) { /// Hold mail notification for hidden assignments until later
2894 $strassignments = get_string("modulenameplural", "assignment");
2895 $strassignment = get_string("modulename", "assignment");
2897 $assignmentinfo = new stdClass();
2898 $assignmentinfo->teacher = fullname($teacher);
2899 $assignmentinfo->assignment = format_string($submission->name,true);
2900 $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2902 $postsubject = "$courseshortname: $strassignments: ".format_string($submission->name,true);
2903 $posttext = "$courseshortname -> $strassignments -> ".format_string($submission->name,true)."\n";
2904 $posttext .= "---------------------------------------------------------------------\n";
2905 $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2906 $posttext .= "---------------------------------------------------------------------\n";
2908 if ($user->mailformat == 1) { // HTML
2909 $posthtml = "<p><font face=\"sans-serif\">".
2910 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$courseshortname</a> ->".
2911 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2912 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2913 $posthtml .= "<hr /><font face=\"sans-serif\">";
2914 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2915 $posthtml .= "</font><hr />";
2920 $eventdata = new stdClass();
2921 $eventdata->modulename = 'assignment';
2922 $eventdata->userfrom = $teacher;
2923 $eventdata->userto = $user;
2924 $eventdata->subject = $postsubject;
2925 $eventdata->fullmessage = $posttext;
2926 $eventdata->fullmessageformat = FORMAT_PLAIN;
2927 $eventdata->fullmessagehtml = $posthtml;
2928 $eventdata->smallmessage = get_string('assignmentmailsmall', 'assignment', $assignmentinfo);
2930 $eventdata->name = 'assignment_updates';
2931 $eventdata->component = 'mod_assignment';
2932 $eventdata->notification = 1;
2933 $eventdata->contexturl = $assignmentinfo->url;
2934 $eventdata->contexturlname = $assignmentinfo->assignment;
2936 message_send($eventdata);
2946 * Return grade for given user or all users.
2948 * @param stdClass $assignment An assignment instance
2949 * @param int $userid Optional user id, 0 means all users
2950 * @return array An array of grades, false if none
2952 function assignment_get_user_grades($assignment, $userid=0) {
2956 $user = "AND u.id = :userid";
2957 $params = array('userid'=>$userid);
2961 $params['aid'] = $assignment->id;
2963 $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2964 s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2965 FROM {user} u, {assignment_submissions} s
2966 WHERE u.id = s.userid AND s.assignment = :aid
2969 return $DB->get_records_sql($sql, $params);
2973 * Update activity grades
2976 * @param stdClass $assignment Assignment instance
2977 * @param int $userid specific user only, 0 means all
2978 * @param bool $nullifnone Not used
2980 function assignment_update_grades($assignment, $userid=0, $nullifnone=true) {
2982 require_once($CFG->libdir.'/gradelib.php');
2984 if ($assignment->grade == 0) {
2985 assignment_grade_item_update($assignment);
2987 } else if ($grades = assignment_get_user_grades($assignment, $userid)) {
2988 foreach($grades as $k=>$v) {
2989 if ($v->rawgrade == -1) {
2990 $grades[$k]->rawgrade = null;
2993 assignment_grade_item_update($assignment, $grades);
2996 assignment_grade_item_update($assignment);
3001 * Update all grades in gradebook.
3003 function assignment_upgrade_grades() {
3006 $sql = "SELECT COUNT('x')
3007 FROM {assignment} a, {course_modules} cm, {modules} m
3008 WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
3009 $count = $DB->count_records_sql($sql);
3011 $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
3012 FROM {assignment} a, {course_modules} cm, {modules} m
3013 WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
3014 $rs = $DB->get_recordset_sql($sql);
3016 // too much debug output
3017 $pbar = new progress_bar('assignmentupgradegrades', 500, true);
3019 foreach ($rs as $assignment) {
3021 upgrade_set_timeout(60*5); // set up timeout, may also abort execution
3022 assignment_update_grades($assignment);
3023 $pbar->update($i, $count, "Updating Assignment grades ($i/$count).");
3025 upgrade_set_timeout(); // reset to default timeout
3031 * Create grade item for given assignment
3034 * @param stdClass $assignment An assignment instance with extra cmidnumber property
3035 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
3036 * @return int 0 if ok, error code otherwise
3038 function assignment_grade_item_update($assignment, $grades=NULL) {
3040 require_once($CFG->libdir.'/gradelib.php');
3042 if (!isset($assignment->courseid)) {
3043 $assignment->courseid = $assignment->course;
3046 $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
3048 if ($assignment->grade > 0) {
3049 $params['gradetype'] = GRADE_TYPE_VALUE;
3050 $params['grademax'] = $assignment->grade;
3051 $params['grademin'] = 0;
3053 } else if ($assignment->grade < 0) {
3054 $params['gradetype'] = GRADE_TYPE_SCALE;
3055 $params['scaleid'] = -$assignment->grade;
3058 $params['gradetype'] = GRADE_TYPE_TEXT; // allow text comments only
3061 if ($grades === 'reset') {
3062 $params['reset'] = true;
3066 return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades, $params);
3070 * Delete grade item for given assignment
3073 * @param object $assignment object
3074 * @return object assignment
3076 function assignment_grade_item_delete($assignment) {
3078 require_once($CFG->libdir.'/gradelib.php');
3080 if (!isset($assignment->courseid)) {
3081 $assignment->courseid = $assignment->course;
3084 return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
3089 * Serves assignment submissions and other files.
3091 * @package mod_assignment
3093 * @param stdClass $course course object
3094 * @param stdClass $cm course module object
3095 * @param stdClass $context context object
3096 * @param string $filearea file area
3097 * @param array $args extra arguments
3098 * @param bool $forcedownload whether or not force download
3099 * @param array $options additional options affecting the file serving
3100 * @return bool false if file not found, does not return if found - just send the file
3102 function assignment_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
3105 if ($context->contextlevel != CONTEXT_MODULE) {
3109 require_login($course, false, $cm);
3111 if (!$assignment = $DB->get_record('assignment', array('id'=>$cm->instance))) {
3115 require_once($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
3116 $assignmentclass = 'assignment_'.$assignment->assignmenttype;
3117 $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm, $course);
3119 return $assignmentinstance->send_file($filearea, $args, $forcedownload, $options);
3122 * Checks if a scale is being used by an assignment
3124 * This is used by the backup code to decide whether to back up a scale
3125 * @param $assignmentid int
3126 * @param $scaleid int
3127 * @return boolean True if the scale is used by the assignment
3129 function assignment_scale_used($assignmentid, $scaleid) {
3134 $rec = $DB->get_record('assignment', array('id'=>$assignmentid,'grade'=>-$scaleid));
3136 if (!empty($rec) && !empty($scaleid)) {
3144 * Checks if scale is being used by any instance of assignment
3146 * This is used to find out if scale used anywhere
3147 * @param $scaleid int
3148 * @return boolean True if the scale is used by any assignment
3150 function assignment_scale_used_anywhere($scaleid) {
3153 if ($scaleid and $DB->record_exists('assignment', array('grade'=>-$scaleid))) {
3161 * Make sure up-to-date events are created for all assignment instances
3163 * This standard function will check all instances of this module
3164 * and make sure there are up-to-date events created for each of them.
3165 * If courseid = 0, then every assignment event in the site is checked, else
3166 * only assignment events belonging to the course specified are checked.
3167 * This function is used, in its new format, by restore_refresh_events()
3169 * @param $courseid int optional If zero then all assignments for all courses are covered
3170 * @return boolean Always returns true
3172 function assignment_refresh_events($courseid = 0) {
3174 require_once($CFG->dirroot.'/calendar/lib.php');
3176 if ($courseid == 0) {
3177 if (! $assignments = $DB->get_records("assignment")) {
3181 if (! $assignments = $DB->get_records("assignment", array("course"=>$courseid))) {
3185 $moduleid = $DB->get_field('modules', 'id', array('name'=>'assignment'));
3187 foreach ($assignments as $assignment) {
3188 $cm = get_coursemodule_from_instance('assignment', $assignment->id, $courseid, false, MUST_EXIST);
3189 $event = new stdClass();
3190 $event->name = $assignment->name;
3191 $event->description = format_module_intro('assignment', $assignment, $cm->id);
3192 $event->timestart = $assignment->timedue;
3194 if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
3195 $calendarevent = calendar_event::load($event->id);
3196 $calendarevent->update($event);
3198 $event->courseid = $assignment->course;
3199 $event->groupid = 0;
3201 $event->modulename = 'assignment';
3202 $event->instance = $assignment->id;
3203 $event->eventtype = 'due';
3204 $event->timeduration = 0;
3205 $event->visible = $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$assignment->id));
3206 calendar_event::create($event);
3214 * Print recent activity from all assignments in a given course
3216 * This is used by the recent activity block
3218 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
3219 global $CFG, $USER, $DB, $OUTPUT;
3221 // do not use log table if possible, it may be huge
3223 if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
3224 u.firstname, u.lastname, u.email, u.picture
3225 FROM {assignment_submissions} asb
3226 JOIN {assignment} a ON a.id = asb.assignment
3227 JOIN {course_modules} cm ON cm.instance = a.id
3228 JOIN {modules} md ON md.id = cm.module
3229 JOIN {user} u ON u.id = asb.userid
3230 WHERE asb.timemodified > ? AND
3232 md.name = 'assignment'
3233 ORDER BY asb.timemodified ASC", array($timestart, $course->id))) {
3237 $modinfo = get_fast_modinfo($course); // reference needed because we might load the groups
3241 foreach($submissions as $submission) {
3242 if (!array_key_exists($submission->cmid, $modinfo->cms)) {
3245 $cm = $modinfo->cms[$submission->cmid];
3246 if (!$cm->uservisible) {
3249 if ($submission->userid == $USER->id) {
3250 $show[] = $submission;
3254 // the act of sumbitting of assignment may be considered private - only graders will see it if specified
3255 if (empty($CFG->assignment_showrecentsubmissions)) {
3256 if (!array_key_exists($cm->id, $grader)) {
3257 $grader[$cm->id] = has_capability('moodle/grade:viewall', context_module::instance($cm->id));
3259 if (!$grader[$cm->id]) {
3264 $groupmode = groups_get_activity_groupmode($cm, $course);
3266 if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', context_module::instance($cm->id))) {
3267 if (isguestuser()) {
3268 // shortcut - guest user does not belong into any group
3272 if (is_null($modinfo->groups)) {
3273 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
3276 // this will be slow - show only users that share group with me in this cm
3277 if (empty($modinfo->groups[$cm->id])) {
3280 $usersgroups = groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
3281 if (is_array($usersgroups)) {
3282 $usersgroups = array_keys($usersgroups);
3283 $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
3284 if (empty($intersect)) {
3289 $show[] = $submission;
3296 echo $OUTPUT->heading(get_string('newsubmissions', 'assignment').':', 3);
3298 foreach ($show as $submission) {
3299 $cm = $modinfo->cms[$submission->cmid];
3300 $link = $CFG->wwwroot.'/mod/assignment/view.php?id='.$cm->id;
3301 print_recent_activity_note($submission->timemodified, $submission, $cm->name, $link, false, $viewfullnames);
3309 * Returns all assignments since a given time in specified forum.
3311 function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0) {
3312 global $CFG, $COURSE, $USER, $DB;