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='') {
181 global $CFG, $PAGE, $OUTPUT;
184 $PAGE->navbar->add($subpage);
187 $PAGE->set_title($this->pagetitle);
188 $PAGE->set_heading($this->course->fullname);
189 $PAGE->set_button($OUTPUT->update_module_button($this->cm->id, 'assignment'));
191 echo $OUTPUT->header();
193 groups_print_activity_menu($this->cm, 'view.php?id=' . $this->cm->id);
195 echo '<div class="reportlink">'.$this->submittedlink().'</div>';
196 echo '<div class="clearer"></div>';
201 * Display the assignment intro
203 * This will most likely be extended by assignment type plug-ins
204 * The default implementation prints the assignment description in a box
206 function view_intro() {
208 echo $OUTPUT->box_start('generalbox boxaligncenter', 'intro');
209 echo format_module_intro('assignment', $this->assignment, $this->cm->id);
210 echo $OUTPUT->box_end();
214 * Display the assignment dates
216 * Prints the assignment start and end dates in a box.
217 * This will be suitable for most assignment types
219 function view_dates() {
221 if (!$this->assignment->timeavailable && !$this->assignment->timedue) {
225 echo $OUTPUT->box_start('generalbox boxaligncenter', '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 echo $OUTPUT->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() {
248 echo $OUTPUT->footer();
252 * Display the feedback to the student
254 * This default method prints the teacher picture and name, date when marked,
255 * grade and teacher submissioncomment.
260 * @param object $submission The submission object or NULL in which case it will be loaded
262 function view_feedback($submission=NULL) {
263 global $USER, $CFG, $DB, $OUTPUT;
264 require_once($CFG->libdir.'/gradelib.php');
266 if (!has_capability('mod/assignment:submit', $this->context, $USER->id, false)) {
267 // can not submit assignments -> no feedback
271 if (!$submission) { /// Get submission for this assignment
272 $submission = $this->get_submission($USER->id);
275 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $USER->id);
276 $item = $grading_info->items[0];
277 $grade = $item->grades[$USER->id];
279 if ($grade->hidden or $grade->grade === false) { // hidden or error
283 if ($grade->grade === null and empty($grade->str_feedback)) { /// Nothing to show yet
287 $graded_date = $grade->dategraded;
288 $graded_by = $grade->usermodified;
290 /// We need the teacher info
291 if (!$teacher = $DB->get_record('user', array('id'=>$graded_by))) {
292 print_error('cannotfindteacher');
295 /// Print the feedback
296 echo $OUTPUT->heading(get_string('feedbackfromteacher', 'assignment', fullname($teacher)));
298 echo '<table cellspacing="0" class="feedback">';
301 echo '<td class="left picture">';
303 echo $OUTPUT->user_picture(moodle_user_picture::make($teacher, $this->course->id));
306 echo '<td class="topic">';
307 echo '<div class="from">';
309 echo '<div class="fullname">'.fullname($teacher).'</div>';
311 echo '<div class="time">'.userdate($graded_date).'</div>';
317 echo '<td class="left side"> </td>';
318 echo '<td class="content">';
319 echo '<div class="grade">';
320 echo get_string("grade").': '.$grade->str_long_grade;
322 echo '<div class="clearer"></div>';
324 echo '<div class="comment">';
325 echo $grade->str_feedback;
333 * Returns a link with info about the state of the assignment submissions
335 * This is used by view_header to put this link at the top right of the page.
336 * For teachers it gives the number of submitted assignments with a link
337 * For students it gives the time of their submission.
338 * This will be suitable for most assignment types.
342 * @param bool $allgroup print all groups info if user can access all groups, suitable for index.php
345 function submittedlink($allgroups=false) {
350 $urlbase = "{$CFG->wwwroot}/mod/assignment/";
352 $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
353 if (has_capability('mod/assignment:grade', $context)) {
354 if ($allgroups and has_capability('moodle/site:accessallgroups', $context)) {
357 $group = groups_get_activity_group($this->cm);
359 if ($count = $this->count_real_submissions($group)) {
360 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
361 get_string('viewsubmissions', 'assignment', $count).'</a>';
363 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
364 get_string('noattempts', 'assignment').'</a>';
367 if (!empty($USER->id)) {
368 if ($submission = $this->get_submission($USER->id)) {
369 if ($submission->timemodified) {
370 if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
371 $submitted = '<span class="early">'.userdate($submission->timemodified).'</span>';
373 $submitted = '<span class="late">'.userdate($submission->timemodified).'</span>';
385 * @todo Document this function
387 function setup_elements(&$mform) {
392 * Create a new assignment activity
394 * Given an object containing all the necessary data,
395 * (defined by the form in mod_form.php) this function
396 * will create a new instance and return the id number
397 * of the new instance.
398 * The due data is added to the calendar
399 * This is common to all assignment types.
403 * @param object $assignment The data from the form on mod_form.php
404 * @return int The id of the assignment
406 function add_instance($assignment) {
409 $assignment->timemodified = time();
410 $assignment->courseid = $assignment->course;
412 if ($returnid = $DB->insert_record("assignment", $assignment)) {
413 $assignment->id = $returnid;
415 if ($assignment->timedue) {
416 $event = new object();
417 $event->name = $assignment->name;
418 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
419 $event->courseid = $assignment->course;
422 $event->modulename = 'assignment';
423 $event->instance = $returnid;
424 $event->eventtype = 'due';
425 $event->timestart = $assignment->timedue;
426 $event->timeduration = 0;
431 assignment_grade_item_update($assignment);
440 * Deletes an assignment activity
442 * Deletes all database records, files and calendar events for this assignment.
446 * @param object $assignment The assignment to be deleted
447 * @return boolean False indicates error
449 function delete_instance($assignment) {
452 $assignment->courseid = $assignment->course;
456 // now get rid of all files
457 $fs = get_file_storage();
458 if ($cm = get_coursemodule_from_instance('assignment', $assignment->id)) {
459 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
460 $fs->delete_area_files($context->id);
463 if (! $DB->delete_records('assignment_submissions', array('assignment'=>$assignment->id))) {
467 if (! $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
471 if (! $DB->delete_records('assignment', array('id'=>$assignment->id))) {
475 assignment_grade_item_delete($assignment);
481 * Updates a new assignment activity
483 * Given an object containing all the necessary data,
484 * (defined by the form in mod_form.php) this function
485 * will update the assignment instance and return the id number
486 * The due date is updated in the calendar
487 * This is common to all assignment types.
491 * @param object $assignment The data from the form on mod_form.php
492 * @return int The assignment id
494 function update_instance($assignment) {
497 $assignment->timemodified = time();
499 $assignment->id = $assignment->instance;
500 $assignment->courseid = $assignment->course;
502 $DB->update_record('assignment', $assignment);
504 if ($assignment->timedue) {
505 $event = new object();
507 if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
509 $event->name = $assignment->name;
510 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
511 $event->timestart = $assignment->timedue;
513 update_event($event);
515 $event = new object();
516 $event->name = $assignment->name;
517 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
518 $event->courseid = $assignment->course;
521 $event->modulename = 'assignment';
522 $event->instance = $assignment->id;
523 $event->eventtype = 'due';
524 $event->timestart = $assignment->timedue;
525 $event->timeduration = 0;
530 $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id));
533 // get existing grade item
534 assignment_grade_item_update($assignment);
540 * Update grade item for this submission.
542 function update_grade($submission) {
543 assignment_update_grades($this->assignment, $submission->userid);
547 * Top-level function for handling of submissions called by submissions.php
549 * This is for handling the teacher interaction with the grading interface
550 * This should be suitable for most assignment types.
553 * @param string $mode Specifies the kind of teacher interaction taking place
555 function submissions($mode) {
556 ///The main switch is changed to facilitate
557 ///1) Batch fast grading
558 ///2) Skip to the next one on the popup
559 ///3) Save and Skip to the next one on the popup
561 //make user global so we can use the id
562 global $USER, $OUTPUT;
564 $mailinfo = optional_param('mailinfo', null, PARAM_BOOL);
565 if (is_null($mailinfo)) {
566 $mailinfo = get_user_preferences('assignment_mailinfo', 0);
568 set_user_preference('assignment_mailinfo', $mailinfo);
572 case 'grade': // We are in a popup window grading
573 if ($submission = $this->process_feedback()) {
574 //IE needs proper header with encoding
575 $PAGE->set_title(get_string('feedback', 'assignment').':'.format_string($this->assignment->name));
576 echo $OUTPUT->header();
577 echo $OUTPUT->heading(get_string('changessaved'));
578 print $this->update_main_listing($submission);
583 case 'single': // We are in a popup window displaying submission
584 $this->display_submission();
587 case 'all': // Main window, display everything
588 $this->display_submissions();
592 ///do the fast grading stuff - this process should work for all 3 subclasses
597 if (isset($_POST['submissioncomment'])) {
598 $col = 'submissioncomment';
601 if (isset($_POST['menu'])) {
606 //both submissioncomment and grade columns collapsed..
607 $this->display_submissions();
611 foreach ($_POST[$col] as $id => $unusedvalue){
613 $id = (int)$id; //clean parameter name
615 $this->process_outcomes($id);
617 if (!$submission = $this->get_submission($id)) {
618 $submission = $this->prepare_new_submission($id);
619 $newsubmission = true;
621 $newsubmission = false;
623 unset($submission->data1); // Don't need to update this.
624 unset($submission->data2); // Don't need to update this.
626 //for fast grade, we need to check if any changes take place
630 $grade = $_POST['menu'][$id];
631 $updatedb = $updatedb || ($submission->grade != $grade);
632 $submission->grade = $grade;
634 if (!$newsubmission) {
635 unset($submission->grade); // Don't need to update this.
639 $commentvalue = trim($_POST['submissioncomment'][$id]);
640 $updatedb = $updatedb || ($submission->submissioncomment != $commentvalue);
641 $submission->submissioncomment = $commentvalue;
643 unset($submission->submissioncomment); // Don't need to update this.
646 $submission->teacher = $USER->id;
648 $submission->mailed = (int)(!$mailinfo);
651 $submission->timemarked = time();
653 //if it is not an update, we don't change the last modified time etc.
654 //this will also not write into database if no submissioncomment and grade is entered.
657 if ($newsubmission) {
658 if (!isset($submission->submissioncomment)) {
659 $submission->submissioncomment = '';
661 $sid = $DB->insert_record('assignment_submissions', $submission);
662 $submission->id = $sid;
664 $DB->update_record('assignment_submissions', $submission);
667 // triger grade event
668 $this->update_grade($submission);
670 //add to log only if updating
671 add_to_log($this->course->id, 'assignment', 'update grades',
672 'submissions.php?id='.$this->assignment->id.'&user='.$submission->userid,
673 $submission->userid, $this->cm->id);
678 $message = $OUTPUT->notification(get_string('changessaved'), 'notifysuccess');
680 $this->display_submissions($message);
685 /// We are currently in pop up, but we want to skip to next one without saving.
686 /// This turns out to be similar to a single case
687 /// The URL used is for the next submission.
689 $this->display_submission();
693 ///We are in pop up. save the current one and go to the next one.
694 //first we save the current changes
695 if ($submission = $this->process_feedback()) {
696 //print_heading(get_string('changessaved'));
697 $extra_javascript = $this->update_main_listing($submission);
700 //then we display the next submission
701 $this->display_submission($extra_javascript);
705 echo "something seriously is wrong!!";
711 * Helper method updating the listing on the main script from popup using javascript
715 * @param $submission object The submission whose data is to be updated on the main page
717 function update_main_listing($submission) {
718 global $SESSION, $CFG, $OUTPUT;
722 $perpage = get_user_preferences('assignment_perpage', 10);
724 $quickgrade = get_user_preferences('assignment_quickgrade', 0);
726 /// Run some Javascript to try and update the parent page
727 $output .= '<script type="text/javascript">'."\n<!--\n";
728 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['submissioncomment'])) {
730 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid.'").value="'
731 .trim($submission->submissioncomment).'";'."\n";
733 $output.= 'opener.document.getElementById("com'.$submission->userid.
734 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment)), 15)."\";\n";
738 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['grade'])) {
739 //echo optional_param('menuindex');
741 $output.= 'opener.document.getElementById("menumenu'.$submission->userid.
742 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT).'";'."\n";
744 $output.= 'opener.document.getElementById("g'.$submission->userid.'").innerHTML="'.
745 $this->display_grade($submission->grade)."\";\n";
748 //need to add student's assignments in there too.
749 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemodified']) &&
750 $submission->timemodified) {
751 $output.= 'opener.document.getElementById("ts'.$submission->userid.
752 '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid)).userdate($submission->timemodified)."\";\n";
755 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemarked']) &&
756 $submission->timemarked) {
757 $output.= 'opener.document.getElementById("tt'.$submission->userid.
758 '").innerHTML="'.userdate($submission->timemarked)."\";\n";
761 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['status'])) {
762 $output.= 'opener.document.getElementById("up'.$submission->userid.'").className="s1";';
763 $buttontext = get_string('update');
764 $url = new moodle_url('/mod/assignment/submissions.php', array(
765 'id' => $this->cm->id,
766 'userid' => $submission->userid,
768 'offset' => (optional_param('offset', '', PARAM_INT)-1)));
770 $link = html_link::make($url, $buttontext);
771 $link->add_action(new popup_action('click', $link->url, 'grade'.$submission->userid, array('height' => 450, 'width' => 700)));
772 $link->title = $buttontext;
773 $button = $OUTPUT->link($link);
775 $output.= 'opener.document.getElementById("up'.$submission->userid.'").innerHTML="'.addslashes_js($button).'";';
778 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $submission->userid);
780 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['finalgrade'])) {
781 $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid.
782 '").innerHTML="'.$grading_info->items[0]->grades[$submission->userid]->str_grade.'";'."\n";
785 if (!empty($CFG->enableoutcomes) and empty($SESSION->flextable['mod-assignment-submissions']->collapse['outcome'])) {
787 if (!empty($grading_info->outcomes)) {
788 foreach($grading_info->outcomes as $n=>$outcome) {
789 if ($outcome->grades[$submission->userid]->locked) {
794 $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.
795 '").selectedIndex="'.$outcome->grades[$submission->userid]->grade.'";'."\n";
798 $options = make_grades_menu(-$outcome->scaleid);
799 $options[0] = get_string('nooutcome', 'grades');
800 $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.'").innerHTML="'.$options[$outcome->grades[$submission->userid]->grade]."\";\n";
807 $output .= "\n-->\n</script>";
812 * Return a grade in user-friendly form, whether it's a scale or not
815 * @param mixed $grade
816 * @return string User-friendly representation of grade
818 function display_grade($grade) {
821 static $scalegrades = array(); // Cache scales for each assignment - they might have different scales!!
823 if ($this->assignment->grade >= 0) { // Normal number
827 return $grade.' / '.$this->assignment->grade;
831 if (empty($scalegrades[$this->assignment->id])) {
832 if ($scale = $DB->get_record('scale', array('id'=>-($this->assignment->grade)))) {
833 $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
838 if (isset($scalegrades[$this->assignment->id][$grade])) {
839 return $scalegrades[$this->assignment->id][$grade];
846 * Display a single submission, ready for grading on a popup window
848 * This default method prints the teacher info and submissioncomment box at the top and
849 * the student info and submission at the bottom.
850 * This method also fetches the necessary data in order to be able to
851 * provide a "Next submission" button.
852 * Calls preprocess_submission() to give assignment type plug-ins a chance
853 * to process submissions before they are graded
854 * This method gets its arguments from the page parameters userid and offset
858 * @param string $extra_javascript
860 function display_submission($extra_javascript = '') {
861 global $CFG, $DB, $PAGE, $OUTPUT;
862 require_once($CFG->libdir.'/gradelib.php');
863 require_once($CFG->libdir.'/tablelib.php');
865 $userid = required_param('userid', PARAM_INT);
866 $offset = required_param('offset', PARAM_INT);//offset for where to start looking for student.
868 if (!$user = $DB->get_record('user', array('id'=>$userid))) {
869 print_error('nousers');
872 if (!$submission = $this->get_submission($user->id)) {
873 $submission = $this->prepare_new_submission($userid);
875 if ($submission->timemodified > $submission->timemarked) {
876 $subtype = 'assignmentnew';
878 $subtype = 'assignmentold';
881 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
882 $disabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
884 /// construct SQL, using current offset to find the data of the next student
885 $course = $this->course;
886 $assignment = $this->assignment;
888 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
890 /// Get all ppl that can submit assignments
892 $currentgroup = groups_get_activity_group($cm);
893 if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $currentgroup, '', false)) {
894 $users = array_keys($users);
897 // if groupmembersonly used, remove users who are not in any group
898 if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
899 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
900 $users = array_intersect($users, array_keys($groupingusers));
907 $select = 'SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt,
908 s.id AS submissionid, s.grade, s.submissioncomment,
909 s.timemodified, s.timemarked,
910 COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ';
911 $sql = 'FROM {user} u '.
912 'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
913 AND s.assignment = '.$this->assignment->id.' '.
914 'WHERE u.id IN ('.implode(',', $users).') ';
916 if ($sort = flexible_table::get_sql_sort('mod-assignment-submissions')) {
917 $sort = 'ORDER BY '.$sort.' ';
920 if (($auser = $DB->get_records_sql($select.$sql.$sort, null, $offset+1, 1)) !== false) {
921 $nextuser = array_shift($auser);
922 /// Calculate user status
923 $nextuser->status = ($nextuser->timemarked > 0) && ($nextuser->timemarked >= $nextuser->timemodified);
924 $nextid = $nextuser->id;
928 $PAGE->set_title(get_string('feedback', 'assignment').':'.fullname($user, true).':'.format_string($this->assignment->name));
929 echo $OUTPUT->header();
931 /// Print any extra javascript needed for saveandnext
932 echo $extra_javascript;
934 echo $PAGE->requires->data_for_js('assignment', Array('nextid'=>$nextid, 'userid'=>$userid))->asap();
935 echo $PAGE->requires->js('mod/assignment/assignment.js')->asap();
937 echo '<table cellspacing="0" class="feedback '.$subtype.'" >';
939 ///Start of teacher info row
942 echo '<td class="picture teacher">';
943 if ($submission->teacher) {
944 $teacher = $DB->get_record('user', array('id'=>$submission->teacher));
949 echo $OUTPUT->user_picture(moodle_user_picture::make($teacher, $this->course->id));
951 echo '<td class="content">';
952 echo '<form id="submitform" action="submissions.php" method="post">';
953 echo '<div>'; // xhtml compatibility - invisiblefieldset was breaking layout here
954 echo '<input type="hidden" name="offset" value="'.($offset+1).'" />';
955 echo '<input type="hidden" name="userid" value="'.$userid.'" />';
956 echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
957 echo '<input type="hidden" name="mode" value="grade" />';
958 echo '<input type="hidden" name="menuindex" value="0" />';//selected menu index
960 //new hidden field, initialized to -1.
961 echo '<input type="hidden" name="saveuserid" value="-1" />';
963 if ($submission->timemarked) {
964 echo '<div class="from">';
965 echo '<div class="fullname">'.fullname($teacher, true).'</div>';
966 echo '<div class="time">'.userdate($submission->timemarked).'</div>';
969 echo '<div class="grade"><label for="menugrade">'.get_string('grade').'</label> ';
970 $select = html_select::make(make_grades_menu($this->assignment->grade), 'grade', $submission->grade, get_string('nograde'));
971 $select->nothingvalue = '-1';
972 $select->disabled = $disabled;
973 echo $OUTPUT->select($select);
976 echo '<div class="clearer"></div>';
977 echo '<div class="finalgrade">'.get_string('finalgrade', 'grades').': '.$grading_info->items[0]->grades[$userid]->str_grade.'</div>';
978 echo '<div class="clearer"></div>';
980 if (!empty($CFG->enableoutcomes)) {
981 foreach($grading_info->outcomes as $n=>$outcome) {
982 echo '<div class="outcome"><label for="menuoutcome_'.$n.'">'.$outcome->name.'</label> ';
983 $options = make_grades_menu(-$outcome->scaleid);
984 if ($outcome->grades[$submission->userid]->locked) {
985 $options[0] = get_string('nooutcome', 'grades');
986 echo $options[$outcome->grades[$submission->userid]->grade];
988 $select = html_select::make($options, 'outcome_'.$n.'['.$userid.']', $outcome->grades[$submission->userid]->grade, get_string('nooutcome', 'grades'));
989 $select->id = 'menuoutcome_'.$n;
990 echo $OUTPUT->select($select);
993 echo '<div class="clearer"></div>';
998 $this->preprocess_submission($submission);
1001 echo '<div class="disabledfeedback">'.$grading_info->items[0]->grades[$userid]->str_feedback.'</div>';
1004 print_textarea($this->usehtmleditor, 14, 58, 0, 0, 'submissioncomment', $submission->submissioncomment, $this->course->id);
1005 if ($this->usehtmleditor) {
1006 echo '<input type="hidden" name="format" value="'.FORMAT_HTML.'" />';
1008 echo '<div class="format">';
1009 echo $OUTPUT->select(html_select::make(format_text_menu(), "format", $submission->format, false));
1010 echo $OUTPUT->help_icon(moodle_help_icon::make("textformat", get_string("helpformatting")));
1015 $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? 'checked="checked"' : '';
1017 ///Print Buttons in Single View
1018 echo '<input type="hidden" name="mailinfo" value="0" />';
1019 echo '<input type="checkbox" id="mailinfo" name="mailinfo" value="1" '.$lastmailinfo.' /><label for="mailinfo">'.get_string('enableemailnotification','assignment').'</label>';
1020 echo '<div class="buttons">';
1021 echo '<input type="submit" name="submit" value="'.get_string('savechanges').'" onclick = "document.getElementById(\'submitform\').menuindex.value = document.getElementById(\'submitform\').grade.selectedIndex" />';
1022 echo '<input type="submit" name="cancel" value="'.get_string('cancel').'" />';
1023 //if there are more to be graded.
1025 echo '<input type="submit" name="saveandnext" value="'.get_string('saveandnext').'" onclick="saveNext()" />';
1026 echo '<input type="submit" name="next" value="'.get_string('next').'" onclick="setNext();" />';
1029 echo '</div></form>';
1031 $customfeedback = $this->custom_feedbackform($submission, true);
1032 if (!empty($customfeedback)) {
1033 echo $customfeedback;
1038 ///End of teacher info row, Start of student info row
1040 echo '<td class="picture user">';
1041 echo $OUTPUT->user_picture(moodle_user_picture::make($user, $this->course->id));
1043 echo '<td class="topic">';
1044 echo '<div class="from">';
1045 echo '<div class="fullname">'.fullname($user, true).'</div>';
1046 if ($submission->timemodified) {
1047 echo '<div class="time">'.userdate($submission->timemodified).
1048 $this->display_lateness($submission->timemodified).'</div>';
1051 $this->print_user_files($user->id);
1055 ///End of student info row
1059 echo $OUTPUT->footer();
1063 * Preprocess submission before grading
1065 * Called by display_submission()
1066 * The default type does nothing here.
1068 * @param object $submission The submission object
1070 function preprocess_submission(&$submission) {
1074 * Display all the submissions ready for grading
1080 * @param string $message
1083 function display_submissions($message='') {
1084 global $CFG, $DB, $USER, $DB, $OUTPUT, $PAGE;
1085 require_once($CFG->libdir.'/gradelib.php');
1087 /* first we check to see if the form has just been submitted
1088 * to request user_preference updates
1091 if (isset($_POST['updatepref'])){
1092 $perpage = optional_param('perpage', 10, PARAM_INT);
1093 $perpage = ($perpage <= 0) ? 10 : $perpage ;
1094 set_user_preference('assignment_perpage', $perpage);
1095 set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
1098 /* next we get perpage and quickgrade (allow quick grade) params
1101 $perpage = get_user_preferences('assignment_perpage', 10);
1103 $quickgrade = get_user_preferences('assignment_quickgrade', 0);
1105 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);
1107 if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
1108 $uses_outcomes = true;
1110 $uses_outcomes = false;
1113 $page = optional_param('page', 0, PARAM_INT);
1114 $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
1116 /// Some shortcuts to make the code read better
1118 $course = $this->course;
1119 $assignment = $this->assignment;
1122 $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
1123 add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->cm->id, $this->assignment->id, $this->cm->id);
1124 $PAGE->navbar->add($this->strsubmissions);
1125 $PAGE->set_title(format_string($this->assignment->name,true));
1126 $PAGE->set_button( update_module_button($cm->id, $course->id, $this->strassignment));
1127 echo $OUTPUT->header();
1129 $course_context = get_context_instance(CONTEXT_COURSE, $course->id);
1130 if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
1131 echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">'
1132 . get_string('seeallcoursegrades', 'grades') . '</a></div>';
1135 if (!empty($message)) {
1136 echo $message; // display messages here if any
1139 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1141 /// Check to see if groups are being used in this assignment
1143 /// find out current groups mode
1144 $groupmode = groups_get_activity_groupmode($cm);
1145 $currentgroup = groups_get_activity_group($cm, true);
1146 groups_print_activity_menu($cm, 'submissions.php?id=' . $this->cm->id);
1148 /// Get all ppl that are allowed to submit assignments
1149 if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $currentgroup, '', false)) {
1150 $users = array_keys($users);
1153 // if groupmembersonly used, remove users who are not in any group
1154 if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
1155 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1156 $users = array_intersect($users, array_keys($groupingusers));
1160 $tablecolumns = array('picture', 'fullname', 'grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade');
1161 if ($uses_outcomes) {
1162 $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
1165 $tableheaders = array('',
1166 get_string('fullname'),
1167 get_string('grade'),
1168 get_string('comment', 'assignment'),
1169 get_string('lastmodified').' ('.get_string('submission', 'assignment').')',
1170 get_string('lastmodified').' ('.get_string('grade').')',
1171 get_string('status'),
1172 get_string('finalgrade', 'grades'));
1173 if ($uses_outcomes) {
1174 $tableheaders[] = get_string('outcome', 'grades');
1177 require_once($CFG->libdir.'/tablelib.php');
1178 $table = new flexible_table('mod-assignment-submissions');
1180 $table->define_columns($tablecolumns);
1181 $table->define_headers($tableheaders);
1182 $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&currentgroup='.$currentgroup);
1184 $table->sortable(true, 'lastname');//sorted by lastname by default
1185 $table->collapsible(true);
1186 $table->initialbars(true);
1188 $table->column_suppress('picture');
1189 $table->column_suppress('fullname');
1191 $table->column_class('picture', 'picture');
1192 $table->column_class('fullname', 'fullname');
1193 $table->column_class('grade', 'grade');
1194 $table->column_class('submissioncomment', 'comment');
1195 $table->column_class('timemodified', 'timemodified');
1196 $table->column_class('timemarked', 'timemarked');
1197 $table->column_class('status', 'status');
1198 $table->column_class('finalgrade', 'finalgrade');
1199 if ($uses_outcomes) {
1200 $table->column_class('outcome', 'outcome');
1203 $table->set_attribute('cellspacing', '0');
1204 $table->set_attribute('id', 'attempts');
1205 $table->set_attribute('class', 'submissions');
1206 $table->set_attribute('width', '100%');
1207 //$table->set_attribute('align', 'center');
1209 $table->no_sorting('finalgrade');
1210 $table->no_sorting('outcome');
1212 // Start working -- this is necessary as soon as the niceties are over
1215 if (empty($users)) {
1216 echo $OUTPUT->heading(get_string('nosubmitusers','assignment'));
1220 /// Construct the SQL
1222 if ($where = $table->get_sql_where()) {
1226 if ($sort = $table->get_sql_sort()) {
1227 $sort = ' ORDER BY '.$sort;
1230 $select = 'SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt,
1231 s.id AS submissionid, s.grade, s.submissioncomment,
1232 s.timemodified, s.timemarked,
1233 COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ';
1234 $sql = 'FROM {user} u '.
1235 'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1236 AND s.assignment = '.$this->assignment->id.' '.
1237 'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1239 $table->pagesize($perpage, count($users));
1241 ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1242 $offset = $page * $perpage;
1244 $strupdate = get_string('update');
1245 $strgrade = get_string('grade');
1246 $grademenu = make_grades_menu($this->assignment->grade);
1248 if (($ausers = $DB->get_records_sql($select.$sql.$sort, null, $table->get_page_start(), $table->get_page_size())) !== false) {
1249 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
1250 foreach ($ausers as $auser) {
1251 $final_grade = $grading_info->items[0]->grades[$auser->id];
1252 $grademax = $grading_info->items[0]->grademax;
1253 $final_grade->formatted_grade = round($final_grade->grade,2) .' / ' . round($grademax,2);
1254 $locked_overridden = 'locked';
1255 if ($final_grade->overridden) {
1256 $locked_overridden = 'overridden';
1259 /// Calculate user status
1260 $auser->status = ($auser->timemarked > 0) && ($auser->timemarked >= $auser->timemodified);
1261 $picture = $OUTPUT->user_picture(moodle_user_picture::make($auser, $course->id));
1263 if (empty($auser->submissionid)) {
1264 $auser->grade = -1; //no submission yet
1267 if (!empty($auser->submissionid)) {
1268 ///Prints student answer and student modified date
1269 ///attach file or print link to student answer, depending on the type of the assignment.
1270 ///Refer to print_student_answer in inherited classes.
1271 if ($auser->timemodified > 0) {
1272 $studentmodified = '<div id="ts'.$auser->id.'">'.$this->print_student_answer($auser->id)
1273 . userdate($auser->timemodified).'</div>';
1275 $studentmodified = '<div id="ts'.$auser->id.'"> </div>';
1277 ///Print grade, dropdown or text
1278 if ($auser->timemarked > 0) {
1279 $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
1281 if ($final_grade->locked or $final_grade->overridden) {
1282 $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1283 } else if ($quickgrade) {
1284 $select = html_select::make(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, get_string('nograde'));
1285 $select->nothingvalue = '-1';
1286 $select->tabindex = $tabindex++;
1287 $menu = $OUTPUT->select($select);
1288 $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
1290 $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1294 $teachermodified = '<div id="tt'.$auser->id.'"> </div>';
1295 if ($final_grade->locked or $final_grade->overridden) {
1296 $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1297 } else if ($quickgrade) {
1298 $select = html_select::make(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, get_string('nograde'));
1299 $select->nothingvalue = '-1';
1300 $select->tabindex = $tabindex++;
1301 $menu = $OUTPUT->select($select);
1302 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1304 $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1308 if ($final_grade->locked or $final_grade->overridden) {
1309 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';
1311 } else if ($quickgrade) {
1312 $comment = '<div id="com'.$auser->id.'">'
1313 . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1314 . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1316 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
1319 $studentmodified = '<div id="ts'.$auser->id.'"> </div>';
1320 $teachermodified = '<div id="tt'.$auser->id.'"> </div>';
1321 $status = '<div id="st'.$auser->id.'"> </div>';
1323 if ($final_grade->locked or $final_grade->overridden) {
1324 $grade = '<div id="g'.$auser->id.'">'.$final_grade->formatted_grade . '</div>';
1325 } else if ($quickgrade) { // allow editing
1326 $select = html_select::make(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, get_string('nograde'));
1327 $select->nothingvalue = '-1';
1328 $select->tabindex = $tabindex++;
1329 $menu = $OUTPUT->select($select);
1330 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1332 $grade = '<div id="g'.$auser->id.'">-</div>';
1335 if ($final_grade->locked or $final_grade->overridden) {
1336 $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
1337 } else if ($quickgrade) {
1338 $comment = '<div id="com'.$auser->id.'">'
1339 . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1340 . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1342 $comment = '<div id="com'.$auser->id.'"> </div>';
1346 if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
1352 $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
1354 ///No more buttons, we use popups ;-).
1355 $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1356 . '&userid='.$auser->id.'&mode=single'.'&offset='.$offset++;
1358 $link = html_link::make($popup_url, $buttontext);
1359 $link->add_action(new popup_action('click', $link->url, 'grade'.$auser->id, array('height' => 600, 'width' => 700)));
1360 $link->title = $buttontext;
1361 $button = $OUTPUT->link($link);
1363 $status = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
1365 $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';
1369 if ($uses_outcomes) {
1371 foreach($grading_info->outcomes as $n=>$outcome) {
1372 $outcomes .= '<div class="outcome"><label>'.$outcome->name.'</label>';
1373 $options = make_grades_menu(-$outcome->scaleid);
1375 if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
1376 $options[0] = get_string('nooutcome', 'grades');
1377 $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
1380 $select = html_select::make($options, 'outcome_'.$n.'['.$auser->id.']', $outcome->grades[$auser->id]->grade, get_string('nooutcome', 'grades'));
1381 $select->nothingvalue = '0';
1382 $select->tabindex = $tabindex++;
1383 $select->id = 'outcome_'.$n.'_'.$auser->id;
1384 $outcomes .= $OUTPUT->select($select);
1386 $outcomes .= '</div>';
1390 $userlink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $auser->id . '&course=' . $course->id . '">' . fullname($auser) . '</a>';
1391 $row = array($picture, $userlink, $grade, $comment, $studentmodified, $teachermodified, $status, $finalgrade);
1392 if ($uses_outcomes) {
1396 $table->add_data($row);
1400 /// Print quickgrade form around the table
1402 echo '<form action="submissions.php" id="fastg" method="post">';
1404 echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
1405 echo '<input type="hidden" name="mode" value="fastgrade" />';
1406 echo '<input type="hidden" name="page" value="'.$page.'" />';
1410 $table->print_html(); /// Print the whole table
1413 $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? 'checked="checked"' : '';
1414 echo '<div class="fgcontrols">';
1415 echo '<div class="emailnotification">';
1416 echo '<label for="mailinfo">'.get_string('enableemailnotification','assignment').'</label>';
1417 echo '<input type="hidden" name="mailinfo" value="0" />';
1418 echo '<input type="checkbox" id="mailinfo" name="mailinfo" value="1" '.$lastmailinfo.' />';
1419 echo $OUTPUT->help_icon(moodle_help_icon::make('emailnotification', get_string('enableemailnotification', 'assignment'), 'assignment')).'</p></div>';
1421 echo '<div class="fastgbutton"><input type="submit" name="fastg" value="'.get_string('saveallfeedback', 'assignment').'" /></div>';
1425 /// End of fast grading form
1427 /// Mini form for setting user preference
1428 echo '<div class="qgprefs">';
1429 echo '<form id="options" action="submissions.php?id='.$this->cm->id.'" method="post"><div>';
1430 echo '<input type="hidden" name="updatepref" value="1" />';
1431 echo '<table id="optiontable">';
1433 echo '<label for="perpage">'.get_string('pagesize','assignment').'</label>';
1436 echo '<input type="text" id="perpage" name="perpage" size="1" value="'.$perpage.'" />';
1437 echo $OUTPUT->help_icon(moodle_help_icon::make('pagesize', get_string('pagesize','assignment'), 'assignment'));
1440 echo '<label for="quickgrade">'.get_string('quickgrade','assignment').'</label>';
1443 $checked = $quickgrade ? 'checked="checked"' : '';
1444 echo '<input type="checkbox" id="quickgrade" name="quickgrade" value="1" '.$checked.' />';
1445 echo $OUTPUT->help_icon(moodle_help_icon::make('quickgrade', get_string('quickgrade', 'assignment'), 'assignment')).'</p></div>';
1447 echo '<tr><td colspan="2">';
1448 echo '<input type="submit" value="'.get_string('savepreferences').'" />';
1449 echo '</td></tr></table>';
1450 echo '</div></form></div>';
1452 echo $OUTPUT->footer();
1456 * Process teacher feedback submission
1458 * This is called by submissions() when a grading even has taken place.
1459 * It gets its data from the submitted form.
1464 * @return object|bool The updated submission object or false
1466 function process_feedback() {
1467 global $CFG, $USER, $DB;
1468 require_once($CFG->libdir.'/gradelib.php');
1470 if (!$feedback = data_submitted()) { // No incoming data?
1474 ///For save and next, we need to know the userid to save, and the userid to go
1475 ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1476 ///as the userid to store
1477 if ((int)$feedback->saveuserid !== -1){
1478 $feedback->userid = $feedback->saveuserid;
1481 if (!empty($feedback->cancel)) { // User hit cancel button
1485 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);
1487 // store outcomes if needed
1488 $this->process_outcomes($feedback->userid);
1490 $submission = $this->get_submission($feedback->userid, true); // Get or make one
1492 if (!$grading_info->items[0]->grades[$feedback->userid]->locked and
1493 !$grading_info->items[0]->grades[$feedback->userid]->overridden) {
1495 $submission->grade = $feedback->grade;
1496 $submission->submissioncomment = $feedback->submissioncomment;
1497 $submission->format = $feedback->format;
1498 $submission->teacher = $USER->id;
1499 $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1501 $submission->mailed = 1; // treat as already mailed
1503 $submission->mailed = 0; // Make sure mail goes out (again, even)
1505 $submission->timemarked = time();
1507 unset($submission->data1); // Don't need to update this.
1508 unset($submission->data2); // Don't need to update this.
1510 if (empty($submission->timemodified)) { // eg for offline assignments
1511 // $submission->timemodified = time();
1514 $DB->update_record('assignment_submissions', $submission);
1516 // triger grade event
1517 $this->update_grade($submission);
1519 add_to_log($this->course->id, 'assignment', 'update grades',
1520 'submissions.php?id='.$this->assignment->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
1527 function process_outcomes($userid) {
1530 if (empty($CFG->enableoutcomes)) {
1534 require_once($CFG->libdir.'/gradelib.php');
1536 if (!$formdata = data_submitted()) {
1541 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
1543 if (!empty($grading_info->outcomes)) {
1544 foreach($grading_info->outcomes as $n=>$old) {
1545 $name = 'outcome_'.$n;
1546 if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
1547 $data[$n] = $formdata->{$name}[$userid];
1551 if (count($data) > 0) {
1552 grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1558 * Load the submission object for a particular user
1562 * @param $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1563 * @param $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1564 * @param bool $teachermodified student submission set if false
1565 * @return object The submission
1567 function get_submission($userid=0, $createnew=false, $teachermodified=false) {
1570 if (empty($userid)) {
1571 $userid = $USER->id;
1574 $submission = $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1576 if ($submission || !$createnew) {
1579 $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
1580 $DB->insert_record("assignment_submissions", $newsubmission);
1582 return $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1586 * Instantiates a new submission object for a given user
1588 * Sets the assignment, userid and times, everything else is set to default values.
1590 * @param int $userid The userid for which we want a submission object
1591 * @param bool $teachermodified student submission set if false
1592 * @return object The submission
1594 function prepare_new_submission($userid, $teachermodified=false) {
1595 $submission = new Object;
1596 $submission->assignment = $this->assignment->id;
1597 $submission->userid = $userid;
1598 $submission->timecreated = time();
1599 // teachers should not be modifying modified date, except offline assignments
1600 if ($teachermodified) {
1601 $submission->timemodified = 0;
1603 $submission->timemodified = $submission->timecreated;
1605 $submission->numfiles = 0;
1606 $submission->data1 = '';
1607 $submission->data2 = '';
1608 $submission->grade = -1;
1609 $submission->submissioncomment = '';
1610 $submission->format = 0;
1611 $submission->teacher = 0;
1612 $submission->timemarked = 0;
1613 $submission->mailed = 0;
1618 * Return all assignment submissions by ENROLLED students (even empty)
1620 * @param string $sort optional field names for the ORDER BY in the sql query
1621 * @param string $dir optional specifying the sort direction, defaults to DESC
1622 * @return array The submission objects indexed by id
1624 function get_submissions($sort='', $dir='DESC') {
1625 return assignment_get_all_submissions($this->assignment, $sort, $dir);
1629 * Counts all real assignment submissions by ENROLLED students (not empty ones)
1631 * @param int $groupid optional If nonzero then count is restricted to this group
1632 * @return int The number of submissions
1634 function count_real_submissions($groupid=0) {
1635 return assignment_count_real_submissions($this->cm, $groupid);
1639 * Alerts teachers by email of new or changed assignments that need grading
1641 * First checks whether the option to email teachers is set for this assignment.
1642 * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1643 * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1647 * @param $submission object The submission that has changed
1650 function email_teachers($submission) {
1653 if (empty($this->assignment->emailteachers)) { // No need to do anything
1657 $user = $DB->get_record('user', array('id'=>$submission->userid));
1659 if ($teachers = $this->get_graders($user)) {
1661 $strassignments = get_string('modulenameplural', 'assignment');
1662 $strassignment = get_string('modulename', 'assignment');
1663 $strsubmitted = get_string('submitted', 'assignment');
1665 foreach ($teachers as $teacher) {
1666 $info = new object();
1667 $info->username = fullname($user, true);
1668 $info->assignment = format_string($this->assignment->name,true);
1669 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
1671 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1672 $posttext = $this->email_teachers_text($info);
1673 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
1675 $eventdata = new object();
1676 $eventdata->modulename = 'assignment';
1677 $eventdata->userfrom = $user;
1678 $eventdata->userto = $teacher;
1679 $eventdata->subject = $postsubject;
1680 $eventdata->fullmessage = $posttext;
1681 $eventdata->fullmessageformat = FORMAT_PLAIN;
1682 $eventdata->fullmessagehtml = $posthtml;
1683 $eventdata->smallmessage = '';
1684 if ( events_trigger('message_send', $eventdata) > 0 ){
1691 * @param string $filearea
1692 * @param array $args
1695 function send_file($filearea, $args) {
1696 debugging('plugin does not implement file sending', DEBUG_DEVELOPER);
1701 * Returns a list of teachers that should be grading given submission
1703 * @param object $user
1706 function get_graders($user) {
1708 $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false);
1711 if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) { // Separate groups are being used
1712 if ($groups = groups_get_all_groups($this->course->id, $user->id)) { // Try to find all groups
1713 foreach ($groups as $group) {
1714 foreach ($potgraders as $t) {
1715 if ($t->id == $user->id) {
1716 continue; // do not send self
1718 if (groups_is_member($group->id, $t->id)) {
1719 $graders[$t->id] = $t;
1724 // user not in group, try to find graders without group
1725 foreach ($potgraders as $t) {
1726 if ($t->id == $user->id) {
1727 continue; // do not send self
1729 if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
1730 $graders[$t->id] = $t;
1735 foreach ($potgraders as $t) {
1736 if ($t->id == $user->id) {
1737 continue; // do not send self
1739 $graders[$t->id] = $t;
1746 * Creates the text content for emails to teachers
1748 * @param $info object The info used by the 'emailteachermail' language string
1751 function email_teachers_text($info) {
1752 $posttext = format_string($this->course->shortname).' -> '.$this->strassignments.' -> '.
1753 format_string($this->assignment->name)."\n";
1754 $posttext .= '---------------------------------------------------------------------'."\n";
1755 $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
1756 $posttext .= "\n---------------------------------------------------------------------\n";
1761 * Creates the html content for emails to teachers
1763 * @param $info object The info used by the 'emailteachermailhtml' language string
1766 function email_teachers_html($info) {
1768 $posthtml = '<p><font face="sans-serif">'.
1769 '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname).'</a> ->'.
1770 '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
1771 '<a href="'.$CFG->wwwroot.'/mod/assignment/view.php?id='.$this->cm->id.'">'.format_string($this->assignment->name).'</a></font></p>';
1772 $posthtml .= '<hr /><font face="sans-serif">';
1773 $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
1774 $posthtml .= '</font><hr />';
1779 * Produces a list of links to the files uploaded by a user
1781 * @param $userid int optional id of the user. If 0 then $USER->id is used.
1782 * @param $return boolean optional defaults to false. If true the list is returned rather than printed
1783 * @return string optional
1785 function print_user_files($userid=0, $return=false) {
1786 global $CFG, $USER, $OUTPUT;
1789 if (!isloggedin()) {
1792 $userid = $USER->id;
1797 $fs = get_file_storage();
1798 $browser = get_file_browser();
1802 if ($files = $fs->get_area_files($this->context->id, 'assignment_submission', $userid, "timemodified", false)) {
1803 $button = new portfolio_add_button();
1804 foreach ($files as $file) {
1805 $filename = $file->get_filename();
1807 $mimetype = $file->get_mimetype();
1808 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/assignment_submission/'.$userid.'/'.$filename);
1809 $output .= '<a href="'.$path.'" ><img src="'.$OUTPUT->old_icon_url(file_mimetype_icon($mimetype)).'" class="icon" alt="'.$mimetype.'" />'.s($filename).'</a>';
1810 if ($this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1811 $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id, 'fileid' => $file->get_id()));
1812 $button->set_formats(portfolio_format_from_file($file));
1813 $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
1815 $output .= '<br />';
1817 if (count($files) > 1 && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1818 $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id));
1819 $button->set_formats(PORTFOLIO_PORMAT_FILE);
1820 $output .= '<br />' . $button->to_html();
1824 $output = '<div class="files">'.$output.'</div>';
1833 * Count the files uploaded by a given user
1835 * @param $userid int The user id
1838 function count_user_files($userid) {
1839 $fs = get_file_storage();
1840 $files = $fs->get_area_files($this->context->id, 'assignment_submission', $userid, "id", false);
1841 return count($files);
1845 * Returns true if the student is allowed to submit
1847 * Checks that the assignment has started and, if the option to prevent late
1848 * submissions is set, also checks that the assignment has not yet closed.
1853 if ($this->assignment->preventlate && $this->assignment->timedue) {
1854 return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
1856 return ($this->assignment->timeavailable <= $time);
1862 * Return true if is set description is hidden till available date
1864 * This is needed by calendar so that hidden descriptions do not
1865 * come up in upcoming events.
1867 * Check that description is hidden till available date
1868 * By default return false
1869 * Assignments types should implement this method if needed
1872 function description_is_hidden() {
1877 * Return an outline of the user's interaction with the assignment
1879 * The default method prints the grade and timemodified
1880 * @param $grade object
1881 * @return object with properties ->info and ->time
1883 function user_outline($grade) {
1885 $result = new object();
1886 $result->info = get_string('grade').': '.$grade->str_long_grade;
1887 $result->time = $grade->dategraded;
1892 * Print complete information about the user's interaction with the assignment
1894 * @param $user object
1896 function user_complete($user, $grade=null) {
1899 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
1900 if ($grade->str_feedback) {
1901 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
1905 if ($submission = $this->get_submission($user->id)) {
1907 $fs = get_file_storage();
1908 $browser = get_file_browser();
1910 if ($files = $fs->get_area_files($this->context->id, 'assignment_submission', $user->id, "timemodified", false)) {
1911 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
1912 foreach ($files as $file) {
1913 $countfiles .= "; ".$file->get_filename();
1917 echo $OUTPUT->box_start();
1918 echo get_string("lastmodified").": ";
1919 echo userdate($submission->timemodified);
1920 echo $this->display_lateness($submission->timemodified);
1922 $this->print_user_files($user->id);
1926 $this->view_feedback($submission);
1928 echo $OUTPUT->box_end();
1931 print_string("notsubmittedyet", "assignment");
1936 * Return a string indicating how late a submission is
1938 * @param $timesubmitted int
1941 function display_lateness($timesubmitted) {
1942 return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
1946 * Empty method stub for all delete actions.
1949 //nothing by default
1950 redirect('view.php?id='.$this->cm->id);
1954 * Empty custom feedback grading form.
1956 function custom_feedbackform($submission, $return=false) {
1957 //nothing by default
1962 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
1963 * for the course (see resource).
1965 * Given a course_module object, this function returns any "extra" information that may be needed
1966 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
1968 * @param $coursemodule object The coursemodule object (record).
1969 * @return object An object on information that the coures will know about (most noticeably, an icon).
1972 function get_coursemodule_info($coursemodule) {
1977 * Plugin cron method - do not use $this here, create new assignment instances if needed.
1981 //no plugin cron by default - override if needed
1985 * Reset all submissions
1987 function reset_userdata($data) {
1990 if (!$DB->count_records('assignment', array('course'=>$data->courseid, 'assignmenttype'=>$this->type))) {
1991 return array(); // no assignments of this type present
1994 $componentstr = get_string('modulenameplural', 'assignment');
1997 $typestr = get_string('type'.$this->type, 'assignment');
1998 // ugly hack to support pluggable assignment type titles...
1999 if($typestr === '[[type'.$this->type.']]'){
2000 $typestr = get_string('type'.$this->type, 'assignment_'.$this->type);
2003 if (!empty($data->reset_assignment_submissions)) {
2004 $assignmentssql = "SELECT a.id
2006 WHERE a.course=? AND a.assignmenttype=?";
2007 $params = array($data->courseid, $this->type);
2009 // now get rid of all submissions and responses
2010 $fs = get_file_storage();
2011 if ($assignments = $DB->get_records_sql($assignmentssql, $params)) {
2012 foreach ($assignments as $assignmentid=>$unused) {
2013 if (!$cm = get_coursemodule_from_instance('assignment', $assignmentid)) {
2016 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2017 $fs->delete_area_files($context->id, 'assignment_submission');
2018 $fs->delete_area_files($context->id, 'assignment_response');
2022 $DB->delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)", $params);
2024 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
2026 if (empty($data->reset_gradebook_grades)) {
2027 // remove all grades from gradebook
2028 assignment_reset_gradebook($data->courseid, $this->type);
2032 /// updating dates - shift may be negative too
2033 if ($data->timeshift) {
2034 shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
2035 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
2042 function portfolio_exportable() {
2047 * base implementation for backing up subtype specific information
2048 * for one single module
2050 * @param filehandle $bf file handle for xml file to write to
2051 * @param mixed $preferences the complete backup preference object
2057 static function backup_one_mod($bf, $preferences, $assignment) {
2062 * base implementation for backing up subtype specific information
2063 * for one single submission
2065 * @param filehandle $bf file handle for xml file to write to
2066 * @param mixed $preferences the complete backup preference object
2067 * @param object $submission the assignment submission db record
2073 static function backup_one_submission($bf, $preferences, $assignment, $submission) {
2078 * base implementation for restoring subtype specific information
2079 * for one single module
2081 * @param array $info the array representing the xml
2082 * @param object $restore the restore preferences
2088 static function restore_one_mod($info, $restore, $assignment) {
2093 * base implementation for restoring subtype specific information
2094 * for one single submission
2096 * @param object $submission the newly created submission
2097 * @param array $info the array representing the xml
2098 * @param object $restore the restore preferences
2104 static function restore_one_submission($info, $restore, $assignment, $submission) {
2108 } ////// End of the assignment_base class
2111 * @package mod-assignment
2112 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
2113 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2115 class mod_assignment_upload_file_form extends moodleform {
2116 function definition() {
2117 $mform = $this->_form;
2118 $instance = $this->_customdata;
2120 //TODO: improve upload size checking
2121 $mform->setMaxFileSize($instance->assignment->maxbytes);
2124 $mform->addElement('file', 'newfile', get_string('uploadafile'));
2127 $mform->addElement('hidden', 'id', $instance->cm->id);
2128 $mform->setType('id', PARAM_INT);
2129 $mform->addElement('hidden', 'action', 'uploadfile');
2130 $mform->setType('action', PARAM_ALPHA);
2133 $this->add_action_buttons(false, get_string('uploadthisfile'));
2138 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
2141 * Deletes an assignment instance
2143 * This is done by calling the delete_instance() method of the assignment type class
2145 function assignment_delete_instance($id){
2148 if (! $assignment = $DB->get_record('assignment', array('id'=>$id))) {
2152 // fall back to base class if plugin missing
2153 $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2154 if (file_exists($classfile)) {
2155 require_once($classfile);
2156 $assignmentclass = "assignment_$assignment->assignmenttype";
2159 debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
2160 $assignmentclass = "assignment_base";
2163 $ass = new $assignmentclass();
2164 return $ass->delete_instance($assignment);
2169 * Updates an assignment instance
2171 * This is done by calling the update_instance() method of the assignment type class
2173 function assignment_update_instance($assignment){
2176 $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2178 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2179 $assignmentclass = "assignment_$assignment->assignmenttype";
2180 $ass = new $assignmentclass();
2181 return $ass->update_instance($assignment);
2186 * Adds an assignment instance
2188 * This is done by calling the add_instance() method of the assignment type class
2190 function assignment_add_instance($assignment) {
2193 $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2195 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2196 $assignmentclass = "assignment_$assignment->assignmenttype";
2197 $ass = new $assignmentclass();
2198 return $ass->add_instance($assignment);
2203 * Returns an outline of a user interaction with an assignment
2205 * This is done by calling the user_outline() method of the assignment type class
2207 function assignment_user_outline($course, $user, $mod, $assignment) {
2210 require_once("$CFG->libdir/gradelib.php");
2211 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2212 $assignmentclass = "assignment_$assignment->assignmenttype";
2213 $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2214 $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2215 if (!empty($grades->items[0]->grades)) {
2216 return $ass->user_outline(reset($grades->items[0]->grades));
2223 * Prints the complete info about a user's interaction with an assignment
2225 * This is done by calling the user_complete() method of the assignment type class
2227 function assignment_user_complete($course, $user, $mod, $assignment) {
2230 require_once("$CFG->libdir/gradelib.php");
2231 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2232 $assignmentclass = "assignment_$assignment->assignmenttype";
2233 $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2234 $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2235 if (empty($grades->items[0]->grades)) {
2238 $grade = reset($grades->items[0]->grades);
2240 return $ass->user_complete($user, $grade);
2244 * Function to be run periodically according to the moodle cron
2246 * Finds all assignment notifications that have yet to be mailed out, and mails them
2248 function assignment_cron () {
2249 global $CFG, $USER, $DB;
2251 /// first execute all crons in plugins
2252 if ($plugins = get_plugin_list('assignment')) {
2253 foreach ($plugins as $plugin=>$dir) {
2254 require_once("$dir/assignment.class.php");
2255 $assignmentclass = "assignment_$plugin";
2256 $ass = new $assignmentclass();
2261 /// Notices older than 1 day will not be mailed. This is to avoid the problem where
2262 /// cron has not been running for a long time, and then suddenly people are flooded
2263 /// with mail from the past few weeks or months
2266 $endtime = $timenow - $CFG->maxeditingtime;
2267 $starttime = $endtime - 24 * 3600; /// One day earlier
2269 if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2271 $realuser = clone($USER);
2273 foreach ($submissions as $key => $submission) {
2274 if (! $DB->set_field("assignment_submissions", "mailed", "1", array("id"=>$submission->id))) {
2275 echo "Could not update the mailed field for id $submission->id. Not mailed.\n";
2276 unset($submissions[$key]);
2282 foreach ($submissions as $submission) {
2284 echo "Processing assignment submission $submission->id\n";
2286 if (! $user = $DB->get_record("user", array("id"=>$submission->userid))) {
2287 echo "Could not find user $post->userid\n";
2291 if (! $course = $DB->get_record("course", array("id"=>$submission->course))) {
2292 echo "Could not find course $submission->course\n";
2296 /// Override the language and timezone of the "current" user, so that
2297 /// mail is customised for the receiver.
2298 cron_setup_user($user, $course);
2300 if (!has_capability('moodle/course:view', get_context_instance(CONTEXT_COURSE, $submission->course), $user->id)) {
2301 echo fullname($user)." not an active participant in " . format_string($course->shortname) . "\n";
2305 if (! $teacher = $DB->get_record("user", array("id"=>$submission->teacher))) {
2306 echo "Could not find teacher $submission->teacher\n";
2310 if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2311 echo "Could not find course module for assignment id $submission->assignment\n";
2315 if (! $mod->visible) { /// Hold mail notification for hidden assignments until later
2319 $strassignments = get_string("modulenameplural", "assignment");
2320 $strassignment = get_string("modulename", "assignment");
2322 $assignmentinfo = new object();
2323 $assignmentinfo->teacher = fullname($teacher);
2324 $assignmentinfo->assignment = format_string($submission->name,true);
2325 $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2327 $postsubject = "$course->shortname: $strassignments: ".format_string($submission->name,true);
2328 $posttext = "$course->shortname -> $strassignments -> ".format_string($submission->name,true)."\n";
2329 $posttext .= "---------------------------------------------------------------------\n";
2330 $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2331 $posttext .= "---------------------------------------------------------------------\n";
2333 if ($user->mailformat == 1) { // HTML
2334 $posthtml = "<p><font face=\"sans-serif\">".
2335 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> ->".
2336 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2337 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2338 $posthtml .= "<hr /><font face=\"sans-serif\">";
2339 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2340 $posthtml .= "</font><hr />";
2345 $eventdata = new object();
2346 $eventdata->modulename = 'assignment';
2347 $eventdata->userfrom = $teacher;
2348 $eventdata->userto = $user;
2349 $eventdata->subject = $postsubject;
2350 $eventdata->fullmessage = $posttext;
2351 $eventdata->fullmessageformat = FORMAT_PLAIN;
2352 $eventdata->fullmessagehtml = $posthtml;
2353 $eventdata->smallmessage = '';
2354 if ( events_trigger('message_send', $eventdata) > 0 ){
2355 echo "Error: assignment cron: Could not send out mail for id $submission->id to user $user->id ($user->email)\n";
2366 * Return grade for given user or all users.
2368 * @param int $assignmentid id of assignment
2369 * @param int $userid optional user id, 0 means all users
2370 * @return array array of grades, false if none
2372 function assignment_get_user_grades($assignment, $userid=0) {
2376 $user = "AND u.id = :userid";
2377 $params = array('userid'=>$userid);
2381 $params['aid'] = $assignment->id;
2383 $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2384 s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2385 FROM {user} u, {assignment_submissions} s
2386 WHERE u.id = s.userid AND s.assignment = :aid
2389 return $DB->get_records_sql($sql, $params);
2393 * Update activity grades
2395 * @param object $assignment
2396 * @param int $userid specific user only, 0 means all
2398 function assignment_update_grades($assignment, $userid=0, $nullifnone=true) {
2400 require_once($CFG->libdir.'/gradelib.php');
2402 if ($assignment->grade == 0) {
2403 assignment_grade_item_update($assignment);
2405 } else if ($grades = assignment_get_user_grades($assignment, $userid)) {
2406 foreach($grades as $k=>$v) {
2407 if ($v->rawgrade == -1) {
2408 $grades[$k]->rawgrade = null;
2411 assignment_grade_item_update($assignment, $grades);
2414 assignment_grade_item_update($assignment);
2419 * Update all grades in gradebook.
2421 function assignment_upgrade_grades() {
2424 $sql = "SELECT COUNT('x')
2425 FROM {assignment} a, {course_modules} cm, {modules} m
2426 WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2427 $count = $DB->count_records_sql($sql);
2429 $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
2430 FROM {assignment} a, {course_modules} cm, {modules} m
2431 WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2432 if ($rs = $DB->get_recordset_sql($sql)) {
2433 // too much debug output
2434 $pbar = new progress_bar('assignmentupgradegrades', 500, true);
2436 foreach ($rs as $assignment) {
2438 upgrade_set_timeout(60*5); // set up timeout, may also abort execution
2439 assignment_update_grades($assignment);
2440 $pbar->update($i, $count, "Updating Assignment grades ($i/$count).");
2443 upgrade_set_timeout(); // reset to default timeout
2448 * Create grade item for given assignment
2450 * @param object $assignment object with extra cmidnumber
2451 * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
2452 * @return int 0 if ok, error code otherwise
2454 function assignment_grade_item_update($assignment, $grades=NULL) {
2456 require_once($CFG->libdir.'/gradelib.php');
2458 if (!isset($assignment->courseid)) {
2459 $assignment->courseid = $assignment->course;
2462 $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
2464 if ($assignment->grade > 0) {
2465 $params['gradetype'] = GRADE_TYPE_VALUE;
2466 $params['grademax'] = $assignment->grade;
2467 $params['grademin'] = 0;
2469 } else if ($assignment->grade < 0) {
2470 $params['gradetype'] = GRADE_TYPE_SCALE;
2471 $params['scaleid'] = -$assignment->grade;
2474 $params['gradetype'] = GRADE_TYPE_TEXT; // allow text comments only
2477 if ($grades === 'reset') {
2478 $params['reset'] = true;
2482 return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades, $params);
2486 * Delete grade item for given assignment
2488 * @param object $assignment object
2489 * @return object assignment
2491 function assignment_grade_item_delete($assignment) {
2493 require_once($CFG->libdir.'/gradelib.php');
2495 if (!isset($assignment->courseid)) {
2496 $assignment->courseid = $assignment->course;
2499 return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
2503 * Returns the users with data in one assignment (students and teachers)
2505 * @param $assignmentid int
2506 * @return array of user objects
2508 function assignment_get_participants($assignmentid) {
2512 $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2514 {assignment_submissions} a
2515 WHERE a.assignment = ? and
2516 u.id = a.userid", array($assignmentid));
2518 $teachers = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2520 {assignment_submissions} a
2521 WHERE a.assignment = ? and
2522 u.id = a.teacher", array($assignmentid));
2524 //Add teachers to students
2526 foreach ($teachers as $teacher) {
2527 $students[$teacher->id] = $teacher;
2530 //Return students array (it contains an array of unique users)
2535 * Serves assingment submissions and otehr files.
2537 * @param object $course
2538 * @param object $cminfo
2539 * @param object $context
2540 * @param string $filearea
2541 * @param array $args
2542 * @param bool $forcedownload
2543 * @return bool false if file not found, does not return if found - justsend the file
2545 function assignment_pluginfile($course, $cminfo, $context, $filearea, $args, $forcedownload) {
2548 if (!$assignment = $DB->get_record('assignment', array('id'=>$cminfo->instance))) {
2551 if (!$cm = get_coursemodule_from_instance('assignment', $assignment->id, $course->id)) {
2555 require_login($course, false, $cm);
2557 require_once($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
2558 $assignmentclass = 'assignment_'.$assignment->assignmenttype;
2559 $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm, $course);
2561 return $assignmentinstance->send_file($filearea, $args);
2564 * Checks if a scale is being used by an assignment
2566 * This is used by the backup code to decide whether to back up a scale
2567 * @param $assignmentid int
2568 * @param $scaleid int
2569 * @return boolean True if the scale is used by the assignment
2571 function assignment_scale_used($assignmentid, $scaleid) {
2576 $rec = $DB->get_record('assignment', array('id'=>$assignmentid,'grade'=>-$scaleid));
2578 if (!empty($rec) && !empty($scaleid)) {
2586 * Checks if scale is being used by any instance of assignment
2588 * This is used to find out if scale used anywhere
2589 * @param $scaleid int
2590 * @return boolean True if the scale is used by any assignment
2592 function assignment_scale_used_anywhere($scaleid) {
2595 if ($scaleid and $DB->record_exists('assignment', array('grade'=>-$scaleid))) {
2603 * Make sure up-to-date events are created for all assignment instances
2605 * This standard function will check all instances of this module
2606 * and make sure there are up-to-date events created for each of them.
2607 * If courseid = 0, then every assignment event in the site is checked, else
2608 * only assignment events belonging to the course specified are checked.
2609 * This function is used, in its new format, by restore_refresh_events()
2611 * @param $courseid int optional If zero then all assignments for all courses are covered
2612 * @return boolean Always returns true
2614 function assignment_refresh_events($courseid = 0) {
2617 if ($courseid == 0) {
2618 if (! $assignments = $DB->get_records("assignment")) {
2622 if (! $assignments = $DB->get_records("assignment", array("course"=>$courseid))) {
2626 $moduleid = $DB->get_field('modules', 'id', array('name'=>'assignment'));
2628 foreach ($assignments as $assignment) {
2629 $cm = get_coursemodule_from_id('assignment', $assignment->id);
2630 $event = new object();
2631 $event->name = $assignment->name;
2632 $event->description = format_module_intro('assignment', $assignment, $cm->id);
2633 $event->timestart = $assignment->timedue;
2635 if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
2636 update_event($event);
2639 $event->courseid = $assignment->course;
2640 $event->groupid = 0;
2642 $event->modulename = 'assignment';
2643 $event->instance = $assignment->id;
2644 $event->eventtype = 'due';
2645 $event->timeduration = 0;
2646 $event->visible = $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$assignment->id));
2655 * Print recent activity from all assignments in a given course
2657 * This is used by the recent activity block
2659 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
2660 global $CFG, $USER, $DB, $OUTPUT;
2662 // do not use log table if possible, it may be huge
2664 if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
2665 u.firstname, u.lastname, u.email, u.picture
2666 FROM {assignment_submissions} asb
2667 JOIN {assignment} a ON a.id = asb.assignment
2668 JOIN {course_modules} cm ON cm.instance = a.id
2669 JOIN {modules} md ON md.id = cm.module
2670 JOIN {user} u ON u.id = asb.userid
2671 WHERE asb.timemodified > ? AND
2673 md.name = 'assignment'
2674 ORDER BY asb.timemodified ASC", array($timestart, $course->id))) {
2678 $modinfo =& get_fast_modinfo($course); // reference needed because we might load the groups
2682 foreach($submissions as $submission) {
2683 if (!array_key_exists($submission->cmid, $modinfo->cms)) {
2686 $cm = $modinfo->cms[$submission->cmid];
2687 if (!$cm->uservisible) {
2690 if ($submission->userid == $USER->id) {
2691 $show[] = $submission;
2695 // the act of sumbitting of assignment may be considered private - only graders will see it if specified
2696 if (empty($CFG->assignment_showrecentsubmissions)) {
2697 if (!array_key_exists($cm->id, $grader)) {
2698 $grader[$cm->id] = has_capability('moodle/grade:viewall', get_context_instance(CONTEXT_MODULE, $cm->id));
2700 if (!$grader[$cm->id]) {
2705 $groupmode = groups_get_activity_groupmode($cm, $course);
2707 if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2708 if (isguestuser()) {
2709 // shortcut - guest user does not belong into any group
2713 if (is_null($modinfo->groups)) {
2714 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2717 // this will be slow - show only users that share group with me in this cm
2718 if (empty($modinfo->groups[$cm->id])) {
2721 $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
2722 if (is_array($usersgroups)) {
2723 $usersgroups = array_keys($usersgroups);
2724 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2725 if (empty($intersect)) {
2730 $show[] = $submission;
2737 echo $OUTPUT->heading(get_string('newsubmissions', 'assignment').':');
2739 foreach ($show as $submission) {
2740 $cm = $modinfo->cms[$submission->cmid];
2741 $link = $CFG->wwwroot.'/mod/assignment/view.php?id='.$cm->id;
2742 print_recent_activity_note($submission->timemodified, $submission, $cm->name, $link, false, $viewfullnames);
2750 * Returns all assignments since a given time in specified forum.
2752 function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0) {
2753 global $CFG, $COURSE, $USER, $DB;
2755 if ($COURSE->id == $courseid) {
2758 $course = $DB->get_record('course', array('id'=>$courseid));
2761 $modinfo =& get_fast_modinfo($course);
2763 $cm = $modinfo->cms[$cmid];
2767 $userselect = "AND u.id = :userid";
2768 $params['userid'] = $userid;
2774 $groupselect = "AND gm.groupid = :groupid";
2775 $groupjoin = "JOIN {groups_members} gm ON gm.userid=u.id";
2776 $params['groupid'] = $groupid;
2782 $params['cminstance'] = $cm->instance;
2783 $params['timestart'] = $timestart;
2785 if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, asb.userid,
2786 u.firstname, u.lastname, u.email, u.picture
2787 FROM {assignment_submissions} asb
2788 JOIN {assignment} a ON a.id = asb.assignment
2789 JOIN {user} u ON u.id = asb.userid
2791 WHERE asb.timemodified > :timestart AND a.id = :cminstance
2792 $userselect $groupselect
2793 ORDER BY asb.timemodified ASC", $params)) {
2797 $groupmode = groups_get_activity_groupmode($cm, $course);
2798 $cm_context = get_context_instance(CONTEXT_MODULE, $cm->id);
2799 $grader = has_capability('moodle/grade:viewall', $cm_context);
2800 $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
2801 $viewfullnames = has_capability('moodle/site:viewfullnames', $cm_context);
2803 if (is_null($modinfo->groups)) {
2804 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2809 foreach($submissions as $submission) {
2810 if ($submission->userid == $USER->id) {
2811 $show[] = $submission;
2814 // the act of submitting of assignment may be considered private - only graders will see it if specified
2815 if (empty($CFG->assignment_showrecentsubmissions)) {
2821 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
2822 if (isguestuser()) {
2823 // shortcut - guest user does not belong into any group
2827 // this will be slow - show only users that share group with me in this cm
2828 if (empty($modinfo->groups[$cm->id])) {
2831 $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
2832 if (is_array($usersgroups)) {
2833 $usersgroups = array_keys($usersgroups);
2834 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2835 if (empty($intersect)) {
2840 $show[] = $submission;
2848 require_once($CFG->libdir.'/gradelib.php');
2850 foreach ($show as $id=>$submission) {
2851 $userids[] = $submission->userid;
2854 $grades = grade_get_grades($courseid, 'mod', 'assignment', $cm->instance, $userids);
2857 $aname = format_string($cm->name,true);
2858 foreach ($show as $submission) {
2859 $tmpactivity = new object();
2861 $tmpactivity->type = 'assignment';
2862 $tmpactivity->cmid = $cm->id;
2863 $tmpactivity->name = $aname;
2864 $tmpactivity->sectionnum = $cm->sectionnum;
2865 $tmpactivity->timestamp = $submission->timemodified;
2868 $tmpactivity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
2871 $tmpactivity->user->userid = $submission->userid;
2872 $tmpactivity->user->fullname = fullname($submission, $viewfullnames);
2873 $tmpactivity->user->picture = $submission->picture;
2875 $activities[$index++] = $tmpactivity;
2882 * Print recent activity from all assignments in a given course
2884 * This is used by course/recent.php
2886 function assignment_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
2887 global $CFG, $OUTPUT;
2889 echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
2891 echo "<tr><td class=\"userpicture\" valign=\"top\">";
2892 echo $OUTPUT->user_picture(moodle_user_picture::make($activity->user, $courseid));
2896 $modname = $modnames[$activity->type];
2897 echo '<div class="title">';
2898 echo "<img src=\"" . $OUTPUT->mod_icon_url('icon', 'assignment') . "\" ".
2899 "class=\"icon\" alt=\"$modname\">";
2900 echo "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id={$activity->cmid}\">{$activity->name}</a>";
2904 if (isset($activity->grade)) {
2905 echo '<div class="grade">';
2906 echo get_string('grade').': ';
2907 echo $activity->grade;
2911 echo '<div class="user">';
2912 echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->userid}&course=$courseid\">"
2913 ."{$activity->user->fullname}</a> - ".userdate($activity->timestamp);
2916 echo "</td></tr></table>";
2919 /// GENERIC SQL FUNCTIONS
2922 * Fetch info from logs
2924 * @param $log object with properties ->info (the assignment id) and ->userid
2925 * @return array with assignment name and user firstname and lastname
2927 function assignment_log_info($log) {
2930 return $DB->get_record_sql("SELECT a.name, u.firstname, u.lastname
2931 FROM {assignment} a, {user} u
2932 WHERE a.id = ? AND u.id = ?", array($log->info, $log->userid));
2936 * Return list of marked submissions that have not been mailed out for currently enrolled students
2940 function assignment_get_unmailed_submissions($starttime, $endtime) {
2943 return $DB->get_records_sql("SELECT s.*, a.course, a.name
2944 FROM {assignment_submissions} s,
2947 AND s.timemarked <= ?
2948 AND s.timemarked >= ?
2949 AND s.assignment = a.id", array($endtime, $starttime));
2953 * Counts all real assignment submissions by ENROLLED students (not empty ones)
2955 * There are also assignment type methods count_real_submissions() wich in the default
2956 * implementation simply call this function.
2957 * @param $groupid int optional If nonzero then count is restricted to this group
2958 * @return int The number of submissions
2960 function assignment_count_real_submissions($cm, $groupid=0) {
2963 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2965 // this is all the users with this capability set, in this context or higher
2966 if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $groupid, '', false)) {
2967 $users = array_keys($users);
2970 // if groupmembersonly used, remove users who are not in any group
2971 if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
2972 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
2973 $users = array_intersect($users, array_keys($groupingusers));
2977 if (empty($users)) {
2981 $userlists = implode(',', $users);
2983 return $DB->count_records_sql("SELECT COUNT('x')
2984 FROM {assignment_submissions}
2985 WHERE assignment = ? AND
2986 timemodified > 0 AND
2987 userid IN ($userlists)", array($cm->instance));
2992 * Return all assignment submissions by ENROLLED students (even empty)
2994 * There are also assignment type methods get_submissions() wich in the default
2995 * implementation simply call this function.
2996 * @param $sort string optional field names for the ORDER BY in the sql query
2997 * @param $dir string optional specifying the sort direction, defaults to DESC
2998 * @return array The submission objects indexed by id
3000 function assignment_get_all_submissions($assignment, $sort="", $dir="DESC") {
3001 /// Return all assignment submissions by ENROLLED students (even empty)
3004 if ($sort == "lastname" or $sort == "firstname") {
3005 $sort = "u.$sort $dir";
3006 } else if (empty($sort)) {
3007 $sort = "a.timemodified DESC";
3009 $sort = "a.$sort $dir";
3012 /* not sure this is needed at all since assignmenet already has a course define, so this join?
3013 $select = "s.course = '$assignment->course' AND";
3014 if ($assignment->course == SITEID) {
3018 return $DB->get_records_sql("SELECT a.*
3019 FROM {assignment_submissions} a, {user} u
3020 WHERE u.id = a.userid
3021 AND a.assignment = ?
3022 ORDER BY $sort", array($assignment->id));
3027 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
3028 * for the course (see resource).
3030 * Given a course_module object, this function returns any "extra" information that may be needed
3031 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
3033 * @param $coursemodule object The coursemodule object (record).
3034 * @return object An object on information that the coures will know about (most noticeably, an icon).
3037 function assignment_get_coursemodule_info($coursemodule) {
3040 if (! $assignment = $DB->get_record('assignment', array('id'=>$coursemodule->instance), 'id, assignmenttype, name')) {
3044 $libfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
3046 if (file_exists($libfile)) {
3047 require_once($libfile);
3048 $assignmentclass = "assignment_$assignment->assignmenttype";
3049 $ass = new $assignmentclass('staticonly');
3050 if ($result = $ass->get_coursemodule_info($coursemodule)) {
3053 $info = new object();
3054 $info->name = $assignment->name;
3059 debugging('Incorrect assignment type: '.$assignment->assignmenttype);
3066 /// OTHER GENERAL FUNCTIONS FOR ASSIGNMENTS ///////////////////////////////////////
3069 * Returns an array of installed assignment types indexed and sorted by name
3071 * @return array The index is the name of the assignment type, the value its full name from the language strings
3073 function assignment_types() {
3075 $names = get_plugin_list('assignment');
3076 foreach ($names as $name=>$dir) {
3077 $types[$name] = get_string('type'.$name, 'assignment');
3079 // ugly hack to support pluggable assignment type titles..
3080 if ($types[$name] == '[[type'.$name.']]') {
3081 $types[$name] = get_string('type'.$name, 'assignment_'.$name);
3088 function assignment_print_overview($courses, &$htmlarray) {
3089 global $USER, $CFG, $DB;
3091 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
3095 if (!$assignments = get_all_instances_in_courses('assignment',$courses)) {
3099 $assignmentids = array();
3101 // Do assignment_base::isopen() here without loading the whole thing for speed
3102 foreach ($assignments as $key => $assignment) {
3104 if ($assignment->timedue) {
3105 if ($assignment->preventlate) {
3106 $isopen = ($assignment->timeavailable <= $time && $time <= $assignment->timedue);
3108 $isopen = ($assignment->timeavailable <= $time);
3111 if (empty($isopen) || empty($assignment->timedue)) {
3112 unset($assignments[$key]);
3114 $assignmentids[] = $assignment->id;
3118 if(empty($assignmentids)){
3119 // no assigments to look at - we're done
3123 $strduedate = get_string('duedate', 'assignment');
3124 $strduedateno = get_string('duedateno', 'assignment');
3125 $strgraded = get_string('graded', 'assignment');
3126 $strnotgradedyet = get_string('notgradedyet', 'assignment');
3127 $strnotsubmittedyet = get_string('notsubmittedyet', 'assignment');
3128 $strsubmitted = get_string('submitted', 'assignment');
3129 $strassignment = get_string('modulename', 'assignment');
3130 $strreviewed = get_string('reviewed','assignment');
3133 // NOTE: we do all possible database work here *outside* of the loop to ensure this scales
3135 list($sqlassignmentids, $assignmentidparams) = $DB->get_in_or_equal($assignmentids);
3137 // build up and array of unmarked submissions indexed by assigment id/ userid
3138 // for use where the user has grading rights on assigment
3139 $rs = $DB->get_recordset_sql("SELECT id, assignment, userid
3140 FROM {assignment_submissions}
3141 WHERE teacher = 0 AND timemarked = 0
3142 AND assignment $sqlassignmentids", $assignmentidparams);
3144 $unmarkedsubmissions = array();
3145 foreach ($rs as $rd) {
3146 $unmarkedsubmissions[$rd->assignment][$rd->userid] = $rd->id;
3151 // get all user submissions, indexed by assigment id
3152 $mysubmissions = $DB->get_records_sql("SELECT assignment, timemarked, teacher, grade
3153 FROM {assignment_submissions}
3154 WHERE userid = ? AND
3155 assignment $sqlassignmentids", array_merge(array($USER->id), $assignmentidparams));
3157 foreach ($assignments as $assignment) {
3158 $str = '<div class="assignment overview"><div class="name">'.$strassignment. ': '.
3159 '<a '.($assignment->visible ? '':' class="dimmed"').
3160 'title="'.$strassignment.'" href="'.$CFG->wwwroot.
3161 '/mod/assignment/view.php?id='.$assignment->coursemodule.'">'.
3162 $assignment->name.'</a></div>';
3163 if ($assignment->timedue) {
3164 $str .= '<div class="info">'.$strduedate.': '.userdate($assignment->timedue).'</div>';
3166 $str .= '<div class="info">'.$strduedateno.'</div>';
3168 $context = get_context_instance(CONTEXT_MODULE, $assignment->coursemodule);
3169 if (has_capability('mod/assignment:grade', $context)) {
3171 // count how many people can submit
3172 $submissions = 0; // init
3173 if ($students = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', 0, '', false)) {
3174 foreach($students as $student){
3175 if(isset($unmarkedsubmissions[$assignment->id][$student->id])){
3182 $str .= get_string('submissionsnotgraded', 'assignment', $submissions);
3185 if(isset($mysubmissions[$assignment->id])){
3187 $submission = $mysubmissions[$assignment->id];
3189 if ($submission->teacher == 0 && $submission->timemarked == 0) {
3190 $str .= $strsubmitted . ', ' . $strnotgradedyet;
3191 } else if ($submission->grade <= 0) {
3192 $str .= $strsubmitted . ', ' . $strreviewed;
3194 $str .= $strsubmitted . ', ' . $strgraded;
3197 $str .= $strnotsubmittedyet . ' ' . assignment_display_lateness(time(), $assignment->timedue);
3201 if (empty($htmlarray[$assignment->course]['assignment'])) {
3202 $htmlarray[$assignment->course]['assignment'] = $str;
3204 $htmlarray[$assignment->course]['assignment'] .= $str;
3209 function assignment_display_lateness($timesubmitted, $timedue) {
3213 $time = $timedue - $timesubmitted;
3215 $timetext = get_string('late', 'assignment', format_time($time));
3216 return ' (<span class="late">'.$timetext.'</span>)';
3218 $timetext = get_string('early', 'assignment', format_time($time));
3219 return ' (<span class="early">'.$timetext.'</span>)';
3223 function assignment_get_view_actions() {
3224 return array('view');
3227 function assignment_get_post_actions() {
3228 return array('upload');
3231 function assignment_get_types() {
3235 $type = new object();
3236 $type->modclass = MOD_CLASS_ACTIVITY;
3237 $type->type = "assignment_group_start";
3238 $type->typestr = '--'.get_string('modulenameplural', 'assignment');
3241 $standardassignments = array('upload','online','uploadsingle','offline');
3242 foreach ($standardassignments as $assignmenttype) {
3243 $type = new object();
3244 $type->modclass = MOD_CLASS_ACTIVITY;
3245 $type->type = "assignment&type=$assignmenttype";
3246 $type->typestr = get_string("type$assignmenttype", 'assignment');
3250 /// Drop-in extra assignment types
3251 $assignmenttypes = get_list_of_plugins('mod/assignment/type');
3252 foreach ($assignmenttypes as $assignmenttype) {
3253 if (!empty($CFG->{'assignment_hide_'.$assignmenttype})) { // Not wanted
3256 if (!in_array($assignmenttype, $standardassignments)) {
3257 $type = new object();
3258 $type->modclass = MOD_CLASS_ACTIVITY;
3259 $type->type = "assignment&type=$assignmenttype";
3260 $type->typestr = get_string("type$assignmenttype", 'assignment_'.$assignmenttype);
3265 $type = new object();
3266 $type->modclass = MOD_CLASS_ACTIVITY;
3267 $type->type = "assignment_group_end";
3268 $type->typestr = '--';
3275 * Removes all grades from gradebook
3276 * @param int $courseid
3277 * @param string optional type
3279 function assignment_reset_gradebook($courseid, $type='') {
3282 $params = array('courseid'=>$courseid);
3284 $type = "AND a.assignmenttype= :type";
3285 $params['type'] = $type;
3288 $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
3289 FROM {assignment} a, {course_modules} cm, {modules} m
3290 WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id AND a.course=:courseid $type";
3292 if ($assignments = $DB->get_records_sql($sql, $params)) {
3293 foreach ($assignments as $assignment) {
3294 assignment_grade_item_update($assignment, 'reset');
3300 * This function is used by the reset_course_userdata function in moodlelib.
3301 * This function will remove all posts from the specified assignment
3302 * and clean up any related data.
3303 * @param $data the data submitted from the reset course.
3304 * @return array status array
3306 function assignment_reset_userdata($data) {
3311 foreach (get_plugin_list('mod/assignment/type') as $type=>$dir) {
3312 require_once("$dir/assignment.class.php");
3313 $assignmentclass = "assignment_$type";
3314 $ass = new $assignmentclass();
3315 $status = array_merge($status, $ass->reset_userdata($data));
3322 * Implementation of the function for printing the form elements that control
3323 * whether the course reset functionality affects the assignment.
3324 * @param $mform form passed by reference
3326 function assignment_reset_course_form_definition(&$mform) {
3327 $mform->addElement('header', 'assignmentheader', get_string('modulenameplural', 'assignment'));
3328 $mform->addElement('advcheckbox', 'reset_assignment_submissions', get_string('deleteallsubmissions','assignment'));
3332 * Course reset form defaults.
3334 function assignment_reset_course_form_defaults($course) {
3335 return array('reset_assignment_submissions'=>1);
3339 * Returns all other caps used in module
3341 function assignment_get_extra_capabilities() {
3342 return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames');
3346 * @package mod-assignment
3347 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
3348 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3350 class assignment_portfolio_caller extends portfolio_module_caller_base {
3353 * the assignment subclass
3355 private $assignment;
3358 * the file to include when waking up to load the assignment subclass def
3360 private $assignmentfile;
3363 * callback arg for a single file export
3367 public static function expected_callbackargs() {
3374 public function load_data() {
3377 if (! $this->cm = get_coursemodule_from_id('assignment', $this->id)) {
3378 throw new portfolio_caller_exception('invalidcoursemodule');
3381 if (! $assignment = $DB->get_record("assignment", array("id"=>$this->cm->instance))) {
3382 throw new portfolio_caller_exception('invalidid', 'assignment');
3385 $this->assignmentfile = $CFG->dirroot . '/mod/assignment/type/' . $assignment->assignmenttype . '/assignment.class.php';
3386 require_once($this->assignmentfile);
3387 $assignmentclass = "assignment_$assignment->assignmenttype";
3389 $this->assignment = new $assignmentclass($this->cm->id, $assignment, $this->cm);
3391 if (!$this->assignment->portfolio_exportable()) {
3392 throw new portfolio_caller_exception('notexportable', 'portfolio', $this->get_return_url());
3395 $this->set_file_and_format_data($this->fileid, $this->assignment->context->id, 'assignment_submission', $this->user->id);
3396 if (empty($this->supportedformats) && is_callable(array($this->assignment, 'portfolio_supported_formats'))) {
3397 $this->supportedformats = $this->assignment->portfolio_supported_formats();
3401 public function prepare_package() {