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 portfoliolib.php */
33 require_once($CFG->libdir.'/portfoliolib.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 {
68 * @todo document this var
72 * @todo document this var
79 * Constructor for the base assignment class
81 * Constructor for the base assignment class.
82 * If cmid is set create the cm, course, assignment objects.
83 * If the assignment is hidden and the user is not a teacher then
84 * this prints a page header and notice.
88 * @param int $cmid the current course module id - not set for new assignments
89 * @param object $assignment usually null, but if we have it we pass it to save db access
90 * @param object $cm usually null, but if we have it we pass it to save db access
91 * @param object $course usually null, but if we have it we pass it to save db access
93 function assignment_base($cmid='staticonly', $assignment=NULL, $cm=NULL, $course=NULL) {
96 if ($cmid == 'staticonly') {
97 //use static functions only!
105 } else if (! $this->cm = get_coursemodule_from_id('assignment', $cmid)) {
106 print_error('invalidcoursemodule');
109 $this->context = get_context_instance(CONTEXT_MODULE, $this->cm->id);
112 $this->course = $course;
113 } else if ($this->cm->course == $COURSE->id) {
114 $this->course = $COURSE;
115 } else if (! $this->course = $DB->get_record('course', array('id'=>$this->cm->course))) {
116 print_error('invalidid', 'assignment');
120 $this->assignment = $assignment;
121 } else if (! $this->assignment = $DB->get_record('assignment', array('id'=>$this->cm->instance))) {
122 print_error('invalidid', 'assignment');
125 $this->assignment->cmidnumber = $this->cm->id; // compatibility with modedit assignment obj
126 $this->assignment->courseid = $this->course->id; // compatibility with modedit assignment obj
128 $this->strassignment = get_string('modulename', 'assignment');
129 $this->strassignments = get_string('modulenameplural', 'assignment');
130 $this->strsubmissions = get_string('submissions', 'assignment');
131 $this->strlastmodified = get_string('lastmodified');
132 $this->pagetitle = strip_tags($this->course->shortname.': '.$this->strassignment.': '.format_string($this->assignment->name,true));
134 // visibility handled by require_login() with $cm parameter
135 // get current group only when really needed
137 /// Set up things for a HTML editor if it's needed
138 if ($this->usehtmleditor = can_use_html_editor()) {
139 $this->defaultformat = FORMAT_HTML;
141 $this->defaultformat = FORMAT_MOODLE;
146 * Display the assignment, used by view.php
148 * This in turn calls the methods producing individual parts of the page
152 $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
153 require_capability('mod/assignment:view', $context);
155 add_to_log($this->course->id, "assignment", "view", "view.php?id={$this->cm->id}",
156 $this->assignment->id, $this->cm->id);
158 $this->view_header();
164 $this->view_feedback();
166 $this->view_footer();
170 * Display the header and top of a page
172 * (this doesn't change much for assignment types)
173 * This is used by the view() method to print the header of view.php but
174 * it can be used on other pages in which case the string to denote the
175 * page in the navigation trail should be passed as an argument
178 * @param string $subpage Description of subpage to be used in navigation trail
180 function view_header($subpage='') {
186 $navigation = build_navigation($subpage, $this->cm);
188 $navigation = build_navigation('', $this->cm);
191 print_header($this->pagetitle, $this->course->fullname, $navigation, '', '',
192 true, update_module_button($this->cm->id, $this->course->id, $this->strassignment),
193 navmenu($this->course, $this->cm));
195 groups_print_activity_menu($this->cm, 'view.php?id=' . $this->cm->id);
197 echo '<div class="reportlink">'.$this->submittedlink().'</div>';
198 echo '<div class="clearer"></div>';
203 * Display the assignment intro
205 * This will most likely be extended by assignment type plug-ins
206 * The default implementation prints the assignment description in a box
208 function view_intro() {
209 print_simple_box_start('center', '', '', 0, 'generalbox', 'intro');
210 echo format_module_intro('assignment', $this->assignment, $this->cm->id);
211 print_simple_box_end();
215 * Display the assignment dates
217 * Prints the assignment start and end dates in a box.
218 * This will be suitable for most assignment types
220 function view_dates() {
221 if (!$this->assignment->timeavailable && !$this->assignment->timedue) {
225 print_simple_box_start('center', '', '', 0, 'generalbox', 'dates');
227 if ($this->assignment->timeavailable) {
228 echo '<tr><td class="c0">'.get_string('availabledate','assignment').':</td>';
229 echo ' <td class="c1">'.userdate($this->assignment->timeavailable).'</td></tr>';
231 if ($this->assignment->timedue) {
232 echo '<tr><td class="c0">'.get_string('duedate','assignment').':</td>';
233 echo ' <td class="c1">'.userdate($this->assignment->timedue).'</td></tr>';
236 print_simple_box_end();
241 * Display the bottom and footer of a page
243 * This default method just prints the footer.
244 * This will be suitable for most assignment types
246 function view_footer() {
247 print_footer($this->course);
251 * Display the feedback to the student
253 * This default method prints the teacher picture and name, date when marked,
254 * grade and teacher submissioncomment.
259 * @param object $submission The submission object or NULL in which case it will be loaded
261 function view_feedback($submission=NULL) {
262 global $USER, $CFG, $DB;
263 require_once($CFG->libdir.'/gradelib.php');
265 if (!has_capability('mod/assignment:submit', $this->context, $USER->id, false)) {
266 // can not submit assignments -> no feedback
270 if (!$submission) { /// Get submission for this assignment
271 $submission = $this->get_submission($USER->id);
274 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $USER->id);
275 $item = $grading_info->items[0];
276 $grade = $item->grades[$USER->id];
278 if ($grade->hidden or $grade->grade === false) { // hidden or error
282 if ($grade->grade === null and empty($grade->str_feedback)) { /// Nothing to show yet
286 $graded_date = $grade->dategraded;
287 $graded_by = $grade->usermodified;
289 /// We need the teacher info
290 if (!$teacher = $DB->get_record('user', array('id'=>$graded_by))) {
291 print_error('cannotfindteacher');
294 /// Print the feedback
295 print_heading(get_string('feedbackfromteacher', 'assignment', fullname($teacher)));
297 echo '<table cellspacing="0" class="feedback">';
300 echo '<td class="left picture">';
302 print_user_picture($teacher, $this->course->id, $teacher->picture);
305 echo '<td class="topic">';
306 echo '<div class="from">';
308 echo '<div class="fullname">'.fullname($teacher).'</div>';
310 echo '<div class="time">'.userdate($graded_date).'</div>';
316 echo '<td class="left side"> </td>';
317 echo '<td class="content">';
318 echo '<div class="grade">';
319 echo get_string("grade").': '.$grade->str_long_grade;
321 echo '<div class="clearer"></div>';
323 echo '<div class="comment">';
324 echo $grade->str_feedback;
332 * Returns a link with info about the state of the assignment submissions
334 * This is used by view_header to put this link at the top right of the page.
335 * For teachers it gives the number of submitted assignments with a link
336 * For students it gives the time of their submission.
337 * This will be suitable for most assignment types.
341 * @param bool $allgroup print all groups info if user can access all groups, suitable for index.php
344 function submittedlink($allgroups=false) {
349 $urlbase = "{$CFG->wwwroot}/mod/assignment/";
351 $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
352 if (has_capability('mod/assignment:grade', $context)) {
353 if ($allgroups and has_capability('moodle/site:accessallgroups', $context)) {
356 $group = groups_get_activity_group($this->cm);
358 if ($count = $this->count_real_submissions($group)) {
359 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
360 get_string('viewsubmissions', 'assignment', $count).'</a>';
362 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
363 get_string('noattempts', 'assignment').'</a>';
366 if (!empty($USER->id)) {
367 if ($submission = $this->get_submission($USER->id)) {
368 if ($submission->timemodified) {
369 if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
370 $submitted = '<span class="early">'.userdate($submission->timemodified).'</span>';
372 $submitted = '<span class="late">'.userdate($submission->timemodified).'</span>';
384 * @todo Document this function
386 function setup_elements(&$mform) {
391 * Create a new assignment activity
393 * Given an object containing all the necessary data,
394 * (defined by the form in mod_form.php) this function
395 * will create a new instance and return the id number
396 * of the new instance.
397 * The due data is added to the calendar
398 * This is common to all assignment types.
402 * @param object $assignment The data from the form on mod_form.php
403 * @return int The id of the assignment
405 function add_instance($assignment) {
408 $assignment->timemodified = time();
409 $assignment->courseid = $assignment->course;
411 if ($returnid = $DB->insert_record("assignment", $assignment)) {
412 $assignment->id = $returnid;
414 if ($assignment->timedue) {
415 $event = new object();
416 $event->name = $assignment->name;
417 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
418 $event->courseid = $assignment->course;
421 $event->modulename = 'assignment';
422 $event->instance = $returnid;
423 $event->eventtype = 'due';
424 $event->timestart = $assignment->timedue;
425 $event->timeduration = 0;
430 assignment_grade_item_update($assignment);
439 * Deletes an assignment activity
441 * Deletes all database records, files and calendar events for this assignment.
445 * @param object $assignment The assignment to be deleted
446 * @return boolean False indicates error
448 function delete_instance($assignment) {
451 $assignment->courseid = $assignment->course;
455 // now get rid of all files
456 $fs = get_file_storage();
457 if ($cm = get_coursemodule_from_instance('assignment', $assignment->id)) {
458 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
459 $fs->delete_area_files($context->id);
462 if (! $DB->delete_records('assignment_submissions', array('assignment'=>$assignment->id))) {
466 if (! $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
470 if (! $DB->delete_records('assignment', array('id'=>$assignment->id))) {
474 assignment_grade_item_delete($assignment);
480 * Updates a new assignment activity
482 * Given an object containing all the necessary data,
483 * (defined by the form in mod_form.php) this function
484 * will update the assignment instance and return the id number
485 * The due date is updated in 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 assignment id
493 function update_instance($assignment) {
496 $assignment->timemodified = time();
498 $assignment->id = $assignment->instance;
499 $assignment->courseid = $assignment->course;
501 $DB->update_record('assignment', $assignment);
503 if ($assignment->timedue) {
504 $event = new object();
506 if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
508 $event->name = $assignment->name;
509 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
510 $event->timestart = $assignment->timedue;
512 update_event($event);
514 $event = new object();
515 $event->name = $assignment->name;
516 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
517 $event->courseid = $assignment->course;
520 $event->modulename = 'assignment';
521 $event->instance = $assignment->id;
522 $event->eventtype = 'due';
523 $event->timestart = $assignment->timedue;
524 $event->timeduration = 0;
529 $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id));
532 // get existing grade item
533 assignment_grade_item_update($assignment);
539 * Update grade item for this submission.
541 function update_grade($submission) {
542 assignment_update_grades($this->assignment, $submission->userid);
546 * Top-level function for handling of submissions called by submissions.php
548 * This is for handling the teacher interaction with the grading interface
549 * This should be suitable for most assignment types.
552 * @param string $mode Specifies the kind of teacher interaction taking place
554 function submissions($mode) {
555 ///The main switch is changed to facilitate
556 ///1) Batch fast grading
557 ///2) Skip to the next one on the popup
558 ///3) Save and Skip to the next one on the popup
560 //make user global so we can use the id
563 $mailinfo = optional_param('mailinfo', null, PARAM_BOOL);
564 if (is_null($mailinfo)) {
565 $mailinfo = get_user_preferences('assignment_mailinfo', 0);
567 set_user_preference('assignment_mailinfo', $mailinfo);
571 case 'grade': // We are in a popup window grading
572 if ($submission = $this->process_feedback()) {
573 //IE needs proper header with encoding
574 print_header(get_string('feedback', 'assignment').':'.format_string($this->assignment->name));
575 print_heading(get_string('changessaved'));
576 print $this->update_main_listing($submission);
581 case 'single': // We are in a popup window displaying submission
582 $this->display_submission();
585 case 'all': // Main window, display everything
586 $this->display_submissions();
590 ///do the fast grading stuff - this process should work for all 3 subclasses
595 if (isset($_POST['submissioncomment'])) {
596 $col = 'submissioncomment';
599 if (isset($_POST['menu'])) {
604 //both submissioncomment and grade columns collapsed..
605 $this->display_submissions();
609 foreach ($_POST[$col] as $id => $unusedvalue){
611 $id = (int)$id; //clean parameter name
613 $this->process_outcomes($id);
615 if (!$submission = $this->get_submission($id)) {
616 $submission = $this->prepare_new_submission($id);
617 $newsubmission = true;
619 $newsubmission = false;
621 unset($submission->data1); // Don't need to update this.
622 unset($submission->data2); // Don't need to update this.
624 //for fast grade, we need to check if any changes take place
628 $grade = $_POST['menu'][$id];
629 $updatedb = $updatedb || ($submission->grade != $grade);
630 $submission->grade = $grade;
632 if (!$newsubmission) {
633 unset($submission->grade); // Don't need to update this.
637 $commentvalue = trim($_POST['submissioncomment'][$id]);
638 $updatedb = $updatedb || ($submission->submissioncomment != $commentvalue);
639 $submission->submissioncomment = $commentvalue;
641 unset($submission->submissioncomment); // Don't need to update this.
644 $submission->teacher = $USER->id;
646 $submission->mailed = (int)(!$mailinfo);
649 $submission->timemarked = time();
651 //if it is not an update, we don't change the last modified time etc.
652 //this will also not write into database if no submissioncomment and grade is entered.
655 if ($newsubmission) {
656 if (!isset($submission->submissioncomment)) {
657 $submission->submissioncomment = '';
659 $sid = $DB->insert_record('assignment_submissions', $submission);
660 $submission->id = $sid;
662 $DB->update_record('assignment_submissions', $submission);
665 // triger grade event
666 $this->update_grade($submission);
668 //add to log only if updating
669 add_to_log($this->course->id, 'assignment', 'update grades',
670 'submissions.php?id='.$this->assignment->id.'&user='.$submission->userid,
671 $submission->userid, $this->cm->id);
676 $message = notify(get_string('changessaved'), 'notifysuccess', 'center', true);
678 $this->display_submissions($message);
683 /// We are currently in pop up, but we want to skip to next one without saving.
684 /// This turns out to be similar to a single case
685 /// The URL used is for the next submission.
687 $this->display_submission();
691 ///We are in pop up. save the current one and go to the next one.
692 //first we save the current changes
693 if ($submission = $this->process_feedback()) {
694 //print_heading(get_string('changessaved'));
695 $extra_javascript = $this->update_main_listing($submission);
698 //then we display the next submission
699 $this->display_submission($extra_javascript);
703 echo "something seriously is wrong!!";
709 * Helper method updating the listing on the main script from popup using javascript
713 * @param $submission object The submission whose data is to be updated on the main page
715 function update_main_listing($submission) {
716 global $SESSION, $CFG;
720 $perpage = get_user_preferences('assignment_perpage', 10);
722 $quickgrade = get_user_preferences('assignment_quickgrade', 0);
724 /// Run some Javascript to try and update the parent page
725 $output .= '<script type="text/javascript">'."\n<!--\n";
726 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['submissioncomment'])) {
728 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid.'").value="'
729 .trim($submission->submissioncomment).'";'."\n";
731 $output.= 'opener.document.getElementById("com'.$submission->userid.
732 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment)), 15)."\";\n";
736 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['grade'])) {
737 //echo optional_param('menuindex');
739 $output.= 'opener.document.getElementById("menumenu'.$submission->userid.
740 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT).'";'."\n";
742 $output.= 'opener.document.getElementById("g'.$submission->userid.'").innerHTML="'.
743 $this->display_grade($submission->grade)."\";\n";
746 //need to add student's assignments in there too.
747 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemodified']) &&
748 $submission->timemodified) {
749 $output.= 'opener.document.getElementById("ts'.$submission->userid.
750 '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid)).userdate($submission->timemodified)."\";\n";
753 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemarked']) &&
754 $submission->timemarked) {
755 $output.= 'opener.document.getElementById("tt'.$submission->userid.
756 '").innerHTML="'.userdate($submission->timemarked)."\";\n";
759 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['status'])) {
760 $output.= 'opener.document.getElementById("up'.$submission->userid.'").className="s1";';
761 $buttontext = get_string('update');
762 $button = link_to_popup_window ('/mod/assignment/submissions.php?id='.$this->cm->id.'&userid='.$submission->userid.'&mode=single'.'&offset='.(optional_param('offset', '', PARAM_INT)-1),
763 'grade'.$submission->userid, $buttontext, 450, 700, $buttontext, 'none', true, 'button'.$submission->userid);
764 $output.= 'opener.document.getElementById("up'.$submission->userid.'").innerHTML="'.addslashes_js($button).'";';
767 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $submission->userid);
769 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['finalgrade'])) {
770 $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid.
771 '").innerHTML="'.$grading_info->items[0]->grades[$submission->userid]->str_grade.'";'."\n";
774 if (!empty($CFG->enableoutcomes) and empty($SESSION->flextable['mod-assignment-submissions']->collapse['outcome'])) {
776 if (!empty($grading_info->outcomes)) {
777 foreach($grading_info->outcomes as $n=>$outcome) {
778 if ($outcome->grades[$submission->userid]->locked) {
783 $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.
784 '").selectedIndex="'.$outcome->grades[$submission->userid]->grade.'";'."\n";
787 $options = make_grades_menu(-$outcome->scaleid);
788 $options[0] = get_string('nooutcome', 'grades');
789 $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.'").innerHTML="'.$options[$outcome->grades[$submission->userid]->grade]."\";\n";
796 $output .= "\n-->\n</script>";
801 * Return a grade in user-friendly form, whether it's a scale or not
804 * @param mixed $grade
805 * @return string User-friendly representation of grade
807 function display_grade($grade) {
810 static $scalegrades = array(); // Cache scales for each assignment - they might have different scales!!
812 if ($this->assignment->grade >= 0) { // Normal number
816 return $grade.' / '.$this->assignment->grade;
820 if (empty($scalegrades[$this->assignment->id])) {
821 if ($scale = $DB->get_record('scale', array('id'=>-($this->assignment->grade)))) {
822 $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
827 if (isset($scalegrades[$this->assignment->id][$grade])) {
828 return $scalegrades[$this->assignment->id][$grade];
835 * Display a single submission, ready for grading on a popup window
837 * This default method prints the teacher info and submissioncomment box at the top and
838 * the student info and submission at the bottom.
839 * This method also fetches the necessary data in order to be able to
840 * provide a "Next submission" button.
841 * Calls preprocess_submission() to give assignment type plug-ins a chance
842 * to process submissions before they are graded
843 * This method gets its arguments from the page parameters userid and offset
847 * @param string $extra_javascript
849 function display_submission($extra_javascript = '') {
850 global $CFG, $DB, $PAGE;
851 require_once($CFG->libdir.'/gradelib.php');
852 require_once($CFG->libdir.'/tablelib.php');
854 $userid = required_param('userid', PARAM_INT);
855 $offset = required_param('offset', PARAM_INT);//offset for where to start looking for student.
857 if (!$user = $DB->get_record('user', array('id'=>$userid))) {
858 print_error('nousers');
861 if (!$submission = $this->get_submission($user->id)) {
862 $submission = $this->prepare_new_submission($userid);
864 if ($submission->timemodified > $submission->timemarked) {
865 $subtype = 'assignmentnew';
867 $subtype = 'assignmentold';
870 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
871 $disabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
873 /// construct SQL, using current offset to find the data of the next student
874 $course = $this->course;
875 $assignment = $this->assignment;
877 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
879 /// Get all ppl that can submit assignments
881 $currentgroup = groups_get_activity_group($cm);
882 if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $currentgroup, '', false)) {
883 $users = array_keys($users);
886 // if groupmembersonly used, remove users who are not in any group
887 if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
888 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
889 $users = array_intersect($users, array_keys($groupingusers));
896 $select = 'SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt,
897 s.id AS submissionid, s.grade, s.submissioncomment,
898 s.timemodified, s.timemarked,
899 COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ';
900 $sql = 'FROM {user} u '.
901 'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
902 AND s.assignment = '.$this->assignment->id.' '.
903 'WHERE u.id IN ('.implode(',', $users).') ';
905 if ($sort = flexible_table::get_sql_sort('mod-assignment-submissions')) {
906 $sort = 'ORDER BY '.$sort.' ';
909 if (($auser = $DB->get_records_sql($select.$sql.$sort, null, $offset+1, 1)) !== false) {
910 $nextuser = array_shift($auser);
911 /// Calculate user status
912 $nextuser->status = ($nextuser->timemarked > 0) && ($nextuser->timemarked >= $nextuser->timemodified);
913 $nextid = $nextuser->id;
917 print_header(get_string('feedback', 'assignment').':'.fullname($user, true).':'.format_string($this->assignment->name));
919 /// Print any extra javascript needed for saveandnext
920 echo $extra_javascript;
922 echo $PAGE->requires->data_for_js('assignment', Array('nextid'=>$nextid, 'userid'=>$userid))->asap();
923 echo $PAGE->requires->js('mod/assignment/assignment.js')->asap();
925 echo '<table cellspacing="0" class="feedback '.$subtype.'" >';
927 ///Start of teacher info row
930 echo '<td class="picture teacher">';
931 if ($submission->teacher) {
932 $teacher = $DB->get_record('user', array('id'=>$submission->teacher));
937 print_user_picture($teacher, $this->course->id, $teacher->picture);
939 echo '<td class="content">';
940 echo '<form id="submitform" action="submissions.php" method="post">';
941 echo '<div>'; // xhtml compatibility - invisiblefieldset was breaking layout here
942 echo '<input type="hidden" name="offset" value="'.($offset+1).'" />';
943 echo '<input type="hidden" name="userid" value="'.$userid.'" />';
944 echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
945 echo '<input type="hidden" name="mode" value="grade" />';
946 echo '<input type="hidden" name="menuindex" value="0" />';//selected menu index
948 //new hidden field, initialized to -1.
949 echo '<input type="hidden" name="saveuserid" value="-1" />';
951 if ($submission->timemarked) {
952 echo '<div class="from">';
953 echo '<div class="fullname">'.fullname($teacher, true).'</div>';
954 echo '<div class="time">'.userdate($submission->timemarked).'</div>';
957 echo '<div class="grade"><label for="menugrade">'.get_string('grade').'</label> ';
958 choose_from_menu(make_grades_menu($this->assignment->grade), 'grade', $submission->grade, get_string('nograde'), '', -1, false, $disabled);
961 echo '<div class="clearer"></div>';
962 echo '<div class="finalgrade">'.get_string('finalgrade', 'grades').': '.$grading_info->items[0]->grades[$userid]->str_grade.'</div>';
963 echo '<div class="clearer"></div>';
965 if (!empty($CFG->enableoutcomes)) {
966 foreach($grading_info->outcomes as $n=>$outcome) {
967 echo '<div class="outcome"><label for="menuoutcome_'.$n.'">'.$outcome->name.'</label> ';
968 $options = make_grades_menu(-$outcome->scaleid);
969 if ($outcome->grades[$submission->userid]->locked) {
970 $options[0] = get_string('nooutcome', 'grades');
971 echo $options[$outcome->grades[$submission->userid]->grade];
973 choose_from_menu($options, 'outcome_'.$n.'['.$userid.']', $outcome->grades[$submission->userid]->grade, get_string('nooutcome', 'grades'), '', 0, false, false, 0, 'menuoutcome_'.$n);
976 echo '<div class="clearer"></div>';
981 $this->preprocess_submission($submission);
984 echo '<div class="disabledfeedback">'.$grading_info->items[0]->grades[$userid]->str_feedback.'</div>';
987 print_textarea($this->usehtmleditor, 14, 58, 0, 0, 'submissioncomment', $submission->submissioncomment, $this->course->id);
988 if ($this->usehtmleditor) {
989 echo '<input type="hidden" name="format" value="'.FORMAT_HTML.'" />';
991 echo '<div class="format">';
992 choose_from_menu(format_text_menu(), "format", $submission->format, "");
993 helpbutton("textformat", get_string("helpformatting"));
998 $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? 'checked="checked"' : '';
1000 ///Print Buttons in Single View
1001 echo '<input type="hidden" name="mailinfo" value="0" />';
1002 echo '<input type="checkbox" id="mailinfo" name="mailinfo" value="1" '.$lastmailinfo.' /><label for="mailinfo">'.get_string('enableemailnotification','assignment').'</label>';
1003 echo '<div class="buttons">';
1004 echo '<input type="submit" name="submit" value="'.get_string('savechanges').'" onclick = "document.getElementById(\'submitform\').menuindex.value = document.getElementById(\'submitform\').grade.selectedIndex" />';
1005 echo '<input type="submit" name="cancel" value="'.get_string('cancel').'" />';
1006 //if there are more to be graded.
1008 echo '<input type="submit" name="saveandnext" value="'.get_string('saveandnext').'" onclick="saveNext()" />';
1009 echo '<input type="submit" name="next" value="'.get_string('next').'" onclick="setNext();" />';
1012 echo '</div></form>';
1014 $customfeedback = $this->custom_feedbackform($submission, true);
1015 if (!empty($customfeedback)) {
1016 echo $customfeedback;
1021 ///End of teacher info row, Start of student info row
1023 echo '<td class="picture user">';
1024 print_user_picture($user, $this->course->id, $user->picture);
1026 echo '<td class="topic">';
1027 echo '<div class="from">';
1028 echo '<div class="fullname">'.fullname($user, true).'</div>';
1029 if ($submission->timemodified) {
1030 echo '<div class="time">'.userdate($submission->timemodified).
1031 $this->display_lateness($submission->timemodified).'</div>';
1034 $this->print_user_files($user->id);
1038 ///End of student info row
1042 print_footer('none');
1046 * Preprocess submission before grading
1048 * Called by display_submission()
1049 * The default type does nothing here.
1051 * @param object $submission The submission object
1053 function preprocess_submission(&$submission) {
1057 * Display all the submissions ready for grading
1063 * @param string $message
1066 function display_submissions($message='') {
1067 global $CFG, $DB, $USER, $DB;
1068 require_once($CFG->libdir.'/gradelib.php');
1070 /* first we check to see if the form has just been submitted
1071 * to request user_preference updates
1074 if (isset($_POST['updatepref'])){
1075 $perpage = optional_param('perpage', 10, PARAM_INT);
1076 $perpage = ($perpage <= 0) ? 10 : $perpage ;
1077 set_user_preference('assignment_perpage', $perpage);
1078 set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
1081 /* next we get perpage and quickgrade (allow quick grade) params
1084 $perpage = get_user_preferences('assignment_perpage', 10);
1086 $quickgrade = get_user_preferences('assignment_quickgrade', 0);
1088 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);
1090 if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
1091 $uses_outcomes = true;
1093 $uses_outcomes = false;
1096 $page = optional_param('page', 0, PARAM_INT);
1097 $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
1099 /// Some shortcuts to make the code read better
1101 $course = $this->course;
1102 $assignment = $this->assignment;
1105 $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
1106 add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->cm->id, $this->assignment->id, $this->cm->id);
1107 $navigation = build_navigation($this->strsubmissions, $this->cm);
1108 print_header_simple(format_string($this->assignment->name,true), "", $navigation,
1109 '', '', true, update_module_button($cm->id, $course->id, $this->strassignment), navmenu($course, $cm));
1111 $course_context = get_context_instance(CONTEXT_COURSE, $course->id);
1112 if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
1113 echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">'
1114 . get_string('seeallcoursegrades', 'grades') . '</a></div>';
1117 if (!empty($message)) {
1118 echo $message; // display messages here if any
1121 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1123 /// Check to see if groups are being used in this assignment
1125 /// find out current groups mode
1126 $groupmode = groups_get_activity_groupmode($cm);
1127 $currentgroup = groups_get_activity_group($cm, true);
1128 groups_print_activity_menu($cm, 'submissions.php?id=' . $this->cm->id);
1130 /// Get all ppl that are allowed to submit assignments
1131 if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $currentgroup, '', false)) {
1132 $users = array_keys($users);
1135 // if groupmembersonly used, remove users who are not in any group
1136 if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
1137 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1138 $users = array_intersect($users, array_keys($groupingusers));
1142 $tablecolumns = array('picture', 'fullname', 'grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade');
1143 if ($uses_outcomes) {
1144 $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
1147 $tableheaders = array('',
1148 get_string('fullname'),
1149 get_string('grade'),
1150 get_string('comment', 'assignment'),
1151 get_string('lastmodified').' ('.get_string('submission', 'assignment').')',
1152 get_string('lastmodified').' ('.get_string('grade').')',
1153 get_string('status'),
1154 get_string('finalgrade', 'grades'));
1155 if ($uses_outcomes) {
1156 $tableheaders[] = get_string('outcome', 'grades');
1159 require_once($CFG->libdir.'/tablelib.php');
1160 $table = new flexible_table('mod-assignment-submissions');
1162 $table->define_columns($tablecolumns);
1163 $table->define_headers($tableheaders);
1164 $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&currentgroup='.$currentgroup);
1166 $table->sortable(true, 'lastname');//sorted by lastname by default
1167 $table->collapsible(true);
1168 $table->initialbars(true);
1170 $table->column_suppress('picture');
1171 $table->column_suppress('fullname');
1173 $table->column_class('picture', 'picture');
1174 $table->column_class('fullname', 'fullname');
1175 $table->column_class('grade', 'grade');
1176 $table->column_class('submissioncomment', 'comment');
1177 $table->column_class('timemodified', 'timemodified');
1178 $table->column_class('timemarked', 'timemarked');
1179 $table->column_class('status', 'status');
1180 $table->column_class('finalgrade', 'finalgrade');
1181 if ($uses_outcomes) {
1182 $table->column_class('outcome', 'outcome');
1185 $table->set_attribute('cellspacing', '0');
1186 $table->set_attribute('id', 'attempts');
1187 $table->set_attribute('class', 'submissions');
1188 $table->set_attribute('width', '100%');
1189 //$table->set_attribute('align', 'center');
1191 $table->no_sorting('finalgrade');
1192 $table->no_sorting('outcome');
1194 // Start working -- this is necessary as soon as the niceties are over
1197 if (empty($users)) {
1198 print_heading(get_string('nosubmitusers','assignment'));
1202 /// Construct the SQL
1204 if ($where = $table->get_sql_where()) {
1208 if ($sort = $table->get_sql_sort()) {
1209 $sort = ' ORDER BY '.$sort;
1212 $select = 'SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt,
1213 s.id AS submissionid, s.grade, s.submissioncomment,
1214 s.timemodified, s.timemarked,
1215 COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ';
1216 $sql = 'FROM {user} u '.
1217 'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1218 AND s.assignment = '.$this->assignment->id.' '.
1219 'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1221 $table->pagesize($perpage, count($users));
1223 ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1224 $offset = $page * $perpage;
1226 $strupdate = get_string('update');
1227 $strgrade = get_string('grade');
1228 $grademenu = make_grades_menu($this->assignment->grade);
1230 if (($ausers = $DB->get_records_sql($select.$sql.$sort, null, $table->get_page_start(), $table->get_page_size())) !== false) {
1231 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
1232 foreach ($ausers as $auser) {
1233 $final_grade = $grading_info->items[0]->grades[$auser->id];
1234 $grademax = $grading_info->items[0]->grademax;
1235 $final_grade->formatted_grade = round($final_grade->grade,2) .' / ' . round($grademax,2);
1236 $locked_overridden = 'locked';
1237 if ($final_grade->overridden) {
1238 $locked_overridden = 'overridden';
1241 /// Calculate user status
1242 $auser->status = ($auser->timemarked > 0) && ($auser->timemarked >= $auser->timemodified);
1243 $picture = print_user_picture($auser, $course->id, $auser->picture, false, true);
1245 if (empty($auser->submissionid)) {
1246 $auser->grade = -1; //no submission yet
1249 if (!empty($auser->submissionid)) {
1250 ///Prints student answer and student modified date
1251 ///attach file or print link to student answer, depending on the type of the assignment.
1252 ///Refer to print_student_answer in inherited classes.
1253 if ($auser->timemodified > 0) {
1254 $studentmodified = '<div id="ts'.$auser->id.'">'.$this->print_student_answer($auser->id)
1255 . userdate($auser->timemodified).'</div>';
1257 $studentmodified = '<div id="ts'.$auser->id.'"> </div>';
1259 ///Print grade, dropdown or text
1260 if ($auser->timemarked > 0) {
1261 $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
1263 if ($final_grade->locked or $final_grade->overridden) {
1264 $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1265 } else if ($quickgrade) {
1266 $menu = choose_from_menu(make_grades_menu($this->assignment->grade),
1267 'menu['.$auser->id.']', $auser->grade,
1268 get_string('nograde'),'',-1,true,false,$tabindex++);
1269 $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
1271 $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1275 $teachermodified = '<div id="tt'.$auser->id.'"> </div>';
1276 if ($final_grade->locked or $final_grade->overridden) {
1277 $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1278 } else if ($quickgrade) {
1279 $menu = choose_from_menu(make_grades_menu($this->assignment->grade),
1280 'menu['.$auser->id.']', $auser->grade,
1281 get_string('nograde'),'',-1,true,false,$tabindex++);
1282 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1284 $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1288 if ($final_grade->locked or $final_grade->overridden) {
1289 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';
1291 } else if ($quickgrade) {
1292 $comment = '<div id="com'.$auser->id.'">'
1293 . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1294 . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1296 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
1299 $studentmodified = '<div id="ts'.$auser->id.'"> </div>';
1300 $teachermodified = '<div id="tt'.$auser->id.'"> </div>';
1301 $status = '<div id="st'.$auser->id.'"> </div>';
1303 if ($final_grade->locked or $final_grade->overridden) {
1304 $grade = '<div id="g'.$auser->id.'">'.$final_grade->formatted_grade . '</div>';
1305 } else if ($quickgrade) { // allow editing
1306 $menu = choose_from_menu(make_grades_menu($this->assignment->grade),
1307 'menu['.$auser->id.']', $auser->grade,
1308 get_string('nograde'),'',-1,true,false,$tabindex++);
1309 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1311 $grade = '<div id="g'.$auser->id.'">-</div>';
1314 if ($final_grade->locked or $final_grade->overridden) {
1315 $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
1316 } else if ($quickgrade) {
1317 $comment = '<div id="com'.$auser->id.'">'
1318 . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1319 . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1321 $comment = '<div id="com'.$auser->id.'"> </div>';
1325 if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
1331 $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
1333 ///No more buttons, we use popups ;-).
1334 $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1335 . '&userid='.$auser->id.'&mode=single'.'&offset='.$offset++;
1336 $button = link_to_popup_window ($popup_url, 'grade'.$auser->id, $buttontext, 600, 780,
1337 $buttontext, 'none', true, 'button'.$auser->id);
1339 $status = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
1341 $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';
1345 if ($uses_outcomes) {
1347 foreach($grading_info->outcomes as $n=>$outcome) {
1348 $outcomes .= '<div class="outcome"><label>'.$outcome->name.'</label>';
1349 $options = make_grades_menu(-$outcome->scaleid);
1351 if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
1352 $options[0] = get_string('nooutcome', 'grades');
1353 $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
1356 $outcomes .= choose_from_menu($options, 'outcome_'.$n.'['.$auser->id.']',
1357 $outcome->grades[$auser->id]->grade, get_string('nooutcome', 'grades'), '', 0, true, false, 0, 'outcome_'.$n.'_'.$auser->id);
1359 $outcomes .= '</div>';
1363 $userlink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $auser->id . '&course=' . $course->id . '">' . fullname($auser) . '</a>';
1364 $row = array($picture, $userlink, $grade, $comment, $studentmodified, $teachermodified, $status, $finalgrade);
1365 if ($uses_outcomes) {
1369 $table->add_data($row);
1373 /// Print quickgrade form around the table
1375 echo '<form action="submissions.php" id="fastg" method="post">';
1377 echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
1378 echo '<input type="hidden" name="mode" value="fastgrade" />';
1379 echo '<input type="hidden" name="page" value="'.$page.'" />';
1383 $table->print_html(); /// Print the whole table
1386 $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? 'checked="checked"' : '';
1387 echo '<div class="fgcontrols">';
1388 echo '<div class="emailnotification">';
1389 echo '<label for="mailinfo">'.get_string('enableemailnotification','assignment').'</label>';
1390 echo '<input type="hidden" name="mailinfo" value="0" />';
1391 echo '<input type="checkbox" id="mailinfo" name="mailinfo" value="1" '.$lastmailinfo.' />';
1392 helpbutton('emailnotification', get_string('enableemailnotification', 'assignment'), 'assignment').'</p></div>';
1394 echo '<div class="fastgbutton"><input type="submit" name="fastg" value="'.get_string('saveallfeedback', 'assignment').'" /></div>';
1398 /// End of fast grading form
1400 /// Mini form for setting user preference
1401 echo '<div class="qgprefs">';
1402 echo '<form id="options" action="submissions.php?id='.$this->cm->id.'" method="post"><div>';
1403 echo '<input type="hidden" name="updatepref" value="1" />';
1404 echo '<table id="optiontable">';
1406 echo '<label for="perpage">'.get_string('pagesize','assignment').'</label>';
1409 echo '<input type="text" id="perpage" name="perpage" size="1" value="'.$perpage.'" />';
1410 helpbutton('pagesize', get_string('pagesize','assignment'), 'assignment');
1413 echo '<label for="quickgrade">'.get_string('quickgrade','assignment').'</label>';
1416 $checked = $quickgrade ? 'checked="checked"' : '';
1417 echo '<input type="checkbox" id="quickgrade" name="quickgrade" value="1" '.$checked.' />';
1418 helpbutton('quickgrade', get_string('quickgrade', 'assignment'), 'assignment').'</p></div>';
1420 echo '<tr><td colspan="2">';
1421 echo '<input type="submit" value="'.get_string('savepreferences').'" />';
1422 echo '</td></tr></table>';
1423 echo '</div></form></div>';
1425 print_footer($this->course);
1429 * Process teacher feedback submission
1431 * This is called by submissions() when a grading even has taken place.
1432 * It gets its data from the submitted form.
1437 * @return object|bool The updated submission object or false
1439 function process_feedback() {
1440 global $CFG, $USER, $DB;
1441 require_once($CFG->libdir.'/gradelib.php');
1443 if (!$feedback = data_submitted()) { // No incoming data?
1447 ///For save and next, we need to know the userid to save, and the userid to go
1448 ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1449 ///as the userid to store
1450 if ((int)$feedback->saveuserid !== -1){
1451 $feedback->userid = $feedback->saveuserid;
1454 if (!empty($feedback->cancel)) { // User hit cancel button
1458 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);
1460 // store outcomes if needed
1461 $this->process_outcomes($feedback->userid);
1463 $submission = $this->get_submission($feedback->userid, true); // Get or make one
1465 if (!$grading_info->items[0]->grades[$feedback->userid]->locked and
1466 !$grading_info->items[0]->grades[$feedback->userid]->overridden) {
1468 $submission->grade = $feedback->grade;
1469 $submission->submissioncomment = $feedback->submissioncomment;
1470 $submission->format = $feedback->format;
1471 $submission->teacher = $USER->id;
1472 $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1474 $submission->mailed = 1; // treat as already mailed
1476 $submission->mailed = 0; // Make sure mail goes out (again, even)
1478 $submission->timemarked = time();
1480 unset($submission->data1); // Don't need to update this.
1481 unset($submission->data2); // Don't need to update this.
1483 if (empty($submission->timemodified)) { // eg for offline assignments
1484 // $submission->timemodified = time();
1487 $DB->update_record('assignment_submissions', $submission);
1489 // triger grade event
1490 $this->update_grade($submission);
1492 add_to_log($this->course->id, 'assignment', 'update grades',
1493 'submissions.php?id='.$this->assignment->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
1500 function process_outcomes($userid) {
1503 if (empty($CFG->enableoutcomes)) {
1507 require_once($CFG->libdir.'/gradelib.php');
1509 if (!$formdata = data_submitted()) {
1514 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
1516 if (!empty($grading_info->outcomes)) {
1517 foreach($grading_info->outcomes as $n=>$old) {
1518 $name = 'outcome_'.$n;
1519 if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
1520 $data[$n] = $formdata->{$name}[$userid];
1524 if (count($data) > 0) {
1525 grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1531 * Load the submission object for a particular user
1535 * @param $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1536 * @param $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1537 * @param bool $teachermodified student submission set if false
1538 * @return object The submission
1540 function get_submission($userid=0, $createnew=false, $teachermodified=false) {
1543 if (empty($userid)) {
1544 $userid = $USER->id;
1547 $submission = $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1549 if ($submission || !$createnew) {
1552 $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
1553 $DB->insert_record("assignment_submissions", $newsubmission);
1555 return $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1559 * Instantiates a new submission object for a given user
1561 * Sets the assignment, userid and times, everything else is set to default values.
1563 * @param int $userid The userid for which we want a submission object
1564 * @param bool $teachermodified student submission set if false
1565 * @return object The submission
1567 function prepare_new_submission($userid, $teachermodified=false) {
1568 $submission = new Object;
1569 $submission->assignment = $this->assignment->id;
1570 $submission->userid = $userid;
1571 //$submission->timecreated = time();
1572 $submission->timecreated = '';
1573 // teachers should not be modifying modified date, except offline assignments
1574 if ($teachermodified) {
1575 $submission->timemodified = 0;
1577 $submission->timemodified = $submission->timecreated;
1579 $submission->numfiles = 0;
1580 $submission->data1 = '';
1581 $submission->data2 = '';
1582 $submission->grade = -1;
1583 $submission->submissioncomment = '';
1584 $submission->format = 0;
1585 $submission->teacher = 0;
1586 $submission->timemarked = 0;
1587 $submission->mailed = 0;
1592 * Return all assignment submissions by ENROLLED students (even empty)
1594 * @param string $sort optional field names for the ORDER BY in the sql query
1595 * @param string $dir optional specifying the sort direction, defaults to DESC
1596 * @return array The submission objects indexed by id
1598 function get_submissions($sort='', $dir='DESC') {
1599 return assignment_get_all_submissions($this->assignment, $sort, $dir);
1603 * Counts all real assignment submissions by ENROLLED students (not empty ones)
1605 * @param int $groupid optional If nonzero then count is restricted to this group
1606 * @return int The number of submissions
1608 function count_real_submissions($groupid=0) {
1609 return assignment_count_real_submissions($this->cm, $groupid);
1613 * Alerts teachers by email of new or changed assignments that need grading
1615 * First checks whether the option to email teachers is set for this assignment.
1616 * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1617 * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1621 * @param $submission object The submission that has changed
1624 function email_teachers($submission) {
1627 if (empty($this->assignment->emailteachers)) { // No need to do anything
1631 $user = $DB->get_record('user', array('id'=>$submission->userid));
1633 if ($teachers = $this->get_graders($user)) {
1635 $strassignments = get_string('modulenameplural', 'assignment');
1636 $strassignment = get_string('modulename', 'assignment');
1637 $strsubmitted = get_string('submitted', 'assignment');
1639 foreach ($teachers as $teacher) {
1640 $info = new object();
1641 $info->username = fullname($user, true);
1642 $info->assignment = format_string($this->assignment->name,true);
1643 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
1645 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1646 $posttext = $this->email_teachers_text($info);
1647 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
1649 $eventdata = new object();
1650 $eventdata->modulename = 'assignment';
1651 $eventdata->userfrom = $user;
1652 $eventdata->userto = $teacher;
1653 $eventdata->subject = $postsubject;
1654 $eventdata->fullmessage = $posttext;
1655 $eventdata->fullmessageformat = FORMAT_PLAIN;
1656 $eventdata->fullmessagehtml = $posthtml;
1657 $eventdata->smallmessage = '';
1658 if ( events_trigger('message_send', $eventdata) > 0 ){
1665 * @param string $filearea
1666 * @param array $args
1669 function send_file($filearea, $args) {
1670 debugging('plugin does not implement file sending', DEBUG_DEVELOPER);
1675 * Returns a list of teachers that should be grading given submission
1677 * @param object $user
1680 function get_graders($user) {
1682 $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false);
1685 if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) { // Separate groups are being used
1686 if ($groups = groups_get_all_groups($this->course->id, $user->id)) { // Try to find all groups
1687 foreach ($groups as $group) {
1688 foreach ($potgraders as $t) {
1689 if ($t->id == $user->id) {
1690 continue; // do not send self
1692 if (groups_is_member($group->id, $t->id)) {
1693 $graders[$t->id] = $t;
1698 // user not in group, try to find graders without group
1699 foreach ($potgraders as $t) {
1700 if ($t->id == $user->id) {
1701 continue; // do not send self
1703 if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
1704 $graders[$t->id] = $t;
1709 foreach ($potgraders as $t) {
1710 if ($t->id == $user->id) {
1711 continue; // do not send self
1713 $graders[$t->id] = $t;
1720 * Creates the text content for emails to teachers
1722 * @param $info object The info used by the 'emailteachermail' language string
1725 function email_teachers_text($info) {
1726 $posttext = format_string($this->course->shortname).' -> '.$this->strassignments.' -> '.
1727 format_string($this->assignment->name)."\n";
1728 $posttext .= '---------------------------------------------------------------------'."\n";
1729 $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
1730 $posttext .= "\n---------------------------------------------------------------------\n";
1735 * Creates the html content for emails to teachers
1737 * @param $info object The info used by the 'emailteachermailhtml' language string
1740 function email_teachers_html($info) {
1742 $posthtml = '<p><font face="sans-serif">'.
1743 '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname).'</a> ->'.
1744 '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
1745 '<a href="'.$CFG->wwwroot.'/mod/assignment/view.php?id='.$this->cm->id.'">'.format_string($this->assignment->name).'</a></font></p>';
1746 $posthtml .= '<hr /><font face="sans-serif">';
1747 $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
1748 $posthtml .= '</font><hr />';
1753 * Produces a list of links to the files uploaded by a user
1755 * @param $userid int optional id of the user. If 0 then $USER->id is used.
1756 * @param $return boolean optional defaults to false. If true the list is returned rather than printed
1757 * @return string optional
1759 function print_user_files($userid=0, $return=false) {
1760 global $CFG, $USER, $OUTPUT;
1763 if (!isloggedin()) {
1766 $userid = $USER->id;
1771 $fs = get_file_storage();
1772 $browser = get_file_browser();
1776 if ($files = $fs->get_area_files($this->context->id, 'assignment_submission', $userid, "timemodified", false)) {
1777 $button = new portfolio_add_button();
1778 foreach ($files as $file) {
1779 $filename = $file->get_filename();
1781 $mimetype = $file->get_mimetype();
1782 $icon = str_replace(array('.gif', '.png'), '', mimeinfo_from_type('icon', $mimetype));
1783 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/assignment_submission/'.$userid.'/'.$filename);
1784 $output .= '<a href="'.$path.'" ><img src="'.$OUTPUT->old_icon_url('f/'.$icon).'" class="icon" alt="'.$icon.'" />'.s($filename).'</a>';
1785 if ($this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1786 $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id, 'fileid' => $file->get_id()));
1787 $button->set_formats(portfolio_format_from_file($file));
1788 $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
1790 $output .= '<br />';
1792 if (count($files) > 1 && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1793 $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id));
1794 $button->set_formats(PORTFOLIO_PORMAT_FILE);
1795 $output .= '<br />' . $button->to_html();
1799 $output = '<div class="files">'.$output.'</div>';
1808 * Count the files uploaded by a given user
1810 * @param $userid int The user id
1813 function count_user_files($userid) {
1814 $fs = get_file_storage();
1815 $files = $fs->get_area_files($this->context->id, 'assignment_submission', $userid, "id", false);
1816 return count($files);
1820 * Returns true if the student is allowed to submit
1822 * Checks that the assignment has started and, if the option to prevent late
1823 * submissions is set, also checks that the assignment has not yet closed.
1828 if ($this->assignment->preventlate && $this->assignment->timedue) {
1829 return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
1831 return ($this->assignment->timeavailable <= $time);
1837 * Return true if is set description is hidden till available date
1839 * This is needed by calendar so that hidden descriptions do not
1840 * come up in upcoming events.
1842 * Check that description is hidden till available date
1843 * By default return false
1844 * Assignments types should implement this method if needed
1847 function description_is_hidden() {
1852 * Return an outline of the user's interaction with the assignment
1854 * The default method prints the grade and timemodified
1855 * @param $user object
1856 * @return object with properties ->info and ->time
1858 function user_outline($user) {
1859 if ($submission = $this->get_submission($user->id)) {
1861 $result = new object();
1862 $result->info = get_string('grade').': '.$this->display_grade($submission->grade);
1863 $result->time = $submission->timemodified;
1870 * Print complete information about the user's interaction with the assignment
1872 * @param $user object
1874 function user_complete($user) {
1875 if ($submission = $this->get_submission($user->id)) {
1877 $fs = get_file_storage();
1878 $browser = get_file_browser();
1880 if ($files = $fs->get_area_files($this->context->id, 'assignment_submission', $user->id, "timemodified", false)) {
1881 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
1882 foreach ($files as $file) {
1883 $countfiles .= "; ".$file->get_filename();
1887 print_simple_box_start();
1888 echo get_string("lastmodified").": ";
1889 echo userdate($submission->timemodified);
1890 echo $this->display_lateness($submission->timemodified);
1892 $this->print_user_files($user->id);
1896 if (empty($submission->timemarked)) {
1897 print_string("notgradedyet", "assignment");
1899 $this->view_feedback($submission);
1902 print_simple_box_end();
1905 print_string("notsubmittedyet", "assignment");
1910 * Return a string indicating how late a submission is
1912 * @param $timesubmitted int
1915 function display_lateness($timesubmitted) {
1916 return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
1920 * Empty method stub for all delete actions.
1923 //nothing by default
1924 redirect('view.php?id='.$this->cm->id);
1928 * Empty custom feedback grading form.
1930 function custom_feedbackform($submission, $return=false) {
1931 //nothing by default
1936 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
1937 * for the course (see resource).
1939 * Given a course_module object, this function returns any "extra" information that may be needed
1940 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
1942 * @param $coursemodule object The coursemodule object (record).
1943 * @return object An object on information that the coures will know about (most noticeably, an icon).
1946 function get_coursemodule_info($coursemodule) {
1951 * Plugin cron method - do not use $this here, create new assignment instances if needed.
1955 //no plugin cron by default - override if needed
1959 * Reset all submissions
1961 function reset_userdata($data) {
1964 if (!$DB->count_records('assignment', array('course'=>$data->courseid, 'assignmenttype'=>$this->type))) {
1965 return array(); // no assignments of this type present
1968 $componentstr = get_string('modulenameplural', 'assignment');
1971 $typestr = get_string('type'.$this->type, 'assignment');
1973 if (!empty($data->reset_assignment_submissions)) {
1974 $assignmentssql = "SELECT a.id
1976 WHERE a.course=? AND a.assignmenttype=?";
1977 $params = array($data->courseid, $this->type);
1979 // now get rid of all submissions and responses
1980 $fs = get_file_storage();
1981 if ($assignments = $DB->get_records_sql($assignmentssql, $params)) {
1982 foreach ($assignments as $assignmentid=>$unused) {
1983 if (!$cm = get_coursemodule_from_instance('assignment', $assignmentid)) {
1986 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1987 $fs->delete_area_files($context->id, 'assignment_submission');
1988 $fs->delete_area_files($context->id, 'assignment_response');
1992 $DB->delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)", $params);
1994 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
1996 if (empty($data->reset_gradebook_grades)) {
1997 // remove all grades from gradebook
1998 assignment_reset_gradebook($data->courseid, $this->type);
2002 /// updating dates - shift may be negative too
2003 if ($data->timeshift) {
2004 shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
2005 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
2012 function portfolio_exportable() {
2015 } ////// End of the assignment_base class
2018 * @package mod-assignment
2019 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
2020 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2022 class mod_assignment_upload_file_form extends moodleform {
2023 function definition() {
2024 $mform = $this->_form;
2025 $instance = $this->_customdata;
2027 //TODO: improve upload size checking
2028 $mform->setMaxFileSize($instance->assignment->maxbytes);
2031 $mform->addElement('file', 'newfile', get_string('uploadafile'));
2034 $mform->addElement('hidden', 'id', $instance->cm->id);
2035 $mform->setType('id', PARAM_INT);
2036 $mform->addElement('hidden', 'action', 'uploadfile');
2037 $mform->setType('action', PARAM_ALPHA);
2040 $this->add_action_buttons(false, get_string('uploadthisfile'));
2045 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
2048 * Deletes an assignment instance
2050 * This is done by calling the delete_instance() method of the assignment type class
2052 function assignment_delete_instance($id){
2055 if (! $assignment = $DB->get_record('assignment', array('id'=>$id))) {
2059 // fall back to base class if plugin missing
2060 $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2061 if (file_exists($classfile)) {
2062 require_once($classfile);
2063 $assignmentclass = "assignment_$assignment->assignmenttype";
2066 debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
2067 $assignmentclass = "assignment_base";
2070 $ass = new $assignmentclass();
2071 return $ass->delete_instance($assignment);
2076 * Updates an assignment instance
2078 * This is done by calling the update_instance() method of the assignment type class
2080 function assignment_update_instance($assignment){
2083 $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2085 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2086 $assignmentclass = "assignment_$assignment->assignmenttype";
2087 $ass = new $assignmentclass();
2088 return $ass->update_instance($assignment);
2093 * Adds an assignment instance
2095 * This is done by calling the add_instance() method of the assignment type class
2097 function assignment_add_instance($assignment) {
2100 $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2102 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2103 $assignmentclass = "assignment_$assignment->assignmenttype";
2104 $ass = new $assignmentclass();
2105 return $ass->add_instance($assignment);
2110 * Returns an outline of a user interaction with an assignment
2112 * This is done by calling the user_outline() method of the assignment type class
2114 function assignment_user_outline($course, $user, $mod, $assignment) {
2117 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2118 $assignmentclass = "assignment_$assignment->assignmenttype";
2119 $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2120 return $ass->user_outline($user);
2124 * Prints the complete info about a user's interaction with an assignment
2126 * This is done by calling the user_complete() method of the assignment type class
2128 function assignment_user_complete($course, $user, $mod, $assignment) {
2131 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2132 $assignmentclass = "assignment_$assignment->assignmenttype";
2133 $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2134 return $ass->user_complete($user);
2138 * Function to be run periodically according to the moodle cron
2140 * Finds all assignment notifications that have yet to be mailed out, and mails them
2142 function assignment_cron () {
2143 global $CFG, $USER, $DB;
2145 /// first execute all crons in plugins
2146 if ($plugins = get_plugin_list('assignment')) {
2147 foreach ($plugins as $plugin=>$dir) {
2148 require_once("$dir/assignment.class.php");
2149 $assignmentclass = "assignment_$plugin";
2150 $ass = new $assignmentclass();
2155 /// Notices older than 1 day will not be mailed. This is to avoid the problem where
2156 /// cron has not been running for a long time, and then suddenly people are flooded
2157 /// with mail from the past few weeks or months
2160 $endtime = $timenow - $CFG->maxeditingtime;
2161 $starttime = $endtime - 24 * 3600; /// One day earlier
2163 if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2165 $realuser = clone($USER);
2167 foreach ($submissions as $key => $submission) {
2168 if (! $DB->set_field("assignment_submissions", "mailed", "1", array("id"=>$submission->id))) {
2169 echo "Could not update the mailed field for id $submission->id. Not mailed.\n";
2170 unset($submissions[$key]);
2176 foreach ($submissions as $submission) {
2178 echo "Processing assignment submission $submission->id\n";
2180 if (! $user = $DB->get_record("user", array("id"=>$submission->userid))) {
2181 echo "Could not find user $post->userid\n";
2185 if (! $course = $DB->get_record("course", array("id"=>$submission->course))) {
2186 echo "Could not find course $submission->course\n";
2190 /// Override the language and timezone of the "current" user, so that
2191 /// mail is customised for the receiver.
2192 cron_setup_user($user, $course);
2194 if (!has_capability('moodle/course:view', get_context_instance(CONTEXT_COURSE, $submission->course), $user->id)) {
2195 echo fullname($user)." not an active participant in " . format_string($course->shortname) . "\n";
2199 if (! $teacher = $DB->get_record("user", array("id"=>$submission->teacher))) {
2200 echo "Could not find teacher $submission->teacher\n";
2204 if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2205 echo "Could not find course module for assignment id $submission->assignment\n";
2209 if (! $mod->visible) { /// Hold mail notification for hidden assignments until later
2213 $strassignments = get_string("modulenameplural", "assignment");
2214 $strassignment = get_string("modulename", "assignment");
2216 $assignmentinfo = new object();
2217 $assignmentinfo->teacher = fullname($teacher);
2218 $assignmentinfo->assignment = format_string($submission->name,true);
2219 $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2221 $postsubject = "$course->shortname: $strassignments: ".format_string($submission->name,true);
2222 $posttext = "$course->shortname -> $strassignments -> ".format_string($submission->name,true)."\n";
2223 $posttext .= "---------------------------------------------------------------------\n";
2224 $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2225 $posttext .= "---------------------------------------------------------------------\n";
2227 if ($user->mailformat == 1) { // HTML
2228 $posthtml = "<p><font face=\"sans-serif\">".
2229 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> ->".
2230 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2231 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2232 $posthtml .= "<hr /><font face=\"sans-serif\">";
2233 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2234 $posthtml .= "</font><hr />";
2239 $eventdata = new object();
2240 $eventdata->modulename = 'assignment';
2241 $eventdata->userfrom = $teacher;
2242 $eventdata->userto = $user;
2243 $eventdata->subject = $postsubject;
2244 $eventdata->fullmessage = $posttext;
2245 $eventdata->fullmessageformat = FORMAT_PLAIN;
2246 $eventdata->fullmessagehtml = $posthtml;
2247 $eventdata->smallmessage = '';
2248 if ( events_trigger('message_send', $eventdata) > 0 ){
2249 echo "Error: assignment cron: Could not send out mail for id $submission->id to user $user->id ($user->email)\n";
2260 * Return grade for given user or all users.
2262 * @param int $assignmentid id of assignment
2263 * @param int $userid optional user id, 0 means all users
2264 * @return array array of grades, false if none
2266 function assignment_get_user_grades($assignment, $userid=0) {
2270 $user = "AND u.id = :userid";
2271 $params = array('userid'=>$userid);
2275 $params['aid'] = $assignment->id;
2277 $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2278 s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2279 FROM {user} u, {assignment_submissions} s
2280 WHERE u.id = s.userid AND s.assignment = :aid
2283 return $DB->get_records_sql($sql, $params);
2287 * Update activity grades
2289 * @param object $assignment
2290 * @param int $userid specific user only, 0 means all
2292 function assignment_update_grades($assignment, $userid=0, $nullifnone=true) {
2294 require_once($CFG->libdir.'/gradelib.php');
2296 if ($assignment->grade == 0) {
2297 assignment_grade_item_update($assignment);
2299 } else if ($grades = assignment_get_user_grades($assignment, $userid)) {
2300 foreach($grades as $k=>$v) {
2301 if ($v->rawgrade == -1) {
2302 $grades[$k]->rawgrade = null;
2305 assignment_grade_item_update($assignment, $grades);
2308 assignment_grade_item_update($assignment);
2313 * Update all grades in gradebook.
2315 function assignment_upgrade_grades() {
2318 $sql = "SELECT COUNT('x')
2319 FROM {assignment} a, {course_modules} cm, {modules} m
2320 WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2321 $count = $DB->count_records_sql($sql);
2323 $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
2324 FROM {assignment} a, {course_modules} cm, {modules} m
2325 WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2326 if ($rs = $DB->get_recordset_sql($sql)) {
2327 // too much debug output
2328 $pbar = new progress_bar('assignmentupgradegrades', 500, true);
2330 foreach ($rs as $assignment) {
2332 upgrade_set_timeout(60*5); // set up timeout, may also abort execution
2333 assignment_update_grades($assignment);
2334 $pbar->update($i, $count, "Updating Assignment grades ($i/$count).");
2337 upgrade_set_timeout(); // reset to default timeout
2342 * Create grade item for given assignment
2344 * @param object $assignment object with extra cmidnumber
2345 * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
2346 * @return int 0 if ok, error code otherwise
2348 function assignment_grade_item_update($assignment, $grades=NULL) {
2350 require_once($CFG->libdir.'/gradelib.php');
2352 if (!isset($assignment->courseid)) {
2353 $assignment->courseid = $assignment->course;
2356 $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
2358 if ($assignment->grade > 0) {
2359 $params['gradetype'] = GRADE_TYPE_VALUE;
2360 $params['grademax'] = $assignment->grade;
2361 $params['grademin'] = 0;
2363 } else if ($assignment->grade < 0) {
2364 $params['gradetype'] = GRADE_TYPE_SCALE;
2365 $params['scaleid'] = -$assignment->grade;
2368 $params['gradetype'] = GRADE_TYPE_TEXT; // allow text comments only
2371 if ($grades === 'reset') {
2372 $params['reset'] = true;
2376 return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades, $params);
2380 * Delete grade item for given assignment
2382 * @param object $assignment object
2383 * @return object assignment
2385 function assignment_grade_item_delete($assignment) {
2387 require_once($CFG->libdir.'/gradelib.php');
2389 if (!isset($assignment->courseid)) {
2390 $assignment->courseid = $assignment->course;
2393 return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
2397 * Returns the users with data in one assignment (students and teachers)
2399 * @param $assignmentid int
2400 * @return array of user objects
2402 function assignment_get_participants($assignmentid) {
2406 $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2408 {assignment_submissions} a
2409 WHERE a.assignment = ? and
2410 u.id = a.userid", array($assignmentid));
2412 $teachers = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2414 {assignment_submissions} a
2415 WHERE a.assignment = ? and
2416 u.id = a.teacher", array($assignmentid));
2418 //Add teachers to students
2420 foreach ($teachers as $teacher) {
2421 $students[$teacher->id] = $teacher;
2424 //Return students array (it contains an array of unique users)
2428 function assignment_pluginfile($course, $cminfo, $context, $filearea, $args) {
2431 if (!$assignment = $DB->get_record('assignment', array('id'=>$cminfo->instance))) {
2434 if (!$cm = get_coursemodule_from_instance('assignment', $assignment->id, $course->id)) {
2438 require_once($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
2439 $assignmentclass = 'assignment_'.$assignment->assignmenttype;
2440 $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm, $course);
2442 return $assignmentinstance->send_file($filearea, $args);
2445 * Checks if a scale is being used by an assignment
2447 * This is used by the backup code to decide whether to back up a scale
2448 * @param $assignmentid int
2449 * @param $scaleid int
2450 * @return boolean True if the scale is used by the assignment
2452 function assignment_scale_used($assignmentid, $scaleid) {
2457 $rec = $DB->get_record('assignment', array('id'=>$assignmentid,'grade'=>-$scaleid));
2459 if (!empty($rec) && !empty($scaleid)) {
2467 * Checks if scale is being used by any instance of assignment
2469 * This is used to find out if scale used anywhere
2470 * @param $scaleid int
2471 * @return boolean True if the scale is used by any assignment
2473 function assignment_scale_used_anywhere($scaleid) {
2476 if ($scaleid and $DB->record_exists('assignment', array('grade'=>-$scaleid))) {
2484 * Make sure up-to-date events are created for all assignment instances
2486 * This standard function will check all instances of this module
2487 * and make sure there are up-to-date events created for each of them.
2488 * If courseid = 0, then every assignment event in the site is checked, else
2489 * only assignment events belonging to the course specified are checked.
2490 * This function is used, in its new format, by restore_refresh_events()
2492 * @param $courseid int optional If zero then all assignments for all courses are covered
2493 * @return boolean Always returns true
2495 function assignment_refresh_events($courseid = 0) {
2498 if ($courseid == 0) {
2499 if (! $assignments = $DB->get_records("assignment")) {
2503 if (! $assignments = $DB->get_records("assignment", array("course"=>$courseid))) {
2507 $moduleid = $DB->get_field('modules', 'id', array('name'=>'assignment'));
2509 foreach ($assignments as $assignment) {
2510 $cm = get_coursemodule_from_id('assignment', $assignment->id);
2511 $event = new object();
2512 $event->name = $assignment->name;
2513 $event->description = format_module_intro('assignment', $assignment, $cm->id);
2514 $event->timestart = $assignment->timedue;
2516 if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
2517 update_event($event);
2520 $event->courseid = $assignment->course;
2521 $event->groupid = 0;
2523 $event->modulename = 'assignment';
2524 $event->instance = $assignment->id;
2525 $event->eventtype = 'due';
2526 $event->timeduration = 0;
2527 $event->visible = $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$assignment->id));
2536 * Print recent activity from all assignments in a given course
2538 * This is used by the recent activity block
2540 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
2541 global $CFG, $USER, $DB;
2543 // do not use log table if possible, it may be huge
2545 if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
2546 u.firstname, u.lastname, u.email, u.picture
2547 FROM {assignment_submissions} asb
2548 JOIN {assignment} a ON a.id = asb.assignment
2549 JOIN {course_modules} cm ON cm.instance = a.id
2550 JOIN {modules} md ON md.id = cm.module
2551 JOIN {user} u ON u.id = asb.userid
2552 WHERE asb.timemodified > ? AND
2554 md.name = 'assignment'
2555 ORDER BY asb.timemodified ASC", array($timestart, $course->id))) {
2559 $modinfo =& get_fast_modinfo($course); // reference needed because we might load the groups
2563 foreach($submissions as $submission) {
2564 if (!array_key_exists($submission->cmid, $modinfo->cms)) {
2567 $cm = $modinfo->cms[$submission->cmid];
2568 if (!$cm->uservisible) {
2571 if ($submission->userid == $USER->id) {
2572 $show[] = $submission;
2576 // the act of sumbitting of assignment may be considered private - only graders will see it if specified
2577 if (empty($CFG->assignment_showrecentsubmissions)) {
2578 if (!array_key_exists($cm->id, $grader)) {
2579 $grader[$cm->id] = has_capability('moodle/grade:viewall', get_context_instance(CONTEXT_MODULE, $cm->id));
2581 if (!$grader[$cm->id]) {
2586 $groupmode = groups_get_activity_groupmode($cm, $course);
2588 if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2589 if (isguestuser()) {
2590 // shortcut - guest user does not belong into any group
2594 if (is_null($modinfo->groups)) {
2595 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2598 // this will be slow - show only users that share group with me in this cm
2599 if (empty($modinfo->groups[$cm->id])) {
2602 $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
2603 if (is_array($usersgroups)) {
2604 $usersgroups = array_keys($usersgroups);
2605 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2606 if (empty($intersect)) {
2611 $show[] = $submission;
2618 print_headline(get_string('newsubmissions', 'assignment').':');
2620 foreach ($show as $submission) {
2621 $cm = $modinfo->cms[$submission->cmid];
2622 $link = $CFG->wwwroot.'/mod/assignment/view.php?id='.$cm->id;
2623 print_recent_activity_note($submission->timemodified, $submission, $cm->name, $link, false, $viewfullnames);
2631 * Returns all assignments since a given time in specified forum.
2633 function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0) {
2634 global $CFG, $COURSE, $USER, $DB;
2636 if ($COURSE->id == $courseid) {
2639 $course = $DB->get_record('course', array('id'=>$courseid));
2642 $modinfo =& get_fast_modinfo($course);
2644 $cm = $modinfo->cms[$cmid];
2648 $userselect = "AND u.id = :userid";
2649 $params['userid'] = $userid;
2655 $groupselect = "AND gm.groupid = :groupid";
2656 $groupjoin = "JOIN {groups_members} gm ON gm.userid=u.id";
2657 $params['groupid'] = $groupid;
2663 $params['cminstance'] = $cm->instance;
2664 $params['timestart'] = $timestart;
2666 if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, asb.userid,
2667 u.firstname, u.lastname, u.email, u.picture
2668 FROM {assignment_submissions} asb
2669 JOIN {assignment} a ON a.id = asb.assignment
2670 JOIN {user} u ON u.id = asb.userid
2672 WHERE asb.timemodified > :timestart AND a.id = :cminstance
2673 $userselect $groupselect
2674 ORDER BY asb.timemodified ASC", $params)) {
2678 $groupmode = groups_get_activity_groupmode($cm, $course);
2679 $cm_context = get_context_instance(CONTEXT_MODULE, $cm->id);
2680 $grader = has_capability('moodle/grade:viewall', $cm_context);
2681 $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
2682 $viewfullnames = has_capability('moodle/site:viewfullnames', $cm_context);
2684 if (is_null($modinfo->groups)) {
2685 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2690 foreach($submissions as $submission) {
2691 if ($submission->userid == $USER->id) {
2692 $show[] = $submission;
2695 // the act of submitting of assignment may be considered private - only graders will see it if specified
2696 if (empty($CFG->assignment_showrecentsubmissions)) {
2702 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
2703 if (isguestuser()) {
2704 // shortcut - guest user does not belong into any group
2708 // this will be slow - show only users that share group with me in this cm
2709 if (empty($modinfo->groups[$cm->id])) {
2712 $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
2713 if (is_array($usersgroups)) {
2714 $usersgroups = array_keys($usersgroups);
2715 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2716 if (empty($intersect)) {
2721 $show[] = $submission;
2729 require_once($CFG->libdir.'/gradelib.php');
2731 foreach ($show as $id=>$submission) {
2732 $userids[] = $submission->userid;
2735 $grades = grade_get_grades($courseid, 'mod', 'assignment', $cm->instance, $userids);
2738 $aname = format_string($cm->name,true);
2739 foreach ($show as $submission) {
2740 $tmpactivity = new object();
2742 $tmpactivity->type = 'assignment';
2743 $tmpactivity->cmid = $cm->id;
2744 $tmpactivity->name = $aname;
2745 $tmpactivity->sectionnum = $cm->sectionnum;
2746 $tmpactivity->timestamp = $submission->timemodified;
2749 $tmpactivity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
2752 $tmpactivity->user->userid = $submission->userid;
2753 $tmpactivity->user->fullname = fullname($submission, $viewfullnames);
2754 $tmpactivity->user->picture = $submission->picture;
2756 $activities[$index++] = $tmpactivity;
2763 * Print recent activity from all assignments in a given course
2765 * This is used by course/recent.php
2767 function assignment_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
2768 global $CFG, $OUTPUT;
2770 echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
2772 echo "<tr><td class=\"userpicture\" valign=\"top\">";
2773 print_user_picture($activity->user->userid, $courseid, $activity->user->picture);
2777 $modname = $modnames[$activity->type];
2778 echo '<div class="title">';
2779 echo "<img src=\"" . $OUTPUT->mod_icon_url('icon', 'assignment') . "\" ".
2780 "class=\"icon\" alt=\"$modname\">";
2781 echo "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id={$activity->cmid}\">{$activity->name}</a>";
2785 if (isset($activity->grade)) {
2786 echo '<div class="grade">';
2787 echo get_string('grade').': ';
2788 echo $activity->grade;
2792 echo '<div class="user">';
2793 echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->userid}&course=$courseid\">"
2794 ."{$activity->user->fullname}</a> - ".userdate($activity->timestamp);
2797 echo "</td></tr></table>";
2800 /// GENERIC SQL FUNCTIONS
2803 * Fetch info from logs
2805 * @param $log object with properties ->info (the assignment id) and ->userid
2806 * @return array with assignment name and user firstname and lastname
2808 function assignment_log_info($log) {
2811 return $DB->get_record_sql("SELECT a.name, u.firstname, u.lastname
2812 FROM {assignment} a, {user} u
2813 WHERE a.id = ? AND u.id = ?", array($log->info, $log->userid));
2817 * Return list of marked submissions that have not been mailed out for currently enrolled students
2821 function assignment_get_unmailed_submissions($starttime, $endtime) {
2824 return $DB->get_records_sql("SELECT s.*, a.course, a.name
2825 FROM {assignment_submissions} s,
2828 AND s.timemarked <= ?
2829 AND s.timemarked >= ?
2830 AND s.assignment = a.id", array($endtime, $starttime));
2834 * Counts all real assignment submissions by ENROLLED students (not empty ones)
2836 * There are also assignment type methods count_real_submissions() wich in the default
2837 * implementation simply call this function.
2838 * @param $groupid int optional If nonzero then count is restricted to this group
2839 * @return int The number of submissions
2841 function assignment_count_real_submissions($cm, $groupid=0) {
2844 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2846 // this is all the users with this capability set, in this context or higher
2847 if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $groupid, '', false)) {
2848 $users = array_keys($users);
2851 // if groupmembersonly used, remove users who are not in any group
2852 if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
2853 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
2854 $users = array_intersect($users, array_keys($groupingusers));
2858 if (empty($users)) {
2862 $userlists = implode(',', $users);
2864 return $DB->count_records_sql("SELECT COUNT('x')
2865 FROM {assignment_submissions}
2866 WHERE assignment = ? AND
2867 timemodified > 0 AND
2868 userid IN ($userlists)", array($cm->instance));
2873 * Return all assignment submissions by ENROLLED students (even empty)
2875 * There are also assignment type methods get_submissions() wich in the default
2876 * implementation simply call this function.
2877 * @param $sort string optional field names for the ORDER BY in the sql query
2878 * @param $dir string optional specifying the sort direction, defaults to DESC
2879 * @return array The submission objects indexed by id
2881 function assignment_get_all_submissions($assignment, $sort="", $dir="DESC") {
2882 /// Return all assignment submissions by ENROLLED students (even empty)
2885 if ($sort == "lastname" or $sort == "firstname") {
2886 $sort = "u.$sort $dir";
2887 } else if (empty($sort)) {
2888 $sort = "a.timemodified DESC";
2890 $sort = "a.$sort $dir";
2893 /* not sure this is needed at all since assignmenet already has a course define, so this join?
2894 $select = "s.course = '$assignment->course' AND";
2895 if ($assignment->course == SITEID) {
2899 return $DB->get_records_sql("SELECT a.*
2900 FROM {assignment_submissions} a, {user} u
2901 WHERE u.id = a.userid
2902 AND a.assignment = ?
2903 ORDER BY $sort", array($assignment->id));
2908 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
2909 * for the course (see resource).
2911 * Given a course_module object, this function returns any "extra" information that may be needed
2912 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
2914 * @param $coursemodule object The coursemodule object (record).
2915 * @return object An object on information that the coures will know about (most noticeably, an icon).
2918 function assignment_get_coursemodule_info($coursemodule) {
2921 if (! $assignment = $DB->get_record('assignment', array('id'=>$coursemodule->instance), 'id, assignmenttype, name')) {
2925 $libfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2927 if (file_exists($libfile)) {
2928 require_once($libfile);
2929 $assignmentclass = "assignment_$assignment->assignmenttype";
2930 $ass = new $assignmentclass('staticonly');
2931 if ($result = $ass->get_coursemodule_info($coursemodule)) {
2934 $info = new object();
2935 $info->name = $assignment->name;
2940 debugging('Incorrect assignment type: '.$assignment->assignmenttype);
2947 /// OTHER GENERAL FUNCTIONS FOR ASSIGNMENTS ///////////////////////////////////////
2950 * Returns an array of installed assignment types indexed and sorted by name
2952 * @return array The index is the name of the assignment type, the value its full name from the language strings
2954 function assignment_types() {
2956 $names = get_plugin_list('assignment');
2957 foreach ($names as $name=>$dir) {
2958 $types[$name] = get_string('type'.$name, 'assignment');
2964 function assignment_print_overview($courses, &$htmlarray) {
2965 global $USER, $CFG, $DB;
2967 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
2971 if (!$assignments = get_all_instances_in_courses('assignment',$courses)) {
2975 $assignmentids = array();
2977 // Do assignment_base::isopen() here without loading the whole thing for speed
2978 foreach ($assignments as $key => $assignment) {
2980 if ($assignment->timedue) {
2981 if ($assignment->preventlate) {
2982 $isopen = ($assignment->timeavailable <= $time && $time <= $assignment->timedue);
2984 $isopen = ($assignment->timeavailable <= $time);
2987 if (empty($isopen) || empty($assignment->timedue)) {
2988 unset($assignments[$key]);
2990 $assignmentids[] = $assignment->id;
2994 if(empty($assignmentids)){
2995 // no assigments to look at - we're done
2999 $strduedate = get_string('duedate', 'assignment');
3000 $strduedateno = get_string('duedateno', 'assignment');
3001 $strgraded = get_string('graded', 'assignment');
3002 $strnotgradedyet = get_string('notgradedyet', 'assignment');
3003 $strnotsubmittedyet = get_string('notsubmittedyet', 'assignment');
3004 $strsubmitted = get_string('submitted', 'assignment');
3005 $strassignment = get_string('modulename', 'assignment');
3006 $strreviewed = get_string('reviewed','assignment');
3009 // NOTE: we do all possible database work here *outside* of the loop to ensure this scales
3011 list($sqlassignmentids, $assignmentidparams) = $DB->get_in_or_equal($assignmentids);
3013 // build up and array of unmarked submissions indexed by assigment id/ userid
3014 // for use where the user has grading rights on assigment
3015 $rs = $DB->get_recordset_sql("SELECT id, assignment, userid
3016 FROM {assignment_submissions}
3017 WHERE teacher = 0 AND timemarked = 0
3018 AND assignment $sqlassignmentids", $assignmentidparams);
3020 $unmarkedsubmissions = array();
3021 foreach ($rs as $rd) {
3022 $unmarkedsubmissions[$rd->assignment][$rd->userid] = $rd->id;
3027 // get all user submissions, indexed by assigment id
3028 $mysubmissions = $DB->get_records_sql("SELECT assignment, timemarked, teacher, grade
3029 FROM {assignment_submissions}
3030 WHERE userid = ? AND
3031 assignment $sqlassignmentids", array_merge(array($USER->id), $assignmentidparams));
3033 foreach ($assignments as $assignment) {
3034 $str = '<div class="assignment overview"><div class="name">'.$strassignment. ': '.
3035 '<a '.($assignment->visible ? '':' class="dimmed"').
3036 'title="'.$strassignment.'" href="'.$CFG->wwwroot.
3037 '/mod/assignment/view.php?id='.$assignment->coursemodule.'">'.
3038 $assignment->name.'</a></div>';
3039 if ($assignment->timedue) {
3040 $str .= '<div class="info">'.$strduedate.': '.userdate($assignment->timedue).'</div>';
3042 $str .= '<div class="info">'.$strduedateno.'</div>';
3044 $context = get_context_instance(CONTEXT_MODULE, $assignment->coursemodule);
3045 if (has_capability('mod/assignment:grade', $context)) {
3047 // count how many people can submit
3048 $submissions = 0; // init
3049 if ($students = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', 0, '', false)) {
3050 foreach($students as $student){
3051 if(isset($unmarkedsubmissions[$assignment->id][$student->id])){
3058 $str .= get_string('submissionsnotgraded', 'assignment', $submissions);
3061 if(isset($mysubmissions[$assignment->id])){
3063 $submission = $mysubmissions[$assignment->id];
3065 if ($submission->teacher == 0 && $submission->timemarked == 0) {
3066 $str .= $strsubmitted . ', ' . $strnotgradedyet;
3067 } else if ($submission->grade <= 0) {
3068 $str .= $strsubmitted . ', ' . $strreviewed;
3070 $str .= $strsubmitted . ', ' . $strgraded;
3073 $str .= $strnotsubmittedyet . ' ' . assignment_display_lateness(time(), $assignment->timedue);
3077 if (empty($htmlarray[$assignment->course]['assignment'])) {
3078 $htmlarray[$assignment->course]['assignment'] = $str;
3080 $htmlarray[$assignment->course]['assignment'] .= $str;
3085 function assignment_display_lateness($timesubmitted, $timedue) {
3089 $time = $timedue - $timesubmitted;
3091 $timetext = get_string('late', 'assignment', format_time($time));
3092 return ' (<span class="late">'.$timetext.'</span>)';
3094 $timetext = get_string('early', 'assignment', format_time($time));
3095 return ' (<span class="early">'.$timetext.'</span>)';
3099 function assignment_get_view_actions() {
3100 return array('view');
3103 function assignment_get_post_actions() {
3104 return array('upload');
3107 function assignment_get_types() {
3111 $type = new object();
3112 $type->modclass = MOD_CLASS_ACTIVITY;
3113 $type->type = "assignment_group_start";
3114 $type->typestr = '--'.get_string('modulenameplural', 'assignment');
3117 $standardassignments = array('upload','online','uploadsingle','offline');
3118 foreach ($standardassignments as $assignmenttype) {
3119 $type = new object();
3120 $type->modclass = MOD_CLASS_ACTIVITY;
3121 $type->type = "assignment&type=$assignmenttype";
3122 $type->typestr = get_string("type$assignmenttype", 'assignment');
3126 /// Drop-in extra assignment types
3127 $assignmenttypes = get_list_of_plugins('mod/assignment/type');
3128 foreach ($assignmenttypes as $assignmenttype) {
3129 if (!empty($CFG->{'assignment_hide_'.$assignmenttype})) { // Not wanted
3132 if (!in_array($assignmenttype, $standardassignments)) {
3133 $type = new object();
3134 $type->modclass = MOD_CLASS_ACTIVITY;
3135 $type->type = "assignment&type=$assignmenttype";
3136 $type->typestr = get_string("type$assignmenttype", 'assignment');
3141 $type = new object();
3142 $type->modclass = MOD_CLASS_ACTIVITY;
3143 $type->type = "assignment_group_end";
3144 $type->typestr = '--';
3151 * Removes all grades from gradebook
3152 * @param int $courseid
3153 * @param string optional type
3155 function assignment_reset_gradebook($courseid, $type='') {
3158 $params = array('courseid'=>$courseid);
3160 $type = "AND a.assignmenttype= :type";
3161 $params['type'] = $type;
3164 $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
3165 FROM {assignment} a, {course_modules} cm, {modules} m
3166 WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id AND a.course=:courseid $type";
3168 if ($assignments = $DB->get_records_sql($sql, $params)) {
3169 foreach ($assignments as $assignment) {
3170 assignment_grade_item_update($assignment, 'reset');
3176 * This function is used by the reset_course_userdata function in moodlelib.
3177 * This function will remove all posts from the specified assignment
3178 * and clean up any related data.
3179 * @param $data the data submitted from the reset course.
3180 * @return array status array
3182 function assignment_reset_userdata($data) {
3187 foreach (get_plugin_list('mod/assignment/type') as $type=>$dir) {
3188 require_once("$dir/assignment.class.php");
3189 $assignmentclass = "assignment_$type";
3190 $ass = new $assignmentclass();
3191 $status = array_merge($status, $ass->reset_userdata($data));
3198 * Implementation of the function for printing the form elements that control
3199 * whether the course reset functionality affects the assignment.
3200 * @param $mform form passed by reference
3202 function assignment_reset_course_form_definition(&$mform) {
3203 $mform->addElement('header', 'assignmentheader', get_string('modulenameplural', 'assignment'));
3204 $mform->addElement('advcheckbox', 'reset_assignment_submissions', get_string('deleteallsubmissions','assignment'));
3208 * Course reset form defaults.
3210 function assignment_reset_course_form_defaults($course) {
3211 return array('reset_assignment_submissions'=>1);
3215 * Returns all other caps used in module
3217 function assignment_get_extra_capabilities() {
3218 return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames');
3222 * @package mod-assignment
3223 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
3224 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3226 class assignment_portfolio_caller extends portfolio_module_caller_base {
3229 * the assignment subclass
3231 private $assignment;
3234 * the file to include when waking up to load the assignment subclass def
3236 private $assignmentfile;
3239 * callback arg for a single file export
3243 public static function expected_callbackargs() {
3250 public function load_data() {
3253 if (! $this->cm = get_coursemodule_from_id('assignment', $this->id)) {
3254 throw new portfolio_caller_exception('invalidcoursemodule');
3257 if (! $assignment = $DB->get_record("assignment", array("id"=>$this->cm->instance))) {
3258 throw new portfolio_caller_exception('invalidid', 'assignment');
3261 $this->assignmentfile = $CFG->dirroot . '/mod/assignment/type/' . $assignment->assignmenttype . '/assignment.class.php';
3262 require_once($this->assignmentfile);
3263 $assignmentclass = "assignment_$assignment->assignmenttype";
3265 $this->assignment = new $assignmentclass($this->cm->id, $assignment, $this->cm);
3267 if (!$this->assignment->portfolio_exportable()) {
3268 throw new portfolio_caller_exception('notexportable', 'portfolio', $this->get_return_url());
3271 $this->set_file_and_format_data($this->fileid, $this->assignment->context->id, 'assignment_submission', $this->user->id);
3272 if (empty($this->supportedformats) && is_callable(array($this->assignment, 'portfolio_supported_formats'))) {
3273 $this->supportedformats = $this->assignment->portfolio_supported_formats();
3277 public function prepare_package() {
3279 if (is_callable(array($this->assignment, 'portfolio_prepare_package'))) {
3280 return $this->assignment->portfolio_prepare_package($this->exporter, $this->user->id);
3282 return $this->prepare_package_file();
3285 public function get_sha1() {
3287 if (is_callable(array($this->assignment, 'portfolio_get_sha1'))) {
3288 return $this->assignment->portfolio_get_sha1($this->user->id);
3290 return $this->get_sha1_file();
3293 public function expected_time() {
3294 if (is_callable(array($this->assignment, 'portfolio_get_expected_time'))) {
3295 return $this->assignment->portfolio_get_expected_time();
3297 return $this->expected_time_file();
3300 public function check_permissions() {
3301 $context = get_context_instance(CONTEXT_MODULE, $this->assignment->cm->id);
3302 return has_capability('mod/assignment:exportownsubmission', $context);
3305 public function __wakeup() {
3308 return true; // too early yet
3310 require_once($this->assignmentfile);
3311 $this->assignment = unserialize(serialize($this->assignment));
3314 public static function display_name() {
3315 return get_string('modulename', 'assignment');
3320 * @param string $feature FEATURE_xx constant for requested feature
3321 * @return mixed True if module supports feature, null if doesn't know
3323 function assignment_supports($feature) {
3325 case FEATURE_GROUPS: return true;
3326 case FEATURE_GROUPINGS: return true;
3327 case FEATURE_GROUPMEMBERSONLY: return true;
3328 case FEATURE_MOD_INTRO: return true;
3329 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
3330 case FEATURE_GRADE_HAS_GRADE: return true;
3331 case FEATURE_GRADE_OUTCOMES: return true;
3332 case FEATURE_MOD_SUBPLUGINS: return array('assignment'=>'mod/assignment/type'); // to be hopefully removed in 2.0
3334 default: return null;