3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * assignment_base is the base class for assignment types
21 * This class provides all the functionality for an assignment
23 * @package mod-assignment
24 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 /** Include eventslib.php */
29 require_once($CFG->libdir
.'/eventslib.php');
30 /** Include formslib.php */
31 require_once($CFG->libdir
.'/formslib.php');
32 /** Include calendar/lib.php */
33 require_once($CFG->dirroot
.'/calendar/lib.php');
35 /** ASSIGNMENT_COUNT_WORDS = 1 */
36 define('ASSIGNMENT_COUNT_WORDS', 1);
37 /** ASSIGNMENT_COUNT_LETTERS = 2 */
38 define('ASSIGNMENT_COUNT_LETTERS', 2);
41 * Standard base class for all assignment submodules (assignment types).
43 * @package mod-assignment
44 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
45 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
47 class assignment_base
{
50 const FILTER_SUBMITTED
= 1;
51 const FILTER_REQUIRE_GRADING
= 2;
74 * @todo document this var
78 * @todo document this var
85 * Constructor for the base assignment class
87 * Constructor for the base assignment class.
88 * If cmid is set create the cm, course, assignment objects.
89 * If the assignment is hidden and the user is not a teacher then
90 * this prints a page header and notice.
94 * @param int $cmid the current course module id - not set for new assignments
95 * @param object $assignment usually null, but if we have it we pass it to save db access
96 * @param object $cm usually null, but if we have it we pass it to save db access
97 * @param object $course usually null, but if we have it we pass it to save db access
99 function assignment_base($cmid='staticonly', $assignment=NULL, $cm=NULL, $course=NULL) {
102 if ($cmid == 'staticonly') {
103 //use static functions only!
111 } else if (! $this->cm
= get_coursemodule_from_id('assignment', $cmid)) {
112 print_error('invalidcoursemodule');
115 $this->context
= get_context_instance(CONTEXT_MODULE
, $this->cm
->id
);
118 $this->course
= $course;
119 } else if ($this->cm
->course
== $COURSE->id
) {
120 $this->course
= $COURSE;
121 } else if (! $this->course
= $DB->get_record('course', array('id'=>$this->cm
->course
))) {
122 print_error('invalidid', 'assignment');
124 $this->coursecontext
= get_context_instance(CONTEXT_COURSE
, $this->course
->id
);
125 $courseshortname = format_text($this->course
->shortname
, true, array('context' => $this->coursecontext
));
128 $this->assignment
= $assignment;
129 } else if (! $this->assignment
= $DB->get_record('assignment', array('id'=>$this->cm
->instance
))) {
130 print_error('invalidid', 'assignment');
133 $this->assignment
->cmidnumber
= $this->cm
->idnumber
; // compatibility with modedit assignment obj
134 $this->assignment
->courseid
= $this->course
->id
; // compatibility with modedit assignment obj
136 $this->strassignment
= get_string('modulename', 'assignment');
137 $this->strassignments
= get_string('modulenameplural', 'assignment');
138 $this->strsubmissions
= get_string('submissions', 'assignment');
139 $this->strlastmodified
= get_string('lastmodified');
140 $this->pagetitle
= strip_tags($courseshortname.': '.$this->strassignment
.': '.format_string($this->assignment
->name
, true, array('context' => $this->context
)));
142 // visibility handled by require_login() with $cm parameter
143 // get current group only when really needed
145 /// Set up things for a HTML editor if it's needed
146 $this->defaultformat
= editors_get_preferred_format();
150 * Display the assignment, used by view.php
152 * This in turn calls the methods producing individual parts of the page
156 $context = get_context_instance(CONTEXT_MODULE
,$this->cm
->id
);
157 require_capability('mod/assignment:view', $context);
159 add_to_log($this->course
->id
, "assignment", "view", "view.php?id={$this->cm->id}",
160 $this->assignment
->id
, $this->cm
->id
);
162 $this->view_header();
168 $this->view_feedback();
170 $this->view_footer();
174 * Display the header and top of a page
176 * (this doesn't change much for assignment types)
177 * This is used by the view() method to print the header of view.php but
178 * it can be used on other pages in which case the string to denote the
179 * page in the navigation trail should be passed as an argument
182 * @param string $subpage Description of subpage to be used in navigation trail
184 function view_header($subpage='') {
185 global $CFG, $PAGE, $OUTPUT;
188 $PAGE->navbar
->add($subpage);
191 $PAGE->set_title($this->pagetitle
);
192 $PAGE->set_heading($this->course
->fullname
);
194 echo $OUTPUT->header();
196 groups_print_activity_menu($this->cm
, $CFG->wwwroot
. '/mod/assignment/view.php?id=' . $this->cm
->id
);
198 echo '<div class="reportlink">'.$this->submittedlink().'</div>';
199 echo '<div class="clearer"></div>';
204 * Display the assignment intro
206 * This will most likely be extended by assignment type plug-ins
207 * The default implementation prints the assignment description in a box
209 function view_intro() {
211 echo $OUTPUT->box_start('generalbox boxaligncenter', 'intro');
212 echo format_module_intro('assignment', $this->assignment
, $this->cm
->id
);
213 echo $OUTPUT->box_end();
214 echo plagiarism_print_disclosure($this->cm
->id
);
218 * Display the assignment dates
220 * Prints the assignment start and end dates in a box.
221 * This will be suitable for most assignment types
223 function view_dates() {
225 if (!$this->assignment
->timeavailable
&& !$this->assignment
->timedue
) {
229 echo $OUTPUT->box_start('generalbox boxaligncenter', 'dates');
231 if ($this->assignment
->timeavailable
) {
232 echo '<tr><td class="c0">'.get_string('availabledate','assignment').':</td>';
233 echo ' <td class="c1">'.userdate($this->assignment
->timeavailable
).'</td></tr>';
235 if ($this->assignment
->timedue
) {
236 echo '<tr><td class="c0">'.get_string('duedate','assignment').':</td>';
237 echo ' <td class="c1">'.userdate($this->assignment
->timedue
).'</td></tr>';
240 echo $OUTPUT->box_end();
245 * Display the bottom and footer of a page
247 * This default method just prints the footer.
248 * This will be suitable for most assignment types
250 function view_footer() {
252 echo $OUTPUT->footer();
256 * Display the feedback to the student
258 * This default method prints the teacher picture and name, date when marked,
259 * grade and teacher submissioncomment.
260 * If advanced grading is used the method render_grade from the
261 * advanced grading controller is called to display the grade.
266 * @param object $submission The submission object or NULL in which case it will be loaded
268 function view_feedback($submission=NULL) {
269 global $USER, $CFG, $DB, $OUTPUT, $PAGE;
270 require_once($CFG->libdir
.'/gradelib.php');
271 require_once("$CFG->dirroot/grade/grading/lib.php");
273 if (!$submission) { /// Get submission for this assignment
275 $submission = $this->get_submission($userid);
277 $userid = $submission->userid
;
279 // Check the user can submit
280 $canviewfeedback = ($userid == $USER->id
&& has_capability('mod/assignment:submit', $this->context
, $USER->id
, false));
281 // If not then check if the user still has the view cap and has a previous submission
282 $canviewfeedback = $canviewfeedback ||
(!empty($submission) && $submission->userid
== $USER->id
&& has_capability('mod/assignment:view', $this->context
));
283 // Or if user can grade (is a teacher or admin)
284 $canviewfeedback = $canviewfeedback ||
has_capability('mod/assignment:grade', $this->context
);
286 if (!$canviewfeedback) {
287 // can not view or submit assignments -> no feedback
291 $grading_info = grade_get_grades($this->course
->id
, 'mod', 'assignment', $this->assignment
->id
, $userid);
292 $item = $grading_info->items
[0];
293 $grade = $item->grades
[$userid];
295 if ($grade->hidden
or $grade->grade
=== false) { // hidden or error
299 if ($grade->grade
=== null and empty($grade->str_feedback
)) { /// Nothing to show yet
303 $graded_date = $grade->dategraded
;
304 $graded_by = $grade->usermodified
;
306 /// We need the teacher info
307 if (!$teacher = $DB->get_record('user', array('id'=>$graded_by))) {
308 print_error('cannotfindteacher');
311 /// Print the feedback
312 echo $OUTPUT->heading(get_string('feedbackfromteacher', 'assignment', fullname($teacher)));
314 echo '<table cellspacing="0" class="feedback">';
317 echo '<td class="left picture">';
319 echo $OUTPUT->user_picture($teacher);
322 echo '<td class="topic">';
323 echo '<div class="from">';
325 echo '<div class="fullname">'.fullname($teacher).'</div>';
327 echo '<div class="time">'.userdate($graded_date).'</div>';
333 echo '<td class="left side"> </td>';
334 echo '<td class="content">';
335 $gradestr = '<div class="grade">'. get_string("grade").': '.$grade->str_long_grade
. '</div>';
336 if (!empty($submission) && $controller = get_grading_manager($this->context
, 'mod_assignment', 'submission')->get_active_controller()) {
337 $controller->set_grade_range(make_grades_menu($this->assignment
->grade
));
338 echo $controller->render_grade($PAGE, $submission->id
, $item, $gradestr, has_capability('mod/assignment:grade', $this->context
));
342 echo '<div class="clearer"></div>';
344 echo '<div class="comment">';
345 echo $grade->str_feedback
;
349 if ($this->type
== 'uploadsingle') { //@TODO: move to overload view_feedback method in the class or is uploadsingle merging into upload?
350 $responsefiles = $this->print_responsefiles($submission->userid
, true);
351 if (!empty($responsefiles)) {
353 echo '<td class="left side"> </td>';
354 echo '<td class="content">';
364 * Returns a link with info about the state of the assignment submissions
366 * This is used by view_header to put this link at the top right of the page.
367 * For teachers it gives the number of submitted assignments with a link
368 * For students it gives the time of their submission.
369 * This will be suitable for most assignment types.
373 * @param bool $allgroup print all groups info if user can access all groups, suitable for index.php
376 function submittedlink($allgroups=false) {
381 $urlbase = "{$CFG->wwwroot}/mod/assignment/";
383 $context = get_context_instance(CONTEXT_MODULE
,$this->cm
->id
);
384 if (has_capability('mod/assignment:grade', $context)) {
385 if ($allgroups and has_capability('moodle/site:accessallgroups', $context)) {
388 $group = groups_get_activity_group($this->cm
);
390 if ($this->type
== 'offline') {
391 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm
->id
.'">'.
392 get_string('viewfeedback', 'assignment').'</a>';
393 } else if ($count = $this->count_real_submissions($group)) {
394 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm
->id
.'">'.
395 get_string('viewsubmissions', 'assignment', $count).'</a>';
397 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm
->id
.'">'.
398 get_string('noattempts', 'assignment').'</a>';
402 if ($submission = $this->get_submission($USER->id
)) {
403 // If the submission has been completed
404 if ($this->is_submitted_with_required_data($submission)) {
405 if ($submission->timemodified
<= $this->assignment
->timedue ||
empty($this->assignment
->timedue
)) {
406 $submitted = '<span class="early">'.userdate($submission->timemodified
).'</span>';
408 $submitted = '<span class="late">'.userdate($submission->timemodified
).'</span>';
419 * Returns whether the assigment supports lateness information
421 * @return bool This assignment type supports lateness (true, default) or no (false)
423 function supports_lateness() {
428 * @todo Document this function
430 function setup_elements(&$mform) {
435 * Any preprocessing needed for the settings form for
436 * this assignment type
438 * @param array $default_values - array to fill in with the default values
439 * in the form 'formelement' => 'value'
440 * @param object $form - the form that is to be displayed
443 function form_data_preprocessing(&$default_values, $form) {
447 * Any extra validation checks needed for the settings
448 * form for this assignment type
450 * See lib/formslib.php, 'validation' function for details
452 function form_validation($data, $files) {
457 * Create a new assignment activity
459 * Given an object containing all the necessary data,
460 * (defined by the form in mod_form.php) this function
461 * will create a new instance and return the id number
462 * of the new instance.
463 * The due data is added to the calendar
464 * This is common to all assignment types.
468 * @param object $assignment The data from the form on mod_form.php
469 * @return int The id of the assignment
471 function add_instance($assignment) {
474 $assignment->timemodified
= time();
475 $assignment->courseid
= $assignment->course
;
477 $returnid = $DB->insert_record("assignment", $assignment);
478 $assignment->id
= $returnid;
480 if ($assignment->timedue
) {
481 $event = new stdClass();
482 $event->name
= $assignment->name
;
483 $event->description
= format_module_intro('assignment', $assignment, $assignment->coursemodule
);
484 $event->courseid
= $assignment->course
;
487 $event->modulename
= 'assignment';
488 $event->instance
= $returnid;
489 $event->eventtype
= 'due';
490 $event->timestart
= $assignment->timedue
;
491 $event->timeduration
= 0;
493 calendar_event
::create($event);
496 assignment_grade_item_update($assignment);
502 * Deletes an assignment activity
504 * Deletes all database records, files and calendar events for this assignment.
508 * @param object $assignment The assignment to be deleted
509 * @return boolean False indicates error
511 function delete_instance($assignment) {
514 $assignment->courseid
= $assignment->course
;
518 // now get rid of all files
519 $fs = get_file_storage();
520 if ($cm = get_coursemodule_from_instance('assignment', $assignment->id
)) {
521 $context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
522 $fs->delete_area_files($context->id
);
525 if (! $DB->delete_records('assignment_submissions', array('assignment'=>$assignment->id
))) {
529 if (! $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id
))) {
533 if (! $DB->delete_records('assignment', array('id'=>$assignment->id
))) {
536 $mod = $DB->get_field('modules','id',array('name'=>'assignment'));
538 assignment_grade_item_delete($assignment);
544 * Updates a new assignment activity
546 * Given an object containing all the necessary data,
547 * (defined by the form in mod_form.php) this function
548 * will update the assignment instance and return the id number
549 * The due date is updated in the calendar
550 * This is common to all assignment types.
554 * @param object $assignment The data from the form on mod_form.php
555 * @return bool success
557 function update_instance($assignment) {
560 $assignment->timemodified
= time();
562 $assignment->id
= $assignment->instance
;
563 $assignment->courseid
= $assignment->course
;
565 $DB->update_record('assignment', $assignment);
567 if ($assignment->timedue
) {
568 $event = new stdClass();
570 if ($event->id
= $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id
))) {
572 $event->name
= $assignment->name
;
573 $event->description
= format_module_intro('assignment', $assignment, $assignment->coursemodule
);
574 $event->timestart
= $assignment->timedue
;
576 $calendarevent = calendar_event
::load($event->id
);
577 $calendarevent->update($event);
579 $event = new stdClass();
580 $event->name
= $assignment->name
;
581 $event->description
= format_module_intro('assignment', $assignment, $assignment->coursemodule
);
582 $event->courseid
= $assignment->course
;
585 $event->modulename
= 'assignment';
586 $event->instance
= $assignment->id
;
587 $event->eventtype
= 'due';
588 $event->timestart
= $assignment->timedue
;
589 $event->timeduration
= 0;
591 calendar_event
::create($event);
594 $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id
));
597 // get existing grade item
598 assignment_grade_item_update($assignment);
604 * Update grade item for this submission.
606 function update_grade($submission) {
607 assignment_update_grades($this->assignment
, $submission->userid
);
611 * Top-level function for handling of submissions called by submissions.php
613 * This is for handling the teacher interaction with the grading interface
614 * This should be suitable for most assignment types.
617 * @param string $mode Specifies the kind of teacher interaction taking place
619 function submissions($mode) {
620 ///The main switch is changed to facilitate
621 ///1) Batch fast grading
622 ///2) Skip to the next one on the popup
623 ///3) Save and Skip to the next one on the popup
625 //make user global so we can use the id
626 global $USER, $OUTPUT, $DB, $PAGE;
628 $mailinfo = optional_param('mailinfo', null, PARAM_BOOL
);
630 if (optional_param('next', null, PARAM_BOOL
)) {
633 if (optional_param('saveandnext', null, PARAM_BOOL
)) {
637 if (is_null($mailinfo)) {
638 if (optional_param('sesskey', null, PARAM_BOOL
)) {
639 set_user_preference('assignment_mailinfo', 0);
641 $mailinfo = get_user_preferences('assignment_mailinfo', 0);
644 set_user_preference('assignment_mailinfo', $mailinfo);
647 if (!($this->validate_and_preprocess_feedback())) {
648 // form was submitted ('Save' or 'Save and next' was pressed, but validation failed)
649 $this->display_submission();
654 case 'grade': // We are in a main window grading
655 if ($submission = $this->process_feedback()) {
656 $this->display_submissions(get_string('changessaved'));
658 $this->display_submissions();
662 case 'single': // We are in a main window displaying one submission
663 if ($submission = $this->process_feedback()) {
664 $this->display_submissions(get_string('changessaved'));
666 $this->display_submission();
670 case 'all': // Main window, display everything
671 $this->display_submissions();
675 ///do the fast grading stuff - this process should work for all 3 subclasses
679 if (isset($_POST['submissioncomment'])) {
680 $col = 'submissioncomment';
683 if (isset($_POST['menu'])) {
688 //both submissioncomment and grade columns collapsed..
689 $this->display_submissions();
693 foreach ($_POST[$col] as $id => $unusedvalue){
695 $id = (int)$id; //clean parameter name
697 $this->process_outcomes($id);
699 if (!$submission = $this->get_submission($id)) {
700 $submission = $this->prepare_new_submission($id);
701 $newsubmission = true;
703 $newsubmission = false;
705 unset($submission->data1
); // Don't need to update this.
706 unset($submission->data2
); // Don't need to update this.
708 //for fast grade, we need to check if any changes take place
712 $grade = $_POST['menu'][$id];
713 $updatedb = $updatedb ||
($submission->grade
!= $grade);
714 $submission->grade
= $grade;
716 if (!$newsubmission) {
717 unset($submission->grade
); // Don't need to update this.
721 $commentvalue = trim($_POST['submissioncomment'][$id]);
722 $updatedb = $updatedb ||
($submission->submissioncomment
!= $commentvalue);
723 $submission->submissioncomment
= $commentvalue;
725 unset($submission->submissioncomment
); // Don't need to update this.
728 $submission->teacher
= $USER->id
;
730 $submission->mailed
= (int)(!$mailinfo);
733 $submission->timemarked
= time();
735 //if it is not an update, we don't change the last modified time etc.
736 //this will also not write into database if no submissioncomment and grade is entered.
739 if ($newsubmission) {
740 if (!isset($submission->submissioncomment
)) {
741 $submission->submissioncomment
= '';
743 $sid = $DB->insert_record('assignment_submissions', $submission);
744 $submission->id
= $sid;
746 $DB->update_record('assignment_submissions', $submission);
749 // trigger grade event
750 $this->update_grade($submission);
752 //add to log only if updating
753 add_to_log($this->course
->id
, 'assignment', 'update grades',
754 'submissions.php?id='.$this->cm
->id
.'&user='.$submission->userid
,
755 $submission->userid
, $this->cm
->id
);
760 $message = $OUTPUT->notification(get_string('changessaved'), 'notifysuccess');
762 $this->display_submissions($message);
767 ///We are in pop up. save the current one and go to the next one.
768 //first we save the current changes
769 if ($submission = $this->process_feedback()) {
770 //print_heading(get_string('changessaved'));
771 //$extra_javascript = $this->update_main_listing($submission);
775 /// We are currently in pop up, but we want to skip to next one without saving.
776 /// This turns out to be similar to a single case
777 /// The URL used is for the next submission.
778 $offset = required_param('offset', PARAM_INT
);
779 $nextid = required_param('nextid', PARAM_INT
);
780 $id = required_param('id', PARAM_INT
);
781 $filter = optional_param('filter', self
::FILTER_ALL
, PARAM_INT
);
783 if ($mode == 'next' ||
$filter !== self
::FILTER_REQUIRE_GRADING
) {
784 $offset = (int)$offset+
1;
786 $redirect = new moodle_url('submissions.php',
787 array('id' => $id, 'offset' => $offset, 'userid' => $nextid,
788 'mode' => 'single', 'filter' => $filter));
794 $this->display_submission();
798 echo "something seriously is wrong!!";
804 * Checks if grading method allows quickgrade mode. At the moment it is hardcoded
805 * that advanced grading methods do not allow quickgrade.
807 * Assignment type plugins are not allowed to override this method
811 public final function quickgrade_mode_allowed() {
813 require_once("$CFG->dirroot/grade/grading/lib.php");
814 if ($controller = get_grading_manager($this->context
, 'mod_assignment', 'submission')->get_active_controller()) {
821 * Helper method updating the listing on the main script from popup using javascript
825 * @param $submission object The submission whose data is to be updated on the main page
827 function update_main_listing($submission) {
828 global $SESSION, $CFG, $OUTPUT;
832 $perpage = get_user_preferences('assignment_perpage', 10);
834 $quickgrade = get_user_preferences('assignment_quickgrade', 0) && $this->quickgrade_mode_allowed();
836 /// Run some Javascript to try and update the parent page
837 $output .= '<script type="text/javascript">'."\n<!--\n";
838 if (empty($SESSION->flextable
['mod-assignment-submissions']->collapse
['submissioncomment'])) {
840 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid
.'").value="'
841 .trim($submission->submissioncomment
).'";'."\n";
843 $output.= 'opener.document.getElementById("com'.$submission->userid
.
844 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment
)), 15)."\";\n";
848 if (empty($SESSION->flextable
['mod-assignment-submissions']->collapse
['grade'])) {
849 //echo optional_param('menuindex');
851 $output.= 'opener.document.getElementById("menumenu'.$submission->userid
.
852 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT
).'";'."\n";
854 $output.= 'opener.document.getElementById("g'.$submission->userid
.'").innerHTML="'.
855 $this->display_grade($submission->grade
)."\";\n";
858 //need to add student's assignments in there too.
859 if (empty($SESSION->flextable
['mod-assignment-submissions']->collapse
['timemodified']) &&
860 $submission->timemodified
) {
861 $output.= 'opener.document.getElementById("ts'.$submission->userid
.
862 '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid
)).userdate($submission->timemodified
)."\";\n";
865 if (empty($SESSION->flextable
['mod-assignment-submissions']->collapse
['timemarked']) &&
866 $submission->timemarked
) {
867 $output.= 'opener.document.getElementById("tt'.$submission->userid
.
868 '").innerHTML="'.userdate($submission->timemarked
)."\";\n";
871 if (empty($SESSION->flextable
['mod-assignment-submissions']->collapse
['status'])) {
872 $output.= 'opener.document.getElementById("up'.$submission->userid
.'").className="s1";';
873 $buttontext = get_string('update');
874 $url = new moodle_url('/mod/assignment/submissions.php', array(
875 'id' => $this->cm
->id
,
876 'userid' => $submission->userid
,
878 'offset' => (optional_param('offset', '', PARAM_INT
)-1)));
879 $button = $OUTPUT->action_link($url, $buttontext, new popup_action('click', $url, 'grade'.$submission->userid
, array('height' => 450, 'width' => 700)), array('ttile'=>$buttontext));
881 $output .= 'opener.document.getElementById("up'.$submission->userid
.'").innerHTML="'.addslashes_js($button).'";';
884 $grading_info = grade_get_grades($this->course
->id
, 'mod', 'assignment', $this->assignment
->id
, $submission->userid
);
886 if (empty($SESSION->flextable
['mod-assignment-submissions']->collapse
['finalgrade'])) {
887 $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid
.
888 '").innerHTML="'.$grading_info->items
[0]->grades
[$submission->userid
]->str_grade
.'";'."\n";
891 if (!empty($CFG->enableoutcomes
) and empty($SESSION->flextable
['mod-assignment-submissions']->collapse
['outcome'])) {
893 if (!empty($grading_info->outcomes
)) {
894 foreach($grading_info->outcomes
as $n=>$outcome) {
895 if ($outcome->grades
[$submission->userid
]->locked
) {
900 $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid
.
901 '").selectedIndex="'.$outcome->grades
[$submission->userid
]->grade
.'";'."\n";
904 $options = make_grades_menu(-$outcome->scaleid
);
905 $options[0] = get_string('nooutcome', 'grades');
906 $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid
.'").innerHTML="'.$options[$outcome->grades
[$submission->userid
]->grade
]."\";\n";
913 $output .= "\n-->\n</script>";
918 * Return a grade in user-friendly form, whether it's a scale or not
921 * @param mixed $grade
922 * @return string User-friendly representation of grade
924 function display_grade($grade) {
927 static $scalegrades = array(); // Cache scales for each assignment - they might have different scales!!
929 if ($this->assignment
->grade
>= 0) { // Normal number
933 return $grade.' / '.$this->assignment
->grade
;
937 if (empty($scalegrades[$this->assignment
->id
])) {
938 if ($scale = $DB->get_record('scale', array('id'=>-($this->assignment
->grade
)))) {
939 $scalegrades[$this->assignment
->id
] = make_menu_from_list($scale->scale
);
944 if (isset($scalegrades[$this->assignment
->id
][$grade])) {
945 return $scalegrades[$this->assignment
->id
][$grade];
952 * Display a single submission, ready for grading on a popup window
954 * This default method prints the teacher info and submissioncomment box at the top and
955 * the student info and submission at the bottom.
956 * This method also fetches the necessary data in order to be able to
957 * provide a "Next submission" button.
958 * Calls preprocess_submission() to give assignment type plug-ins a chance
959 * to process submissions before they are graded
960 * This method gets its arguments from the page parameters userid and offset
964 * @param string $extra_javascript
966 function display_submission($offset=-1,$userid =-1, $display=true) {
967 global $CFG, $DB, $PAGE, $OUTPUT, $USER;
968 require_once($CFG->libdir
.'/gradelib.php');
969 require_once($CFG->libdir
.'/tablelib.php');
970 require_once("$CFG->dirroot/repository/lib.php");
971 require_once("$CFG->dirroot/grade/grading/lib.php");
973 $userid = required_param('userid', PARAM_INT
);
976 $offset = required_param('offset', PARAM_INT
);//offset for where to start looking for student.
978 $filter = optional_param('filter', 0, PARAM_INT
);
980 if (!$user = $DB->get_record('user', array('id'=>$userid))) {
981 print_error('nousers');
984 if (!$submission = $this->get_submission($user->id
)) {
985 $submission = $this->prepare_new_submission($userid);
987 if ($submission->timemodified
> $submission->timemarked
) {
988 $subtype = 'assignmentnew';
990 $subtype = 'assignmentold';
993 $grading_info = grade_get_grades($this->course
->id
, 'mod', 'assignment', $this->assignment
->id
, array($user->id
));
994 $gradingdisabled = $grading_info->items
[0]->grades
[$userid]->locked ||
$grading_info->items
[0]->grades
[$userid]->overridden
;
996 /// construct SQL, using current offset to find the data of the next student
997 $course = $this->course
;
998 $assignment = $this->assignment
;
1000 $context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
1002 //reset filter to all for offline assignment
1003 if ($assignment->assignmenttype
== 'offline' && $filter == self
::FILTER_SUBMITTED
) {
1004 $filter = self
::FILTER_ALL
;
1006 /// Get all ppl that can submit assignments
1008 $currentgroup = groups_get_activity_group($cm);
1009 $users = get_enrolled_users($context, 'mod/assignment:submit', $currentgroup, 'u.id');
1011 $users = array_keys($users);
1012 // if groupmembersonly used, remove users who are not in any group
1013 if (!empty($CFG->enablegroupmembersonly
) and $cm->groupmembersonly
) {
1014 if ($groupingusers = groups_get_grouping_members($cm->groupingid
, 'u.id', 'u.id')) {
1015 $users = array_intersect($users, array_keys($groupingusers));
1022 if($filter == self
::FILTER_SUBMITTED
) {
1023 $where .= 's.timemodified > 0 AND ';
1024 } else if($filter == self
::FILTER_REQUIRE_GRADING
) {
1025 $where .= 's.timemarked < s.timemodified AND ';
1029 $userfields = user_picture
::fields('u', array('lastaccess'));
1030 $select = "SELECT $userfields,
1031 s.id AS submissionid, s.grade, s.submissioncomment,
1032 s.timemodified, s.timemarked,
1033 CASE WHEN s.timemarked > 0 AND s.timemarked >= s.timemodified THEN 1
1034 ELSE 0 END AS status ";
1036 $sql = 'FROM {user} u '.
1037 'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1038 AND s.assignment = '.$this->assignment
->id
.' '.
1039 'WHERE '.$where.'u.id IN ('.implode(',', $users).') ';
1041 if ($sort = flexible_table
::get_sort_for_table('mod-assignment-submissions')) {
1042 $sort = 'ORDER BY '.$sort.' ';
1044 $auser = $DB->get_records_sql($select.$sql.$sort, null, $offset, 2);
1046 if (is_array($auser) && count($auser)>1) {
1047 $nextuser = next($auser);
1048 $nextid = $nextuser->id
;
1052 if ($submission->teacher
) {
1053 $teacher = $DB->get_record('user', array('id'=>$submission->teacher
));
1059 $this->preprocess_submission($submission);
1061 $mformdata = new stdClass();
1062 $mformdata->context
= $this->context
;
1063 $mformdata->maxbytes
= $this->course
->maxbytes
;
1064 $mformdata->courseid
= $this->course
->id
;
1065 $mformdata->teacher
= $teacher;
1066 $mformdata->assignment
= $assignment;
1067 $mformdata->submission
= $submission;
1068 $mformdata->lateness
= $this->display_lateness($submission->timemodified
);
1069 $mformdata->auser
= $auser;
1070 $mformdata->user
= $user;
1071 $mformdata->offset
= $offset;
1072 $mformdata->userid
= $userid;
1073 $mformdata->cm
= $this->cm
;
1074 $mformdata->grading_info
= $grading_info;
1075 $mformdata->enableoutcomes
= $CFG->enableoutcomes
;
1076 $mformdata->grade
= $this->assignment
->grade
;
1077 $mformdata->gradingdisabled
= $gradingdisabled;
1078 $mformdata->nextid
= $nextid;
1079 $mformdata->submissioncomment
= $submission->submissioncomment
;
1080 $mformdata->submissioncommentformat
= FORMAT_HTML
;
1081 $mformdata->submission_content
= $this->print_user_files($user->id
,true);
1082 $mformdata->filter
= $filter;
1083 $mformdata->mailinfo
= get_user_preferences('assignment_mailinfo', 0);
1084 if ($assignment->assignmenttype
== 'upload') {
1085 $mformdata->fileui_options
= array('subdirs'=>1, 'maxbytes'=>$assignment->maxbytes
, 'maxfiles'=>$assignment->var1
, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL
);
1086 } elseif ($assignment->assignmenttype
== 'uploadsingle') {
1087 $mformdata->fileui_options
= array('subdirs'=>0, 'maxbytes'=>$CFG->userquota
, 'maxfiles'=>1, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL
);
1089 $advancedgradingwarning = false;
1090 $gradingmanager = get_grading_manager($this->context
, 'mod_assignment', 'submission');
1091 if ($gradingmethod = $gradingmanager->get_active_method()) {
1092 $controller = $gradingmanager->get_controller($gradingmethod);
1093 if ($controller->is_form_available()) {
1095 if (!empty($submission->id
)) {
1096 $itemid = $submission->id
;
1098 if ($gradingdisabled && $itemid) {
1099 $mformdata->advancedgradinginstance
= $controller->get_current_instance($USER->id
, $itemid);
1100 } else if (!$gradingdisabled) {
1101 $instanceid = optional_param('advancedgradinginstanceid', 0, PARAM_INT
);
1102 $mformdata->advancedgradinginstance
= $controller->get_or_create_instance($instanceid, $USER->id
, $itemid);
1105 $advancedgradingwarning = $controller->form_unavailable_notification();
1109 $submitform = new mod_assignment_grading_form( null, $mformdata );
1112 $ret_data = new stdClass();
1113 $ret_data->mform
= $submitform;
1114 if (isset($mformdata->fileui_options
)) {
1115 $ret_data->fileui_options
= $mformdata->fileui_options
;
1120 if ($submitform->is_cancelled()) {
1121 redirect('submissions.php?id='.$this->cm
->id
);
1124 $submitform->set_data($mformdata);
1126 $PAGE->set_title($this->course
->fullname
. ': ' .get_string('feedback', 'assignment').' - '.fullname($user, true));
1127 $PAGE->set_heading($this->course
->fullname
);
1128 $PAGE->navbar
->add(get_string('submissions', 'assignment'), new moodle_url('/mod/assignment/submissions.php', array('id'=>$cm->id
)));
1129 $PAGE->navbar
->add(fullname($user, true));
1131 echo $OUTPUT->header();
1132 echo $OUTPUT->heading(get_string('feedback', 'assignment').': '.fullname($user, true));
1134 // display mform here...
1135 if ($advancedgradingwarning) {
1136 echo $OUTPUT->notification($advancedgradingwarning, 'error');
1138 $submitform->display();
1140 $customfeedback = $this->custom_feedbackform($submission, true);
1141 if (!empty($customfeedback)) {
1142 echo $customfeedback;
1145 echo $OUTPUT->footer();
1149 * Preprocess submission before grading
1151 * Called by display_submission()
1152 * The default type does nothing here.
1154 * @param object $submission The submission object
1156 function preprocess_submission(&$submission) {
1160 * Display all the submissions ready for grading
1166 * @param string $message
1169 function display_submissions($message='') {
1170 global $CFG, $DB, $USER, $DB, $OUTPUT, $PAGE;
1171 require_once($CFG->libdir
.'/gradelib.php');
1173 /* first we check to see if the form has just been submitted
1174 * to request user_preference updates
1177 $filters = array(self
::FILTER_ALL
=> get_string('all'),
1178 self
::FILTER_REQUIRE_GRADING
=> get_string('requiregrading', 'assignment'));
1180 $updatepref = optional_param('updatepref', 0, PARAM_BOOL
);
1182 $perpage = optional_param('perpage', 10, PARAM_INT
);
1183 $perpage = ($perpage <= 0) ?
10 : $perpage ;
1184 $filter = optional_param('filter', 0, PARAM_INT
);
1185 set_user_preference('assignment_perpage', $perpage);
1186 set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL
));
1187 set_user_preference('assignment_filter', $filter);
1190 /* next we get perpage and quickgrade (allow quick grade) params
1193 $perpage = get_user_preferences('assignment_perpage', 10);
1194 $quickgrade = get_user_preferences('assignment_quickgrade', 0) && $this->quickgrade_mode_allowed();
1195 $filter = get_user_preferences('assignment_filter', 0);
1196 $grading_info = grade_get_grades($this->course
->id
, 'mod', 'assignment', $this->assignment
->id
);
1198 if (!empty($CFG->enableoutcomes
) and !empty($grading_info->outcomes
)) {
1199 $uses_outcomes = true;
1201 $uses_outcomes = false;
1204 $page = optional_param('page', 0, PARAM_INT
);
1205 $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
1207 /// Some shortcuts to make the code read better
1209 $course = $this->course
;
1210 $assignment = $this->assignment
;
1212 $hassubmission = false;
1214 // reset filter to all for offline assignment only.
1215 if ($assignment->assignmenttype
== 'offline') {
1216 if ($filter == self
::FILTER_SUBMITTED
) {
1217 $filter = self
::FILTER_ALL
;
1220 $filters[self
::FILTER_SUBMITTED
] = get_string('submitted', 'assignment');
1223 $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
1224 add_to_log($course->id
, 'assignment', 'view submission', 'submissions.php?id='.$this->cm
->id
, $this->assignment
->id
, $this->cm
->id
);
1226 $PAGE->set_title(format_string($this->assignment
->name
,true));
1227 $PAGE->set_heading($this->course
->fullname
);
1228 echo $OUTPUT->header();
1230 echo '<div class="usersubmissions">';
1232 //hook to allow plagiarism plugins to update status/print links.
1233 echo plagiarism_update_status($this->course
, $this->cm
);
1235 $course_context = get_context_instance(CONTEXT_COURSE
, $course->id
);
1236 if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
1237 echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot
. '/grade/report/grader/index.php?id=' . $course->id
. '">'
1238 . get_string('seeallcoursegrades', 'grades') . '</a></div>';
1241 if (!empty($message)) {
1242 echo $message; // display messages here if any
1245 $context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
1247 /// Check to see if groups are being used in this assignment
1249 /// find out current groups mode
1250 $groupmode = groups_get_activity_groupmode($cm);
1251 $currentgroup = groups_get_activity_group($cm, true);
1252 groups_print_activity_menu($cm, $CFG->wwwroot
. '/mod/assignment/submissions.php?id=' . $this->cm
->id
);
1254 /// Print quickgrade form around the table
1256 $formattrs = array();
1257 $formattrs['action'] = new moodle_url('/mod/assignment/submissions.php');
1258 $formattrs['id'] = 'fastg';
1259 $formattrs['method'] = 'post';
1261 echo html_writer
::start_tag('form', $formattrs);
1262 echo html_writer
::empty_tag('input', array('type'=>'hidden', 'name'=>'id', 'value'=> $this->cm
->id
));
1263 echo html_writer
::empty_tag('input', array('type'=>'hidden', 'name'=>'mode', 'value'=> 'fastgrade'));
1264 echo html_writer
::empty_tag('input', array('type'=>'hidden', 'name'=>'page', 'value'=> $page));
1265 echo html_writer
::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=> sesskey()));
1268 /// Get all ppl that are allowed to submit assignments
1269 list($esql, $params) = get_enrolled_sql($context, 'mod/assignment:submit', $currentgroup);
1271 if ($filter == self
::FILTER_ALL
) {
1272 $sql = "SELECT u.id FROM {user} u ".
1273 "LEFT JOIN ($esql) eu ON eu.id=u.id ".
1274 "WHERE u.deleted = 0 AND eu.id=u.id ";
1276 $wherefilter = ' AND s.assignment = '. $this->assignment
->id
;
1277 $assignmentsubmission = "LEFT JOIN {assignment_submissions} s ON (u.id = s.userid) ";
1278 if($filter == self
::FILTER_SUBMITTED
) {
1279 $wherefilter .= ' AND s.timemodified > 0 ';
1280 } else if($filter == self
::FILTER_REQUIRE_GRADING
&& $assignment->assignmenttype
!= 'offline') {
1281 $wherefilter .= ' AND s.timemarked < s.timemodified ';
1282 } else { // require grading for offline assignment
1283 $assignmentsubmission = "";
1287 $sql = "SELECT u.id FROM {user} u ".
1288 "LEFT JOIN ($esql) eu ON eu.id=u.id ".
1289 $assignmentsubmission.
1290 "WHERE u.deleted = 0 AND eu.id=u.id ".
1294 $users = $DB->get_records_sql($sql, $params);
1295 if (!empty($users)) {
1296 if($assignment->assignmenttype
== 'offline' && $filter == self
::FILTER_REQUIRE_GRADING
) {
1297 //remove users who has submitted their assignment
1298 foreach ($this->get_submissions() as $submission) {
1299 if (array_key_exists($submission->userid
, $users)) {
1300 unset($users[$submission->userid
]);
1304 $users = array_keys($users);
1307 // if groupmembersonly used, remove users who are not in any group
1308 if ($users and !empty($CFG->enablegroupmembersonly
) and $cm->groupmembersonly
) {
1309 if ($groupingusers = groups_get_grouping_members($cm->groupingid
, 'u.id', 'u.id')) {
1310 $users = array_intersect($users, array_keys($groupingusers));
1314 $extrafields = get_extra_user_fields($context);
1315 $tablecolumns = array_merge(array('picture', 'fullname'), $extrafields,
1316 array('grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade'));
1317 if ($uses_outcomes) {
1318 $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
1321 $extrafieldnames = array();
1322 foreach ($extrafields as $field) {
1323 $extrafieldnames[] = get_user_field_name($field);
1325 $tableheaders = array_merge(
1326 array('', get_string('fullnameuser')),
1329 get_string('grade'),
1330 get_string('comment', 'assignment'),
1331 get_string('lastmodified').' ('.get_string('submission', 'assignment').')',
1332 get_string('lastmodified').' ('.get_string('grade').')',
1333 get_string('status'),
1334 get_string('finalgrade', 'grades'),
1336 if ($uses_outcomes) {
1337 $tableheaders[] = get_string('outcome', 'grades');
1340 require_once($CFG->libdir
.'/tablelib.php');
1341 $table = new flexible_table('mod-assignment-submissions');
1343 $table->define_columns($tablecolumns);
1344 $table->define_headers($tableheaders);
1345 $table->define_baseurl($CFG->wwwroot
.'/mod/assignment/submissions.php?id='.$this->cm
->id
.'&currentgroup='.$currentgroup);
1347 $table->sortable(true, 'lastname');//sorted by lastname by default
1348 $table->collapsible(true);
1349 $table->initialbars(true);
1351 $table->column_suppress('picture');
1352 $table->column_suppress('fullname');
1354 $table->column_class('picture', 'picture');
1355 $table->column_class('fullname', 'fullname');
1356 foreach ($extrafields as $field) {
1357 $table->column_class($field, $field);
1359 $table->column_class('grade', 'grade');
1360 $table->column_class('submissioncomment', 'comment');
1361 $table->column_class('timemodified', 'timemodified');
1362 $table->column_class('timemarked', 'timemarked');
1363 $table->column_class('status', 'status');
1364 $table->column_class('finalgrade', 'finalgrade');
1365 if ($uses_outcomes) {
1366 $table->column_class('outcome', 'outcome');
1369 $table->set_attribute('cellspacing', '0');
1370 $table->set_attribute('id', 'attempts');
1371 $table->set_attribute('class', 'submissions');
1372 $table->set_attribute('width', '100%');
1374 $table->no_sorting('finalgrade');
1375 $table->no_sorting('outcome');
1377 // Start working -- this is necessary as soon as the niceties are over
1380 /// Construct the SQL
1381 list($where, $params) = $table->get_sql_where();
1386 if ($filter == self
::FILTER_SUBMITTED
) {
1387 $where .= 's.timemodified > 0 AND ';
1388 } else if($filter == self
::FILTER_REQUIRE_GRADING
) {
1390 if ($assignment->assignmenttype
!= 'offline') {
1391 $where .= 's.timemarked < s.timemodified AND ';
1395 if ($sort = $table->get_sql_sort()) {
1396 $sort = ' ORDER BY '.$sort;
1399 $ufields = user_picture
::fields('u', $extrafields);
1400 if (!empty($users)) {
1401 $select = "SELECT $ufields,
1402 s.id AS submissionid, s.grade, s.submissioncomment,
1403 s.timemodified, s.timemarked,
1404 CASE WHEN s.timemarked > 0 AND s.timemarked >= s.timemodified THEN 1
1405 ELSE 0 END AS status ";
1407 $sql = 'FROM {user} u '.
1408 'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1409 AND s.assignment = '.$this->assignment
->id
.' '.
1410 'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1412 $ausers = $DB->get_records_sql($select.$sql.$sort, $params, $table->get_page_start(), $table->get_page_size());
1414 $table->pagesize($perpage, count($users));
1416 ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1417 $offset = $page * $perpage;
1418 $strupdate = get_string('update');
1419 $strgrade = get_string('grade');
1420 $strview = get_string('view');
1421 $grademenu = make_grades_menu($this->assignment
->grade
);
1423 if ($ausers !== false) {
1424 $grading_info = grade_get_grades($this->course
->id
, 'mod', 'assignment', $this->assignment
->id
, array_keys($ausers));
1425 $endposition = $offset +
$perpage;
1426 $currentposition = 0;
1427 foreach ($ausers as $auser) {
1428 if ($currentposition == $offset && $offset < $endposition) {
1430 $final_grade = $grading_info->items
[0]->grades
[$auser->id
];
1431 $grademax = $grading_info->items
[0]->grademax
;
1432 $final_grade->formatted_grade
= round($final_grade->grade
,2) .' / ' . round($grademax,2);
1433 $locked_overridden = 'locked';
1434 if ($final_grade->overridden
) {
1435 $locked_overridden = 'overridden';
1438 // TODO add here code if advanced grading grade must be reviewed => $auser->status=0
1440 $picture = $OUTPUT->user_picture($auser);
1442 if (empty($auser->submissionid
)) {
1443 $auser->grade
= -1; //no submission yet
1446 if (!empty($auser->submissionid
)) {
1447 $hassubmission = true;
1448 ///Prints student answer and student modified date
1449 ///attach file or print link to student answer, depending on the type of the assignment.
1450 ///Refer to print_student_answer in inherited classes.
1451 if ($auser->timemodified
> 0) {
1452 $studentmodifiedcontent = $this->print_student_answer($auser->id
)
1453 . userdate($auser->timemodified
);
1454 if ($assignment->timedue
&& $auser->timemodified
> $assignment->timedue
&& $this->supports_lateness()) {
1455 $studentmodifiedcontent .= $this->display_lateness($auser->timemodified
);
1459 $studentmodifiedcontent = ' ';
1461 $studentmodified = html_writer
::tag('div', $studentmodifiedcontent, array('id' => 'ts' . $auser->id
));
1462 ///Print grade, dropdown or text
1463 if ($auser->timemarked
> 0) {
1464 $teachermodified = '<div id="tt'.$auser->id
.'">'.userdate($auser->timemarked
).'</div>';
1466 if ($final_grade->locked
or $final_grade->overridden
) {
1467 $grade = '<div id="g'.$auser->id
.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade
.'</div>';
1468 } else if ($quickgrade) {
1469 $attributes = array();
1470 $attributes['tabindex'] = $tabindex++
;
1471 $menu = html_writer
::label(get_string('assignment:grade', 'assignment'), 'menumenu'. $auser->id
, false, array('class' => 'accesshide'));
1472 $menu .= html_writer
::select(make_grades_menu($this->assignment
->grade
), 'menu['.$auser->id
.']', $auser->grade
, array(-1=>get_string('nograde')), $attributes);
1473 $grade = '<div id="g'.$auser->id
.'">'. $menu .'</div>';
1475 $grade = '<div id="g'.$auser->id
.'">'.$this->display_grade($auser->grade
).'</div>';
1479 $teachermodified = '<div id="tt'.$auser->id
.'"> </div>';
1480 if ($final_grade->locked
or $final_grade->overridden
) {
1481 $grade = '<div id="g'.$auser->id
.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade
.'</div>';
1482 } else if ($quickgrade) {
1483 $attributes = array();
1484 $attributes['tabindex'] = $tabindex++
;
1485 $menu = html_writer
::label(get_string('assignment:grade', 'assignment'), 'menumenu'. $auser->id
, false, array('class' => 'accesshide'));
1486 $menu .= html_writer
::select(make_grades_menu($this->assignment
->grade
), 'menu['.$auser->id
.']', $auser->grade
, array(-1=>get_string('nograde')), $attributes);
1487 $grade = '<div id="g'.$auser->id
.'">'.$menu.'</div>';
1489 $grade = '<div id="g'.$auser->id
.'">'.$this->display_grade($auser->grade
).'</div>';
1493 if ($final_grade->locked
or $final_grade->overridden
) {
1494 $comment = '<div id="com'.$auser->id
.'">'.shorten_text(strip_tags($final_grade->str_feedback
),15).'</div>';
1496 } else if ($quickgrade) {
1497 $comment = '<div id="com'.$auser->id
.'">'
1498 . '<textarea tabindex="'.$tabindex++
.'" name="submissioncomment['.$auser->id
.']" id="submissioncomment'
1499 . $auser->id
.'" rows="2" cols="20">'.($auser->submissioncomment
).'</textarea></div>';
1501 $comment = '<div id="com'.$auser->id
.'">'.shorten_text(strip_tags($auser->submissioncomment
),15).'</div>';
1504 $studentmodified = '<div id="ts'.$auser->id
.'"> </div>';
1505 $teachermodified = '<div id="tt'.$auser->id
.'"> </div>';
1506 $status = '<div id="st'.$auser->id
.'"> </div>';
1508 if ($final_grade->locked
or $final_grade->overridden
) {
1509 $grade = '<div id="g'.$auser->id
.'">'.$final_grade->formatted_grade
. '</div>';
1510 $hassubmission = true;
1511 } else if ($quickgrade) { // allow editing
1512 $attributes = array();
1513 $attributes['tabindex'] = $tabindex++
;
1514 $menu = html_writer
::label(get_string('assignment:grade', 'assignment'), 'menumenu'. $auser->id
, false, array('class' => 'accesshide'));
1515 $menu .= html_writer
::select(make_grades_menu($this->assignment
->grade
), 'menu['.$auser->id
.']', $auser->grade
, array(-1=>get_string('nograde')), $attributes);
1516 $grade = '<div id="g'.$auser->id
.'">'.$menu.'</div>';
1517 $hassubmission = true;
1519 $grade = '<div id="g'.$auser->id
.'">-</div>';
1522 if ($final_grade->locked
or $final_grade->overridden
) {
1523 $comment = '<div id="com'.$auser->id
.'">'.$final_grade->str_feedback
.'</div>';
1524 } else if ($quickgrade) {
1525 $comment = '<div id="com'.$auser->id
.'">'
1526 . '<textarea tabindex="'.$tabindex++
.'" name="submissioncomment['.$auser->id
.']" id="submissioncomment'
1527 . $auser->id
.'" rows="2" cols="20">'.($auser->submissioncomment
).'</textarea></div>';
1529 $comment = '<div id="com'.$auser->id
.'"> </div>';
1533 if (empty($auser->status
)) { /// Confirm we have exclusively 0 or 1
1539 $buttontext = ($auser->status
== 1) ?
$strupdate : $strgrade;
1540 if ($final_grade->locked
or $final_grade->overridden
) {
1541 $buttontext = $strview;
1544 ///No more buttons, we use popups ;-).
1545 $popup_url = '/mod/assignment/submissions.php?id='.$this->cm
->id
1546 . '&userid='.$auser->id
.'&mode=single'.'&filter='.$filter.'&offset='.$offset++
;
1548 $button = $OUTPUT->action_link($popup_url, $buttontext);
1550 $status = '<div id="up'.$auser->id
.'" class="s'.$auser->status
.'">'.$button.'</div>';
1552 $finalgrade = '<span id="finalgrade_'.$auser->id
.'">'.$final_grade->str_grade
.'</span>';
1556 if ($uses_outcomes) {
1558 foreach($grading_info->outcomes
as $n=>$outcome) {
1559 $outcomes .= '<div class="outcome"><label for="'. 'outcome_'.$n.'_'.$auser->id
.'">'.$outcome->name
.'</label>';
1560 $options = make_grades_menu(-$outcome->scaleid
);
1562 if ($outcome->grades
[$auser->id
]->locked
or !$quickgrade) {
1563 $options[0] = get_string('nooutcome', 'grades');
1564 $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id
.'">'.$options[$outcome->grades
[$auser->id
]->grade
].'</span>';
1566 $attributes = array();
1567 $attributes['tabindex'] = $tabindex++
;
1568 $attributes['id'] = 'outcome_'.$n.'_'.$auser->id
;
1569 $outcomes .= ' '.html_writer
::select($options, 'outcome_'.$n.'['.$auser->id
.']', $outcome->grades
[$auser->id
]->grade
, array(0=>get_string('nooutcome', 'grades')), $attributes);
1571 $outcomes .= '</div>';
1575 $userlink = '<a href="' . $CFG->wwwroot
. '/user/view.php?id=' . $auser->id
. '&course=' . $course->id
. '">' . fullname($auser, has_capability('moodle/site:viewfullnames', $this->context
)) . '</a>';
1576 $extradata = array();
1577 foreach ($extrafields as $field) {
1578 $extradata[] = $auser->{$field};
1580 $row = array_merge(array($picture, $userlink), $extradata,
1581 array($grade, $comment, $studentmodified, $teachermodified,
1582 $status, $finalgrade));
1583 if ($uses_outcomes) {
1586 $table->add_data($row, $rowclass);
1590 if ($hassubmission && method_exists($this, 'download_submissions')) {
1591 echo html_writer
::start_tag('div', array('class' => 'mod-assignment-download-link'));
1592 echo html_writer
::link(new moodle_url('/mod/assignment/submissions.php', array('id' => $this->cm
->id
, 'download' => 'zip')), get_string('downloadall', 'assignment'));
1593 echo html_writer
::end_tag('div');
1595 $table->print_html(); /// Print the whole table
1597 if ($filter == self
::FILTER_SUBMITTED
) {
1598 echo html_writer
::tag('div', get_string('nosubmisson', 'assignment'), array('class'=>'nosubmisson'));
1599 } else if ($filter == self
::FILTER_REQUIRE_GRADING
) {
1600 echo html_writer
::tag('div', get_string('norequiregrading', 'assignment'), array('class'=>'norequiregrading'));
1605 /// Print quickgrade form around the table
1606 if ($quickgrade && $table->started_output
&& !empty($users)){
1607 $mailinfopref = false;
1608 if (get_user_preferences('assignment_mailinfo', 1)) {
1609 $mailinfopref = true;
1611 $emailnotification = html_writer
::checkbox('mailinfo', 1, $mailinfopref, get_string('enablenotification','assignment'));
1613 $emailnotification .= $OUTPUT->help_icon('enablenotification', 'assignment');
1614 echo html_writer
::tag('div', $emailnotification, array('class'=>'emailnotification'));
1616 $savefeedback = html_writer
::empty_tag('input', array('type'=>'submit', 'name'=>'fastg', 'value'=>get_string('saveallfeedback', 'assignment')));
1617 echo html_writer
::tag('div', $savefeedback, array('class'=>'fastgbutton'));
1619 echo html_writer
::end_tag('form');
1620 } else if ($quickgrade) {
1621 echo html_writer
::end_tag('form');
1625 /// End of fast grading form
1627 /// Mini form for setting user preference
1629 $formaction = new moodle_url('/mod/assignment/submissions.php', array('id'=>$this->cm
->id
));
1630 $mform = new MoodleQuickForm('optionspref', 'post', $formaction, '', array('class'=>'optionspref'));
1632 $mform->addElement('hidden', 'updatepref');
1633 $mform->setDefault('updatepref', 1);
1634 $mform->addElement('header', 'qgprefs', get_string('optionalsettings', 'assignment'));
1635 $mform->addElement('select', 'filter', get_string('show'), $filters);
1637 $mform->setDefault('filter', $filter);
1639 $mform->addElement('text', 'perpage', get_string('pagesize', 'assignment'), array('size'=>1));
1640 $mform->setDefault('perpage', $perpage);
1642 if ($this->quickgrade_mode_allowed()) {
1643 $mform->addElement('checkbox', 'quickgrade', get_string('quickgrade','assignment'));
1644 $mform->setDefault('quickgrade', $quickgrade);
1645 $mform->addHelpButton('quickgrade', 'quickgrade', 'assignment');
1648 $mform->addElement('submit', 'savepreferences', get_string('savepreferences'));
1652 echo $OUTPUT->footer();
1656 * If the form was cancelled ('Cancel' or 'Next' was pressed), call cancel method
1657 * from advanced grading (if applicable) and returns true
1658 * If the form was submitted, validates it and returns false if validation did not pass.
1659 * If validation passes, preprocess advanced grading (if applicable) and returns true.
1661 * Note to the developers: This is NOT the correct way to implement advanced grading
1662 * in grading form. The assignment grading was written long time ago and unfortunately
1663 * does not fully use the mforms. Usually function is_validated() is called to
1664 * validate the form and get_data() is called to get the data from the form.
1666 * Here we have to push the calculated grade to $_POST['xgrade'] because further processing
1667 * of the form gets the data not from form->get_data(), but from $_POST (using statement
1668 * like $feedback = data_submitted() )
1670 protected function validate_and_preprocess_feedback() {
1672 require_once($CFG->libdir
.'/gradelib.php');
1673 if (!($feedback = data_submitted()) ||
!isset($feedback->userid
) ||
!isset($feedback->offset
)) {
1674 return true; // No incoming data, nothing to validate
1676 $userid = required_param('userid', PARAM_INT
);
1677 $offset = required_param('offset', PARAM_INT
);
1678 $gradinginfo = grade_get_grades($this->course
->id
, 'mod', 'assignment', $this->assignment
->id
, array($userid));
1679 $gradingdisabled = $gradinginfo->items
[0]->grades
[$userid]->locked ||
$gradinginfo->items
[0]->grades
[$userid]->overridden
;
1680 if ($gradingdisabled) {
1683 $submissiondata = $this->display_submission($offset, $userid, false);
1684 $mform = $submissiondata->mform
;
1685 $gradinginstance = $mform->use_advanced_grading();
1686 if (optional_param('cancel', false, PARAM_BOOL
) ||
optional_param('next', false, PARAM_BOOL
)) {
1687 // form was cancelled
1688 if ($gradinginstance) {
1689 $gradinginstance->cancel();
1691 } else if ($mform->is_submitted()) {
1692 // form was submitted (= a submit button other than 'cancel' or 'next' has been clicked)
1693 if (!$mform->is_validated()) {
1696 // preprocess advanced grading here
1697 if ($gradinginstance) {
1698 $data = $mform->get_data();
1699 // create submission if it did not exist yet because we need submission->id for storing the grading instance
1700 $submission = $this->get_submission($userid, true);
1701 $_POST['xgrade'] = $gradinginstance->submit_and_get_grade($data->advancedgrading
, $submission->id
);
1708 * Process teacher feedback submission
1710 * This is called by submissions() when a grading even has taken place.
1711 * It gets its data from the submitted form.
1716 * @return object|bool The updated submission object or false
1718 function process_feedback($formdata=null) {
1719 global $CFG, $USER, $DB;
1720 require_once($CFG->libdir
.'/gradelib.php');
1722 if (!$feedback = data_submitted() or !confirm_sesskey()) { // No incoming data?
1726 ///For save and next, we need to know the userid to save, and the userid to go
1727 ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1728 ///as the userid to store
1729 if ((int)$feedback->saveuserid
!== -1){
1730 $feedback->userid
= $feedback->saveuserid
;
1733 if (!empty($feedback->cancel
)) { // User hit cancel button
1737 $grading_info = grade_get_grades($this->course
->id
, 'mod', 'assignment', $this->assignment
->id
, $feedback->userid
);
1739 // store outcomes if needed
1740 $this->process_outcomes($feedback->userid
);
1742 $submission = $this->get_submission($feedback->userid
, true); // Get or make one
1744 if (!($grading_info->items
[0]->grades
[$feedback->userid
]->locked ||
1745 $grading_info->items
[0]->grades
[$feedback->userid
]->overridden
) ) {
1747 $submission->grade
= $feedback->xgrade
;
1748 $submission->submissioncomment
= $feedback->submissioncomment_editor
['text'];
1749 $submission->teacher
= $USER->id
;
1750 $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1752 $submission->mailed
= 1; // treat as already mailed
1754 $submission->mailed
= 0; // Make sure mail goes out (again, even)
1756 $submission->timemarked
= time();
1758 unset($submission->data1
); // Don't need to update this.
1759 unset($submission->data2
); // Don't need to update this.
1761 if (empty($submission->timemodified
)) { // eg for offline assignments
1762 // $submission->timemodified = time();
1765 $DB->update_record('assignment_submissions', $submission);
1767 // triger grade event
1768 $this->update_grade($submission);
1770 add_to_log($this->course
->id
, 'assignment', 'update grades',
1771 'submissions.php?id='.$this->cm
->id
.'&user='.$feedback->userid
, $feedback->userid
, $this->cm
->id
);
1772 if (!is_null($formdata)) {
1773 if ($this->type
== 'upload' ||
$this->type
== 'uploadsingle') {
1774 $mformdata = $formdata->mform
->get_data();
1775 $mformdata = file_postupdate_standard_filemanager($mformdata, 'files', $formdata->fileui_options
, $this->context
, 'mod_assignment', 'response', $submission->id
);
1784 function process_outcomes($userid) {
1787 if (empty($CFG->enableoutcomes
)) {
1791 require_once($CFG->libdir
.'/gradelib.php');
1793 if (!$formdata = data_submitted() or !confirm_sesskey()) {
1798 $grading_info = grade_get_grades($this->course
->id
, 'mod', 'assignment', $this->assignment
->id
, $userid);
1800 if (!empty($grading_info->outcomes
)) {
1801 foreach($grading_info->outcomes
as $n=>$old) {
1802 $name = 'outcome_'.$n;
1803 if (isset($formdata->{$name}[$userid]) and $old->grades
[$userid]->grade
!= $formdata->{$name}[$userid]) {
1804 $data[$n] = $formdata->{$name}[$userid];
1808 if (count($data) > 0) {
1809 grade_update_outcomes('mod/assignment', $this->course
->id
, 'mod', 'assignment', $this->assignment
->id
, $userid, $data);
1815 * Load the submission object for a particular user
1819 * @param int $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1820 * @param bool $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1821 * @param bool $teachermodified student submission set if false
1822 * @return object|bool The submission or false (if $createnew is false and there is no existing submission).
1824 function get_submission($userid=0, $createnew=false, $teachermodified=false) {
1827 if (empty($userid)) {
1828 $userid = $USER->id
;
1831 $submission = $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment
->id
, 'userid'=>$userid));
1835 } else if (!$createnew) {
1838 $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
1839 $DB->insert_record("assignment_submissions", $newsubmission);
1841 return $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment
->id
, 'userid'=>$userid));
1845 * Check the given submission is complete. Preliminary rows are often created in the assignment_submissions
1846 * table before a submission actually takes place. This function checks to see if the given submission has actually
1849 * @param stdClass $submission The submission we want to check for completion
1850 * @return bool Indicates if the submission was found to be complete
1852 public function is_submitted_with_required_data($submission) {
1853 return $submission->timemodified
;
1857 * Instantiates a new submission object for a given user
1859 * Sets the assignment, userid and times, everything else is set to default values.
1861 * @param int $userid The userid for which we want a submission object
1862 * @param bool $teachermodified student submission set if false
1863 * @return object The submission
1865 function prepare_new_submission($userid, $teachermodified=false) {
1866 $submission = new stdClass();
1867 $submission->assignment
= $this->assignment
->id
;
1868 $submission->userid
= $userid;
1869 $submission->timecreated
= time();
1870 // teachers should not be modifying modified date, except offline assignments
1871 if ($teachermodified) {
1872 $submission->timemodified
= 0;
1874 $submission->timemodified
= $submission->timecreated
;
1876 $submission->numfiles
= 0;
1877 $submission->data1
= '';
1878 $submission->data2
= '';
1879 $submission->grade
= -1;
1880 $submission->submissioncomment
= '';
1881 $submission->format
= 0;
1882 $submission->teacher
= 0;
1883 $submission->timemarked
= 0;
1884 $submission->mailed
= 0;
1889 * Return all assignment submissions by ENROLLED students (even empty)
1891 * @param string $sort optional field names for the ORDER BY in the sql query
1892 * @param string $dir optional specifying the sort direction, defaults to DESC
1893 * @return array The submission objects indexed by id
1895 function get_submissions($sort='', $dir='DESC') {
1896 return assignment_get_all_submissions($this->assignment
, $sort, $dir);
1900 * Counts all complete (real) assignment submissions by enrolled students
1902 * @param int $groupid (optional) If nonzero then count is restricted to this group
1903 * @return int The number of submissions
1905 function count_real_submissions($groupid=0) {
1909 // Grab the context assocated with our course module
1910 $context = get_context_instance(CONTEXT_MODULE
, $this->cm
->id
);
1912 // Get ids of users enrolled in the given course.
1913 list($enroledsql, $params) = get_enrolled_sql($context, 'mod/assignment:view', $groupid);
1914 $params['assignmentid'] = $this->cm
->instance
;
1916 // Get ids of users enrolled in the given course.
1917 return $DB->count_records_sql("SELECT COUNT('x')
1918 FROM {assignment_submissions} s
1919 LEFT JOIN {assignment} a ON a.id = s.assignment
1920 INNER JOIN ($enroledsql) u ON u.id = s.userid
1921 WHERE s.assignment = :assignmentid AND
1922 s.timemodified > 0", $params);
1926 * Alerts teachers by email of new or changed assignments that need grading
1928 * First checks whether the option to email teachers is set for this assignment.
1929 * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1930 * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1934 * @param $submission object The submission that has changed
1937 function email_teachers($submission) {
1940 if (empty($this->assignment
->emailteachers
)) { // No need to do anything
1944 $user = $DB->get_record('user', array('id'=>$submission->userid
));
1946 if ($teachers = $this->get_graders($user)) {
1948 $strassignments = get_string('modulenameplural', 'assignment');
1949 $strassignment = get_string('modulename', 'assignment');
1950 $strsubmitted = get_string('submitted', 'assignment');
1952 foreach ($teachers as $teacher) {
1953 $info = new stdClass();
1954 $info->username
= fullname($user, true);
1955 $info->assignment
= format_string($this->assignment
->name
,true);
1956 $info->url
= $CFG->wwwroot
.'/mod/assignment/submissions.php?id='.$this->cm
->id
;
1957 $info->timeupdated
= userdate($submission->timemodified
, '%c', $teacher->timezone
);
1959 $postsubject = $strsubmitted.': '.$info->username
.' -> '.$this->assignment
->name
;
1960 $posttext = $this->email_teachers_text($info);
1961 $posthtml = ($teacher->mailformat
== 1) ?
$this->email_teachers_html($info) : '';
1963 $eventdata = new stdClass();
1964 $eventdata->modulename
= 'assignment';
1965 $eventdata->userfrom
= $user;
1966 $eventdata->userto
= $teacher;
1967 $eventdata->subject
= $postsubject;
1968 $eventdata->fullmessage
= $posttext;
1969 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
1970 $eventdata->fullmessagehtml
= $posthtml;
1971 $eventdata->smallmessage
= $postsubject;
1973 $eventdata->name
= 'assignment_updates';
1974 $eventdata->component
= 'mod_assignment';
1975 $eventdata->notification
= 1;
1976 $eventdata->contexturl
= $info->url
;
1977 $eventdata->contexturlname
= $info->assignment
;
1979 message_send($eventdata);
1985 * @param string $filearea
1986 * @param array $args
1989 function send_file($filearea, $args) {
1990 debugging('plugin does not implement file sending', DEBUG_DEVELOPER
);
1995 * Returns a list of teachers that should be grading given submission
1997 * @param object $user
2000 function get_graders($user) {
2004 list($enrolledsql, $params) = get_enrolled_sql($this->context
, 'mod/assignment:grade', 0, true);
2007 JOIN ($enrolledsql) je ON je.id = u.id";
2008 $potgraders = $DB->get_records_sql($sql, $params);
2011 if (groups_get_activity_groupmode($this->cm
) == SEPARATEGROUPS
) { // Separate groups are being used
2012 if ($groups = groups_get_all_groups($this->course
->id
, $user->id
)) { // Try to find all groups
2013 foreach ($groups as $group) {
2014 foreach ($potgraders as $t) {
2015 if ($t->id
== $user->id
) {
2016 continue; // do not send self
2018 if (groups_is_member($group->id
, $t->id
)) {
2019 $graders[$t->id
] = $t;
2024 // user not in group, try to find graders without group
2025 foreach ($potgraders as $t) {
2026 if ($t->id
== $user->id
) {
2027 continue; // do not send self
2029 if (!groups_get_all_groups($this->course
->id
, $t->id
)) { //ugly hack
2030 $graders[$t->id
] = $t;
2035 foreach ($potgraders as $t) {
2036 if ($t->id
== $user->id
) {
2037 continue; // do not send self
2039 $graders[$t->id
] = $t;
2046 * Creates the text content for emails to teachers
2048 * @param $info object The info used by the 'emailteachermail' language string
2051 function email_teachers_text($info) {
2052 $posttext = format_string($this->course
->shortname
, true, array('context' => $this->coursecontext
)).' -> '.
2053 $this->strassignments
.' -> '.
2054 format_string($this->assignment
->name
, true, array('context' => $this->context
))."\n";
2055 $posttext .= '---------------------------------------------------------------------'."\n";
2056 $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
2057 $posttext .= "\n---------------------------------------------------------------------\n";
2062 * Creates the html content for emails to teachers
2064 * @param $info object The info used by the 'emailteachermailhtml' language string
2067 function email_teachers_html($info) {
2069 $posthtml = '<p><font face="sans-serif">'.
2070 '<a href="'.$CFG->wwwroot
.'/course/view.php?id='.$this->course
->id
.'">'.format_string($this->course
->shortname
, true, array('context' => $this->coursecontext
)).'</a> ->'.
2071 '<a href="'.$CFG->wwwroot
.'/mod/assignment/index.php?id='.$this->course
->id
.'">'.$this->strassignments
.'</a> ->'.
2072 '<a href="'.$CFG->wwwroot
.'/mod/assignment/view.php?id='.$this->cm
->id
.'">'.format_string($this->assignment
->name
, true, array('context' => $this->context
)).'</a></font></p>';
2073 $posthtml .= '<hr /><font face="sans-serif">';
2074 $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
2075 $posthtml .= '</font><hr />';
2080 * Produces a list of links to the files uploaded by a user
2082 * @param $userid int optional id of the user. If 0 then $USER->id is used.
2083 * @param $return boolean optional defaults to false. If true the list is returned rather than printed
2084 * @return string optional
2086 function print_user_files($userid=0, $return=false) {
2087 global $CFG, $USER, $OUTPUT;
2090 if (!isloggedin()) {
2093 $userid = $USER->id
;
2098 $submission = $this->get_submission($userid);
2103 $fs = get_file_storage();
2104 $files = $fs->get_area_files($this->context
->id
, 'mod_assignment', 'submission', $submission->id
, "timemodified", false);
2105 if (!empty($files)) {
2106 require_once($CFG->dirroot
. '/mod/assignment/locallib.php');
2107 if ($CFG->enableportfolios
) {
2108 require_once($CFG->libdir
.'/portfoliolib.php');
2109 $button = new portfolio_add_button();
2111 foreach ($files as $file) {
2112 $filename = $file->get_filename();
2113 $mimetype = $file->get_mimetype();
2114 $path = file_encode_url($CFG->wwwroot
.'/pluginfile.php', '/'.$this->context
->id
.'/mod_assignment/submission/'.$submission->id
.'/'.$filename);
2115 $output .= '<a href="'.$path.'" ><img src="'.$OUTPUT->pix_url(file_mimetype_icon($mimetype)).'" class="icon" alt="'.$mimetype.'" />'.s($filename).'</a>';
2116 if ($CFG->enableportfolios
&& $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context
)) {
2117 $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm
->id
, 'submissionid' => $submission->id
, 'fileid' => $file->get_id()), '/mod/assignment/locallib.php');
2118 $button->set_format_by_file($file);
2119 $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK
);
2122 if ($CFG->enableplagiarism
) {
2123 require_once($CFG->libdir
.'/plagiarismlib.php');
2124 $output .= plagiarism_get_links(array('userid'=>$userid, 'file'=>$file, 'cmid'=>$this->cm
->id
, 'course'=>$this->course
, 'assignment'=>$this->assignment
));
2125 $output .= '<br />';
2128 if ($CFG->enableportfolios
&& count($files) > 1 && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context
)) {
2129 $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm
->id
, 'submissionid' => $submission->id
), '/mod/assignment/locallib.php');
2130 $output .= '<br />' . $button->to_html(PORTFOLIO_ADD_TEXT_LINK
);
2134 $output = '<div class="files">'.$output.'</div>';
2143 * Count the files uploaded by a given user
2145 * @param $itemid int The submission's id as the file's itemid.
2148 function count_user_files($itemid) {
2149 $fs = get_file_storage();
2150 $files = $fs->get_area_files($this->context
->id
, 'mod_assignment', 'submission', $itemid, "id", false);
2151 return count($files);
2155 * Returns true if the student is allowed to submit
2157 * Checks that the assignment has started and, if the option to prevent late
2158 * submissions is set, also checks that the assignment has not yet closed.
2163 if ($this->assignment
->preventlate
&& $this->assignment
->timedue
) {
2164 return ($this->assignment
->timeavailable
<= $time && $time <= $this->assignment
->timedue
);
2166 return ($this->assignment
->timeavailable
<= $time);
2172 * Return true if is set description is hidden till available date
2174 * This is needed by calendar so that hidden descriptions do not
2175 * come up in upcoming events.
2177 * Check that description is hidden till available date
2178 * By default return false
2179 * Assignments types should implement this method if needed
2182 function description_is_hidden() {
2187 * Return an outline of the user's interaction with the assignment
2189 * The default method prints the grade and timemodified
2190 * @param $grade object
2191 * @return object with properties ->info and ->time
2193 function user_outline($grade) {
2195 $result = new stdClass();
2196 $result->info
= get_string('grade').': '.$grade->str_long_grade
;
2197 $result->time
= $grade->dategraded
;
2202 * Print complete information about the user's interaction with the assignment
2204 * @param $user object
2206 function user_complete($user, $grade=null) {
2209 if ($submission = $this->get_submission($user->id
)) {
2211 $fs = get_file_storage();
2213 if ($files = $fs->get_area_files($this->context
->id
, 'mod_assignment', 'submission', $submission->id
, "timemodified", false)) {
2214 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
2215 foreach ($files as $file) {
2216 $countfiles .= "; ".$file->get_filename();
2220 echo $OUTPUT->box_start();
2221 echo get_string("lastmodified").": ";
2222 echo userdate($submission->timemodified
);
2223 echo $this->display_lateness($submission->timemodified
);
2225 $this->print_user_files($user->id
);
2229 $this->view_feedback($submission);
2231 echo $OUTPUT->box_end();
2235 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade
);
2236 if ($grade->str_feedback
) {
2237 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback
);
2240 print_string("notsubmittedyet", "assignment");
2245 * Return a string indicating how late a submission is
2247 * @param $timesubmitted int
2250 function display_lateness($timesubmitted) {
2251 return assignment_display_lateness($timesubmitted, $this->assignment
->timedue
);
2255 * Empty method stub for all delete actions.
2258 //nothing by default
2259 redirect('view.php?id='.$this->cm
->id
);
2263 * Empty custom feedback grading form.
2265 function custom_feedbackform($submission, $return=false) {
2266 //nothing by default
2271 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
2272 * for the course (see resource).
2274 * Given a course_module object, this function returns any "extra" information that may be needed
2275 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
2277 * @param $coursemodule object The coursemodule object (record).
2278 * @return cached_cm_info Object used to customise appearance on course page
2280 function get_coursemodule_info($coursemodule) {
2285 * Plugin cron method - do not use $this here, create new assignment instances if needed.
2289 //no plugin cron by default - override if needed
2293 * Reset all submissions
2295 function reset_userdata($data) {
2298 if (!$DB->count_records('assignment', array('course'=>$data->courseid
, 'assignmenttype'=>$this->type
))) {
2299 return array(); // no assignments of this type present
2302 $componentstr = get_string('modulenameplural', 'assignment');
2305 $typestr = get_string('type'.$this->type
, 'assignment');
2306 // ugly hack to support pluggable assignment type titles...
2307 if($typestr === '[[type'.$this->type
.']]'){
2308 $typestr = get_string('type'.$this->type
, 'assignment_'.$this->type
);
2311 if (!empty($data->reset_assignment_submissions
)) {
2312 $assignmentssql = "SELECT a.id
2314 WHERE a.course=? AND a.assignmenttype=?";
2315 $params = array($data->courseid
, $this->type
);
2317 // now get rid of all submissions and responses
2318 $fs = get_file_storage();
2319 if ($assignments = $DB->get_records_sql($assignmentssql, $params)) {
2320 foreach ($assignments as $assignmentid=>$unused) {
2321 if (!$cm = get_coursemodule_from_instance('assignment', $assignmentid)) {
2324 $context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
2325 $fs->delete_area_files($context->id
, 'mod_assignment', 'submission');
2326 $fs->delete_area_files($context->id
, 'mod_assignment', 'response');
2330 $DB->delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)", $params);
2332 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
2334 if (empty($data->reset_gradebook_grades
)) {
2335 // remove all grades from gradebook
2336 assignment_reset_gradebook($data->courseid
, $this->type
);
2340 /// updating dates - shift may be negative too
2341 if ($data->timeshift
) {
2342 shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift
, $data->courseid
);
2343 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
2350 function portfolio_exportable() {
2355 * base implementation for backing up subtype specific information
2356 * for one single module
2358 * @param filehandle $bf file handle for xml file to write to
2359 * @param mixed $preferences the complete backup preference object
2365 static function backup_one_mod($bf, $preferences, $assignment) {
2370 * base implementation for backing up subtype specific information
2371 * for one single submission
2373 * @param filehandle $bf file handle for xml file to write to
2374 * @param mixed $preferences the complete backup preference object
2375 * @param object $submission the assignment submission db record
2381 static function backup_one_submission($bf, $preferences, $assignment, $submission) {
2386 * base implementation for restoring subtype specific information
2387 * for one single module
2389 * @param array $info the array representing the xml
2390 * @param object $restore the restore preferences
2396 static function restore_one_mod($info, $restore, $assignment) {
2401 * base implementation for restoring subtype specific information
2402 * for one single submission
2404 * @param object $submission the newly created submission
2405 * @param array $info the array representing the xml
2406 * @param object $restore the restore preferences
2412 static function restore_one_submission($info, $restore, $assignment, $submission) {
2416 } ////// End of the assignment_base class
2419 class mod_assignment_grading_form
extends moodleform
{
2420 /** @var stores the advaned grading instance (if used in grading) */
2421 private $advancegradinginstance;
2423 function definition() {
2425 $mform =& $this->_form
;
2427 if (isset($this->_customdata
->advancedgradinginstance
)) {
2428 $this->use_advanced_grading($this->_customdata
->advancedgradinginstance
);
2431 $formattr = $mform->getAttributes();
2432 $formattr['id'] = 'submitform';
2433 $mform->setAttributes($formattr);
2435 $mform->addElement('hidden', 'offset', ($this->_customdata
->offset+
1));
2436 $mform->setType('offset', PARAM_INT
);
2437 $mform->addElement('hidden', 'userid', $this->_customdata
->userid
);
2438 $mform->setType('userid', PARAM_INT
);
2439 $mform->addElement('hidden', 'nextid', $this->_customdata
->nextid
);
2440 $mform->setType('nextid', PARAM_INT
);
2441 $mform->addElement('hidden', 'id', $this->_customdata
->cm
->id
);
2442 $mform->setType('id', PARAM_INT
);
2443 $mform->addElement('hidden', 'sesskey', sesskey());
2444 $mform->setType('sesskey', PARAM_ALPHANUM
);
2445 $mform->addElement('hidden', 'mode', 'grade');
2446 $mform->setType('mode', PARAM_TEXT
);
2447 $mform->addElement('hidden', 'menuindex', "0");
2448 $mform->setType('menuindex', PARAM_INT
);
2449 $mform->addElement('hidden', 'saveuserid', "-1");
2450 $mform->setType('saveuserid', PARAM_INT
);
2451 $mform->addElement('hidden', 'filter', "0");
2452 $mform->setType('filter', PARAM_INT
);
2454 $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata
->user
),
2455 fullname($this->_customdata
->user
, true) . '<br/>' .
2456 userdate($this->_customdata
->submission
->timemodified
) .
2457 $this->_customdata
->lateness
);
2459 $this->add_submission_content();
2460 $this->add_grades_section();
2462 $this->add_feedback_section();
2464 if ($this->_customdata
->submission
->timemarked
) {
2465 $datestring = userdate($this->_customdata
->submission
->timemarked
)." (".format_time(time() - $this->_customdata
->submission
->timemarked
).")";
2466 $mform->addElement('header', 'Last Grade', get_string('lastgrade', 'assignment'));
2467 $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata
->teacher
) ,
2468 fullname($this->_customdata
->teacher
,true).
2469 '<br/>'.$datestring);
2472 $this->add_action_buttons();
2477 * Gets or sets the instance for advanced grading
2479 * @param gradingform_instance $gradinginstance
2481 public function use_advanced_grading($gradinginstance = false) {
2482 if ($gradinginstance !== false) {
2483 $this->advancegradinginstance
= $gradinginstance;
2485 return $this->advancegradinginstance
;
2488 function add_grades_section() {
2490 $mform =& $this->_form
;
2491 $attributes = array();
2492 if ($this->_customdata
->gradingdisabled
) {
2493 $attributes['disabled'] ='disabled';
2496 $mform->addElement('header', 'Grades', get_string('grades', 'grades'));
2498 $grademenu = make_grades_menu($this->_customdata
->assignment
->grade
);
2499 if ($gradinginstance = $this->use_advanced_grading()) {
2500 $gradinginstance->get_controller()->set_grade_range($grademenu);
2501 $gradingelement = $mform->addElement('grading', 'advancedgrading', get_string('grade').':', array('gradinginstance' => $gradinginstance));
2502 if ($this->_customdata
->gradingdisabled
) {
2503 $gradingelement->freeze();
2505 $mform->addElement('hidden', 'advancedgradinginstanceid', $gradinginstance->get_id());
2508 // use simple direct grading
2509 $grademenu['-1'] = get_string('nograde');
2511 $mform->addElement('select', 'xgrade', get_string('grade').':', $grademenu, $attributes);
2512 $mform->setDefault('xgrade', $this->_customdata
->submission
->grade
); //@fixme some bug when element called 'grade' makes it break
2513 $mform->setType('xgrade', PARAM_INT
);
2516 if (!empty($this->_customdata
->enableoutcomes
)) {
2517 foreach($this->_customdata
->grading_info
->outcomes
as $n=>$outcome) {
2518 $options = make_grades_menu(-$outcome->scaleid
);
2519 if ($outcome->grades
[$this->_customdata
->submission
->userid
]->locked
) {
2520 $options[0] = get_string('nooutcome', 'grades');
2521 $mform->addElement('static', 'outcome_'.$n.'['.$this->_customdata
->userid
.']', $outcome->name
.':',
2522 $options[$outcome->grades
[$this->_customdata
->submission
->userid
]->grade
]);
2524 $options[''] = get_string('nooutcome', 'grades');
2525 $attributes = array('id' => 'menuoutcome_'.$n );
2526 $mform->addElement('select', 'outcome_'.$n.'['.$this->_customdata
->userid
.']', $outcome->name
.':', $options, $attributes );
2527 $mform->setType('outcome_'.$n.'['.$this->_customdata
->userid
.']', PARAM_INT
);
2528 $mform->setDefault('outcome_'.$n.'['.$this->_customdata
->userid
.']', $outcome->grades
[$this->_customdata
->submission
->userid
]->grade
);
2532 $course_context = get_context_instance(CONTEXT_MODULE
, $this->_customdata
->cm
->id
);
2533 if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
2534 $grade = '<a href="'.$CFG->wwwroot
.'/grade/report/grader/index.php?id='. $this->_customdata
->courseid
.'" >'.
2535 $this->_customdata
->grading_info
->items
[0]->grades
[$this->_customdata
->userid
]->str_grade
. '</a>';
2537 $grade = $this->_customdata
->grading_info
->items
[0]->grades
[$this->_customdata
->userid
]->str_grade
;
2539 $mform->addElement('static', 'finalgrade', get_string('currentgrade', 'assignment').':' ,$grade);
2540 $mform->setType('finalgrade', PARAM_INT
);
2545 * @global core_renderer $OUTPUT
2547 function add_feedback_section() {
2549 $mform =& $this->_form
;
2550 $mform->addElement('header', 'Feed Back', get_string('feedback', 'grades'));
2552 if ($this->_customdata
->gradingdisabled
) {
2553 $mform->addElement('static', 'disabledfeedback', $this->_customdata
->grading_info
->items
[0]->grades
[$this->_customdata
->userid
]->str_feedback
);
2557 $mform->addElement('editor', 'submissioncomment_editor', get_string('feedback', 'assignment').':', null, $this->get_editor_options() );
2558 $mform->setType('submissioncomment_editor', PARAM_RAW
); // to be cleaned before display
2559 $mform->setDefault('submissioncomment_editor', $this->_customdata
->submission
->submissioncomment
);
2560 //$mform->addRule('submissioncomment', get_string('required'), 'required', null, 'client');
2561 switch ($this->_customdata
->assignment
->assignmenttype
) {
2563 case 'uploadsingle' :
2564 $mform->addElement('filemanager', 'files_filemanager', get_string('responsefiles', 'assignment'). ':', null, $this->_customdata
->fileui_options
);
2569 $mform->addElement('hidden', 'mailinfo_h', "0");
2570 $mform->setType('mailinfo_h', PARAM_INT
);
2571 $mform->addElement('checkbox', 'mailinfo',get_string('enablenotification','assignment').
2572 $OUTPUT->help_icon('enablenotification', 'assignment') .':' );
2573 $mform->setType('mailinfo', PARAM_INT
);
2577 function add_action_buttons() {
2578 $mform =& $this->_form
;
2579 //if there are more to be graded.
2580 if ($this->_customdata
->nextid
>0) {
2581 $buttonarray=array();
2582 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2583 //@todo: fix accessibility: javascript dependency not necessary
2584 $buttonarray[] = &$mform->createElement('submit', 'saveandnext', get_string('saveandnext'));
2585 $buttonarray[] = &$mform->createElement('submit', 'next', get_string('next'));
2586 $buttonarray[] = &$mform->createElement('cancel');
2588 $buttonarray=array();
2589 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2590 $buttonarray[] = &$mform->createElement('cancel');
2592 $mform->addGroup($buttonarray, 'grading_buttonar', '', array(' '), false);
2593 $mform->closeHeaderBefore('grading_buttonar');
2594 $mform->setType('grading_buttonar', PARAM_RAW
);
2597 function add_submission_content() {
2598 $mform =& $this->_form
;
2599 $mform->addElement('header', 'Submission', get_string('submission', 'assignment'));
2600 $mform->addElement('static', '', '' , $this->_customdata
->submission_content
);
2603 protected function get_editor_options() {
2604 $editoroptions = array();
2605 $editoroptions['component'] = 'mod_assignment';
2606 $editoroptions['filearea'] = 'feedback';
2607 $editoroptions['noclean'] = false;
2608 $editoroptions['maxfiles'] = 0; //TODO: no files for now, we need to first implement assignment_feedback area, integration with gradebook, files support in quickgrading, etc. (skodak)
2609 $editoroptions['maxbytes'] = $this->_customdata
->maxbytes
;
2610 $editoroptions['context'] = $this->_customdata
->context
;
2611 return $editoroptions;
2614 public function set_data($data) {
2615 $editoroptions = $this->get_editor_options();
2616 if (!isset($data->text
)) {
2619 if (!isset($data->format
)) {
2620 $data->textformat
= FORMAT_HTML
;
2622 $data->textformat
= $data->format
;
2625 if (!empty($this->_customdata
->submission
->id
)) {
2626 $itemid = $this->_customdata
->submission
->id
;
2631 switch ($this->_customdata
->assignment
->assignmenttype
) {
2633 case 'uploadsingle' :
2634 $data = file_prepare_standard_filemanager($data, 'files', $editoroptions, $this->_customdata
->context
, 'mod_assignment', 'response', $itemid);
2640 $data = file_prepare_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata
->context
, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2641 return parent
::set_data($data);
2644 public function get_data() {
2645 $data = parent
::get_data();
2647 if (!empty($this->_customdata
->submission
->id
)) {
2648 $itemid = $this->_customdata
->submission
->id
;
2650 $itemid = null; //TODO: this is wrong, itemid MUST be known when saving files!! (skodak)
2654 $editoroptions = $this->get_editor_options();
2655 switch ($this->_customdata
->assignment
->assignmenttype
) {
2657 case 'uploadsingle' :
2658 $data = file_postupdate_standard_filemanager($data, 'files', $editoroptions, $this->_customdata
->context
, 'mod_assignment', 'response', $itemid);
2663 $data = file_postupdate_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata
->context
, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2666 if ($this->use_advanced_grading() && !isset($data->advancedgrading
)) {
2667 $data->advancedgrading
= null;
2674 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
2677 * Deletes an assignment instance
2679 * This is done by calling the delete_instance() method of the assignment type class
2681 function assignment_delete_instance($id){
2684 if (! $assignment = $DB->get_record('assignment', array('id'=>$id))) {
2688 // fall back to base class if plugin missing
2689 $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2690 if (file_exists($classfile)) {
2691 require_once($classfile);
2692 $assignmentclass = "assignment_$assignment->assignmenttype";
2695 debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
2696 $assignmentclass = "assignment_base";
2699 $ass = new $assignmentclass();
2700 return $ass->delete_instance($assignment);
2705 * Updates an assignment instance
2707 * This is done by calling the update_instance() method of the assignment type class
2709 function assignment_update_instance($assignment){
2712 $assignment->assignmenttype
= clean_param($assignment->assignmenttype
, PARAM_PLUGIN
);
2714 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2715 $assignmentclass = "assignment_$assignment->assignmenttype";
2716 $ass = new $assignmentclass();
2717 return $ass->update_instance($assignment);
2722 * Adds an assignment instance
2724 * This is done by calling the add_instance() method of the assignment type class
2726 function assignment_add_instance($assignment) {
2729 $assignment->assignmenttype
= clean_param($assignment->assignmenttype
, PARAM_PLUGIN
);
2731 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2732 $assignmentclass = "assignment_$assignment->assignmenttype";
2733 $ass = new $assignmentclass();
2734 return $ass->add_instance($assignment);
2739 * Returns an outline of a user interaction with an assignment
2741 * This is done by calling the user_outline() method of the assignment type class
2743 function assignment_user_outline($course, $user, $mod, $assignment) {
2746 require_once("$CFG->libdir/gradelib.php");
2747 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2748 $assignmentclass = "assignment_$assignment->assignmenttype";
2749 $ass = new $assignmentclass($mod->id
, $assignment, $mod, $course);
2750 $grades = grade_get_grades($course->id
, 'mod', 'assignment', $assignment->id
, $user->id
);
2751 if (!empty($grades->items
[0]->grades
)) {
2752 return $ass->user_outline(reset($grades->items
[0]->grades
));
2759 * Prints the complete info about a user's interaction with an assignment
2761 * This is done by calling the user_complete() method of the assignment type class
2763 function assignment_user_complete($course, $user, $mod, $assignment) {
2766 require_once("$CFG->libdir/gradelib.php");
2767 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2768 $assignmentclass = "assignment_$assignment->assignmenttype";
2769 $ass = new $assignmentclass($mod->id
, $assignment, $mod, $course);
2770 $grades = grade_get_grades($course->id
, 'mod', 'assignment', $assignment->id
, $user->id
);
2771 if (empty($grades->items
[0]->grades
)) {
2774 $grade = reset($grades->items
[0]->grades
);
2776 return $ass->user_complete($user, $grade);
2780 * Function to be run periodically according to the moodle cron
2782 * Finds all assignment notifications that have yet to be mailed out, and mails them
2784 function assignment_cron () {
2785 global $CFG, $USER, $DB;
2787 /// first execute all crons in plugins
2788 if ($plugins = get_plugin_list('assignment')) {
2789 foreach ($plugins as $plugin=>$dir) {
2790 require_once("$dir/assignment.class.php");
2791 $assignmentclass = "assignment_$plugin";
2792 $ass = new $assignmentclass();
2797 /// Notices older than 1 day will not be mailed. This is to avoid the problem where
2798 /// cron has not been running for a long time, and then suddenly people are flooded
2799 /// with mail from the past few weeks or months
2802 $endtime = $timenow - $CFG->maxeditingtime
;
2803 $starttime = $endtime - 24 * 3600; /// One day earlier
2805 if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2807 $realuser = clone($USER);
2809 foreach ($submissions as $key => $submission) {
2810 $DB->set_field("assignment_submissions", "mailed", "1", array("id"=>$submission->id
));
2815 foreach ($submissions as $submission) {
2817 echo "Processing assignment submission $submission->id\n";
2819 if (! $user = $DB->get_record("user", array("id"=>$submission->userid
))) {
2820 echo "Could not find user $user->id\n";
2824 if (! $course = $DB->get_record("course", array("id"=>$submission->course
))) {
2825 echo "Could not find course $submission->course\n";
2829 /// Override the language and timezone of the "current" user, so that
2830 /// mail is customised for the receiver.
2831 cron_setup_user($user, $course);
2833 $coursecontext = get_context_instance(CONTEXT_COURSE
, $submission->course
);
2834 $courseshortname = format_string($course->shortname
, true, array('context' => $coursecontext));
2835 if (!is_enrolled($coursecontext, $user->id
)) {
2836 echo fullname($user)." not an active participant in " . $courseshortname . "\n";
2840 if (! $teacher = $DB->get_record("user", array("id"=>$submission->teacher
))) {
2841 echo "Could not find teacher $submission->teacher\n";
2845 if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment
, $course->id
)) {
2846 echo "Could not find course module for assignment id $submission->assignment\n";
2850 if (! $mod->visible
) { /// Hold mail notification for hidden assignments until later
2854 $strassignments = get_string("modulenameplural", "assignment");
2855 $strassignment = get_string("modulename", "assignment");
2857 $assignmentinfo = new stdClass();
2858 $assignmentinfo->teacher
= fullname($teacher);
2859 $assignmentinfo->assignment
= format_string($submission->name
,true);
2860 $assignmentinfo->url
= "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2862 $postsubject = "$courseshortname: $strassignments: ".format_string($submission->name
,true);
2863 $posttext = "$courseshortname -> $strassignments -> ".format_string($submission->name
,true)."\n";
2864 $posttext .= "---------------------------------------------------------------------\n";
2865 $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2866 $posttext .= "---------------------------------------------------------------------\n";
2868 if ($user->mailformat
== 1) { // HTML
2869 $posthtml = "<p><font face=\"sans-serif\">".
2870 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$courseshortname</a> ->".
2871 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2872 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name
,true)."</a></font></p>";
2873 $posthtml .= "<hr /><font face=\"sans-serif\">";
2874 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2875 $posthtml .= "</font><hr />";
2880 $eventdata = new stdClass();
2881 $eventdata->modulename
= 'assignment';
2882 $eventdata->userfrom
= $teacher;
2883 $eventdata->userto
= $user;
2884 $eventdata->subject
= $postsubject;
2885 $eventdata->fullmessage
= $posttext;
2886 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
2887 $eventdata->fullmessagehtml
= $posthtml;
2888 $eventdata->smallmessage
= get_string('assignmentmailsmall', 'assignment', $assignmentinfo);
2890 $eventdata->name
= 'assignment_updates';
2891 $eventdata->component
= 'mod_assignment';
2892 $eventdata->notification
= 1;
2893 $eventdata->contexturl
= $assignmentinfo->url
;
2894 $eventdata->contexturlname
= $assignmentinfo->assignment
;
2896 message_send($eventdata);
2906 * Return grade for given user or all users.
2908 * @param int $assignmentid id of assignment
2909 * @param int $userid optional user id, 0 means all users
2910 * @return array array of grades, false if none
2912 function assignment_get_user_grades($assignment, $userid=0) {
2916 $user = "AND u.id = :userid";
2917 $params = array('userid'=>$userid);
2921 $params['aid'] = $assignment->id
;
2923 $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2924 s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2925 FROM {user} u, {assignment_submissions} s
2926 WHERE u.id = s.userid AND s.assignment = :aid
2929 return $DB->get_records_sql($sql, $params);
2933 * Update activity grades
2935 * @param object $assignment
2936 * @param int $userid specific user only, 0 means all
2938 function assignment_update_grades($assignment, $userid=0, $nullifnone=true) {
2940 require_once($CFG->libdir
.'/gradelib.php');
2942 if ($assignment->grade
== 0) {
2943 assignment_grade_item_update($assignment);
2945 } else if ($grades = assignment_get_user_grades($assignment, $userid)) {
2946 foreach($grades as $k=>$v) {
2947 if ($v->rawgrade
== -1) {
2948 $grades[$k]->rawgrade
= null;
2951 assignment_grade_item_update($assignment, $grades);
2954 assignment_grade_item_update($assignment);
2959 * Update all grades in gradebook.
2961 function assignment_upgrade_grades() {
2964 $sql = "SELECT COUNT('x')
2965 FROM {assignment} a, {course_modules} cm, {modules} m
2966 WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2967 $count = $DB->count_records_sql($sql);
2969 $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
2970 FROM {assignment} a, {course_modules} cm, {modules} m
2971 WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2972 $rs = $DB->get_recordset_sql($sql);
2974 // too much debug output
2975 $pbar = new progress_bar('assignmentupgradegrades', 500, true);
2977 foreach ($rs as $assignment) {
2979 upgrade_set_timeout(60*5); // set up timeout, may also abort execution
2980 assignment_update_grades($assignment);
2981 $pbar->update($i, $count, "Updating Assignment grades ($i/$count).");
2983 upgrade_set_timeout(); // reset to default timeout
2989 * Create grade item for given assignment
2991 * @param object $assignment object with extra cmidnumber
2992 * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
2993 * @return int 0 if ok, error code otherwise
2995 function assignment_grade_item_update($assignment, $grades=NULL) {
2997 require_once($CFG->libdir
.'/gradelib.php');
2999 if (!isset($assignment->courseid
)) {
3000 $assignment->courseid
= $assignment->course
;
3003 $params = array('itemname'=>$assignment->name
, 'idnumber'=>$assignment->cmidnumber
);
3005 if ($assignment->grade
> 0) {
3006 $params['gradetype'] = GRADE_TYPE_VALUE
;
3007 $params['grademax'] = $assignment->grade
;
3008 $params['grademin'] = 0;
3010 } else if ($assignment->grade
< 0) {
3011 $params['gradetype'] = GRADE_TYPE_SCALE
;
3012 $params['scaleid'] = -$assignment->grade
;
3015 $params['gradetype'] = GRADE_TYPE_TEXT
; // allow text comments only
3018 if ($grades === 'reset') {
3019 $params['reset'] = true;
3023 return grade_update('mod/assignment', $assignment->courseid
, 'mod', 'assignment', $assignment->id
, 0, $grades, $params);
3027 * Delete grade item for given assignment
3029 * @param object $assignment object
3030 * @return object assignment
3032 function assignment_grade_item_delete($assignment) {
3034 require_once($CFG->libdir
.'/gradelib.php');
3036 if (!isset($assignment->courseid
)) {
3037 $assignment->courseid
= $assignment->course
;
3040 return grade_update('mod/assignment', $assignment->courseid
, 'mod', 'assignment', $assignment->id
, 0, NULL, array('deleted'=>1));
3044 * Returns the users with data in one assignment (students and teachers)
3046 * @todo: deprecated - to be deleted in 2.2
3048 * @param $assignmentid int
3049 * @return array of user objects
3051 function assignment_get_participants($assignmentid) {
3055 $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
3057 {assignment_submissions} a
3058 WHERE a.assignment = ? and
3059 u.id = a.userid", array($assignmentid));
3061 $teachers = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
3063 {assignment_submissions} a
3064 WHERE a.assignment = ? and
3065 u.id = a.teacher", array($assignmentid));
3067 //Add teachers to students
3069 foreach ($teachers as $teacher) {
3070 $students[$teacher->id
] = $teacher;
3073 //Return students array (it contains an array of unique users)
3078 * Serves assignment submissions and other files.
3080 * @param object $course
3082 * @param object $context
3083 * @param string $filearea
3084 * @param array $args
3085 * @param bool $forcedownload
3086 * @return bool false if file not found, does not return if found - just send the file
3088 function assignment_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) {
3091 if ($context->contextlevel
!= CONTEXT_MODULE
) {
3095 require_login($course, false, $cm);
3097 if (!$assignment = $DB->get_record('assignment', array('id'=>$cm->instance
))) {
3101 require_once($CFG->dirroot
.'/mod/assignment/type/'.$assignment->assignmenttype
.'/assignment.class.php');
3102 $assignmentclass = 'assignment_'.$assignment->assignmenttype
;
3103 $assignmentinstance = new $assignmentclass($cm->id
, $assignment, $cm, $course);
3105 return $assignmentinstance->send_file($filearea, $args);
3108 * Checks if a scale is being used by an assignment
3110 * This is used by the backup code to decide whether to back up a scale
3111 * @param $assignmentid int
3112 * @param $scaleid int
3113 * @return boolean True if the scale is used by the assignment
3115 function assignment_scale_used($assignmentid, $scaleid) {
3120 $rec = $DB->get_record('assignment', array('id'=>$assignmentid,'grade'=>-$scaleid));
3122 if (!empty($rec) && !empty($scaleid)) {
3130 * Checks if scale is being used by any instance of assignment
3132 * This is used to find out if scale used anywhere
3133 * @param $scaleid int
3134 * @return boolean True if the scale is used by any assignment
3136 function assignment_scale_used_anywhere($scaleid) {
3139 if ($scaleid and $DB->record_exists('assignment', array('grade'=>-$scaleid))) {
3147 * Make sure up-to-date events are created for all assignment instances
3149 * This standard function will check all instances of this module
3150 * and make sure there are up-to-date events created for each of them.
3151 * If courseid = 0, then every assignment event in the site is checked, else
3152 * only assignment events belonging to the course specified are checked.
3153 * This function is used, in its new format, by restore_refresh_events()
3155 * @param $courseid int optional If zero then all assignments for all courses are covered
3156 * @return boolean Always returns true
3158 function assignment_refresh_events($courseid = 0) {
3161 if ($courseid == 0) {
3162 if (! $assignments = $DB->get_records("assignment")) {
3166 if (! $assignments = $DB->get_records("assignment", array("course"=>$courseid))) {
3170 $moduleid = $DB->get_field('modules', 'id', array('name'=>'assignment'));
3172 foreach ($assignments as $assignment) {
3173 $cm = get_coursemodule_from_id('assignment', $assignment->id
);
3174 $event = new stdClass();
3175 $event->name
= $assignment->name
;
3176 $event->description
= format_module_intro('assignment', $assignment, $cm->id
);
3177 $event->timestart
= $assignment->timedue
;
3179 if ($event->id
= $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id
))) {
3180 update_event($event);
3183 $event->courseid
= $assignment->course
;
3184 $event->groupid
= 0;
3186 $event->modulename
= 'assignment';
3187 $event->instance
= $assignment->id
;
3188 $event->eventtype
= 'due';
3189 $event->timeduration
= 0;
3190 $event->visible
= $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$assignment->id
));
3199 * Print recent activity from all assignments in a given course
3201 * This is used by the recent activity block
3203 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
3204 global $CFG, $USER, $DB, $OUTPUT;
3206 // do not use log table if possible, it may be huge
3208 if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
3209 u.firstname, u.lastname, u.email, u.picture
3210 FROM {assignment_submissions} asb
3211 JOIN {assignment} a ON a.id = asb.assignment
3212 JOIN {course_modules} cm ON cm.instance = a.id
3213 JOIN {modules} md ON md.id = cm.module
3214 JOIN {user} u ON u.id = asb.userid
3215 WHERE asb.timemodified > ? AND
3217 md.name = 'assignment'
3218 ORDER BY asb.timemodified ASC", array($timestart, $course->id
))) {
3222 $modinfo =& get_fast_modinfo($course); // reference needed because we might load the groups
3226 foreach($submissions as $submission) {
3227 if (!array_key_exists($submission->cmid
, $modinfo->cms
)) {
3230 $cm = $modinfo->cms
[$submission->cmid
];
3231 if (!$cm->uservisible
) {
3234 if ($submission->userid
== $USER->id
) {
3235 $show[] = $submission;
3239 // the act of sumbitting of assignment may be considered private - only graders will see it if specified
3240 if (empty($CFG->assignment_showrecentsubmissions
)) {
3241 if (!array_key_exists($cm->id
, $grader)) {
3242 $grader[$cm->id
] = has_capability('moodle/grade:viewall', get_context_instance(CONTEXT_MODULE
, $cm->id
));
3244 if (!$grader[$cm->id
]) {
3249 $groupmode = groups_get_activity_groupmode($cm, $course);
3251 if ($groupmode == SEPARATEGROUPS
and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE
, $cm->id
))) {
3252 if (isguestuser()) {
3253 // shortcut - guest user does not belong into any group
3257 if (is_null($modinfo->groups
)) {
3258 $modinfo->groups
= groups_get_user_groups($course->id
); // load all my groups and cache it in modinfo
3261 // this will be slow - show only users that share group with me in this cm
3262 if (empty($modinfo->groups
[$cm->id
])) {
3265 $usersgroups = groups_get_all_groups($course->id
, $submission->userid
, $cm->groupingid
);
3266 if (is_array($usersgroups)) {
3267 $usersgroups = array_keys($usersgroups);
3268 $intersect = array_intersect($usersgroups, $modinfo->groups
[$cm->id
]);
3269 if (empty($intersect)) {
3274 $show[] = $submission;
3281 echo $OUTPUT->heading(get_string('newsubmissions', 'assignment').':', 3);
3283 foreach ($show as $submission) {
3284 $cm = $modinfo->cms
[$submission->cmid
];
3285 $link = $CFG->wwwroot
.'/mod/assignment/view.php?id='.$cm->id
;
3286 print_recent_activity_note($submission->timemodified
, $submission, $cm->name
, $link, false, $viewfullnames);
3294 * Returns all assignments since a given time in specified forum.
3296 function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0) {
3297 global $CFG, $COURSE, $USER, $DB;
3299 if ($COURSE->id
== $courseid) {
3302 $course = $DB->get_record('course', array('id'=>$courseid));
3305 $modinfo =& get_fast_modinfo($course);
3307 $cm = $modinfo->cms
[$cmid];
3311 $userselect = "AND u.id = :userid";
3312 $params['userid'] = $userid;
3318 $groupselect = "AND gm.groupid = :groupid";
3319 $groupjoin = "JOIN {groups_members} gm ON gm.userid=u.id";
3320 $params['groupid'] = $groupid;
3326 $params['cminstance'] = $cm->instance
;
3327 $params['timestart'] = $timestart;
3329 $userfields = user_picture
::fields('u', null, 'userid');
3331 if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified,
3333 FROM {assignment_submissions} asb
3334 JOIN {assignment} a ON a.id = asb.assignment
3335 JOIN {user} u ON u.id = asb.userid
3337 WHERE asb.timemodified > :timestart AND a.id = :cminstance
3338 $userselect $groupselect
3339 ORDER BY asb.timemodified ASC", $params)) {
3343 $groupmode = groups_get_activity_groupmode($cm, $course);
3344 $cm_context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
3345 $grader = has_capability('moodle/grade:viewall', $cm_context);
3346 $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
3347 $viewfullnames = has_capability('moodle/site:viewfullnames', $cm_context);
3349 if (is_null($modinfo->groups
)) {
3350 $modinfo->groups
= groups_get_user_groups($course->id
); // load all my groups and cache it in modinfo
3355 foreach($submissions as $submission) {
3356 if ($submission->userid
== $USER->id
) {
3357 $show[] = $submission;
3360 // the act of submitting of assignment may be considered private - only graders will see it if specified
3361 if (empty($CFG->assignment_showrecentsubmissions
)) {
3367 if ($groupmode == SEPARATEGROUPS
and !$accessallgroups) {
3368 if (isguestuser()) {
3369 // shortcut - guest user does not belong into any group
3373 // this will be slow - show only users that share group with me in this cm
3374 if (empty($modinfo->groups
[$cm->id
])) {
3377 $usersgroups = groups_get_all_groups($course->id
, $cm->userid
, $cm->groupingid
);
3378 if (is_array($usersgroups)) {
3379 $usersgroups = array_keys($usersgroups);
3380 $intersect = array_intersect($usersgroups, $modinfo->groups
[$cm->id
]);
3381 if (empty($intersect)) {
3386 $show[] = $submission;
3394 require_once($CFG->libdir
.'/gradelib.php');
3396 foreach ($show as $id=>$submission) {
3397 $userids[] = $submission->userid
;
3400 $grades = grade_get_grades($courseid, 'mod', 'assignment', $cm->instance
, $userids);
3403 $aname = format_string($cm->name
,true);
3404 foreach ($show as $submission) {
3405 $tmpactivity = new stdClass();
3407 $tmpactivity->type
= 'assignment';
3408 $tmpactivity->cmid
= $cm->id
;
3409 $tmpactivity->name
= $aname;
3410 $tmpactivity->sectionnum
= $cm->sectionnum
;
3411 $tmpactivity->timestamp
= $submission->timemodified
;
3414 $tmpactivity->grade
= $grades->items
[0]->grades
[$submission->userid
]->str_long_grade
;
3417 $userfields = explode(',', user_picture
::fields());
3418 foreach ($userfields as $userfield) {
3419 if ($userfield == 'id') {
3420 $tmpactivity->user
->{$userfield} = $submission->userid
; // aliased in SQL above
3422 $tmpactivity->user
->{$userfield} = $submission->{$userfield};
3425 $tmpactivity->user
->fullname
= fullname($submission, $viewfullnames);
3427 $activities[$index++
] = $tmpactivity;
3434 * Print recent activity from all assignments in a given course
3436 * This is used by course/recent.php
3438 function assignment_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
3439 global $CFG, $OUTPUT;
3441 echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
3443 echo "<tr><td class=\"userpicture\" valign=\"top\">";
3444 echo $OUTPUT->user_picture($activity->user
);
3448 $modname = $modnames[$activity->type
];
3449 echo '<div class="title">';
3450 echo "<img src=\"" . $OUTPUT->pix_url('icon', 'assignment') . "\" ".
3451 "class=\"icon\" alt=\"$modname\">";
3452 echo "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id={$activity->cmid}\">{$activity->name}</a>";
3456 if (isset($activity->grade
)) {
3457 echo '<div class="grade">';
3458 echo get_string('grade').': ';
3459 echo $activity->grade
;
3463 echo '<div class="user">';
3464 echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->id}&course=$courseid\">"
3465 ."{$activity->user->fullname}</a> - ".userdate($activity->timestamp
);
3468 echo "</td></tr></table>";
3471 /// GENERIC SQL FUNCTIONS
3474 * Fetch info from logs
3476 * @param $log object with properties ->info (the assignment id) and ->userid
3477 * @return array with assignment name and user firstname and lastname
3479 function assignment_log_info($log) {
3482 return $DB->get_record_sql("SELECT a.name, u.firstname, u.lastname
3483 FROM {assignment} a, {user} u
3484 WHERE a.id = ? AND u.id = ?", array($log->info
, $log->userid
));
3488 * Return list of marked submissions that have not been mailed out for currently enrolled students
3492 function assignment_get_unmailed_submissions($starttime, $endtime) {
3495 return $DB->get_records_sql("SELECT s.*, a.course, a.name
3496 FROM {assignment_submissions} s,
3499 AND s.timemarked <= ?
3500 AND s.timemarked >= ?
3501 AND s.assignment = a.id", array($endtime, $starttime));
3505 * Counts all complete (real) assignment submissions by enrolled students for the given course modeule.
3507 * @deprecated Since Moodle 2.2 MDL-abc - Please do not use this function any more.
3508 * @param cm_info $cm The course module that we wish to perform the count on.
3509 * @param int $groupid (optional) If nonzero then count is restricted to this group
3510 * @return int The number of submissions
3512 function assignment_count_real_submissions($cm, $groupid=0) {
3515 // Grab the assignment type for the given course module
3516 $assignmenttype = $DB->get_field($cm->modname
, 'assignmenttype', array('id' => $cm->instance
), MUST_EXIST
);
3518 // Create the expected class file path and class name for the returned assignemnt type
3519 $filename = "{$CFG->dirroot}/mod/assignment/type/{$assignmenttype}/assignment.class.php";
3520 $classname = "assignment_{$assignmenttype}";
3522 // If the file exists and the class is not already loaded we require the class file
3523 if (file_exists($filename) && !class_exists($classname)) {
3524 require_once($filename);
3526 // If the required class is still not loaded then we revert to assignment base
3527 if (!class_exists($classname)) {
3528 $classname = 'assignment_base';
3530 $instance = new $classname;
3532 // Attach the course module to the assignment type instance and then call the method for counting submissions
3533 $instance->cm
= $cm;
3534 return $instance->count_real_submissions($groupid);
3538 * Return all assignment submissions by ENROLLED students (even empty)
3540 * There are also assignment type methods get_submissions() wich in the default
3541 * implementation simply call this function.
3542 * @param $sort string optional field names for the ORDER BY in the sql query
3543 * @param $dir string optional specifying the sort direction, defaults to DESC
3544 * @return array The submission objects indexed by id
3546 function assignment_get_all_submissions($assignment, $sort="", $dir="DESC") {
3547 /// Return all assignment submissions by ENROLLED students (even empty)
3550 if ($sort == "lastname" or $sort == "firstname") {
3551 $sort = "u.$sort $dir";
3552 } else if (empty($sort)) {
3553 $sort = "a.timemodified DESC";
3555 $sort = "a.$sort $dir";
3558 /* not sure this is needed at all since assignment already has a course define, so this join?
3559 $select = "s.course = '$assignment->course' AND";
3560 if ($assignment->course == SITEID) {
3564 return $DB->get_records_sql("SELECT a.*
3565 FROM {assignment_submissions} a, {user} u
3566 WHERE u.id = a.userid
3567 AND a.assignment = ?
3568 ORDER BY $sort", array($assignment->id
));
3573 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
3574 * for the course (see resource).
3576 * Given a course_module object, this function returns any "extra" information that may be needed
3577 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
3579 * @param $coursemodule object The coursemodule object (record).
3580 * @return cached_cm_info An object on information that the courses will know about (most noticeably, an icon).
3582 function assignment_get_coursemodule_info($coursemodule) {
3585 if (! $assignment = $DB->get_record('assignment', array('id'=>$coursemodule->instance
),
3586 'id, assignmenttype, name, intro, introformat')) {
3590 $libfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
3592 if (file_exists($libfile)) {
3593 require_once($libfile);
3594 $assignmentclass = "assignment_$assignment->assignmenttype";
3595 $ass = new $assignmentclass('staticonly');
3596 if (!($result = $ass->get_coursemodule_info($coursemodule))) {
3597 $result = new cached_cm_info();
3598 $result->name
= $assignment->name
;
3600 if ($coursemodule->showdescription
) {
3601 // Convert intro to html. Do not filter cached version, filters run at display time.
3602 $result->content
= format_module_intro('assignment', $assignment, $coursemodule->id
, false);
3606 debugging('Incorrect assignment type: '.$assignment->assignmenttype
);
3613 /// OTHER GENERAL FUNCTIONS FOR ASSIGNMENTS ///////////////////////////////////////
3616 * Returns an array of installed assignment types indexed and sorted by name
3618 * @return array The index is the name of the assignment type, the value its full name from the language strings
3620 function assignment_types() {
3622 $names = get_plugin_list('assignment');
3623 foreach ($names as $name=>$dir) {
3624 $types[$name] = get_string('type'.$name, 'assignment');
3626 // ugly hack to support pluggable assignment type titles..
3627 if ($types[$name] == '[[type'.$name.']]') {
3628 $types[$name] = get_string('type'.$name, 'assignment_'.$name);
3635 function assignment_print_overview($courses, &$htmlarray) {
3636 global $USER, $CFG, $DB;
3637 require_once($CFG->libdir
.'/gradelib.php');
3639 if (empty($courses) ||
!is_array($courses) ||
count($courses) == 0) {
3643 if (!$assignments = get_all_instances_in_courses('assignment',$courses)) {
3647 $assignmentids = array();
3649 // Do assignment_base::isopen() here without loading the whole thing for speed
3650 foreach ($assignments as $key => $assignment) {
3652 if ($assignment->timedue
) {
3653 if ($assignment->preventlate
) {
3654 $isopen = ($assignment->timeavailable
<= $time && $time <= $assignment->timedue
);
3656 $isopen = ($assignment->timeavailable
<= $time);
3659 if (empty($isopen) ||
empty($assignment->timedue
)) {
3660 unset($assignments[$key]);
3662 $assignmentids[] = $assignment->id
;
3666 if (empty($assignmentids)){
3667 // no assignments to look at - we're done
3671 $strduedate = get_string('duedate', 'assignment');
3672 $strduedateno = get_string('duedateno', 'assignment');
3673 $strgraded = get_string('graded', 'assignment');
3674 $strnotgradedyet = get_string('notgradedyet', 'assignment');
3675 $strnotsubmittedyet = get_string('notsubmittedyet', 'assignment');
3676 $strsubmitted = get_string('submitted', 'assignment');
3677 $strassignment = get_string('modulename', 'assignment');
3678 $strreviewed = get_string('reviewed','assignment');
3681 // NOTE: we do all possible database work here *outside* of the loop to ensure this scales
3683 list($sqlassignmentids, $assignmentidparams) = $DB->get_in_or_equal($assignmentids);
3685 // build up and array of unmarked submissions indexed by assignment id/ userid
3686 // for use where the user has grading rights on assignment
3687 $rs = $DB->get_recordset_sql("SELECT id, assignment, userid
3688 FROM {assignment_submissions}
3689 WHERE teacher = 0 AND timemarked = 0
3690 AND assignment $sqlassignmentids", $assignmentidparams);
3692 $unmarkedsubmissions = array();
3693 foreach ($rs as $rd) {
3694 $unmarkedsubmissions[$rd->assignment
][$rd->userid
] = $rd->id
;
3699 // get all user submissions, indexed by assignment id
3700 $mysubmissions = $DB->get_records_sql("SELECT assignment, timemarked, teacher, grade
3701 FROM {assignment_submissions}
3702 WHERE userid = ? AND
3703 assignment $sqlassignmentids", array_merge(array($USER->id
), $assignmentidparams));
3705 foreach ($assignments as $assignment) {
3706 $grading_info = grade_get_grades($assignment->course
, 'mod', 'assignment', $assignment->id
, $USER->id
);
3707 $final_grade = $grading_info->items
[0]->grades
[$USER->id
];
3709 $str = '<div class="assignment overview"><div class="name">'.$strassignment. ': '.
3710 '<a '.($assignment->visible ?
'':' class="dimmed"').
3711 'title="'.$strassignment.'" href="'.$CFG->wwwroot
.
3712 '/mod/assignment/view.php?id='.$assignment->coursemodule
.'">'.
3713 $assignment->name
.'</a></div>';
3714 if ($assignment->timedue
) {
3715 $str .= '<div class="info">'.$strduedate.': '.userdate($assignment->timedue
).'</div>';
3717 $str .= '<div class="info">'.$strduedateno.'</div>';
3719 $context = get_context_instance(CONTEXT_MODULE
, $assignment->coursemodule
);
3720 if (has_capability('mod/assignment:grade', $context)) {
3722 // count how many people can submit
3723 $submissions = 0; // init
3724 if ($students = get_enrolled_users($context, 'mod/assignment:view', 0, 'u.id')) {
3725 foreach ($students as $student) {
3726 if (isset($unmarkedsubmissions[$assignment->id
][$student->id
])) {
3733 $link = new moodle_url('/mod/assignment/submissions.php', array('id'=>$assignment->coursemodule
));
3734 $str .= '<div class="details"><a href="'.$link.'">'.get_string('submissionsnotgraded', 'assignment', $submissions).'</a></div>';
3737 $str .= '<div class="details">';
3738 if (isset($mysubmissions[$assignment->id
])) {
3740 $submission = $mysubmissions[$assignment->id
];
3742 if ($submission->teacher
== 0 && $submission->timemarked
== 0 && !$final_grade->grade
) {
3743 $str .= $strsubmitted . ', ' . $strnotgradedyet;
3744 } else if ($submission->grade
<= 0 && !$final_grade->grade
) {
3745 $str .= $strsubmitted . ', ' . $strreviewed;
3747 $str .= $strsubmitted . ', ' . $strgraded;
3750 $str .= $strnotsubmittedyet . ' ' . assignment_display_lateness(time(), $assignment->timedue
);
3755 if (empty($htmlarray[$assignment->course
]['assignment'])) {
3756 $htmlarray[$assignment->course
]['assignment'] = $str;
3758 $htmlarray[$assignment->course
]['assignment'] .= $str;
3763 function assignment_display_lateness($timesubmitted, $timedue) {
3767 $time = $timedue - $timesubmitted;
3769 $timetext = get_string('late', 'assignment', format_time($time));
3770 return ' (<span class="late">'.$timetext.'</span>)';
3772 $timetext = get_string('early', 'assignment', format_time($time));
3773 return ' (<span class="early">'.$timetext.'</span>)';
3777 function assignment_get_view_actions() {
3778 return array('view');
3781 function assignment_get_post_actions() {
3782 return array('upload');
3785 function assignment_get_types() {
3789 $type = new stdClass();
3790 $type->modclass
= MOD_CLASS_ACTIVITY
;
3791 $type->type
= "assignment_group_start";
3792 $type->typestr
= '--'.get_string('modulenameplural', 'assignment');
3795 $standardassignments = array('upload','online','uploadsingle','offline');
3796 foreach ($standardassignments as $assignmenttype) {
3797 $type = new stdClass();
3798 $type->modclass
= MOD_CLASS_ACTIVITY
;
3799 $type->type
= "assignment&type=$assignmenttype";
3800 $type->typestr
= get_string("type$assignmenttype", 'assignment');
3804 /// Drop-in extra assignment types
3805 $assignmenttypes = get_list_of_plugins('mod/assignment/type');
3806 foreach ($assignmenttypes as $assignmenttype) {
3807 if (!empty($CFG->{'assignment_hide_'.$assignmenttype})) { // Not wanted
3810 if (!in_array($assignmenttype, $standardassignments)) {
3811 $type = new stdClass();
3812 $type->modclass
= MOD_CLASS_ACTIVITY
;
3813 $type->type
= "assignment&type=$assignmenttype";
3814 $type->typestr
= get_string("type$assignmenttype", 'assignment_'.$assignmenttype);
3819 $type = new stdClass();
3820 $type->modclass
= MOD_CLASS_ACTIVITY
;
3821 $type->type
= "assignment_group_end";
3822 $type->typestr
= '--';
3829 * Removes all grades from gradebook
3830 * @param int $courseid
3831 * @param string optional type
3833 function assignment_reset_gradebook($courseid, $type='') {
3836 $params = array('courseid'=>$courseid);
3838 $type = "AND a.assignmenttype= :type";
3839 $params['type'] = $type;
3842 $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
3843 FROM {assignment} a, {course_modules} cm, {modules} m
3844 WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id AND a.course=:courseid $type";
3846 if ($assignments = $DB->get_records_sql($sql, $params)) {
3847 foreach ($assignments as $assignment) {
3848 assignment_grade_item_update($assignment, 'reset');
3854 * This function is used by the reset_course_userdata function in moodlelib.
3855 * This function will remove all posts from the specified assignment
3856 * and clean up any related data.
3857 * @param $data the data submitted from the reset course.
3858 * @return array status array
3860 function assignment_reset_userdata($data) {
3864 foreach (get_plugin_list('assignment') as $type=>$dir) {
3865 require_once("$dir/assignment.class.php");
3866 $assignmentclass = "assignment_$type";
3867 $ass = new $assignmentclass();
3868 $status = array_merge($status, $ass->reset_userdata($data));
3875 * Implementation of the function for printing the form elements that control
3876 * whether the course reset functionality affects the assignment.
3877 * @param $mform form passed by reference
3879 function assignment_reset_course_form_definition(&$mform) {
3880 $mform->addElement('header', 'assignmentheader', get_string('modulenameplural', 'assignment'));
3881 $mform->addElement('advcheckbox', 'reset_assignment_submissions', get_string('deleteallsubmissions','assignment'));
3885 * Course reset form defaults.
3887 function assignment_reset_course_form_defaults($course) {
3888 return array('reset_assignment_submissions'=>1);
3892 * Returns all other caps used in module
3894 function assignment_get_extra_capabilities() {
3895 return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames', 'moodle/grade:managegradingforms');
3899 * @param string $feature FEATURE_xx constant for requested feature
3900 * @return mixed True if module supports feature, null if doesn't know
3902 function assignment_supports($feature) {
3904 case FEATURE_GROUPS
: return true;
3905 case FEATURE_GROUPINGS
: return true;
3906 case FEATURE_GROUPMEMBERSONLY
: return true;
3907 case FEATURE_MOD_INTRO
: return true;
3908 case FEATURE_COMPLETION_TRACKS_VIEWS
: return true;
3909 case FEATURE_GRADE_HAS_GRADE
: return true;
3910 case FEATURE_GRADE_OUTCOMES
: return true;
3911 case FEATURE_GRADE_HAS_GRADE
: return true;
3912 case FEATURE_BACKUP_MOODLE2
: return true;
3913 case FEATURE_SHOW_DESCRIPTION
: return true;
3914 case FEATURE_ADVANCED_GRADING
: return true;
3916 default: return null;
3921 * Adds module specific settings to the settings block
3923 * @param settings_navigation $settings The settings navigation object
3924 * @param navigation_node $assignmentnode The node to add module settings to
3926 function assignment_extend_settings_navigation(settings_navigation
$settings, navigation_node
$assignmentnode) {
3927 global $PAGE, $DB, $USER, $CFG;
3929 $assignmentrow = $DB->get_record("assignment", array("id" => $PAGE->cm
->instance
));
3930 require_once "$CFG->dirroot/mod/assignment/type/$assignmentrow->assignmenttype/assignment.class.php";
3932 $assignmentclass = 'assignment_'.$assignmentrow->assignmenttype
;
3933 $assignmentinstance = new $assignmentclass($PAGE->cm
->id
, $assignmentrow, $PAGE->cm
, $PAGE->course
);
3937 // Add assignment submission information
3938 if (has_capability('mod/assignment:grade', $PAGE->cm
->context
)) {
3939 if ($allgroups && has_capability('moodle/site:accessallgroups', $PAGE->cm
->context
)) {
3942 $group = groups_get_activity_group($PAGE->cm
);
3944 $link = new moodle_url('/mod/assignment/submissions.php', array('id'=>$PAGE->cm
->id
));
3945 if ($assignmentrow->assignmenttype
== 'offline') {
3946 $string = get_string('viewfeedback', 'assignment');
3947 } else if ($count = $assignmentinstance->count_real_submissions($group)) {
3948 $string = get_string('viewsubmissions', 'assignment', $count);
3950 $string = get_string('noattempts', 'assignment');
3952 $assignmentnode->add($string, $link, navigation_node
::TYPE_SETTING
);
3955 if (is_object($assignmentinstance) && method_exists($assignmentinstance, 'extend_settings_navigation')) {
3956 $assignmentinstance->extend_settings_navigation($assignmentnode);
3961 * generate zip file from array of given files
3962 * @param array $filesforzipping - array of files to pass into archive_to_pathname
3963 * @return path of temp file - note this returned file does not have a .zip extension - it is a temp file.
3965 function assignment_pack_files($filesforzipping) {
3967 //create path for new zip file.
3968 $tempzip = tempnam($CFG->tempdir
.'/', 'assignment_');
3970 $zipper = new zip_packer();
3971 if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
3978 * Lists all file areas current user may browse
3980 * @param object $course
3982 * @param object $context
3985 function assignment_get_file_areas($course, $cm, $context) {
3987 if (has_capability('moodle/course:managefiles', $context)) {
3988 $areas['submission'] = get_string('assignmentsubmission', 'assignment');
3994 * File browsing support for assignment module.
3996 * @param file_browser $browser
3997 * @param array $areas
3998 * @param stdClass $course
3999 * @param cm_info $cm
4000 * @param context $context
4001 * @param string $filearea
4002 * @param int $itemid
4003 * @param string $filepath
4004 * @param string $filename
4005 * @return file_info_stored file_info_stored instance or null if not found
4007 function mod_assignment_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
4008 global $CFG, $DB, $USER;
4010 if ($context->contextlevel
!= CONTEXT_MODULE ||
$filearea != 'submission') {
4013 if (!$submission = $DB->get_record('assignment_submissions', array('id' => $itemid))) {
4016 if (!(($submission->userid
== $USER->id
&& has_capability('mod/assignment:view', $context))
4017 ||
has_capability('mod/assignment:grade', $context))) {
4018 // no permission to view this submission
4022 $fs = get_file_storage();
4023 $filepath = is_null($filepath) ?
'/' : $filepath;
4024 $filename = is_null($filename) ?
'.' : $filename;
4025 if (!($storedfile = $fs->get_file($context->id
, 'mod_assignment', $filearea, $itemid, $filepath, $filename))) {
4028 $urlbase = $CFG->wwwroot
.'/pluginfile.php';
4029 return new file_info_stored($browser, $context, $storedfile, $urlbase, $filearea, $itemid, true, true, false);
4033 * Return a list of page types
4034 * @param string $pagetype current page type
4035 * @param stdClass $parentcontext Block's parent context
4036 * @param stdClass $currentcontext Current context of block
4038 function assignment_page_type_list($pagetype, $parentcontext, $currentcontext) {
4039 $module_pagetype = array(
4040 'mod-assignment-*'=>get_string('page-mod-assignment-x', 'assignment'),
4041 'mod-assignment-view'=>get_string('page-mod-assignment-view', 'assignment'),
4042 'mod-assignment-submissions'=>get_string('page-mod-assignment-submissions', 'assignment')
4044 return $module_pagetype;
4048 * Lists all gradable areas for the advanced grading methods gramework
4052 function assignment_grading_areas_list() {
4053 return array('submission' => get_string('submissions', 'mod_assignment'));