3 * assignment_base is the base class for assignment types
5 * This class provides all the functionality for an assignment
8 DEFINE ('ASSIGNMENT_COUNT_WORDS', 1);
9 DEFINE ('ASSIGNMENT_COUNT_LETTERS', 2);
12 * Standard base class for all assignment submodules (assignment types).
14 class assignment_base
{
30 * Constructor for the base assignment class
32 * Constructor for the base assignment class.
33 * If cmid is set create the cm, course, assignment objects.
34 * If the assignment is hidden and the user is not a teacher then
35 * this prints a page header and notice.
37 * @param cmid integer, the current course module id - not set for new assignments
38 * @param assignment object, usually null, but if we have it we pass it to save db access
39 * @param cm object, usually null, but if we have it we pass it to save db access
40 * @param course object, usually null, but if we have it we pass it to save db access
42 function assignment_base($cmid='staticonly', $assignment=NULL, $cm=NULL, $course=NULL) {
45 if ($cmid == 'staticonly') {
46 //use static functions only!
54 } else if (! $this->cm
= get_coursemodule_from_id('assignment', $cmid)) {
55 error('Course Module ID was incorrect');
58 $this->context
= get_context_instance(CONTEXT_MODULE
, $this->cm
->id
);
61 $this->course
= $course;
62 } else if ($this->cm
->course
== $COURSE->id
) {
63 $this->course
= $COURSE;
64 } else if (! $this->course
= get_record('course', 'id', $this->cm
->course
)) {
65 error('Course is misconfigured');
69 $this->assignment
= $assignment;
70 } else if (! $this->assignment
= get_record('assignment', 'id', $this->cm
->instance
)) {
71 error('assignment ID was incorrect');
74 $this->assignment
->cmidnumber
= $this->cm
->id
; // compatibility with modedit assignment obj
75 $this->assignment
->courseid
= $this->course
->id
; // compatibility with modedit assignment obj
77 $this->strassignment
= get_string('modulename', 'assignment');
78 $this->strassignments
= get_string('modulenameplural', 'assignment');
79 $this->strsubmissions
= get_string('submissions', 'assignment');
80 $this->strlastmodified
= get_string('lastmodified');
81 $this->pagetitle
= strip_tags($this->course
->shortname
.': '.$this->strassignment
.': '.format_string($this->assignment
->name
,true));
83 // visibility handled by require_login() with $cm parameter
84 // get current group only when really needed
86 /// Set up things for a HTML editor if it's needed
87 if ($this->usehtmleditor
= can_use_html_editor()) {
88 $this->defaultformat
= FORMAT_HTML
;
90 $this->defaultformat
= FORMAT_MOODLE
;
95 * Display the assignment, used by view.php
97 * This in turn calls the methods producing individual parts of the page
101 $context = get_context_instance(CONTEXT_MODULE
,$this->cm
->id
);
102 require_capability('mod/assignment:view', $context);
104 add_to_log($this->course
->id
, "assignment", "view", "view.php?id={$this->cm->id}",
105 $this->assignment
->id
, $this->cm
->id
);
107 $this->view_header();
113 $this->view_feedback();
115 $this->view_footer();
119 * Display the header and top of a page
121 * (this doesn't change much for assignment types)
122 * This is used by the view() method to print the header of view.php but
123 * it can be used on other pages in which case the string to denote the
124 * page in the navigation trail should be passed as an argument
126 * @param $subpage string Description of subpage to be used in navigation trail
128 function view_header($subpage='') {
134 $navigation = build_navigation($subpage, $this->cm
);
136 $navigation = build_navigation('', $this->cm
);
139 print_header($this->pagetitle
, $this->course
->fullname
, $navigation, '', '',
140 true, update_module_button($this->cm
->id
, $this->course
->id
, $this->strassignment
),
141 navmenu($this->course
, $this->cm
));
143 groups_print_activity_menu($this->cm
, 'view.php?id=' . $this->cm
->id
);
145 echo '<div class="reportlink">'.$this->submittedlink().'</div>';
146 echo '<div class="clearer"></div>';
151 * Display the assignment intro
153 * This will most likely be extended by assignment type plug-ins
154 * The default implementation prints the assignment description in a box
156 function view_intro() {
157 print_simple_box_start('center', '', '', 0, 'generalbox', 'intro');
158 $formatoptions = new stdClass
;
159 $formatoptions->noclean
= true;
160 echo format_text($this->assignment
->description
, $this->assignment
->format
, $formatoptions);
161 print_simple_box_end();
165 * Display the assignment dates
167 * Prints the assignment start and end dates in a box.
168 * This will be suitable for most assignment types
170 function view_dates() {
171 if (!$this->assignment
->timeavailable
&& !$this->assignment
->timedue
) {
175 print_simple_box_start('center', '', '', 0, 'generalbox', 'dates');
177 if ($this->assignment
->timeavailable
) {
178 echo '<tr><td class="c0">'.get_string('availabledate','assignment').':</td>';
179 echo ' <td class="c1">'.userdate($this->assignment
->timeavailable
).'</td></tr>';
181 if ($this->assignment
->timedue
) {
182 echo '<tr><td class="c0">'.get_string('duedate','assignment').':</td>';
183 echo ' <td class="c1">'.userdate($this->assignment
->timedue
).'</td></tr>';
186 print_simple_box_end();
191 * Display the bottom and footer of a page
193 * This default method just prints the footer.
194 * This will be suitable for most assignment types
196 function view_footer() {
197 print_footer($this->course
);
201 * Display the feedback to the student
203 * This default method prints the teacher picture and name, date when marked,
204 * grade and teacher submissioncomment.
206 * @param $submission object The submission object or NULL in which case it will be loaded
208 function view_feedback($submission=NULL) {
210 require_once($CFG->libdir
.'/gradelib.php');
212 if (!has_capability('mod/assignment:submit', $this->context
, $USER->id
, false)) {
213 // can not submit assignments -> no feedback
217 if (!$submission) { /// Get submission for this assignment
218 $submission = $this->get_submission($USER->id
);
221 $grading_info = grade_get_grades($this->course
->id
, 'mod', 'assignment', $this->assignment
->id
, $USER->id
);
222 $item = $grading_info->items
[0];
223 $grade = $item->grades
[$USER->id
];
225 if ($grade->hidden
or $grade->grade
=== false) { // hidden or error
229 if ($grade->grade
=== null and empty($grade->str_feedback
)) { /// Nothing to show yet
233 $graded_date = $grade->dategraded
;
234 $graded_by = $grade->usermodified
;
236 /// We need the teacher info
237 if (!$teacher = get_record('user', 'id', $graded_by)) {
238 error('Could not find the teacher');
241 /// Print the feedback
242 print_heading(get_string('feedbackfromteacher', 'assignment', $this->course
->teacher
)); // TODO: fix teacher string
244 echo '<table cellspacing="0" class="feedback">';
247 echo '<td class="left picture">';
249 print_user_picture($teacher, $this->course
->id
, $teacher->picture
);
252 echo '<td class="topic">';
253 echo '<div class="from">';
255 echo '<div class="fullname">'.fullname($teacher).'</div>';
257 echo '<div class="time">'.userdate($graded_date).'</div>';
263 echo '<td class="left side"> </td>';
264 echo '<td class="content">';
265 echo '<div class="grade">';
266 echo get_string("grade").': '.$grade->str_long_grade
;
268 echo '<div class="clearer"></div>';
270 echo '<div class="comment">';
271 echo $grade->str_feedback
;
279 * Returns a link with info about the state of the assignment submissions
281 * This is used by view_header to put this link at the top right of the page.
282 * For teachers it gives the number of submitted assignments with a link
283 * For students it gives the time of their submission.
284 * This will be suitable for most assignment types.
285 * @param bool $allgroup print all groups info if user can access all groups, suitable for index.php
288 function submittedlink($allgroups=false) {
293 $context = get_context_instance(CONTEXT_MODULE
,$this->cm
->id
);
294 if (has_capability('mod/assignment:grade', $context)) {
295 if ($allgroups and has_capability('moodle/site:accessallgroups', $context)) {
298 $group = groups_get_activity_group($this->cm
);
300 if ($count = $this->count_real_submissions($group)) {
301 $submitted = '<a href="submissions.php?id='.$this->cm
->id
.'">'.
302 get_string('viewsubmissions', 'assignment', $count).'</a>';
304 $submitted = '<a href="submissions.php?id='.$this->cm
->id
.'">'.
305 get_string('noattempts', 'assignment').'</a>';
308 if (!empty($USER->id
)) {
309 if ($submission = $this->get_submission($USER->id
)) {
310 if ($submission->timemodified
) {
311 if ($submission->timemodified
<= $this->assignment
->timedue ||
empty($this->assignment
->timedue
)) {
312 $submitted = '<span class="early">'.userdate($submission->timemodified
).'</span>';
314 $submitted = '<span class="late">'.userdate($submission->timemodified
).'</span>';
325 function setup_elements(&$mform) {
330 * Create a new assignment activity
332 * Given an object containing all the necessary data,
333 * (defined by the form in mod.html) this function
334 * will create a new instance and return the id number
335 * of the new instance.
336 * The due data is added to the calendar
337 * This is common to all assignment types.
339 * @param $assignment object The data from the form on mod.html
340 * @return int The id of the assignment
342 function add_instance($assignment) {
345 $assignment->timemodified
= time();
346 $assignment->courseid
= $assignment->course
;
348 if ($returnid = insert_record("assignment", $assignment)) {
349 $assignment->id
= $returnid;
351 if ($assignment->timedue
) {
352 $event = new object();
353 $event->name
= $assignment->name
;
354 $event->description
= $assignment->description
;
355 $event->courseid
= $assignment->course
;
358 $event->modulename
= 'assignment';
359 $event->instance
= $returnid;
360 $event->eventtype
= 'due';
361 $event->timestart
= $assignment->timedue
;
362 $event->timeduration
= 0;
367 $assignment = stripslashes_recursive($assignment);
368 assignment_grade_item_update($assignment);
377 * Deletes an assignment activity
379 * Deletes all database records, files and calendar events for this assignment.
380 * @param $assignment object The assignment to be deleted
381 * @return boolean False indicates error
383 function delete_instance($assignment) {
386 $assignment->courseid
= $assignment->course
;
390 if (! delete_records('assignment_submissions', 'assignment', $assignment->id
)) {
394 if (! delete_records('assignment', 'id', $assignment->id
)) {
398 if (! delete_records('event', 'modulename', 'assignment', 'instance', $assignment->id
)) {
402 // delete file area with all attachments - ignore errors
403 require_once($CFG->libdir
.'/filelib.php');
404 fulldelete($CFG->dataroot
.'/'.$assignment->course
.'/'.$CFG->moddata
.'/assignment/'.$assignment->id
);
406 assignment_grade_item_delete($assignment);
412 * Updates a new assignment activity
414 * Given an object containing all the necessary data,
415 * (defined by the form in mod.html) this function
416 * will update the assignment instance and return the id number
417 * The due date is updated in the calendar
418 * This is common to all assignment types.
420 * @param $assignment object The data from the form on mod.html
421 * @return int The assignment id
423 function update_instance($assignment) {
426 $assignment->timemodified
= time();
428 $assignment->id
= $assignment->instance
;
429 $assignment->courseid
= $assignment->course
;
431 if (!update_record('assignment', $assignment)) {
435 if ($assignment->timedue
) {
436 $event = new object();
438 if ($event->id
= get_field('event', 'id', 'modulename', 'assignment', 'instance', $assignment->id
)) {
440 $event->name
= $assignment->name
;
441 $event->description
= $assignment->description
;
442 $event->timestart
= $assignment->timedue
;
444 update_event($event);
446 $event = new object();
447 $event->name
= $assignment->name
;
448 $event->description
= $assignment->description
;
449 $event->courseid
= $assignment->course
;
452 $event->modulename
= 'assignment';
453 $event->instance
= $assignment->id
;
454 $event->eventtype
= 'due';
455 $event->timestart
= $assignment->timedue
;
456 $event->timeduration
= 0;
461 delete_records('event', 'modulename', 'assignment', 'instance', $assignment->id
);
464 // get existing grade item
465 $assignment = stripslashes_recursive($assignment);
467 assignment_grade_item_update($assignment);
473 * Update grade item for this submission.
475 function update_grade($submission) {
476 assignment_update_grades($this->assignment
, $submission->userid
);
480 * Top-level function for handling of submissions called by submissions.php
482 * This is for handling the teacher interaction with the grading interface
483 * This should be suitable for most assignment types.
485 * @param $mode string Specifies the kind of teacher interaction taking place
487 function submissions($mode) {
488 ///The main switch is changed to facilitate
489 ///1) Batch fast grading
490 ///2) Skip to the next one on the popup
491 ///3) Save and Skip to the next one on the popup
493 //make user global so we can use the id
496 $mailinfo = optional_param('mailinfo', null, PARAM_BOOL
);
497 if (is_null($mailinfo)) {
498 $mailinfo = get_user_preferences('assignment_mailinfo', 0);
500 set_user_preference('assignment_mailinfo', $mailinfo);
504 case 'grade': // We are in a popup window grading
505 if ($submission = $this->process_feedback()) {
506 //IE needs proper header with encoding
507 print_header(get_string('feedback', 'assignment').':'.format_string($this->assignment
->name
));
508 print_heading(get_string('changessaved'));
509 print $this->update_main_listing($submission);
514 case 'single': // We are in a popup window displaying submission
515 $this->display_submission();
518 case 'all': // Main window, display everything
519 $this->display_submissions();
523 ///do the fast grading stuff - this process should work for all 3 subclasses
528 if (isset($_POST['submissioncomment'])) {
529 $col = 'submissioncomment';
532 if (isset($_POST['menu'])) {
537 //both submissioncomment and grade columns collapsed..
538 $this->display_submissions();
542 foreach ($_POST[$col] as $id => $unusedvalue){
544 $id = (int)$id; //clean parameter name
546 $this->process_outcomes($id);
548 if (!$submission = $this->get_submission($id)) {
549 $submission = $this->prepare_new_submission($id);
550 $newsubmission = true;
552 $newsubmission = false;
554 unset($submission->data1
); // Don't need to update this.
555 unset($submission->data2
); // Don't need to update this.
557 //for fast grade, we need to check if any changes take place
561 $grade = $_POST['menu'][$id];
562 $updatedb = $updatedb ||
($submission->grade
!= $grade);
563 $submission->grade
= $grade;
565 if (!$newsubmission) {
566 unset($submission->grade
); // Don't need to update this.
570 $commentvalue = trim($_POST['submissioncomment'][$id]);
571 $updatedb = $updatedb ||
($submission->submissioncomment
!= stripslashes($commentvalue));
572 $submission->submissioncomment
= $commentvalue;
574 unset($submission->submissioncomment
); // Don't need to update this.
577 $submission->teacher
= $USER->id
;
579 $submission->mailed
= (int)(!$mailinfo);
582 $submission->timemarked
= time();
584 //if it is not an update, we don't change the last modified time etc.
585 //this will also not write into database if no submissioncomment and grade is entered.
588 if ($newsubmission) {
589 if (!isset($submission->submissioncomment
)) {
590 $submission->submissioncomment
= '';
592 if (!$sid = insert_record('assignment_submissions', $submission)) {
595 $submission->id
= $sid;
597 if (!update_record('assignment_submissions', $submission)) {
602 // triger grade event
603 $this->update_grade($submission);
605 //add to log only if updating
606 add_to_log($this->course
->id
, 'assignment', 'update grades',
607 'submissions.php?id='.$this->assignment
->id
.'&user='.$submission->userid
,
608 $submission->userid
, $this->cm
->id
);
613 $message = notify(get_string('changessaved'), 'notifysuccess', 'center', true);
615 $this->display_submissions($message);
620 /// We are currently in pop up, but we want to skip to next one without saving.
621 /// This turns out to be similar to a single case
622 /// The URL used is for the next submission.
624 $this->display_submission();
628 ///We are in pop up. save the current one and go to the next one.
629 //first we save the current changes
630 if ($submission = $this->process_feedback()) {
631 //print_heading(get_string('changessaved'));
632 $extra_javascript = $this->update_main_listing($submission);
635 //then we display the next submission
636 $this->display_submission($extra_javascript);
640 echo "something seriously is wrong!!";
646 * Helper method updating the listing on the main script from popup using javascript
648 * @param $submission object The submission whose data is to be updated on the main page
650 function update_main_listing($submission) {
651 global $SESSION, $CFG;
655 $perpage = get_user_preferences('assignment_perpage', 10);
657 $quickgrade = get_user_preferences('assignment_quickgrade', 0);
659 /// Run some Javascript to try and update the parent page
660 $output .= '<script type="text/javascript">'."\n<!--\n";
661 if (empty($SESSION->flextable
['mod-assignment-submissions']->collapse
['submissioncomment'])) {
663 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid
.'").value="'
664 .trim($submission->submissioncomment
).'";'."\n";
666 $output.= 'opener.document.getElementById("com'.$submission->userid
.
667 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment
)), 15)."\";\n";
671 if (empty($SESSION->flextable
['mod-assignment-submissions']->collapse
['grade'])) {
672 //echo optional_param('menuindex');
674 $output.= 'opener.document.getElementById("menumenu'.$submission->userid
.
675 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT
).'";'."\n";
677 $output.= 'opener.document.getElementById("g'.$submission->userid
.'").innerHTML="'.
678 $this->display_grade($submission->grade
)."\";\n";
681 //need to add student's assignments in there too.
682 if (empty($SESSION->flextable
['mod-assignment-submissions']->collapse
['timemodified']) &&
683 $submission->timemodified
) {
684 $output.= 'opener.document.getElementById("ts'.$submission->userid
.
685 '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid
)).userdate($submission->timemodified
)."\";\n";
688 if (empty($SESSION->flextable
['mod-assignment-submissions']->collapse
['timemarked']) &&
689 $submission->timemarked
) {
690 $output.= 'opener.document.getElementById("tt'.$submission->userid
.
691 '").innerHTML="'.userdate($submission->timemarked
)."\";\n";
694 if (empty($SESSION->flextable
['mod-assignment-submissions']->collapse
['status'])) {
695 $output.= 'opener.document.getElementById("up'.$submission->userid
.'").className="s1";';
696 $buttontext = get_string('update');
697 $button = link_to_popup_window ('/mod/assignment/submissions.php?id='.$this->cm
->id
.'&userid='.$submission->userid
.'&mode=single'.'&offset='.(optional_param('offset', '', PARAM_INT
)-1),
698 'grade'.$submission->userid
, $buttontext, 450, 700, $buttontext, 'none', true, 'button'.$submission->userid
);
699 $output.= 'opener.document.getElementById("up'.$submission->userid
.'").innerHTML="'.addslashes_js($button).'";';
702 $grading_info = grade_get_grades($this->course
->id
, 'mod', 'assignment', $this->assignment
->id
, $submission->userid
);
704 if (empty($SESSION->flextable
['mod-assignment-submissions']->collapse
['finalgrade'])) {
705 $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid
.
706 '").innerHTML="'.$grading_info->items
[0]->grades
[$submission->userid
]->str_grade
.'";'."\n";
709 if (!empty($CFG->enableoutcomes
) and empty($SESSION->flextable
['mod-assignment-submissions']->collapse
['outcome'])) {
711 if (!empty($grading_info->outcomes
)) {
712 foreach($grading_info->outcomes
as $n=>$outcome) {
713 if ($outcome->grades
[$submission->userid
]->locked
) {
718 $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid
.
719 '").selectedIndex="'.$outcome->grades
[$submission->userid
]->grade
.'";'."\n";
722 $options = make_grades_menu(-$outcome->scaleid
);
723 $options[0] = get_string('nooutcome', 'grades');
724 $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid
.'").innerHTML="'.$options[$outcome->grades
[$submission->userid
]->grade
]."\";\n";
731 $output .= "\n-->\n</script>";
736 * Return a grade in user-friendly form, whether it's a scale or not
739 * @return string User-friendly representation of grade
741 function display_grade($grade) {
743 static $scalegrades = array(); // Cache scales for each assignment - they might have different scales!!
745 if ($this->assignment
->grade
>= 0) { // Normal number
749 return $grade.' / '.$this->assignment
->grade
;
753 if (empty($scalegrades[$this->assignment
->id
])) {
754 if ($scale = get_record('scale', 'id', -($this->assignment
->grade
))) {
755 $scalegrades[$this->assignment
->id
] = make_menu_from_list($scale->scale
);
760 if (isset($scalegrades[$this->assignment
->id
][$grade])) {
761 return $scalegrades[$this->assignment
->id
][$grade];
768 * Display a single submission, ready for grading on a popup window
770 * This default method prints the teacher info and submissioncomment box at the top and
771 * the student info and submission at the bottom.
772 * This method also fetches the necessary data in order to be able to
773 * provide a "Next submission" button.
774 * Calls preprocess_submission() to give assignment type plug-ins a chance
775 * to process submissions before they are graded
776 * This method gets its arguments from the page parameters userid and offset
778 function display_submission($extra_javascript = '') {
781 require_once($CFG->libdir
.'/gradelib.php');
782 require_once($CFG->libdir
.'/tablelib.php');
784 $userid = required_param('userid', PARAM_INT
);
785 $offset = required_param('offset', PARAM_INT
);//offset for where to start looking for student.
787 if (!$user = get_record('user', 'id', $userid)) {
788 error('No such user!');
791 if (!$submission = $this->get_submission($user->id
)) {
792 $submission = $this->prepare_new_submission($userid);
794 if ($submission->timemodified
> $submission->timemarked
) {
795 $subtype = 'assignmentnew';
797 $subtype = 'assignmentold';
800 $grading_info = grade_get_grades($this->course
->id
, 'mod', 'assignment', $this->assignment
->id
, array($user->id
));
801 $disabled = $grading_info->items
[0]->grades
[$userid]->locked ||
$grading_info->items
[0]->grades
[$userid]->overridden
;
803 /// construct SQL, using current offset to find the data of the next student
804 $course = $this->course
;
805 $assignment = $this->assignment
;
807 $context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
809 /// Get all ppl that can submit assignments
811 $currentgroup = groups_get_activity_group($cm);
812 if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $currentgroup, '', false)) {
813 $users = array_keys($users);
816 // if groupmembersonly used, remove users who are not in any group
817 if ($users and !empty($CFG->enablegroupings
) and $cm->groupmembersonly
) {
818 if ($groupingusers = groups_get_grouping_members($cm->groupingid
, 'u.id', 'u.id')) {
819 $users = array_intersect($users, array_keys($groupingusers));
826 $select = 'SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt,
827 s.id AS submissionid, s.grade, s.submissioncomment,
828 s.timemodified, s.timemarked,
829 COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ';
830 $sql = 'FROM '.$CFG->prefix
.'user u '.
831 'LEFT JOIN '.$CFG->prefix
.'assignment_submissions s ON u.id = s.userid
832 AND s.assignment = '.$this->assignment
->id
.' '.
833 'WHERE u.id IN ('.implode(',', $users).') ';
835 if ($sort = flexible_table
::get_sql_sort('mod-assignment-submissions')) {
836 $sort = 'ORDER BY '.$sort.' ';
839 if (($auser = get_records_sql($select.$sql.$sort, $offset+
1, 1)) !== false) {
840 $nextuser = array_shift($auser);
841 /// Calculate user status
842 $nextuser->status
= ($nextuser->timemarked
> 0) && ($nextuser->timemarked
>= $nextuser->timemodified
);
843 $nextid = $nextuser->id
;
847 print_header(get_string('feedback', 'assignment').':'.fullname($user, true).':'.format_string($this->assignment
->name
));
849 /// Print any extra javascript needed for saveandnext
850 echo $extra_javascript;
852 ///SOme javascript to help with setting up >.>
854 echo '<script type="text/javascript">'."\n";
855 echo 'function setNext(){'."\n";
856 echo 'document.getElementById(\'submitform\').mode.value=\'next\';'."\n";
857 echo 'document.getElementById(\'submitform\').userid.value="'.$nextid.'";'."\n";
860 echo 'function saveNext(){'."\n";
861 echo 'document.getElementById(\'submitform\').mode.value=\'saveandnext\';'."\n";
862 echo 'document.getElementById(\'submitform\').userid.value="'.$nextid.'";'."\n";
863 echo 'document.getElementById(\'submitform\').saveuserid.value="'.$userid.'";'."\n";
864 echo 'document.getElementById(\'submitform\').menuindex.value = document.getElementById(\'submitform\').grade.selectedIndex;'."\n";
867 echo '</script>'."\n";
868 echo '<table cellspacing="0" class="feedback '.$subtype.'" >';
870 ///Start of teacher info row
873 echo '<td class="picture teacher">';
874 if ($submission->teacher
) {
875 $teacher = get_record('user', 'id', $submission->teacher
);
880 print_user_picture($teacher, $this->course
->id
, $teacher->picture
);
882 echo '<td class="content">';
883 echo '<form id="submitform" action="submissions.php" method="post">';
884 echo '<div>'; // xhtml compatibility - invisiblefieldset was breaking layout here
885 echo '<input type="hidden" name="offset" value="'.($offset+
1).'" />';
886 echo '<input type="hidden" name="userid" value="'.$userid.'" />';
887 echo '<input type="hidden" name="id" value="'.$this->cm
->id
.'" />';
888 echo '<input type="hidden" name="mode" value="grade" />';
889 echo '<input type="hidden" name="menuindex" value="0" />';//selected menu index
891 //new hidden field, initialized to -1.
892 echo '<input type="hidden" name="saveuserid" value="-1" />';
894 if ($submission->timemarked
) {
895 echo '<div class="from">';
896 echo '<div class="fullname">'.fullname($teacher, true).'</div>';
897 echo '<div class="time">'.userdate($submission->timemarked
).'</div>';
900 echo '<div class="grade"><label for="menugrade">'.get_string('grade').'</label> ';
901 choose_from_menu(make_grades_menu($this->assignment
->grade
), 'grade', $submission->grade
, get_string('nograde'), '', -1, false, $disabled);
904 echo '<div class="clearer"></div>';
905 echo '<div class="finalgrade">'.get_string('finalgrade', 'grades').': '.$grading_info->items
[0]->grades
[$userid]->str_grade
.'</div>';
906 echo '<div class="clearer"></div>';
908 if (!empty($CFG->enableoutcomes
)) {
909 foreach($grading_info->outcomes
as $n=>$outcome) {
910 echo '<div class="outcome"><label for="menuoutcome_'.$n.'">'.$outcome->name
.'</label> ';
911 $options = make_grades_menu(-$outcome->scaleid
);
912 if ($outcome->grades
[$submission->userid
]->locked
) {
913 $options[0] = get_string('nooutcome', 'grades');
914 echo $options[$outcome->grades
[$submission->userid
]->grade
];
916 choose_from_menu($options, 'outcome_'.$n.'['.$userid.']', $outcome->grades
[$submission->userid
]->grade
, get_string('nooutcome', 'grades'), '', 0, false, false, 0, 'menuoutcome_'.$n);
919 echo '<div class="clearer"></div>';
924 $this->preprocess_submission($submission);
927 echo '<div class="disabledfeedback">'.$grading_info->items
[0]->grades
[$userid]->str_feedback
.'</div>';
930 print_textarea($this->usehtmleditor
, 14, 58, 0, 0, 'submissioncomment', $submission->submissioncomment
, $this->course
->id
);
931 if ($this->usehtmleditor
) {
932 echo '<input type="hidden" name="format" value="'.FORMAT_HTML
.'" />';
934 echo '<div class="format">';
935 choose_from_menu(format_text_menu(), "format", $submission->format
, "");
936 helpbutton("textformat", get_string("helpformatting"));
941 $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ?
'checked="checked"' : '';
943 ///Print Buttons in Single View
944 echo '<input type="hidden" name="mailinfo" value="0" />';
945 echo '<input type="checkbox" id="mailinfo" name="mailinfo" value="1" '.$lastmailinfo.' /><label for="mailinfo">'.get_string('enableemailnotification','assignment').'</label>';
946 echo '<div class="buttons">';
947 echo '<input type="submit" name="submit" value="'.get_string('savechanges').'" onclick = "document.getElementById(\'submitform\').menuindex.value = document.getElementById(\'submitform\').grade.selectedIndex" />';
948 echo '<input type="submit" name="cancel" value="'.get_string('cancel').'" />';
949 //if there are more to be graded.
951 echo '<input type="submit" name="saveandnext" value="'.get_string('saveandnext').'" onclick="saveNext()" />';
952 echo '<input type="submit" name="next" value="'.get_string('next').'" onclick="setNext();" />';
955 echo '</div></form>';
957 $customfeedback = $this->custom_feedbackform($submission, true);
958 if (!empty($customfeedback)) {
959 echo $customfeedback;
964 ///End of teacher info row, Start of student info row
966 echo '<td class="picture user">';
967 print_user_picture($user, $this->course
->id
, $user->picture
);
969 echo '<td class="topic">';
970 echo '<div class="from">';
971 echo '<div class="fullname">'.fullname($user, true).'</div>';
972 if ($submission->timemodified
) {
973 echo '<div class="time">'.userdate($submission->timemodified
).
974 $this->display_lateness($submission->timemodified
).'</div>';
977 $this->print_user_files($user->id
);
981 ///End of student info row
985 if (!$disabled and $this->usehtmleditor
) {
989 print_footer('none');
993 * Preprocess submission before grading
995 * Called by display_submission()
996 * The default type does nothing here.
997 * @param $submission object The submission object
999 function preprocess_submission(&$submission) {
1003 * Display all the submissions ready for grading
1005 function display_submissions($message='') {
1006 global $CFG, $db, $USER;
1007 require_once($CFG->libdir
.'/gradelib.php');
1009 /* first we check to see if the form has just been submitted
1010 * to request user_preference updates
1013 if (isset($_POST['updatepref'])){
1014 $perpage = optional_param('perpage', 10, PARAM_INT
);
1015 $perpage = ($perpage <= 0) ?
10 : $perpage ;
1016 set_user_preference('assignment_perpage', $perpage);
1017 set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL
));
1020 /* next we get perpage and quickgrade (allow quick grade) params
1023 $perpage = get_user_preferences('assignment_perpage', 10);
1025 $quickgrade = get_user_preferences('assignment_quickgrade', 0);
1027 $grading_info = grade_get_grades($this->course
->id
, 'mod', 'assignment', $this->assignment
->id
);
1029 if (!empty($CFG->enableoutcomes
) and !empty($grading_info->outcomes
)) {
1030 $uses_outcomes = true;
1032 $uses_outcomes = false;
1035 $page = optional_param('page', 0, PARAM_INT
);
1036 $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
1038 /// Some shortcuts to make the code read better
1040 $course = $this->course
;
1041 $assignment = $this->assignment
;
1044 $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
1046 add_to_log($course->id
, 'assignment', 'view submission', 'submissions.php?id='.$this->assignment
->id
, $this->assignment
->id
, $this->cm
->id
);
1048 $navigation = build_navigation($this->strsubmissions
, $this->cm
);
1049 print_header_simple(format_string($this->assignment
->name
,true), "", $navigation,
1050 '', '', true, update_module_button($cm->id
, $course->id
, $this->strassignment
), navmenu($course, $cm));
1052 $course_context = get_context_instance(CONTEXT_COURSE
, $course->id
);
1053 if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
1054 echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot
. '/grade/report/grader/index.php?id=' . $course->id
. '">'
1055 . get_string('seeallcoursegrades', 'grades') . '</a></div>';
1058 if (!empty($message)) {
1059 echo $message; // display messages here if any
1062 $context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
1064 /// Check to see if groups are being used in this assignment
1066 /// find out current groups mode
1067 $groupmode = groups_get_activity_groupmode($cm);
1068 $currentgroup = groups_get_activity_group($cm, true);
1069 groups_print_activity_menu($cm, 'submissions.php?id=' . $this->cm
->id
);
1071 /// Get all ppl that are allowed to submit assignments
1072 if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $currentgroup, '', false)) {
1073 $users = array_keys($users);
1076 // if groupmembersonly used, remove users who are not in any group
1077 if ($users and !empty($CFG->enablegroupings
) and $cm->groupmembersonly
) {
1078 if ($groupingusers = groups_get_grouping_members($cm->groupingid
, 'u.id', 'u.id')) {
1079 $users = array_intersect($users, array_keys($groupingusers));
1083 $tablecolumns = array('picture', 'fullname', 'grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade');
1084 if ($uses_outcomes) {
1085 $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
1088 $tableheaders = array('',
1089 get_string('fullname'),
1090 get_string('grade'),
1091 get_string('comment', 'assignment'),
1092 get_string('lastmodified').' ('.$course->student
.')',
1093 get_string('lastmodified').' ('.$course->teacher
.')',
1094 get_string('status'),
1095 get_string('finalgrade', 'grades'));
1096 if ($uses_outcomes) {
1097 $tableheaders[] = get_string('outcome', 'grades');
1100 require_once($CFG->libdir
.'/tablelib.php');
1101 $table = new flexible_table('mod-assignment-submissions');
1103 $table->define_columns($tablecolumns);
1104 $table->define_headers($tableheaders);
1105 $table->define_baseurl($CFG->wwwroot
.'/mod/assignment/submissions.php?id='.$this->cm
->id
.'&currentgroup='.$currentgroup);
1107 $table->sortable(true, 'lastname');//sorted by lastname by default
1108 $table->collapsible(true);
1109 $table->initialbars(true);
1111 $table->column_suppress('picture');
1112 $table->column_suppress('fullname');
1114 $table->column_class('picture', 'picture');
1115 $table->column_class('fullname', 'fullname');
1116 $table->column_class('grade', 'grade');
1117 $table->column_class('submissioncomment', 'comment');
1118 $table->column_class('timemodified', 'timemodified');
1119 $table->column_class('timemarked', 'timemarked');
1120 $table->column_class('status', 'status');
1121 $table->column_class('finalgrade', 'finalgrade');
1122 if ($uses_outcomes) {
1123 $table->column_class('outcome', 'outcome');
1126 $table->set_attribute('cellspacing', '0');
1127 $table->set_attribute('id', 'attempts');
1128 $table->set_attribute('class', 'submissions');
1129 $table->set_attribute('width', '100%');
1130 //$table->set_attribute('align', 'center');
1132 $table->no_sorting('finalgrade');
1133 $table->no_sorting('outcome');
1135 // Start working -- this is necessary as soon as the niceties are over
1138 if (empty($users)) {
1139 print_heading(get_string('nosubmitusers','assignment'));
1143 /// Construct the SQL
1145 if ($where = $table->get_sql_where()) {
1149 if ($sort = $table->get_sql_sort()) {
1150 $sort = ' ORDER BY '.$sort;
1153 $select = 'SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt,
1154 s.id AS submissionid, s.grade, s.submissioncomment,
1155 s.timemodified, s.timemarked,
1156 COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ';
1157 $sql = 'FROM '.$CFG->prefix
.'user u '.
1158 'LEFT JOIN '.$CFG->prefix
.'assignment_submissions s ON u.id = s.userid
1159 AND s.assignment = '.$this->assignment
->id
.' '.
1160 'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1162 $table->pagesize($perpage, count($users));
1164 ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1165 $offset = $page * $perpage;
1167 $strupdate = get_string('update');
1168 $strgrade = get_string('grade');
1169 $grademenu = make_grades_menu($this->assignment
->grade
);
1171 if (($ausers = get_records_sql($select.$sql.$sort, $table->get_page_start(), $table->get_page_size())) !== false) {
1172 $grading_info = grade_get_grades($this->course
->id
, 'mod', 'assignment', $this->assignment
->id
, array_keys($ausers));
1173 foreach ($ausers as $auser) {
1174 $final_grade = $grading_info->items
[0]->grades
[$auser->id
];
1175 $grademax = $grading_info->items
[0]->grademax
;
1176 $final_grade->formatted_grade
= round($final_grade->grade
,2) .' / ' . round($grademax,2);
1177 $locked_overridden = 'locked';
1178 if ($final_grade->overridden
) {
1179 $locked_overridden = 'overridden';
1182 /// Calculate user status
1183 $auser->status
= ($auser->timemarked
> 0) && ($auser->timemarked
>= $auser->timemodified
);
1184 $picture = print_user_picture($auser, $course->id
, $auser->picture
, false, true);
1186 if (empty($auser->submissionid
)) {
1187 $auser->grade
= -1; //no submission yet
1190 if (!empty($auser->submissionid
)) {
1191 ///Prints student answer and student modified date
1192 ///attach file or print link to student answer, depending on the type of the assignment.
1193 ///Refer to print_student_answer in inherited classes.
1194 if ($auser->timemodified
> 0) {
1195 $studentmodified = '<div id="ts'.$auser->id
.'">'.$this->print_student_answer($auser->id
)
1196 . userdate($auser->timemodified
).'</div>';
1198 $studentmodified = '<div id="ts'.$auser->id
.'"> </div>';
1200 ///Print grade, dropdown or text
1201 if ($auser->timemarked
> 0) {
1202 $teachermodified = '<div id="tt'.$auser->id
.'">'.userdate($auser->timemarked
).'</div>';
1204 if ($final_grade->locked
or $final_grade->overridden
) {
1205 $grade = '<div id="g'.$auser->id
.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade
.'</div>';
1206 } else if ($quickgrade) {
1207 $menu = choose_from_menu(make_grades_menu($this->assignment
->grade
),
1208 'menu['.$auser->id
.']', $auser->grade
,
1209 get_string('nograde'),'',-1,true,false,$tabindex++
);
1210 $grade = '<div id="g'.$auser->id
.'">'. $menu .'</div>';
1212 $grade = '<div id="g'.$auser->id
.'">'.$this->display_grade($auser->grade
).'</div>';
1216 $teachermodified = '<div id="tt'.$auser->id
.'"> </div>';
1217 if ($final_grade->locked
or $final_grade->overridden
) {
1218 $grade = '<div id="g'.$auser->id
.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade
.'</div>';
1219 } else if ($quickgrade) {
1220 $menu = choose_from_menu(make_grades_menu($this->assignment
->grade
),
1221 'menu['.$auser->id
.']', $auser->grade
,
1222 get_string('nograde'),'',-1,true,false,$tabindex++
);
1223 $grade = '<div id="g'.$auser->id
.'">'.$menu.'</div>';
1225 $grade = '<div id="g'.$auser->id
.'">'.$this->display_grade($auser->grade
).'</div>';
1229 if ($final_grade->locked
or $final_grade->overridden
) {
1230 $comment = '<div id="com'.$auser->id
.'">'.shorten_text(strip_tags($final_grade->str_feedback
),15).'</div>';
1232 } else if ($quickgrade) {
1233 $comment = '<div id="com'.$auser->id
.'">'
1234 . '<textarea tabindex="'.$tabindex++
.'" name="submissioncomment['.$auser->id
.']" id="submissioncomment'
1235 . $auser->id
.'" rows="2" cols="20">'.($auser->submissioncomment
).'</textarea></div>';
1237 $comment = '<div id="com'.$auser->id
.'">'.shorten_text(strip_tags($auser->submissioncomment
),15).'</div>';
1240 $studentmodified = '<div id="ts'.$auser->id
.'"> </div>';
1241 $teachermodified = '<div id="tt'.$auser->id
.'"> </div>';
1242 $status = '<div id="st'.$auser->id
.'"> </div>';
1244 if ($final_grade->locked
or $final_grade->overridden
) {
1245 $grade = '<div id="g'.$auser->id
.'">'.$final_grade->formatted_grade
. '</div>';
1246 } else if ($quickgrade) { // allow editing
1247 $menu = choose_from_menu(make_grades_menu($this->assignment
->grade
),
1248 'menu['.$auser->id
.']', $auser->grade
,
1249 get_string('nograde'),'',-1,true,false,$tabindex++
);
1250 $grade = '<div id="g'.$auser->id
.'">'.$menu.'</div>';
1252 $grade = '<div id="g'.$auser->id
.'">-</div>';
1255 if ($final_grade->locked
or $final_grade->overridden
) {
1256 $comment = '<div id="com'.$auser->id
.'">'.$final_grade->str_feedback
.'</div>';
1257 } else if ($quickgrade) {
1258 $comment = '<div id="com'.$auser->id
.'">'
1259 . '<textarea tabindex="'.$tabindex++
.'" name="submissioncomment['.$auser->id
.']" id="submissioncomment'
1260 . $auser->id
.'" rows="2" cols="20">'.($auser->submissioncomment
).'</textarea></div>';
1262 $comment = '<div id="com'.$auser->id
.'"> </div>';
1266 if (empty($auser->status
)) { /// Confirm we have exclusively 0 or 1
1272 $buttontext = ($auser->status
== 1) ?
$strupdate : $strgrade;
1274 ///No more buttons, we use popups ;-).
1275 $popup_url = '/mod/assignment/submissions.php?id='.$this->cm
->id
1276 . '&userid='.$auser->id
.'&mode=single'.'&offset='.$offset++
;
1277 $button = link_to_popup_window ($popup_url, 'grade'.$auser->id
, $buttontext, 600, 780,
1278 $buttontext, 'none', true, 'button'.$auser->id
);
1280 $status = '<div id="up'.$auser->id
.'" class="s'.$auser->status
.'">'.$button.'</div>';
1282 $finalgrade = '<span id="finalgrade_'.$auser->id
.'">'.$final_grade->str_grade
.'</span>';
1286 if ($uses_outcomes) {
1288 foreach($grading_info->outcomes
as $n=>$outcome) {
1289 $outcomes .= '<div class="outcome"><label>'.$outcome->name
.'</label>';
1290 $options = make_grades_menu(-$outcome->scaleid
);
1292 if ($outcome->grades
[$auser->id
]->locked
or !$quickgrade) {
1293 $options[0] = get_string('nooutcome', 'grades');
1294 $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id
.'">'.$options[$outcome->grades
[$auser->id
]->grade
].'</span>';
1297 $outcomes .= choose_from_menu($options, 'outcome_'.$n.'['.$auser->id
.']',
1298 $outcome->grades
[$auser->id
]->grade
, get_string('nooutcome', 'grades'), '', 0, true, false, 0, 'outcome_'.$n.'_'.$auser->id
);
1300 $outcomes .= '</div>';
1304 $userlink = '<a href="' . $CFG->wwwroot
. '/user/view.php?id=' . $auser->id
. '&course=' . $course->id
. '">' . fullname($auser) . '</a>';
1305 $row = array($picture, $userlink, $grade, $comment, $studentmodified, $teachermodified, $status, $finalgrade);
1306 if ($uses_outcomes) {
1310 $table->add_data($row);
1314 /// Print quickgrade form around the table
1316 echo '<form action="submissions.php" id="fastg" method="post">';
1318 echo '<input type="hidden" name="id" value="'.$this->cm
->id
.'" />';
1319 echo '<input type="hidden" name="mode" value="fastgrade" />';
1320 echo '<input type="hidden" name="page" value="'.$page.'" />';
1324 $table->print_html(); /// Print the whole table
1327 $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ?
'checked="checked"' : '';
1328 echo '<div class="fgcontrols">';
1329 echo '<div class="emailnotification">';
1330 echo '<label for="mailinfo">'.get_string('enableemailnotification','assignment').'</label>';
1331 echo '<input type="hidden" name="mailinfo" value="0" />';
1332 echo '<input type="checkbox" id="mailinfo" name="mailinfo" value="1" '.$lastmailinfo.' />';
1333 helpbutton('emailnotification', get_string('enableemailnotification', 'assignment'), 'assignment').'</p></div>';
1335 echo '<div class="fastgbutton"><input type="submit" name="fastg" value="'.get_string('saveallfeedback', 'assignment').'" /></div>';
1339 /// End of fast grading form
1341 /// Mini form for setting user preference
1342 echo '<div class="qgprefs">';
1343 echo '<form id="options" action="submissions.php?id='.$this->cm
->id
.'" method="post"><div>';
1344 echo '<input type="hidden" name="updatepref" value="1" />';
1345 echo '<table id="optiontable">';
1347 echo '<label for="perpage">'.get_string('pagesize','assignment').'</label>';
1350 echo '<input type="text" id="perpage" name="perpage" size="1" value="'.$perpage.'" />';
1351 helpbutton('pagesize', get_string('pagesize','assignment'), 'assignment');
1354 echo '<label for="quickgrade">'.get_string('quickgrade','assignment').'</label>';
1357 $checked = $quickgrade ?
'checked="checked"' : '';
1358 echo '<input type="checkbox" id="quickgrade" name="quickgrade" value="1" '.$checked.' />';
1359 helpbutton('quickgrade', get_string('quickgrade', 'assignment'), 'assignment').'</p></div>';
1361 echo '<tr><td colspan="2">';
1362 echo '<input type="submit" value="'.get_string('savepreferences').'" />';
1363 echo '</td></tr></table>';
1364 echo '</div></form></div>';
1366 print_footer($this->course
);
1370 * Process teacher feedback submission
1372 * This is called by submissions() when a grading even has taken place.
1373 * It gets its data from the submitted form.
1374 * @return object The updated submission object
1376 function process_feedback() {
1378 require_once($CFG->libdir
.'/gradelib.php');
1380 if (!$feedback = data_submitted()) { // No incoming data?
1384 ///For save and next, we need to know the userid to save, and the userid to go
1385 ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1386 ///as the userid to store
1387 if ((int)$feedback->saveuserid
!== -1){
1388 $feedback->userid
= $feedback->saveuserid
;
1391 if (!empty($feedback->cancel
)) { // User hit cancel button
1395 $grading_info = grade_get_grades($this->course
->id
, 'mod', 'assignment', $this->assignment
->id
, $feedback->userid
);
1397 // store outcomes if needed
1398 $this->process_outcomes($feedback->userid
);
1400 $submission = $this->get_submission($feedback->userid
, true); // Get or make one
1402 if (!$grading_info->items
[0]->grades
[$feedback->userid
]->locked
and
1403 !$grading_info->items
[0]->grades
[$feedback->userid
]->overridden
) {
1405 $submission->grade
= $feedback->grade
;
1406 $submission->submissioncomment
= $feedback->submissioncomment
;
1407 $submission->format
= $feedback->format
;
1408 $submission->teacher
= $USER->id
;
1409 $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1411 $submission->mailed
= 1; // treat as already mailed
1413 $submission->mailed
= 0; // Make sure mail goes out (again, even)
1415 $submission->timemarked
= time();
1417 unset($submission->data1
); // Don't need to update this.
1418 unset($submission->data2
); // Don't need to update this.
1420 if (empty($submission->timemodified
)) { // eg for offline assignments
1421 // $submission->timemodified = time();
1424 if (! update_record('assignment_submissions', $submission)) {
1428 // triger grade event
1429 $this->update_grade($submission);
1431 add_to_log($this->course
->id
, 'assignment', 'update grades',
1432 'submissions.php?id='.$this->assignment
->id
.'&user='.$feedback->userid
, $feedback->userid
, $this->cm
->id
);
1439 function process_outcomes($userid) {
1442 if (empty($CFG->enableoutcomes
)) {
1446 require_once($CFG->libdir
.'/gradelib.php');
1448 if (!$formdata = data_submitted()) {
1453 $grading_info = grade_get_grades($this->course
->id
, 'mod', 'assignment', $this->assignment
->id
, $userid);
1455 if (!empty($grading_info->outcomes
)) {
1456 foreach($grading_info->outcomes
as $n=>$old) {
1457 $name = 'outcome_'.$n;
1458 if (isset($formdata->{$name}[$userid]) and $old->grades
[$userid]->grade
!= $formdata->{$name}[$userid]) {
1459 $data[$n] = $formdata->{$name}[$userid];
1463 if (count($data) > 0) {
1464 grade_update_outcomes('mod/assignment', $this->course
->id
, 'mod', 'assignment', $this->assignment
->id
, $userid, $data);
1470 * Load the submission object for a particular user
1472 * @param $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1473 * @param $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1474 * @param bool $teachermodified student submission set if false
1475 * @return object The submission
1477 function get_submission($userid=0, $createnew=false, $teachermodified=false) {
1480 if (empty($userid)) {
1481 $userid = $USER->id
;
1484 $submission = get_record('assignment_submissions', 'assignment', $this->assignment
->id
, 'userid', $userid);
1486 if ($submission ||
!$createnew) {
1489 $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
1490 if (!insert_record("assignment_submissions", $newsubmission)) {
1491 error("Could not insert a new empty submission");
1494 return get_record('assignment_submissions', 'assignment', $this->assignment
->id
, 'userid', $userid);
1498 * Instantiates a new submission object for a given user
1500 * Sets the assignment, userid and times, everything else is set to default values.
1501 * @param $userid int The userid for which we want a submission object
1502 * @param bool $teachermodified student submission set if false
1503 * @return object The submission
1505 function prepare_new_submission($userid, $teachermodified=false) {
1506 $submission = new Object;
1507 $submission->assignment
= $this->assignment
->id
;
1508 $submission->userid
= $userid;
1509 //$submission->timecreated = time();
1510 $submission->timecreated
= '';
1511 // teachers should not be modifying modified date, except offline assignments
1512 if ($teachermodified) {
1513 $submission->timemodified
= 0;
1515 $submission->timemodified
= $submission->timecreated
;
1517 $submission->numfiles
= 0;
1518 $submission->data1
= '';
1519 $submission->data2
= '';
1520 $submission->grade
= -1;
1521 $submission->submissioncomment
= '';
1522 $submission->format
= 0;
1523 $submission->teacher
= 0;
1524 $submission->timemarked
= 0;
1525 $submission->mailed
= 0;
1530 * Return all assignment submissions by ENROLLED students (even empty)
1532 * @param $sort string optional field names for the ORDER BY in the sql query
1533 * @param $dir string optional specifying the sort direction, defaults to DESC
1534 * @return array The submission objects indexed by id
1536 function get_submissions($sort='', $dir='DESC') {
1537 return assignment_get_all_submissions($this->assignment
, $sort, $dir);
1541 * Counts all real assignment submissions by ENROLLED students (not empty ones)
1543 * @param $groupid int optional If nonzero then count is restricted to this group
1544 * @return int The number of submissions
1546 function count_real_submissions($groupid=0) {
1547 return assignment_count_real_submissions($this->cm
, $groupid);
1551 * Alerts teachers by email of new or changed assignments that need grading
1553 * First checks whether the option to email teachers is set for this assignment.
1554 * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1555 * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1556 * @param $submission object The submission that has changed
1558 function email_teachers($submission) {
1561 if (empty($this->assignment
->emailteachers
)) { // No need to do anything
1565 $user = get_record('user', 'id', $submission->userid
);
1567 if ($teachers = $this->get_graders($user)) {
1569 $strassignments = get_string('modulenameplural', 'assignment');
1570 $strassignment = get_string('modulename', 'assignment');
1571 $strsubmitted = get_string('submitted', 'assignment');
1573 foreach ($teachers as $teacher) {
1574 $info = new object();
1575 $info->username
= fullname($user, true);
1576 $info->assignment
= format_string($this->assignment
->name
,true);
1577 $info->url
= $CFG->wwwroot
.'/mod/assignment/submissions.php?id='.$this->cm
->id
;
1579 $postsubject = $strsubmitted.': '.$info->username
.' -> '.$this->assignment
->name
;
1580 $posttext = $this->email_teachers_text($info);
1581 $posthtml = ($teacher->mailformat
== 1) ?
$this->email_teachers_html($info) : '';
1583 @email_to_user
($teacher, $user, $postsubject, $posttext, $posthtml); // If it fails, oh well, too bad.
1589 * Returns a list of teachers that should be grading given submission
1591 function get_graders($user) {
1593 $potgraders = get_users_by_capability($this->context
, 'mod/assignment:grade', '', '', '', '', '', '', false, false);
1596 if (groups_get_activity_groupmode($this->cm
) == SEPARATEGROUPS
) { // Separate groups are being used
1597 if ($groups = groups_get_all_groups($this->course
->id
, $user->id
)) { // Try to find all groups
1598 foreach ($groups as $group) {
1599 foreach ($potgraders as $t) {
1600 if ($t->id
== $user->id
) {
1601 continue; // do not send self
1603 if (groups_is_member($group->id
, $t->id
)) {
1604 $graders[$t->id
] = $t;
1609 // user not in group, try to find graders without group
1610 foreach ($potgraders as $t) {
1611 if ($t->id
== $user->id
) {
1612 continue; // do not send self
1614 if (!groups_get_all_groups($this->course
->id
, $t->id
)) { //ugly hack
1615 $graders[$t->id
] = $t;
1620 foreach ($potgraders as $t) {
1621 if ($t->id
== $user->id
) {
1622 continue; // do not send self
1624 $graders[$t->id
] = $t;
1631 * Creates the text content for emails to teachers
1633 * @param $info object The info used by the 'emailteachermail' language string
1636 function email_teachers_text($info) {
1637 $posttext = format_string($this->course
->shortname
).' -> '.$this->strassignments
.' -> '.
1638 format_string($this->assignment
->name
)."\n";
1639 $posttext .= '---------------------------------------------------------------------'."\n";
1640 $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
1641 $posttext .= "\n---------------------------------------------------------------------\n";
1646 * Creates the html content for emails to teachers
1648 * @param $info object The info used by the 'emailteachermailhtml' language string
1651 function email_teachers_html($info) {
1653 $posthtml = '<p><font face="sans-serif">'.
1654 '<a href="'.$CFG->wwwroot
.'/course/view.php?id='.$this->course
->id
.'">'.format_string($this->course
->shortname
).'</a> ->'.
1655 '<a href="'.$CFG->wwwroot
.'/mod/assignment/index.php?id='.$this->course
->id
.'">'.$this->strassignments
.'</a> ->'.
1656 '<a href="'.$CFG->wwwroot
.'/mod/assignment/view.php?id='.$this->cm
->id
.'">'.format_string($this->assignment
->name
).'</a></font></p>';
1657 $posthtml .= '<hr /><font face="sans-serif">';
1658 $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
1659 $posthtml .= '</font><hr />';
1664 * Produces a list of links to the files uploaded by a user
1666 * @param $userid int optional id of the user. If 0 then $USER->id is used.
1667 * @param $return boolean optional defaults to false. If true the list is returned rather than printed
1668 * @return string optional
1670 function print_user_files($userid=0, $return=false) {
1674 if (!isloggedin()) {
1677 $userid = $USER->id
;
1680 $filearea = $this->file_area_name($userid);
1684 if ($basedir = $this->file_area($userid)) {
1685 if ($files = get_directory_list($basedir)) {
1686 require_once($CFG->libdir
.'/filelib.php');
1687 foreach ($files as $key => $file) {
1689 $icon = mimeinfo('icon', $file);
1690 $ffurl = get_file_url("$filearea/$file", array('forcedownload'=>1));
1692 $output .= '<img src="'.$CFG->pixpath
.'/f/'.$icon.'" class="icon" alt="'.$icon.'" />'.
1693 '<a href="'.$ffurl.'" >'.$file.'</a><br />';
1698 $output = '<div class="files">'.$output.'</div>';
1707 * Count the files uploaded by a given user
1709 * @param $userid int The user id
1712 function count_user_files($userid) {
1715 $filearea = $this->file_area_name($userid);
1717 if ( is_dir($CFG->dataroot
.'/'.$filearea) && $basedir = $this->file_area($userid)) {
1718 if ($files = get_directory_list($basedir)) {
1719 return count($files);
1726 * Creates a directory file name, suitable for make_upload_directory()
1728 * @param $userid int The user id
1729 * @return string path to file area
1731 function file_area_name($userid) {
1734 return $this->course
->id
.'/'.$CFG->moddata
.'/assignment/'.$this->assignment
->id
.'/'.$userid;
1738 * Makes an upload directory
1740 * @param $userid int The user id
1741 * @return string path to file area.
1743 function file_area($userid) {
1744 return make_upload_directory( $this->file_area_name($userid) );
1748 * Returns true if the student is allowed to submit
1750 * Checks that the assignment has started and, if the option to prevent late
1751 * submissions is set, also checks that the assignment has not yet closed.
1756 if ($this->assignment
->preventlate
&& $this->assignment
->timedue
) {
1757 return ($this->assignment
->timeavailable
<= $time && $time <= $this->assignment
->timedue
);
1759 return ($this->assignment
->timeavailable
<= $time);
1765 * Return true if is set description is hidden till available date
1767 * This is needed by calendar so that hidden descriptions do not
1768 * come up in upcoming events.
1770 * Check that description is hidden till available date
1771 * By default return false
1772 * Assignments types should implement this method if needed
1775 function description_is_hidden() {
1780 * Return an outline of the user's interaction with the assignment
1782 * The default method prints the grade and timemodified
1783 * @param $user object
1784 * @return object with properties ->info and ->time
1786 function user_outline($user) {
1787 if ($submission = $this->get_submission($user->id
)) {
1789 $result = new object();
1790 $result->info
= get_string('grade').': '.$this->display_grade($submission->grade
);
1791 $result->time
= $submission->timemodified
;
1798 * Print complete information about the user's interaction with the assignment
1800 * @param $user object
1802 function user_complete($user) {
1803 if ($submission = $this->get_submission($user->id
)) {
1804 if ($basedir = $this->file_area($user->id
)) {
1805 if ($files = get_directory_list($basedir)) {
1806 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
1807 foreach ($files as $file) {
1808 $countfiles .= "; $file";
1813 print_simple_box_start();
1814 echo get_string("lastmodified").": ";
1815 echo userdate($submission->timemodified
);
1816 echo $this->display_lateness($submission->timemodified
);
1818 $this->print_user_files($user->id
);
1822 if (empty($submission->timemarked
)) {
1823 print_string("notgradedyet", "assignment");
1825 $this->view_feedback($submission);
1828 print_simple_box_end();
1831 print_string("notsubmittedyet", "assignment");
1836 * Return a string indicating how late a submission is
1838 * @param $timesubmitted int
1841 function display_lateness($timesubmitted) {
1842 return assignment_display_lateness($timesubmitted, $this->assignment
->timedue
);
1846 * Empty method stub for all delete actions.
1849 //nothing by default
1850 redirect('view.php?id='.$this->cm
->id
);
1854 * Empty custom feedback grading form.
1856 function custom_feedbackform($submission, $return=false) {
1857 //nothing by default
1862 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
1863 * for the course (see resource).
1865 * Given a course_module object, this function returns any "extra" information that may be needed
1866 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
1868 * @param $coursemodule object The coursemodule object (record).
1869 * @return object An object on information that the coures will know about (most noticeably, an icon).
1872 function get_coursemodule_info($coursemodule) {
1877 * Plugin cron method - do not use $this here, create new assignment instances if needed.
1881 //no plugin cron by default - override if needed
1885 * Reset all submissions
1887 function reset_userdata($data) {
1889 require_once($CFG->libdir
.'/filelib.php');
1891 if (!count_records('assignment', 'course', $data->courseid
, 'assignmenttype', $this->type
)) {
1892 return array(); // no assignments of this type present
1895 $componentstr = get_string('modulenameplural', 'assignment');
1898 $typestr = get_string('type'.$this->type
, 'assignment');
1900 if (!empty($data->reset_assignment_submissions
)) {
1901 $assignmentssql = "SELECT a.id
1902 FROM {$CFG->prefix}assignment a
1903 WHERE a.course={$data->courseid} AND a.assignmenttype='{$this->type}'";
1905 delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)");
1907 if ($assignments = get_records_sql($assignmentssql)) {
1908 foreach ($assignments as $assignmentid=>$unused) {
1909 fulldelete($CFG->dataroot
.'/'.$data->courseid
.'/moddata/assignment/'.$assignmentid);
1913 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
1915 if (empty($data->reset_gradebook_grades
)) {
1916 // remove all grades from gradebook
1917 assignment_reset_gradebook($data->courseid
, $this->type
);
1921 /// updating dates - shift may be negative too
1922 if ($data->timeshift
) {
1923 shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift
, $data->courseid
);
1924 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
1929 } ////// End of the assignment_base class
1933 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
1936 * Deletes an assignment instance
1938 * This is done by calling the delete_instance() method of the assignment type class
1940 function assignment_delete_instance($id){
1943 if (! $assignment = get_record('assignment', 'id', $id)) {
1947 // fall back to base class if plugin missing
1948 $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
1949 if (file_exists($classfile)) {
1950 require_once($classfile);
1951 $assignmentclass = "assignment_$assignment->assignmenttype";
1954 debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
1955 $assignmentclass = "assignment_base";
1958 $ass = new $assignmentclass();
1959 return $ass->delete_instance($assignment);
1964 * Updates an assignment instance
1966 * This is done by calling the update_instance() method of the assignment type class
1968 function assignment_update_instance($assignment){
1971 $assignment->assignmenttype
= clean_param($assignment->assignmenttype
, PARAM_SAFEDIR
);
1973 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
1974 $assignmentclass = "assignment_$assignment->assignmenttype";
1975 $ass = new $assignmentclass();
1976 return $ass->update_instance($assignment);
1981 * Adds an assignment instance
1983 * This is done by calling the add_instance() method of the assignment type class
1985 function assignment_add_instance($assignment) {
1988 $assignment->assignmenttype
= clean_param($assignment->assignmenttype
, PARAM_SAFEDIR
);
1990 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
1991 $assignmentclass = "assignment_$assignment->assignmenttype";
1992 $ass = new $assignmentclass();
1993 return $ass->add_instance($assignment);
1998 * Returns an outline of a user interaction with an assignment
2000 * This is done by calling the user_outline() method of the assignment type class
2002 function assignment_user_outline($course, $user, $mod, $assignment) {
2005 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2006 $assignmentclass = "assignment_$assignment->assignmenttype";
2007 $ass = new $assignmentclass($mod->id
, $assignment, $mod, $course);
2008 return $ass->user_outline($user);
2012 * Prints the complete info about a user's interaction with an assignment
2014 * This is done by calling the user_complete() method of the assignment type class
2016 function assignment_user_complete($course, $user, $mod, $assignment) {
2019 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2020 $assignmentclass = "assignment_$assignment->assignmenttype";
2021 $ass = new $assignmentclass($mod->id
, $assignment, $mod, $course);
2022 return $ass->user_complete($user);
2026 * Function to be run periodically according to the moodle cron
2028 * Finds all assignment notifications that have yet to be mailed out, and mails them
2030 function assignment_cron () {
2034 /// first execute all crons in plugins
2035 if ($plugins = get_list_of_plugins('mod/assignment/type')) {
2036 foreach ($plugins as $plugin) {
2037 require_once("$CFG->dirroot/mod/assignment/type/$plugin/assignment.class.php");
2038 $assignmentclass = "assignment_$plugin";
2039 $ass = new $assignmentclass();
2044 /// Notices older than 1 day will not be mailed. This is to avoid the problem where
2045 /// cron has not been running for a long time, and then suddenly people are flooded
2046 /// with mail from the past few weeks or months
2049 $endtime = $timenow - $CFG->maxeditingtime
;
2050 $starttime = $endtime - 24 * 3600; /// One day earlier
2052 if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2054 $realuser = clone($USER);
2056 foreach ($submissions as $key => $submission) {
2057 if (! set_field("assignment_submissions", "mailed", "1", "id", "$submission->id")) {
2058 echo "Could not update the mailed field for id $submission->id. Not mailed.\n";
2059 unset($submissions[$key]);
2065 foreach ($submissions as $submission) {
2067 echo "Processing assignment submission $submission->id\n";
2069 if (! $user = get_record("user", "id", "$submission->userid")) {
2070 echo "Could not find user $post->userid\n";
2074 if (! $course = get_record("course", "id", "$submission->course")) {
2075 echo "Could not find course $submission->course\n";
2079 /// Override the language and timezone of the "current" user, so that
2080 /// mail is customised for the receiver.
2082 course_setup($course);
2084 if (!has_capability('moodle/course:view', get_context_instance(CONTEXT_COURSE
, $submission->course
), $user->id
)) {
2085 echo fullname($user)." not an active participant in " . format_string($course->shortname
) . "\n";
2089 if (! $teacher = get_record("user", "id", "$submission->teacher")) {
2090 echo "Could not find teacher $submission->teacher\n";
2094 if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment
, $course->id
)) {
2095 echo "Could not find course module for assignment id $submission->assignment\n";
2099 if (! $mod->visible
) { /// Hold mail notification for hidden assignments until later
2103 $strassignments = get_string("modulenameplural", "assignment");
2104 $strassignment = get_string("modulename", "assignment");
2106 $assignmentinfo = new object();
2107 $assignmentinfo->teacher
= fullname($teacher);
2108 $assignmentinfo->assignment
= format_string($submission->name
,true);
2109 $assignmentinfo->url
= "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2111 $postsubject = "$course->shortname: $strassignments: ".format_string($submission->name
,true);
2112 $posttext = "$course->shortname -> $strassignments -> ".format_string($submission->name
,true)."\n";
2113 $posttext .= "---------------------------------------------------------------------\n";
2114 $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2115 $posttext .= "---------------------------------------------------------------------\n";
2117 if ($user->mailformat
== 1) { // HTML
2118 $posthtml = "<p><font face=\"sans-serif\">".
2119 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> ->".
2120 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2121 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name
,true)."</a></font></p>";
2122 $posthtml .= "<hr /><font face=\"sans-serif\">";
2123 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2124 $posthtml .= "</font><hr />";
2129 if (! email_to_user($user, $teacher, $postsubject, $posttext, $posthtml)) {
2130 echo "Error: assignment cron: Could not send out mail for id $submission->id to user $user->id ($user->email)\n";
2135 course_setup(SITEID
); // reset cron user language, theme and timezone settings
2143 * Return grade for given user or all users.
2145 * @param int $assignmentid id of assignment
2146 * @param int $userid optional user id, 0 means all users
2147 * @return array array of grades, false if none
2149 function assignment_get_user_grades($assignment, $userid=0) {
2152 $user = $userid ?
"AND u.id = $userid" : "";
2154 $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2155 s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2156 FROM {$CFG->prefix}user u, {$CFG->prefix}assignment_submissions s
2157 WHERE u.id = s.userid AND s.assignment = $assignment->id
2160 return get_records_sql($sql);
2164 * Update grades by firing grade_updated event
2166 * @param object $assignment null means all assignments
2167 * @param int $userid specific user only, 0 mean all
2169 function assignment_update_grades($assignment=null, $userid=0, $nullifnone=true) {
2171 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
2172 require_once($CFG->libdir
.'/gradelib.php');
2175 if ($assignment != null) {
2176 if ($grades = assignment_get_user_grades($assignment, $userid)) {
2177 foreach($grades as $k=>$v) {
2178 if ($v->rawgrade
== -1) {
2179 $grades[$k]->rawgrade
= null;
2182 assignment_grade_item_update($assignment, $grades);
2184 assignment_grade_item_update($assignment);
2188 $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
2189 FROM {$CFG->prefix}assignment a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
2190 WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2191 if ($rs = get_recordset_sql($sql)) {
2192 while ($assignment = rs_fetch_next_record($rs)) {
2193 if ($assignment->grade
!= 0) {
2194 assignment_update_grades($assignment);
2196 assignment_grade_item_update($assignment);
2205 * Create grade item for given assignment
2207 * @param object $assignment object with extra cmidnumber
2208 * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
2209 * @return int 0 if ok, error code otherwise
2211 function assignment_grade_item_update($assignment, $grades=NULL) {
2213 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
2214 require_once($CFG->libdir
.'/gradelib.php');
2217 if (!isset($assignment->courseid
)) {
2218 $assignment->courseid
= $assignment->course
;
2221 $params = array('itemname'=>$assignment->name
, 'idnumber'=>$assignment->cmidnumber
);
2223 if ($assignment->grade
> 0) {
2224 $params['gradetype'] = GRADE_TYPE_VALUE
;
2225 $params['grademax'] = $assignment->grade
;
2226 $params['grademin'] = 0;
2228 } else if ($assignment->grade
< 0) {
2229 $params['gradetype'] = GRADE_TYPE_SCALE
;
2230 $params['scaleid'] = -$assignment->grade
;
2233 $params['gradetype'] = GRADE_TYPE_TEXT
; // allow text comments only
2236 if ($grades === 'reset') {
2237 $params['reset'] = true;
2241 return grade_update('mod/assignment', $assignment->courseid
, 'mod', 'assignment', $assignment->id
, 0, $grades, $params);
2245 * Delete grade item for given assignment
2247 * @param object $assignment object
2248 * @return object assignment
2250 function assignment_grade_item_delete($assignment) {
2252 require_once($CFG->libdir
.'/gradelib.php');
2254 if (!isset($assignment->courseid
)) {
2255 $assignment->courseid
= $assignment->course
;
2258 return grade_update('mod/assignment', $assignment->courseid
, 'mod', 'assignment', $assignment->id
, 0, NULL, array('deleted'=>1));
2262 * Returns the users with data in one assignment (students and teachers)
2264 * @param $assignmentid int
2265 * @return array of user objects
2267 function assignment_get_participants($assignmentid) {
2272 $students = get_records_sql("SELECT DISTINCT u.id, u.id
2273 FROM {$CFG->prefix}user u,
2274 {$CFG->prefix}assignment_submissions a
2275 WHERE a.assignment = '$assignmentid' and
2278 $teachers = get_records_sql("SELECT DISTINCT u.id, u.id
2279 FROM {$CFG->prefix}user u,
2280 {$CFG->prefix}assignment_submissions a
2281 WHERE a.assignment = '$assignmentid' and
2284 //Add teachers to students
2286 foreach ($teachers as $teacher) {
2287 $students[$teacher->id
] = $teacher;
2290 //Return students array (it contains an array of unique users)
2295 * Checks if a scale is being used by an assignment
2297 * This is used by the backup code to decide whether to back up a scale
2298 * @param $assignmentid int
2299 * @param $scaleid int
2300 * @return boolean True if the scale is used by the assignment
2302 function assignment_scale_used($assignmentid, $scaleid) {
2306 $rec = get_record('assignment','id',$assignmentid,'grade',-$scaleid);
2308 if (!empty($rec) && !empty($scaleid)) {
2316 * Checks if scale is being used by any instance of assignment
2318 * This is used to find out if scale used anywhere
2319 * @param $scaleid int
2320 * @return boolean True if the scale is used by any assignment
2322 function assignment_scale_used_anywhere($scaleid) {
2323 if ($scaleid and record_exists('assignment', 'grade', -$scaleid)) {
2331 * Make sure up-to-date events are created for all assignment instances
2333 * This standard function will check all instances of this module
2334 * and make sure there are up-to-date events created for each of them.
2335 * If courseid = 0, then every assignment event in the site is checked, else
2336 * only assignment events belonging to the course specified are checked.
2337 * This function is used, in its new format, by restore_refresh_events()
2339 * @param $courseid int optional If zero then all assignments for all courses are covered
2340 * @return boolean Always returns true
2342 function assignment_refresh_events($courseid = 0) {
2344 if ($courseid == 0) {
2345 if (! $assignments = get_records("assignment")) {
2349 if (! $assignments = get_records("assignment", "course", $courseid)) {
2353 $moduleid = get_field('modules', 'id', 'name', 'assignment');
2355 foreach ($assignments as $assignment) {
2357 $event->name
= addslashes($assignment->name
);
2358 $event->description
= addslashes($assignment->description
);
2359 $event->timestart
= $assignment->timedue
;
2361 if ($event->id
= get_field('event', 'id', 'modulename', 'assignment', 'instance', $assignment->id
)) {
2362 update_event($event);
2365 $event->courseid
= $assignment->course
;
2366 $event->groupid
= 0;
2368 $event->modulename
= 'assignment';
2369 $event->instance
= $assignment->id
;
2370 $event->eventtype
= 'due';
2371 $event->timeduration
= 0;
2372 $event->visible
= get_field('course_modules', 'visible', 'module', $moduleid, 'instance', $assignment->id
);
2381 * Print recent activity from all assignments in a given course
2383 * This is used by the recent activity block
2385 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
2388 // do not use log table if possible, it may be huge
2390 if (!$submissions = get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
2391 u.firstname, u.lastname, u.email, u.picture
2392 FROM {$CFG->prefix}assignment_submissions asb
2393 JOIN {$CFG->prefix}assignment a ON a.id = asb.assignment
2394 JOIN {$CFG->prefix}course_modules cm ON cm.instance = a.id
2395 JOIN {$CFG->prefix}modules md ON md.id = cm.module
2396 JOIN {$CFG->prefix}user u ON u.id = asb.userid
2397 WHERE asb.timemodified > $timestart AND
2398 a.course = {$course->id} AND
2399 md.name = 'assignment'
2400 ORDER BY asb.timemodified ASC")) {
2404 $modinfo =& get_fast_modinfo($course); // reference needed because we might load the groups
2408 foreach($submissions as $submission) {
2409 if (!array_key_exists($submission->cmid
, $modinfo->cms
)) {
2412 $cm = $modinfo->cms
[$submission->cmid
];
2413 if (!$cm->uservisible
) {
2416 if ($submission->userid
== $USER->id
) {
2417 $show[] = $submission;
2421 // the act of sumitting of assignemnt may be considered private - only graders will see it if specified
2422 if (empty($CFG->assignment_showrecentsubmissions
)) {
2423 if (!array_key_exists($cm->id
, $grader)) {
2424 $grader[$cm->id
] = has_capability('moodle/grade:viewall', get_context_instance(CONTEXT_MODULE
, $cm->id
));
2426 if (!$grader[$cm->id
]) {
2431 $groupmode = groups_get_activity_groupmode($cm, $course);
2433 if ($groupmode == SEPARATEGROUPS
and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE
, $cm->id
))) {
2434 if (isguestuser()) {
2435 // shortcut - guest user does not belong into any group
2439 if (is_null($modinfo->groups
)) {
2440 $modinfo->groups
= groups_get_user_groups($course->id
); // load all my groups and cache it in modinfo
2443 // this will be slow - show only users that share group with me in this cm
2444 if (empty($modinfo->groups
[$cm->id
])) {
2447 $usersgroups = groups_get_all_groups($course->id
, $cm->userid
, $cm->groupingid
);
2448 if (is_array($usersgroups)) {
2449 $usersgroups = array_keys($usersgroups);
2450 $interset = array_intersect($usersgroups, $modinfo->groups
[$cm->id
]);
2451 if (empty($intersect)) {
2456 $show[] = $submission;
2463 print_headline(get_string('newsubmissions', 'assignment').':');
2465 foreach ($show as $submission) {
2466 $cm = $modinfo->cms
[$submission->cmid
];
2467 $link = $CFG->wwwroot
.'/mod/assignment/view.php?id='.$cm->id
;
2468 print_recent_activity_note($submission->timemodified
, $submission, $cm->name
, $link, false, $viewfullnames);
2476 * Returns all assignments since a given time in specified forum.
2478 function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0) {
2480 global $CFG, $COURSE, $USER;
2482 if ($COURSE->id
== $courseid) {
2485 $course = get_record('course', 'id', $courseid);
2488 $modinfo =& get_fast_modinfo($course);
2490 $cm = $modinfo->cms
[$cmid];
2493 $userselect = "AND u.id = $userid";
2499 $groupselect = "AND gm.groupid = $groupid";
2500 $groupjoin = "JOIN {$CFG->prefix}groups_members gm ON gm.userid=u.id";
2506 if (!$submissions = get_records_sql("SELECT asb.id, asb.timemodified, asb.userid,
2507 u.firstname, u.lastname, u.email, u.picture
2508 FROM {$CFG->prefix}assignment_submissions asb
2509 JOIN {$CFG->prefix}assignment a ON a.id = asb.assignment
2510 JOIN {$CFG->prefix}user u ON u.id = asb.userid
2512 WHERE asb.timemodified > $timestart AND a.id = $cm->instance
2513 $userselect $groupselect
2514 ORDER BY asb.timemodified ASC")) {
2518 $groupmode = groups_get_activity_groupmode($cm, $course);
2519 $cm_context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
2520 $grader = has_capability('moodle/grade:viewall', $cm_context);
2521 $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
2522 $viewfullnames = has_capability('moodle/site:viewfullnames', $cm_context);
2524 if (is_null($modinfo->groups
)) {
2525 $modinfo->groups
= groups_get_user_groups($course->id
); // load all my groups and cache it in modinfo
2530 foreach($submissions as $submission) {
2531 if ($submission->userid
== $USER->id
) {
2532 $show[] = $submission;
2536 // the act of sumitting of assignemnt may be considered private - only graders will see it if specified
2537 if (!empty($CFG->assignment_showrecentsubmissions
)) {
2543 if ($groupmode == SEPARATEGROUPS
and !$accessallgroups) {
2544 if (isguestuser()) {
2545 // shortcut - guest user does not belong into any group
2549 // this will be slow - show only users that share group with me in this cm
2550 if (empty($modinfo->groups
[$cm->id
])) {
2553 $usersgroups = groups_get_all_groups($course->id
, $cm->userid
, $cm->groupingid
);
2554 if (is_array($usersgroups)) {
2555 $usersgroups = array_keys($usersgroups);
2556 $interset = array_intersect($usersgroups, $modinfo->groups
[$cm->id
]);
2557 if (empty($intersect)) {
2562 $show[] = $submission;
2570 require_once($CFG->libdir
.'/gradelib.php');
2572 foreach ($show as $id=>$submission) {
2573 $userids[] = $submission->userid
;
2576 $grades = grade_get_grades($courseid, 'mod', 'assignment', $cm->instance
, $userids);
2579 $aname = format_string($cm->name
,true);
2580 foreach ($show as $submission) {
2581 $tmpactivity = new object();
2583 $tmpactivity->type
= 'assignment';
2584 $tmpactivity->cmid
= $cm->id
;
2585 $tmpactivity->name
= $aname;
2586 $tmpactivity->sectionnum
= $cm->sectionnum
;
2587 $tmpactivity->timestamp
= $submission->timemodified
;
2590 $tmpactivity->grade
= $grades->items
[0]->grades
[$submission->userid
]->str_long_grade
;
2593 $tmpactivity->user
->userid
= $submission->userid
;
2594 $tmpactivity->user
->fullname
= fullname($submission, $viewfullnames);
2595 $tmpactivity->user
->picture
= $submission->picture
;
2597 $activities[$index++
] = $tmpactivity;
2604 * Print recent activity from all assignments in a given course
2606 * This is used by course/recent.php
2608 function assignment_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
2611 echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
2613 echo "<tr><td class=\"userpicture\" valign=\"top\">";
2614 print_user_picture($activity->user
->userid
, $courseid, $activity->user
->picture
);
2618 $modname = $modnames[$activity->type
];
2619 echo '<div class="title">';
2620 echo "<img src=\"$CFG->modpixpath/assignment/icon.gif\" ".
2621 "class=\"icon\" alt=\"$modname\">";
2622 echo "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id={$activity->cmid}\">{$activity->name}</a>";
2626 if (isset($activity->grade
)) {
2627 echo '<div class="grade">';
2628 echo get_string('grade').': ';
2629 echo $activity->grade
;
2633 echo '<div class="user">';
2634 echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->userid}&course=$courseid\">"
2635 ."{$activity->user->fullname}</a> - ".userdate($activity->timestamp
);
2638 echo "</td></tr></table>";
2641 /// GENERIC SQL FUNCTIONS
2644 * Fetch info from logs
2646 * @param $log object with properties ->info (the assignment id) and ->userid
2647 * @return array with assignment name and user firstname and lastname
2649 function assignment_log_info($log) {
2651 return get_record_sql("SELECT a.name, u.firstname, u.lastname
2652 FROM {$CFG->prefix}assignment a,
2653 {$CFG->prefix}user u
2654 WHERE a.id = '$log->info'
2655 AND u.id = '$log->userid'");
2659 * Return list of marked submissions that have not been mailed out for currently enrolled students
2663 function assignment_get_unmailed_submissions($starttime, $endtime) {
2667 return get_records_sql("SELECT s.*, a.course, a.name
2668 FROM {$CFG->prefix}assignment_submissions s,
2669 {$CFG->prefix}assignment a
2671 AND s.timemarked <= $endtime
2672 AND s.timemarked >= $starttime
2673 AND s.assignment = a.id");
2675 /* return get_records_sql("SELECT s.*, a.course, a.name
2676 FROM {$CFG->prefix}assignment_submissions s,
2677 {$CFG->prefix}assignment a,
2678 {$CFG->prefix}user_students us
2680 AND s.timemarked <= $endtime
2681 AND s.timemarked >= $starttime
2682 AND s.assignment = a.id
2683 AND s.userid = us.userid
2684 AND a.course = us.course");
2689 * Counts all real assignment submissions by ENROLLED students (not empty ones)
2691 * There are also assignment type methods count_real_submissions() wich in the default
2692 * implementation simply call this function.
2693 * @param $groupid int optional If nonzero then count is restricted to this group
2694 * @return int The number of submissions
2696 function assignment_count_real_submissions($cm, $groupid=0) {
2699 $context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
2701 // this is all the users with this capability set, in this context or higher
2702 if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $groupid, '', false)) {
2703 $users = array_keys($users);
2706 // if groupmembersonly used, remove users who are not in any group
2707 if ($users and !empty($CFG->enablegroupings
) and $cm->groupmembersonly
) {
2708 if ($groupingusers = groups_get_grouping_members($cm->groupingid
, 'u.id', 'u.id')) {
2709 $users = array_intersect($users, array_keys($groupingusers));
2713 if (empty($users)) {
2717 $userlists = implode(',', $users);
2719 return count_records_sql("SELECT COUNT('x')
2720 FROM {$CFG->prefix}assignment_submissions
2721 WHERE assignment = $cm->instance AND
2722 timemodified > 0 AND
2723 userid IN ($userlists)");
2728 * Return all assignment submissions by ENROLLED students (even empty)
2730 * There are also assignment type methods get_submissions() wich in the default
2731 * implementation simply call this function.
2732 * @param $sort string optional field names for the ORDER BY in the sql query
2733 * @param $dir string optional specifying the sort direction, defaults to DESC
2734 * @return array The submission objects indexed by id
2736 function assignment_get_all_submissions($assignment, $sort="", $dir="DESC") {
2737 /// Return all assignment submissions by ENROLLED students (even empty)
2740 if ($sort == "lastname" or $sort == "firstname") {
2741 $sort = "u.$sort $dir";
2742 } else if (empty($sort)) {
2743 $sort = "a.timemodified DESC";
2745 $sort = "a.$sort $dir";
2748 /* not sure this is needed at all since assignmenet already has a course define, so this join?
2749 $select = "s.course = '$assignment->course' AND";
2750 if ($assignment->course == SITEID) {
2754 return get_records_sql("SELECT a.*
2755 FROM {$CFG->prefix}assignment_submissions a,
2756 {$CFG->prefix}user u
2757 WHERE u.id = a.userid
2758 AND a.assignment = '$assignment->id'
2761 /* return get_records_sql("SELECT a.*
2762 FROM {$CFG->prefix}assignment_submissions a,
2763 {$CFG->prefix}user_students s,
2764 {$CFG->prefix}user u
2765 WHERE a.userid = s.userid
2767 AND $select a.assignment = '$assignment->id'
2773 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
2774 * for the course (see resource).
2776 * Given a course_module object, this function returns any "extra" information that may be needed
2777 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
2779 * @param $coursemodule object The coursemodule object (record).
2780 * @return object An object on information that the coures will know about (most noticeably, an icon).
2783 function assignment_get_coursemodule_info($coursemodule) {
2786 if (! $assignment = get_record('assignment', 'id', $coursemodule->instance
, '', '', '', '', 'id, assignmenttype, name')) {
2790 $libfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2792 if (file_exists($libfile)) {
2793 require_once($libfile);
2794 $assignmentclass = "assignment_$assignment->assignmenttype";
2795 $ass = new $assignmentclass('staticonly');
2796 if ($result = $ass->get_coursemodule_info($coursemodule)) {
2799 $info = new object();
2800 $info->name
= $assignment->name
;
2805 debugging('Incorrect assignment type: '.$assignment->assignmenttype
);
2812 /// OTHER GENERAL FUNCTIONS FOR ASSIGNMENTS ///////////////////////////////////////
2815 * Returns an array of installed assignment types indexed and sorted by name
2817 * @return array The index is the name of the assignment type, the value its full name from the language strings
2819 function assignment_types() {
2821 $names = get_list_of_plugins('mod/assignment/type');
2822 foreach ($names as $name) {
2823 $types[$name] = get_string('type'.$name, 'assignment');
2830 * Executes upgrade scripts for assignment types when necessary
2832 function assignment_upgrade_submodules() {
2836 /// Install/upgrade assignment types (it uses, simply, the standard plugin architecture)
2837 upgrade_plugins('assignment_type', 'mod/assignment/type', "$CFG->wwwroot/$CFG->admin/index.php");
2841 function assignment_print_overview($courses, &$htmlarray) {
2845 if (empty($courses) ||
!is_array($courses) ||
count($courses) == 0) {
2849 if (!$assignments = get_all_instances_in_courses('assignment',$courses)) {
2853 // Do assignment_base::isopen() here without loading the whole thing for speed
2854 foreach ($assignments as $key => $assignment) {
2856 if ($assignment->timedue
) {
2857 if ($assignment->preventlate
) {
2858 $isopen = ($assignment->timeavailable
<= $time && $time <= $assignment->timedue
);
2860 $isopen = ($assignment->timeavailable
<= $time);
2863 if (empty($isopen) ||
empty($assignment->timedue
)) {
2864 unset($assignments[$key]);
2868 $strduedate = get_string('duedate', 'assignment');
2869 $strduedateno = get_string('duedateno', 'assignment');
2870 $strgraded = get_string('graded', 'assignment');
2871 $strnotgradedyet = get_string('notgradedyet', 'assignment');
2872 $strnotsubmittedyet = get_string('notsubmittedyet', 'assignment');
2873 $strsubmitted = get_string('submitted', 'assignment');
2874 $strassignment = get_string('modulename', 'assignment');
2875 $strreviewed = get_string('reviewed','assignment');
2877 foreach ($assignments as $assignment) {
2878 $str = '<div class="assignment overview"><div class="name">'.$strassignment. ': '.
2879 '<a '.($assignment->visible ?
'':' class="dimmed"').
2880 'title="'.$strassignment.'" href="'.$CFG->wwwroot
.
2881 '/mod/assignment/view.php?id='.$assignment->coursemodule
.'">'.
2882 $assignment->name
.'</a></div>';
2883 if ($assignment->timedue
) {
2884 $str .= '<div class="info">'.$strduedate.': '.userdate($assignment->timedue
).'</div>';
2886 $str .= '<div class="info">'.$strduedateno.'</div>';
2888 $context = get_context_instance(CONTEXT_MODULE
, $assignment->coursemodule
);
2889 if (has_capability('mod/assignment:grade', $context)) {
2891 // count how many people can submit
2892 $submissions = 0; // init
2893 if ($students = get_users_by_capability($context, 'mod/assignment:submit', '', '', '', '', 0, '', false)) {
2894 foreach ($students as $student) {
2895 if (record_exists_sql("SELECT id FROM {$CFG->prefix}assignment_submissions
2896 WHERE assignment = $assignment->id AND
2897 userid = $student->id AND
2906 $str .= get_string('submissionsnotgraded', 'assignment', $submissions);
2910 FROM {$CFG->prefix}assignment_submissions
2911 WHERE userid = '$USER->id'
2912 AND assignment = '{$assignment->id}'";
2913 if ($submission = get_record_sql($sql)) {
2914 if ($submission->teacher
== 0 && $submission->timemarked
== 0) {
2915 $str .= $strsubmitted . ', ' . $strnotgradedyet;
2916 } else if ($submission->grade
<= 0) {
2917 $str .= $strsubmitted . ', ' . $strreviewed;
2919 $str .= $strsubmitted . ', ' . $strgraded;
2922 $str .= $strnotsubmittedyet . ' ' . assignment_display_lateness(time(), $assignment->timedue
);
2926 if (empty($htmlarray[$assignment->course
]['assignment'])) {
2927 $htmlarray[$assignment->course
]['assignment'] = $str;
2929 $htmlarray[$assignment->course
]['assignment'] .= $str;
2934 function assignment_display_lateness($timesubmitted, $timedue) {
2938 $time = $timedue - $timesubmitted;
2940 $timetext = get_string('late', 'assignment', format_time($time));
2941 return ' (<span class="late">'.$timetext.'</span>)';
2943 $timetext = get_string('early', 'assignment', format_time($time));
2944 return ' (<span class="early">'.$timetext.'</span>)';
2948 function assignment_get_view_actions() {
2949 return array('view');
2952 function assignment_get_post_actions() {
2953 return array('upload');
2956 function assignment_get_types() {
2960 $type = new object();
2961 $type->modclass
= MOD_CLASS_ACTIVITY
;
2962 $type->type
= "assignment_group_start";
2963 $type->typestr
= '--'.get_string('modulenameplural', 'assignment');
2966 $standardassignments = array('upload','online','uploadsingle','offline');
2967 foreach ($standardassignments as $assignmenttype) {
2968 $type = new object();
2969 $type->modclass
= MOD_CLASS_ACTIVITY
;
2970 $type->type
= "assignment&type=$assignmenttype";
2971 $type->typestr
= get_string("type$assignmenttype", 'assignment');
2975 /// Drop-in extra assignment types
2976 $assignmenttypes = get_list_of_plugins('mod/assignment/type');
2977 foreach ($assignmenttypes as $assignmenttype) {
2978 if (!empty($CFG->{'assignment_hide_'.$assignmenttype})) { // Not wanted
2981 if (!in_array($assignmenttype, $standardassignments)) {
2982 $type = new object();
2983 $type->modclass
= MOD_CLASS_ACTIVITY
;
2984 $type->type
= "assignment&type=$assignmenttype";
2985 $type->typestr
= get_string("type$assignmenttype", 'assignment');
2990 $type = new object();
2991 $type->modclass
= MOD_CLASS_ACTIVITY
;
2992 $type->type
= "assignment_group_end";
2993 $type->typestr
= '--';
3000 * Removes all grades from gradebook
3001 * @param int $courseid
3002 * @param string optional type
3004 function assignment_reset_gradebook($courseid, $type='') {
3007 $type = $type ?
"AND a.assignmenttype='$type'" : '';
3009 $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
3010 FROM {$CFG->prefix}assignment a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
3011 WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id AND a.course=$courseid $type";
3013 if ($assignments = get_records_sql($sql)) {
3014 foreach ($assignments as $assignment) {
3015 assignment_grade_item_update($assignment, 'reset');
3021 * This function is used by the reset_course_userdata function in moodlelib.
3022 * This function will remove all posts from the specified assignment
3023 * and clean up any related data.
3024 * @param $data the data submitted from the reset course.
3025 * @return array status array
3027 function assignment_reset_userdata($data) {
3032 foreach (get_list_of_plugins('mod/assignment/type') as $type) {
3033 require_once("$CFG->dirroot/mod/assignment/type/$type/assignment.class.php");
3034 $assignmentclass = "assignment_$type";
3035 $ass = new $assignmentclass();
3036 $status = array_merge($status, $ass->reset_userdata($data));
3043 * Implementation of the function for printing the form elements that control
3044 * whether the course reset functionality affects the assignment.
3045 * @param $mform form passed by reference
3047 function assignment_reset_course_form_definition(&$mform) {
3048 $mform->addElement('header', 'assignmentheader', get_string('modulenameplural', 'assignment'));
3049 $mform->addElement('advcheckbox', 'reset_assignment_submissions', get_string('deleteallsubmissions','assignment'));
3053 * Course reset form defaults.
3055 function assignment_reset_course_form_defaults($course) {
3056 return array('reset_assignment_submissions'=>1);