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>';
200 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM
))) {
201 echo $OUTPUT->notification(get_string('upgradenotification', 'assignment'));
202 $adminurl = new moodle_url('/admin/tool/assignmentupgrade/listnotupgraded.php');
203 echo $OUTPUT->single_button($adminurl, get_string('viewassignmentupgradetool', 'assignment'));
209 * Display the assignment intro
211 * This will most likely be extended by assignment type plug-ins
212 * The default implementation prints the assignment description in a box
214 function view_intro() {
216 echo $OUTPUT->box_start('generalbox boxaligncenter', 'intro');
217 echo format_module_intro('assignment', $this->assignment
, $this->cm
->id
);
218 echo $OUTPUT->box_end();
219 echo plagiarism_print_disclosure($this->cm
->id
);
223 * Display the assignment dates
225 * Prints the assignment start and end dates in a box.
226 * This will be suitable for most assignment types
228 function view_dates() {
230 if (!$this->assignment
->timeavailable
&& !$this->assignment
->timedue
) {
234 echo $OUTPUT->box_start('generalbox boxaligncenter', 'dates');
236 if ($this->assignment
->timeavailable
) {
237 echo '<tr><td class="c0">'.get_string('availabledate','assignment').':</td>';
238 echo ' <td class="c1">'.userdate($this->assignment
->timeavailable
).'</td></tr>';
240 if ($this->assignment
->timedue
) {
241 echo '<tr><td class="c0">'.get_string('duedate','assignment').':</td>';
242 echo ' <td class="c1">'.userdate($this->assignment
->timedue
).'</td></tr>';
245 echo $OUTPUT->box_end();
250 * Display the bottom and footer of a page
252 * This default method just prints the footer.
253 * This will be suitable for most assignment types
255 function view_footer() {
257 echo $OUTPUT->footer();
261 * Display the feedback to the student
263 * This default method prints the teacher picture and name, date when marked,
264 * grade and teacher submissioncomment.
265 * If advanced grading is used the method render_grade from the
266 * advanced grading controller is called to display the grade.
271 * @param object $submission The submission object or NULL in which case it will be loaded
273 function view_feedback($submission=NULL) {
274 global $USER, $CFG, $DB, $OUTPUT, $PAGE;
275 require_once($CFG->libdir
.'/gradelib.php');
276 require_once("$CFG->dirroot/grade/grading/lib.php");
278 if (!$submission) { /// Get submission for this assignment
280 $submission = $this->get_submission($userid);
282 $userid = $submission->userid
;
284 // Check the user can submit
285 $canviewfeedback = ($userid == $USER->id
&& has_capability('mod/assignment:submit', $this->context
, $USER->id
, false));
286 // If not then check if the user still has the view cap and has a previous submission
287 $canviewfeedback = $canviewfeedback ||
(!empty($submission) && $submission->userid
== $USER->id
&& has_capability('mod/assignment:view', $this->context
));
288 // Or if user can grade (is a teacher or admin)
289 $canviewfeedback = $canviewfeedback ||
has_capability('mod/assignment:grade', $this->context
);
291 if (!$canviewfeedback) {
292 // can not view or submit assignments -> no feedback
296 $grading_info = grade_get_grades($this->course
->id
, 'mod', 'assignment', $this->assignment
->id
, $userid);
297 $item = $grading_info->items
[0];
298 $grade = $item->grades
[$userid];
300 if ($grade->hidden
or $grade->grade
=== false) { // hidden or error
304 if ($grade->grade
=== null and empty($grade->str_feedback
)) { /// Nothing to show yet
308 $graded_date = $grade->dategraded
;
309 $graded_by = $grade->usermodified
;
311 /// We need the teacher info
312 if (!$teacher = $DB->get_record('user', array('id'=>$graded_by))) {
313 print_error('cannotfindteacher');
316 /// Print the feedback
317 echo $OUTPUT->heading(get_string('feedbackfromteacher', 'assignment', fullname($teacher)));
319 echo '<table cellspacing="0" class="feedback">';
322 echo '<td class="left picture">';
324 echo $OUTPUT->user_picture($teacher);
327 echo '<td class="topic">';
328 echo '<div class="from">';
330 echo '<div class="fullname">'.fullname($teacher).'</div>';
332 echo '<div class="time">'.userdate($graded_date).'</div>';
338 echo '<td class="left side"> </td>';
339 echo '<td class="content">';
340 $gradestr = '<div class="grade">'. get_string("grade").': '.$grade->str_long_grade
. '</div>';
341 if (!empty($submission) && $controller = get_grading_manager($this->context
, 'mod_assignment', 'submission')->get_active_controller()) {
342 $controller->set_grade_range(make_grades_menu($this->assignment
->grade
));
343 echo $controller->render_grade($PAGE, $submission->id
, $item, $gradestr, has_capability('mod/assignment:grade', $this->context
));
347 echo '<div class="clearer"></div>';
349 echo '<div class="comment">';
350 echo $grade->str_feedback
;
354 if ($this->type
== 'uploadsingle') { //@TODO: move to overload view_feedback method in the class or is uploadsingle merging into upload?
355 $responsefiles = $this->print_responsefiles($submission->userid
, true);
356 if (!empty($responsefiles)) {
358 echo '<td class="left side"> </td>';
359 echo '<td class="content">';
369 * Returns a link with info about the state of the assignment submissions
371 * This is used by view_header to put this link at the top right of the page.
372 * For teachers it gives the number of submitted assignments with a link
373 * For students it gives the time of their submission.
374 * This will be suitable for most assignment types.
378 * @param bool $allgroup print all groups info if user can access all groups, suitable for index.php
381 function submittedlink($allgroups=false) {
386 $urlbase = "{$CFG->wwwroot}/mod/assignment/";
388 $context = get_context_instance(CONTEXT_MODULE
,$this->cm
->id
);
389 if (has_capability('mod/assignment:grade', $context)) {
390 if ($allgroups and has_capability('moodle/site:accessallgroups', $context)) {
393 $group = groups_get_activity_group($this->cm
);
395 if ($this->type
== 'offline') {
396 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm
->id
.'">'.
397 get_string('viewfeedback', 'assignment').'</a>';
398 } else if ($count = $this->count_real_submissions($group)) {
399 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm
->id
.'">'.
400 get_string('viewsubmissions', 'assignment', $count).'</a>';
402 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm
->id
.'">'.
403 get_string('noattempts', 'assignment').'</a>';
407 if ($submission = $this->get_submission($USER->id
)) {
408 // If the submission has been completed
409 if ($this->is_submitted_with_required_data($submission)) {
410 if ($submission->timemodified
<= $this->assignment
->timedue ||
empty($this->assignment
->timedue
)) {
411 $submitted = '<span class="early">'.userdate($submission->timemodified
).'</span>';
413 $submitted = '<span class="late">'.userdate($submission->timemodified
).'</span>';
424 * Returns whether the assigment supports lateness information
426 * @return bool This assignment type supports lateness (true, default) or no (false)
428 function supports_lateness() {
433 * @todo Document this function
435 function setup_elements(&$mform) {
440 * Any preprocessing needed for the settings form for
441 * this assignment type
443 * @param array $default_values - array to fill in with the default values
444 * in the form 'formelement' => 'value'
445 * @param object $form - the form that is to be displayed
448 function form_data_preprocessing(&$default_values, $form) {
452 * Any extra validation checks needed for the settings
453 * form for this assignment type
455 * See lib/formslib.php, 'validation' function for details
457 function form_validation($data, $files) {
462 * Create a new assignment activity
464 * Given an object containing all the necessary data,
465 * (defined by the form in mod_form.php) this function
466 * will create a new instance and return the id number
467 * of the new instance.
468 * The due data is added to the calendar
469 * This is common to all assignment types.
473 * @param object $assignment The data from the form on mod_form.php
474 * @return int The id of the assignment
476 function add_instance($assignment) {
479 $assignment->timemodified
= time();
480 $assignment->courseid
= $assignment->course
;
482 $returnid = $DB->insert_record("assignment", $assignment);
483 $assignment->id
= $returnid;
485 if ($assignment->timedue
) {
486 $event = new stdClass();
487 $event->name
= $assignment->name
;
488 $event->description
= format_module_intro('assignment', $assignment, $assignment->coursemodule
);
489 $event->courseid
= $assignment->course
;
492 $event->modulename
= 'assignment';
493 $event->instance
= $returnid;
494 $event->eventtype
= 'due';
495 $event->timestart
= $assignment->timedue
;
496 $event->timeduration
= 0;
498 calendar_event
::create($event);
501 assignment_grade_item_update($assignment);
507 * Deletes an assignment activity
509 * Deletes all database records, files and calendar events for this assignment.
513 * @param object $assignment The assignment to be deleted
514 * @return boolean False indicates error
516 function delete_instance($assignment) {
519 $assignment->courseid
= $assignment->course
;
523 // now get rid of all files
524 $fs = get_file_storage();
525 if ($cm = get_coursemodule_from_instance('assignment', $assignment->id
)) {
526 $context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
527 $fs->delete_area_files($context->id
);
530 if (! $DB->delete_records('assignment_submissions', array('assignment'=>$assignment->id
))) {
534 if (! $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id
))) {
538 if (! $DB->delete_records('assignment', array('id'=>$assignment->id
))) {
541 $mod = $DB->get_field('modules','id',array('name'=>'assignment'));
543 assignment_grade_item_delete($assignment);
549 * Updates a new assignment activity
551 * Given an object containing all the necessary data,
552 * (defined by the form in mod_form.php) this function
553 * will update the assignment instance and return the id number
554 * The due date is updated in the calendar
555 * This is common to all assignment types.
559 * @param object $assignment The data from the form on mod_form.php
560 * @return bool success
562 function update_instance($assignment) {
565 $assignment->timemodified
= time();
567 $assignment->id
= $assignment->instance
;
568 $assignment->courseid
= $assignment->course
;
570 $DB->update_record('assignment', $assignment);
572 if ($assignment->timedue
) {
573 $event = new stdClass();
575 if ($event->id
= $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id
))) {
577 $event->name
= $assignment->name
;
578 $event->description
= format_module_intro('assignment', $assignment, $assignment->coursemodule
);
579 $event->timestart
= $assignment->timedue
;
581 $calendarevent = calendar_event
::load($event->id
);
582 $calendarevent->update($event);
584 $event = new stdClass();
585 $event->name
= $assignment->name
;
586 $event->description
= format_module_intro('assignment', $assignment, $assignment->coursemodule
);
587 $event->courseid
= $assignment->course
;
590 $event->modulename
= 'assignment';
591 $event->instance
= $assignment->id
;
592 $event->eventtype
= 'due';
593 $event->timestart
= $assignment->timedue
;
594 $event->timeduration
= 0;
596 calendar_event
::create($event);
599 $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id
));
602 // get existing grade item
603 assignment_grade_item_update($assignment);
609 * Update grade item for this submission.
611 * @param stdClass $submission The submission instance
613 function update_grade($submission) {
614 assignment_update_grades($this->assignment
, $submission->userid
);
618 * Top-level function for handling of submissions called by submissions.php
620 * This is for handling the teacher interaction with the grading interface
621 * This should be suitable for most assignment types.
624 * @param string $mode Specifies the kind of teacher interaction taking place
626 function submissions($mode) {
627 ///The main switch is changed to facilitate
628 ///1) Batch fast grading
629 ///2) Skip to the next one on the popup
630 ///3) Save and Skip to the next one on the popup
632 //make user global so we can use the id
633 global $USER, $OUTPUT, $DB, $PAGE;
635 $mailinfo = optional_param('mailinfo', null, PARAM_BOOL
);
637 if (optional_param('next', null, PARAM_BOOL
)) {
640 if (optional_param('saveandnext', null, PARAM_BOOL
)) {
644 if (is_null($mailinfo)) {
645 if (optional_param('sesskey', null, PARAM_BOOL
)) {
646 set_user_preference('assignment_mailinfo', 0);
648 $mailinfo = get_user_preferences('assignment_mailinfo', 0);
651 set_user_preference('assignment_mailinfo', $mailinfo);
654 if (!($this->validate_and_preprocess_feedback())) {
655 // form was submitted ('Save' or 'Save and next' was pressed, but validation failed)
656 $this->display_submission();
661 case 'grade': // We are in a main window grading
662 if ($submission = $this->process_feedback()) {
663 $this->display_submissions(get_string('changessaved'));
665 $this->display_submissions();
669 case 'single': // We are in a main window displaying one submission
670 if ($submission = $this->process_feedback()) {
671 $this->display_submissions(get_string('changessaved'));
673 $this->display_submission();
677 case 'all': // Main window, display everything
678 $this->display_submissions();
682 ///do the fast grading stuff - this process should work for all 3 subclasses
686 if (isset($_POST['submissioncomment'])) {
687 $col = 'submissioncomment';
690 if (isset($_POST['menu'])) {
695 //both submissioncomment and grade columns collapsed..
696 $this->display_submissions();
700 foreach ($_POST[$col] as $id => $unusedvalue){
702 $id = (int)$id; //clean parameter name
704 $this->process_outcomes($id);
706 if (!$submission = $this->get_submission($id)) {
707 $submission = $this->prepare_new_submission($id);
708 $newsubmission = true;
710 $newsubmission = false;
712 unset($submission->data1
); // Don't need to update this.
713 unset($submission->data2
); // Don't need to update this.
715 //for fast grade, we need to check if any changes take place
719 $grade = $_POST['menu'][$id];
720 $updatedb = $updatedb ||
($submission->grade
!= $grade);
721 $submission->grade
= $grade;
723 if (!$newsubmission) {
724 unset($submission->grade
); // Don't need to update this.
728 $commentvalue = trim($_POST['submissioncomment'][$id]);
729 $updatedb = $updatedb ||
($submission->submissioncomment
!= $commentvalue);
730 $submission->submissioncomment
= $commentvalue;
732 unset($submission->submissioncomment
); // Don't need to update this.
735 $submission->teacher
= $USER->id
;
737 $submission->mailed
= (int)(!$mailinfo);
740 $submission->timemarked
= time();
742 //if it is not an update, we don't change the last modified time etc.
743 //this will also not write into database if no submissioncomment and grade is entered.
746 if ($newsubmission) {
747 if (!isset($submission->submissioncomment
)) {
748 $submission->submissioncomment
= '';
750 $sid = $DB->insert_record('assignment_submissions', $submission);
751 $submission->id
= $sid;
753 $DB->update_record('assignment_submissions', $submission);
756 // trigger grade event
757 $this->update_grade($submission);
759 //add to log only if updating
760 add_to_log($this->course
->id
, 'assignment', 'update grades',
761 'submissions.php?id='.$this->cm
->id
.'&user='.$submission->userid
,
762 $submission->userid
, $this->cm
->id
);
767 $message = $OUTPUT->notification(get_string('changessaved'), 'notifysuccess');
769 $this->display_submissions($message);
774 ///We are in pop up. save the current one and go to the next one.
775 //first we save the current changes
776 if ($submission = $this->process_feedback()) {
777 //print_heading(get_string('changessaved'));
778 //$extra_javascript = $this->update_main_listing($submission);
782 /// We are currently in pop up, but we want to skip to next one without saving.
783 /// This turns out to be similar to a single case
784 /// The URL used is for the next submission.
785 $offset = required_param('offset', PARAM_INT
);
786 $nextid = required_param('nextid', PARAM_INT
);
787 $id = required_param('id', PARAM_INT
);
788 $filter = optional_param('filter', self
::FILTER_ALL
, PARAM_INT
);
790 if ($mode == 'next' ||
$filter !== self
::FILTER_REQUIRE_GRADING
) {
791 $offset = (int)$offset+
1;
793 $redirect = new moodle_url('submissions.php',
794 array('id' => $id, 'offset' => $offset, 'userid' => $nextid,
795 'mode' => 'single', 'filter' => $filter));
801 $this->display_submission();
805 echo "something seriously is wrong!!";
811 * Checks if grading method allows quickgrade mode. At the moment it is hardcoded
812 * that advanced grading methods do not allow quickgrade.
814 * Assignment type plugins are not allowed to override this method
818 public final function quickgrade_mode_allowed() {
820 require_once("$CFG->dirroot/grade/grading/lib.php");
821 if ($controller = get_grading_manager($this->context
, 'mod_assignment', 'submission')->get_active_controller()) {
828 * Helper method updating the listing on the main script from popup using javascript
832 * @param $submission object The submission whose data is to be updated on the main page
834 function update_main_listing($submission) {
835 global $SESSION, $CFG, $OUTPUT;
839 $perpage = get_user_preferences('assignment_perpage', 10);
841 $quickgrade = get_user_preferences('assignment_quickgrade', 0) && $this->quickgrade_mode_allowed();
843 /// Run some Javascript to try and update the parent page
844 $output .= '<script type="text/javascript">'."\n<!--\n";
845 if (empty($SESSION->flextable
['mod-assignment-submissions']->collapse
['submissioncomment'])) {
847 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid
.'").value="'
848 .trim($submission->submissioncomment
).'";'."\n";
850 $output.= 'opener.document.getElementById("com'.$submission->userid
.
851 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment
)), 15)."\";\n";
855 if (empty($SESSION->flextable
['mod-assignment-submissions']->collapse
['grade'])) {
856 //echo optional_param('menuindex');
858 $output.= 'opener.document.getElementById("menumenu'.$submission->userid
.
859 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT
).'";'."\n";
861 $output.= 'opener.document.getElementById("g'.$submission->userid
.'").innerHTML="'.
862 $this->display_grade($submission->grade
)."\";\n";
865 //need to add student's assignments in there too.
866 if (empty($SESSION->flextable
['mod-assignment-submissions']->collapse
['timemodified']) &&
867 $submission->timemodified
) {
868 $output.= 'opener.document.getElementById("ts'.$submission->userid
.
869 '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid
)).userdate($submission->timemodified
)."\";\n";
872 if (empty($SESSION->flextable
['mod-assignment-submissions']->collapse
['timemarked']) &&
873 $submission->timemarked
) {
874 $output.= 'opener.document.getElementById("tt'.$submission->userid
.
875 '").innerHTML="'.userdate($submission->timemarked
)."\";\n";
878 if (empty($SESSION->flextable
['mod-assignment-submissions']->collapse
['status'])) {
879 $output.= 'opener.document.getElementById("up'.$submission->userid
.'").className="s1";';
880 $buttontext = get_string('update');
881 $url = new moodle_url('/mod/assignment/submissions.php', array(
882 'id' => $this->cm
->id
,
883 'userid' => $submission->userid
,
885 'offset' => (optional_param('offset', '', PARAM_INT
)-1)));
886 $button = $OUTPUT->action_link($url, $buttontext, new popup_action('click', $url, 'grade'.$submission->userid
, array('height' => 450, 'width' => 700)), array('ttile'=>$buttontext));
888 $output .= 'opener.document.getElementById("up'.$submission->userid
.'").innerHTML="'.addslashes_js($button).'";';
891 $grading_info = grade_get_grades($this->course
->id
, 'mod', 'assignment', $this->assignment
->id
, $submission->userid
);
893 if (empty($SESSION->flextable
['mod-assignment-submissions']->collapse
['finalgrade'])) {
894 $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid
.
895 '").innerHTML="'.$grading_info->items
[0]->grades
[$submission->userid
]->str_grade
.'";'."\n";
898 if (!empty($CFG->enableoutcomes
) and empty($SESSION->flextable
['mod-assignment-submissions']->collapse
['outcome'])) {
900 if (!empty($grading_info->outcomes
)) {
901 foreach($grading_info->outcomes
as $n=>$outcome) {
902 if ($outcome->grades
[$submission->userid
]->locked
) {
907 $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid
.
908 '").selectedIndex="'.$outcome->grades
[$submission->userid
]->grade
.'";'."\n";
911 $options = make_grades_menu(-$outcome->scaleid
);
912 $options[0] = get_string('nooutcome', 'grades');
913 $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid
.'").innerHTML="'.$options[$outcome->grades
[$submission->userid
]->grade
]."\";\n";
920 $output .= "\n-->\n</script>";
925 * Return a grade in user-friendly form, whether it's a scale or not
928 * @param mixed $grade
929 * @return string User-friendly representation of grade
931 function display_grade($grade) {
934 static $scalegrades = array(); // Cache scales for each assignment - they might have different scales!!
936 if ($this->assignment
->grade
>= 0) { // Normal number
940 return $grade.' / '.$this->assignment
->grade
;
944 if (empty($scalegrades[$this->assignment
->id
])) {
945 if ($scale = $DB->get_record('scale', array('id'=>-($this->assignment
->grade
)))) {
946 $scalegrades[$this->assignment
->id
] = make_menu_from_list($scale->scale
);
951 if (isset($scalegrades[$this->assignment
->id
][$grade])) {
952 return $scalegrades[$this->assignment
->id
][$grade];
959 * Display a single submission, ready for grading on a popup window
961 * This default method prints the teacher info and submissioncomment box at the top and
962 * the student info and submission at the bottom.
963 * This method also fetches the necessary data in order to be able to
964 * provide a "Next submission" button.
965 * Calls preprocess_submission() to give assignment type plug-ins a chance
966 * to process submissions before they are graded
967 * This method gets its arguments from the page parameters userid and offset
971 * @param string $extra_javascript
973 function display_submission($offset=-1,$userid =-1, $display=true) {
974 global $CFG, $DB, $PAGE, $OUTPUT, $USER;
975 require_once($CFG->libdir
.'/gradelib.php');
976 require_once($CFG->libdir
.'/tablelib.php');
977 require_once("$CFG->dirroot/repository/lib.php");
978 require_once("$CFG->dirroot/grade/grading/lib.php");
980 $userid = required_param('userid', PARAM_INT
);
983 $offset = required_param('offset', PARAM_INT
);//offset for where to start looking for student.
985 $filter = optional_param('filter', 0, PARAM_INT
);
987 if (!$user = $DB->get_record('user', array('id'=>$userid))) {
988 print_error('nousers');
991 if (!$submission = $this->get_submission($user->id
)) {
992 $submission = $this->prepare_new_submission($userid);
994 if ($submission->timemodified
> $submission->timemarked
) {
995 $subtype = 'assignmentnew';
997 $subtype = 'assignmentold';
1000 $grading_info = grade_get_grades($this->course
->id
, 'mod', 'assignment', $this->assignment
->id
, array($user->id
));
1001 $gradingdisabled = $grading_info->items
[0]->grades
[$userid]->locked ||
$grading_info->items
[0]->grades
[$userid]->overridden
;
1003 /// construct SQL, using current offset to find the data of the next student
1004 $course = $this->course
;
1005 $assignment = $this->assignment
;
1007 $context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
1009 //reset filter to all for offline assignment
1010 if ($assignment->assignmenttype
== 'offline' && $filter == self
::FILTER_SUBMITTED
) {
1011 $filter = self
::FILTER_ALL
;
1013 /// Get all ppl that can submit assignments
1015 $currentgroup = groups_get_activity_group($cm);
1016 $users = get_enrolled_users($context, 'mod/assignment:submit', $currentgroup, 'u.id');
1018 $users = array_keys($users);
1019 // if groupmembersonly used, remove users who are not in any group
1020 if (!empty($CFG->enablegroupmembersonly
) and $cm->groupmembersonly
) {
1021 if ($groupingusers = groups_get_grouping_members($cm->groupingid
, 'u.id', 'u.id')) {
1022 $users = array_intersect($users, array_keys($groupingusers));
1029 if($filter == self
::FILTER_SUBMITTED
) {
1030 $where .= 's.timemodified > 0 AND ';
1031 } else if($filter == self
::FILTER_REQUIRE_GRADING
) {
1032 $where .= 's.timemarked < s.timemodified AND ';
1036 $userfields = user_picture
::fields('u', array('lastaccess'));
1037 $select = "SELECT $userfields,
1038 s.id AS submissionid, s.grade, s.submissioncomment,
1039 s.timemodified, s.timemarked,
1040 CASE WHEN s.timemarked > 0 AND s.timemarked >= s.timemodified THEN 1
1041 ELSE 0 END AS status ";
1043 $sql = 'FROM {user} u '.
1044 'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1045 AND s.assignment = '.$this->assignment
->id
.' '.
1046 'WHERE '.$where.'u.id IN ('.implode(',', $users).') ';
1048 if ($sort = flexible_table
::get_sort_for_table('mod-assignment-submissions')) {
1049 $sort = 'ORDER BY '.$sort.' ';
1051 $auser = $DB->get_records_sql($select.$sql.$sort, null, $offset, 2);
1053 if (is_array($auser) && count($auser)>1) {
1054 $nextuser = next($auser);
1055 $nextid = $nextuser->id
;
1059 if ($submission->teacher
) {
1060 $teacher = $DB->get_record('user', array('id'=>$submission->teacher
));
1066 $this->preprocess_submission($submission);
1068 $mformdata = new stdClass();
1069 $mformdata->context
= $this->context
;
1070 $mformdata->maxbytes
= $this->course
->maxbytes
;
1071 $mformdata->courseid
= $this->course
->id
;
1072 $mformdata->teacher
= $teacher;
1073 $mformdata->assignment
= $assignment;
1074 $mformdata->submission
= $submission;
1075 $mformdata->lateness
= $this->display_lateness($submission->timemodified
);
1076 $mformdata->auser
= $auser;
1077 $mformdata->user
= $user;
1078 $mformdata->offset
= $offset;
1079 $mformdata->userid
= $userid;
1080 $mformdata->cm
= $this->cm
;
1081 $mformdata->grading_info
= $grading_info;
1082 $mformdata->enableoutcomes
= $CFG->enableoutcomes
;
1083 $mformdata->grade
= $this->assignment
->grade
;
1084 $mformdata->gradingdisabled
= $gradingdisabled;
1085 $mformdata->nextid
= $nextid;
1086 $mformdata->submissioncomment
= $submission->submissioncomment
;
1087 $mformdata->submissioncommentformat
= FORMAT_HTML
;
1088 $mformdata->submission_content
= $this->print_user_files($user->id
,true);
1089 $mformdata->filter
= $filter;
1090 $mformdata->mailinfo
= get_user_preferences('assignment_mailinfo', 0);
1091 if ($assignment->assignmenttype
== 'upload') {
1092 $mformdata->fileui_options
= array('subdirs'=>1, 'maxbytes'=>$assignment->maxbytes
, 'maxfiles'=>$assignment->var1
, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL
);
1093 } elseif ($assignment->assignmenttype
== 'uploadsingle') {
1094 $mformdata->fileui_options
= array('subdirs'=>0, 'maxbytes'=>$CFG->userquota
, 'maxfiles'=>1, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL
);
1096 $advancedgradingwarning = false;
1097 $gradingmanager = get_grading_manager($this->context
, 'mod_assignment', 'submission');
1098 if ($gradingmethod = $gradingmanager->get_active_method()) {
1099 $controller = $gradingmanager->get_controller($gradingmethod);
1100 if ($controller->is_form_available()) {
1102 if (!empty($submission->id
)) {
1103 $itemid = $submission->id
;
1105 if ($gradingdisabled && $itemid) {
1106 $mformdata->advancedgradinginstance
= $controller->get_current_instance($USER->id
, $itemid);
1107 } else if (!$gradingdisabled) {
1108 $instanceid = optional_param('advancedgradinginstanceid', 0, PARAM_INT
);
1109 $mformdata->advancedgradinginstance
= $controller->get_or_create_instance($instanceid, $USER->id
, $itemid);
1112 $advancedgradingwarning = $controller->form_unavailable_notification();
1116 $submitform = new assignment_grading_form( null, $mformdata );
1119 $ret_data = new stdClass();
1120 $ret_data->mform
= $submitform;
1121 if (isset($mformdata->fileui_options
)) {
1122 $ret_data->fileui_options
= $mformdata->fileui_options
;
1127 if ($submitform->is_cancelled()) {
1128 redirect('submissions.php?id='.$this->cm
->id
);
1131 $submitform->set_data($mformdata);
1133 $PAGE->set_title($this->course
->fullname
. ': ' .get_string('feedback', 'assignment').' - '.fullname($user, true));
1134 $PAGE->set_heading($this->course
->fullname
);
1135 $PAGE->navbar
->add(get_string('submissions', 'assignment'), new moodle_url('/mod/assignment/submissions.php', array('id'=>$cm->id
)));
1136 $PAGE->navbar
->add(fullname($user, true));
1138 echo $OUTPUT->header();
1139 echo $OUTPUT->heading(get_string('feedback', 'assignment').': '.fullname($user, true));
1141 // display mform here...
1142 if ($advancedgradingwarning) {
1143 echo $OUTPUT->notification($advancedgradingwarning, 'error');
1145 $submitform->display();
1147 $customfeedback = $this->custom_feedbackform($submission, true);
1148 if (!empty($customfeedback)) {
1149 echo $customfeedback;
1152 echo $OUTPUT->footer();
1156 * Preprocess submission before grading
1158 * Called by display_submission()
1159 * The default type does nothing here.
1161 * @param object $submission The submission object
1163 function preprocess_submission(&$submission) {
1167 * Display all the submissions ready for grading
1173 * @param string $message
1176 function display_submissions($message='') {
1177 global $CFG, $DB, $USER, $DB, $OUTPUT, $PAGE;
1178 require_once($CFG->libdir
.'/gradelib.php');
1180 /* first we check to see if the form has just been submitted
1181 * to request user_preference updates
1184 $filters = array(self
::FILTER_ALL
=> get_string('all'),
1185 self
::FILTER_REQUIRE_GRADING
=> get_string('requiregrading', 'assignment'));
1187 $updatepref = optional_param('updatepref', 0, PARAM_BOOL
);
1189 $perpage = optional_param('perpage', 10, PARAM_INT
);
1190 $perpage = ($perpage <= 0) ?
10 : $perpage ;
1191 $filter = optional_param('filter', 0, PARAM_INT
);
1192 set_user_preference('assignment_perpage', $perpage);
1193 set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL
));
1194 set_user_preference('assignment_filter', $filter);
1197 /* next we get perpage and quickgrade (allow quick grade) params
1200 $perpage = get_user_preferences('assignment_perpage', 10);
1201 $quickgrade = get_user_preferences('assignment_quickgrade', 0) && $this->quickgrade_mode_allowed();
1202 $filter = get_user_preferences('assignment_filter', 0);
1203 $grading_info = grade_get_grades($this->course
->id
, 'mod', 'assignment', $this->assignment
->id
);
1205 if (!empty($CFG->enableoutcomes
) and !empty($grading_info->outcomes
)) {
1206 $uses_outcomes = true;
1208 $uses_outcomes = false;
1211 $page = optional_param('page', 0, PARAM_INT
);
1212 $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
1214 /// Some shortcuts to make the code read better
1216 $course = $this->course
;
1217 $assignment = $this->assignment
;
1219 $hassubmission = false;
1221 // reset filter to all for offline assignment only.
1222 if ($assignment->assignmenttype
== 'offline') {
1223 if ($filter == self
::FILTER_SUBMITTED
) {
1224 $filter = self
::FILTER_ALL
;
1227 $filters[self
::FILTER_SUBMITTED
] = get_string('submitted', 'assignment');
1230 $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
1231 add_to_log($course->id
, 'assignment', 'view submission', 'submissions.php?id='.$this->cm
->id
, $this->assignment
->id
, $this->cm
->id
);
1233 $PAGE->set_title(format_string($this->assignment
->name
,true));
1234 $PAGE->set_heading($this->course
->fullname
);
1235 echo $OUTPUT->header();
1237 echo '<div class="usersubmissions">';
1239 //hook to allow plagiarism plugins to update status/print links.
1240 echo plagiarism_update_status($this->course
, $this->cm
);
1242 $course_context = get_context_instance(CONTEXT_COURSE
, $course->id
);
1243 if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
1244 echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot
. '/grade/report/grader/index.php?id=' . $course->id
. '">'
1245 . get_string('seeallcoursegrades', 'grades') . '</a></div>';
1248 if (!empty($message)) {
1249 echo $message; // display messages here if any
1252 $context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
1254 /// Check to see if groups are being used in this assignment
1256 /// find out current groups mode
1257 $groupmode = groups_get_activity_groupmode($cm);
1258 $currentgroup = groups_get_activity_group($cm, true);
1259 groups_print_activity_menu($cm, $CFG->wwwroot
. '/mod/assignment/submissions.php?id=' . $this->cm
->id
);
1261 /// Print quickgrade form around the table
1263 $formattrs = array();
1264 $formattrs['action'] = new moodle_url('/mod/assignment/submissions.php');
1265 $formattrs['id'] = 'fastg';
1266 $formattrs['method'] = 'post';
1268 echo html_writer
::start_tag('form', $formattrs);
1269 echo html_writer
::empty_tag('input', array('type'=>'hidden', 'name'=>'id', 'value'=> $this->cm
->id
));
1270 echo html_writer
::empty_tag('input', array('type'=>'hidden', 'name'=>'mode', 'value'=> 'fastgrade'));
1271 echo html_writer
::empty_tag('input', array('type'=>'hidden', 'name'=>'page', 'value'=> $page));
1272 echo html_writer
::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=> sesskey()));
1275 /// Get all ppl that are allowed to submit assignments
1276 list($esql, $params) = get_enrolled_sql($context, 'mod/assignment:submit', $currentgroup);
1278 if ($filter == self
::FILTER_ALL
) {
1279 $sql = "SELECT u.id FROM {user} u ".
1280 "LEFT JOIN ($esql) eu ON eu.id=u.id ".
1281 "WHERE u.deleted = 0 AND eu.id=u.id ";
1283 $wherefilter = ' AND s.assignment = '. $this->assignment
->id
;
1284 $assignmentsubmission = "LEFT JOIN {assignment_submissions} s ON (u.id = s.userid) ";
1285 if($filter == self
::FILTER_SUBMITTED
) {
1286 $wherefilter .= ' AND s.timemodified > 0 ';
1287 } else if($filter == self
::FILTER_REQUIRE_GRADING
&& $assignment->assignmenttype
!= 'offline') {
1288 $wherefilter .= ' AND s.timemarked < s.timemodified ';
1289 } else { // require grading for offline assignment
1290 $assignmentsubmission = "";
1294 $sql = "SELECT u.id FROM {user} u ".
1295 "LEFT JOIN ($esql) eu ON eu.id=u.id ".
1296 $assignmentsubmission.
1297 "WHERE u.deleted = 0 AND eu.id=u.id ".
1301 $users = $DB->get_records_sql($sql, $params);
1302 if (!empty($users)) {
1303 if($assignment->assignmenttype
== 'offline' && $filter == self
::FILTER_REQUIRE_GRADING
) {
1304 //remove users who has submitted their assignment
1305 foreach ($this->get_submissions() as $submission) {
1306 if (array_key_exists($submission->userid
, $users)) {
1307 unset($users[$submission->userid
]);
1311 $users = array_keys($users);
1314 // if groupmembersonly used, remove users who are not in any group
1315 if ($users and !empty($CFG->enablegroupmembersonly
) and $cm->groupmembersonly
) {
1316 if ($groupingusers = groups_get_grouping_members($cm->groupingid
, 'u.id', 'u.id')) {
1317 $users = array_intersect($users, array_keys($groupingusers));
1321 $extrafields = get_extra_user_fields($context);
1322 $tablecolumns = array_merge(array('picture', 'fullname'), $extrafields,
1323 array('grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade'));
1324 if ($uses_outcomes) {
1325 $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
1328 $extrafieldnames = array();
1329 foreach ($extrafields as $field) {
1330 $extrafieldnames[] = get_user_field_name($field);
1332 $tableheaders = array_merge(
1333 array('', get_string('fullnameuser')),
1336 get_string('grade'),
1337 get_string('comment', 'assignment'),
1338 get_string('lastmodified').' ('.get_string('submission', 'assignment').')',
1339 get_string('lastmodified').' ('.get_string('grade').')',
1340 get_string('status'),
1341 get_string('finalgrade', 'grades'),
1343 if ($uses_outcomes) {
1344 $tableheaders[] = get_string('outcome', 'grades');
1347 require_once($CFG->libdir
.'/tablelib.php');
1348 $table = new flexible_table('mod-assignment-submissions');
1350 $table->define_columns($tablecolumns);
1351 $table->define_headers($tableheaders);
1352 $table->define_baseurl($CFG->wwwroot
.'/mod/assignment/submissions.php?id='.$this->cm
->id
.'&currentgroup='.$currentgroup);
1354 $table->sortable(true, 'lastname');//sorted by lastname by default
1355 $table->collapsible(true);
1356 $table->initialbars(true);
1358 $table->column_suppress('picture');
1359 $table->column_suppress('fullname');
1361 $table->column_class('picture', 'picture');
1362 $table->column_class('fullname', 'fullname');
1363 foreach ($extrafields as $field) {
1364 $table->column_class($field, $field);
1366 $table->column_class('grade', 'grade');
1367 $table->column_class('submissioncomment', 'comment');
1368 $table->column_class('timemodified', 'timemodified');
1369 $table->column_class('timemarked', 'timemarked');
1370 $table->column_class('status', 'status');
1371 $table->column_class('finalgrade', 'finalgrade');
1372 if ($uses_outcomes) {
1373 $table->column_class('outcome', 'outcome');
1376 $table->set_attribute('cellspacing', '0');
1377 $table->set_attribute('id', 'attempts');
1378 $table->set_attribute('class', 'submissions');
1379 $table->set_attribute('width', '100%');
1381 $table->no_sorting('finalgrade');
1382 $table->no_sorting('outcome');
1383 $table->text_sorting('submissioncomment');
1385 // Start working -- this is necessary as soon as the niceties are over
1388 /// Construct the SQL
1389 list($where, $params) = $table->get_sql_where();
1394 if ($filter == self
::FILTER_SUBMITTED
) {
1395 $where .= 's.timemodified > 0 AND ';
1396 } else if($filter == self
::FILTER_REQUIRE_GRADING
) {
1398 if ($assignment->assignmenttype
!= 'offline') {
1399 $where .= 's.timemarked < s.timemodified AND ';
1403 if ($sort = $table->get_sql_sort()) {
1404 $sort = ' ORDER BY '.$sort;
1407 $ufields = user_picture
::fields('u', $extrafields);
1408 if (!empty($users)) {
1409 $select = "SELECT $ufields,
1410 s.id AS submissionid, s.grade, s.submissioncomment,
1411 s.timemodified, s.timemarked,
1412 CASE WHEN s.timemarked > 0 AND s.timemarked >= s.timemodified THEN 1
1413 ELSE 0 END AS status ";
1415 $sql = 'FROM {user} u '.
1416 'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1417 AND s.assignment = '.$this->assignment
->id
.' '.
1418 'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1420 $ausers = $DB->get_records_sql($select.$sql.$sort, $params, $table->get_page_start(), $table->get_page_size());
1422 $table->pagesize($perpage, count($users));
1424 ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1425 $offset = $page * $perpage;
1426 $strupdate = get_string('update');
1427 $strgrade = get_string('grade');
1428 $strview = get_string('view');
1429 $grademenu = make_grades_menu($this->assignment
->grade
);
1431 if ($ausers !== false) {
1432 $grading_info = grade_get_grades($this->course
->id
, 'mod', 'assignment', $this->assignment
->id
, array_keys($ausers));
1433 $endposition = $offset +
$perpage;
1434 $currentposition = 0;
1435 foreach ($ausers as $auser) {
1436 if ($currentposition == $offset && $offset < $endposition) {
1438 $final_grade = $grading_info->items
[0]->grades
[$auser->id
];
1439 $grademax = $grading_info->items
[0]->grademax
;
1440 $final_grade->formatted_grade
= round($final_grade->grade
,2) .' / ' . round($grademax,2);
1441 $locked_overridden = 'locked';
1442 if ($final_grade->overridden
) {
1443 $locked_overridden = 'overridden';
1446 // TODO add here code if advanced grading grade must be reviewed => $auser->status=0
1448 $picture = $OUTPUT->user_picture($auser);
1450 if (empty($auser->submissionid
)) {
1451 $auser->grade
= -1; //no submission yet
1454 if (!empty($auser->submissionid
)) {
1455 $hassubmission = true;
1456 ///Prints student answer and student modified date
1457 ///attach file or print link to student answer, depending on the type of the assignment.
1458 ///Refer to print_student_answer in inherited classes.
1459 if ($auser->timemodified
> 0) {
1460 $studentmodifiedcontent = $this->print_student_answer($auser->id
)
1461 . userdate($auser->timemodified
);
1462 if ($assignment->timedue
&& $auser->timemodified
> $assignment->timedue
&& $this->supports_lateness()) {
1463 $studentmodifiedcontent .= $this->display_lateness($auser->timemodified
);
1467 $studentmodifiedcontent = ' ';
1469 $studentmodified = html_writer
::tag('div', $studentmodifiedcontent, array('id' => 'ts' . $auser->id
));
1470 ///Print grade, dropdown or text
1471 if ($auser->timemarked
> 0) {
1472 $teachermodified = '<div id="tt'.$auser->id
.'">'.userdate($auser->timemarked
).'</div>';
1474 if ($final_grade->locked
or $final_grade->overridden
) {
1475 $grade = '<div id="g'.$auser->id
.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade
.'</div>';
1476 } else if ($quickgrade) {
1477 $attributes = array();
1478 $attributes['tabindex'] = $tabindex++
;
1479 $menu = html_writer
::label(get_string('assignment:grade', 'assignment'), 'menumenu'. $auser->id
, false, array('class' => 'accesshide'));
1480 $menu .= html_writer
::select(make_grades_menu($this->assignment
->grade
), 'menu['.$auser->id
.']', $auser->grade
, array(-1=>get_string('nograde')), $attributes);
1481 $grade = '<div id="g'.$auser->id
.'">'. $menu .'</div>';
1483 $grade = '<div id="g'.$auser->id
.'">'.$this->display_grade($auser->grade
).'</div>';
1487 $teachermodified = '<div id="tt'.$auser->id
.'"> </div>';
1488 if ($final_grade->locked
or $final_grade->overridden
) {
1489 $grade = '<div id="g'.$auser->id
.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade
.'</div>';
1490 } else if ($quickgrade) {
1491 $attributes = array();
1492 $attributes['tabindex'] = $tabindex++
;
1493 $menu = html_writer
::label(get_string('assignment:grade', 'assignment'), 'menumenu'. $auser->id
, false, array('class' => 'accesshide'));
1494 $menu .= html_writer
::select(make_grades_menu($this->assignment
->grade
), 'menu['.$auser->id
.']', $auser->grade
, array(-1=>get_string('nograde')), $attributes);
1495 $grade = '<div id="g'.$auser->id
.'">'.$menu.'</div>';
1497 $grade = '<div id="g'.$auser->id
.'">'.$this->display_grade($auser->grade
).'</div>';
1501 if ($final_grade->locked
or $final_grade->overridden
) {
1502 $comment = '<div id="com'.$auser->id
.'">'.shorten_text(strip_tags($final_grade->str_feedback
),15).'</div>';
1504 } else if ($quickgrade) {
1505 $comment = '<div id="com'.$auser->id
.'">'
1506 . '<textarea tabindex="'.$tabindex++
.'" name="submissioncomment['.$auser->id
.']" id="submissioncomment'
1507 . $auser->id
.'" rows="2" cols="20">'.($auser->submissioncomment
).'</textarea></div>';
1509 $comment = '<div id="com'.$auser->id
.'">'.shorten_text(strip_tags($auser->submissioncomment
),15).'</div>';
1512 $studentmodified = '<div id="ts'.$auser->id
.'"> </div>';
1513 $teachermodified = '<div id="tt'.$auser->id
.'"> </div>';
1514 $status = '<div id="st'.$auser->id
.'"> </div>';
1516 if ($final_grade->locked
or $final_grade->overridden
) {
1517 $grade = '<div id="g'.$auser->id
.'">'.$final_grade->formatted_grade
. '</div>';
1518 $hassubmission = true;
1519 } else if ($quickgrade) { // allow editing
1520 $attributes = array();
1521 $attributes['tabindex'] = $tabindex++
;
1522 $menu = html_writer
::label(get_string('assignment:grade', 'assignment'), 'menumenu'. $auser->id
, false, array('class' => 'accesshide'));
1523 $menu .= html_writer
::select(make_grades_menu($this->assignment
->grade
), 'menu['.$auser->id
.']', $auser->grade
, array(-1=>get_string('nograde')), $attributes);
1524 $grade = '<div id="g'.$auser->id
.'">'.$menu.'</div>';
1525 $hassubmission = true;
1527 $grade = '<div id="g'.$auser->id
.'">-</div>';
1530 if ($final_grade->locked
or $final_grade->overridden
) {
1531 $comment = '<div id="com'.$auser->id
.'">'.$final_grade->str_feedback
.'</div>';
1532 } else if ($quickgrade) {
1533 $comment = '<div id="com'.$auser->id
.'">'
1534 . '<textarea tabindex="'.$tabindex++
.'" name="submissioncomment['.$auser->id
.']" id="submissioncomment'
1535 . $auser->id
.'" rows="2" cols="20">'.($auser->submissioncomment
).'</textarea></div>';
1537 $comment = '<div id="com'.$auser->id
.'"> </div>';
1541 if (empty($auser->status
)) { /// Confirm we have exclusively 0 or 1
1547 $buttontext = ($auser->status
== 1) ?
$strupdate : $strgrade;
1548 if ($final_grade->locked
or $final_grade->overridden
) {
1549 $buttontext = $strview;
1552 ///No more buttons, we use popups ;-).
1553 $popup_url = '/mod/assignment/submissions.php?id='.$this->cm
->id
1554 . '&userid='.$auser->id
.'&mode=single'.'&filter='.$filter.'&offset='.$offset++
;
1556 $button = $OUTPUT->action_link($popup_url, $buttontext);
1558 $status = '<div id="up'.$auser->id
.'" class="s'.$auser->status
.'">'.$button.'</div>';
1560 $finalgrade = '<span id="finalgrade_'.$auser->id
.'">'.$final_grade->str_grade
.'</span>';
1564 if ($uses_outcomes) {
1566 foreach($grading_info->outcomes
as $n=>$outcome) {
1567 $outcomes .= '<div class="outcome"><label for="'. 'outcome_'.$n.'_'.$auser->id
.'">'.$outcome->name
.'</label>';
1568 $options = make_grades_menu(-$outcome->scaleid
);
1570 if ($outcome->grades
[$auser->id
]->locked
or !$quickgrade) {
1571 $options[0] = get_string('nooutcome', 'grades');
1572 $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id
.'">'.$options[$outcome->grades
[$auser->id
]->grade
].'</span>';
1574 $attributes = array();
1575 $attributes['tabindex'] = $tabindex++
;
1576 $attributes['id'] = 'outcome_'.$n.'_'.$auser->id
;
1577 $outcomes .= ' '.html_writer
::select($options, 'outcome_'.$n.'['.$auser->id
.']', $outcome->grades
[$auser->id
]->grade
, array(0=>get_string('nooutcome', 'grades')), $attributes);
1579 $outcomes .= '</div>';
1583 $userlink = '<a href="' . $CFG->wwwroot
. '/user/view.php?id=' . $auser->id
. '&course=' . $course->id
. '">' . fullname($auser, has_capability('moodle/site:viewfullnames', $this->context
)) . '</a>';
1584 $extradata = array();
1585 foreach ($extrafields as $field) {
1586 $extradata[] = $auser->{$field};
1588 $row = array_merge(array($picture, $userlink), $extradata,
1589 array($grade, $comment, $studentmodified, $teachermodified,
1590 $status, $finalgrade));
1591 if ($uses_outcomes) {
1594 $table->add_data($row, $rowclass);
1598 if ($hassubmission && method_exists($this, 'download_submissions')) {
1599 echo html_writer
::start_tag('div', array('class' => 'mod-assignment-download-link'));
1600 echo html_writer
::link(new moodle_url('/mod/assignment/submissions.php', array('id' => $this->cm
->id
, 'download' => 'zip')), get_string('downloadall', 'assignment'));
1601 echo html_writer
::end_tag('div');
1603 $table->print_html(); /// Print the whole table
1605 if ($filter == self
::FILTER_SUBMITTED
) {
1606 echo html_writer
::tag('div', get_string('nosubmisson', 'assignment'), array('class'=>'nosubmisson'));
1607 } else if ($filter == self
::FILTER_REQUIRE_GRADING
) {
1608 echo html_writer
::tag('div', get_string('norequiregrading', 'assignment'), array('class'=>'norequiregrading'));
1613 /// Print quickgrade form around the table
1614 if ($quickgrade && $table->started_output
&& !empty($users)){
1615 $mailinfopref = false;
1616 if (get_user_preferences('assignment_mailinfo', 1)) {
1617 $mailinfopref = true;
1619 $emailnotification = html_writer
::checkbox('mailinfo', 1, $mailinfopref, get_string('enablenotification','assignment'));
1621 $emailnotification .= $OUTPUT->help_icon('enablenotification', 'assignment');
1622 echo html_writer
::tag('div', $emailnotification, array('class'=>'emailnotification'));
1624 $savefeedback = html_writer
::empty_tag('input', array('type'=>'submit', 'name'=>'fastg', 'value'=>get_string('saveallfeedback', 'assignment')));
1625 echo html_writer
::tag('div', $savefeedback, array('class'=>'fastgbutton'));
1627 echo html_writer
::end_tag('form');
1628 } else if ($quickgrade) {
1629 echo html_writer
::end_tag('form');
1633 /// End of fast grading form
1635 /// Mini form for setting user preference
1637 $formaction = new moodle_url('/mod/assignment/submissions.php', array('id'=>$this->cm
->id
));
1638 $mform = new MoodleQuickForm('optionspref', 'post', $formaction, '', array('class'=>'optionspref'));
1640 $mform->addElement('hidden', 'updatepref');
1641 $mform->setDefault('updatepref', 1);
1642 $mform->addElement('header', 'qgprefs', get_string('optionalsettings', 'assignment'));
1643 $mform->addElement('select', 'filter', get_string('show'), $filters);
1645 $mform->setDefault('filter', $filter);
1647 $mform->addElement('text', 'perpage', get_string('pagesize', 'assignment'), array('size'=>1));
1648 $mform->setDefault('perpage', $perpage);
1650 if ($this->quickgrade_mode_allowed()) {
1651 $mform->addElement('checkbox', 'quickgrade', get_string('quickgrade','assignment'));
1652 $mform->setDefault('quickgrade', $quickgrade);
1653 $mform->addHelpButton('quickgrade', 'quickgrade', 'assignment');
1656 $mform->addElement('submit', 'savepreferences', get_string('savepreferences'));
1660 echo $OUTPUT->footer();
1664 * If the form was cancelled ('Cancel' or 'Next' was pressed), call cancel method
1665 * from advanced grading (if applicable) and returns true
1666 * If the form was submitted, validates it and returns false if validation did not pass.
1667 * If validation passes, preprocess advanced grading (if applicable) and returns true.
1669 * Note to the developers: This is NOT the correct way to implement advanced grading
1670 * in grading form. The assignment grading was written long time ago and unfortunately
1671 * does not fully use the mforms. Usually function is_validated() is called to
1672 * validate the form and get_data() is called to get the data from the form.
1674 * Here we have to push the calculated grade to $_POST['xgrade'] because further processing
1675 * of the form gets the data not from form->get_data(), but from $_POST (using statement
1676 * like $feedback = data_submitted() )
1678 protected function validate_and_preprocess_feedback() {
1680 require_once($CFG->libdir
.'/gradelib.php');
1681 if (!($feedback = data_submitted()) ||
!isset($feedback->userid
) ||
!isset($feedback->offset
)) {
1682 return true; // No incoming data, nothing to validate
1684 $userid = required_param('userid', PARAM_INT
);
1685 $offset = required_param('offset', PARAM_INT
);
1686 $gradinginfo = grade_get_grades($this->course
->id
, 'mod', 'assignment', $this->assignment
->id
, array($userid));
1687 $gradingdisabled = $gradinginfo->items
[0]->grades
[$userid]->locked ||
$gradinginfo->items
[0]->grades
[$userid]->overridden
;
1688 if ($gradingdisabled) {
1691 $submissiondata = $this->display_submission($offset, $userid, false);
1692 $mform = $submissiondata->mform
;
1693 $gradinginstance = $mform->use_advanced_grading();
1694 if (optional_param('cancel', false, PARAM_BOOL
) ||
optional_param('next', false, PARAM_BOOL
)) {
1695 // form was cancelled
1696 if ($gradinginstance) {
1697 $gradinginstance->cancel();
1699 } else if ($mform->is_submitted()) {
1700 // form was submitted (= a submit button other than 'cancel' or 'next' has been clicked)
1701 if (!$mform->is_validated()) {
1704 // preprocess advanced grading here
1705 if ($gradinginstance) {
1706 $data = $mform->get_data();
1707 // create submission if it did not exist yet because we need submission->id for storing the grading instance
1708 $submission = $this->get_submission($userid, true);
1709 $_POST['xgrade'] = $gradinginstance->submit_and_get_grade($data->advancedgrading
, $submission->id
);
1716 * Process teacher feedback submission
1718 * This is called by submissions() when a grading even has taken place.
1719 * It gets its data from the submitted form.
1724 * @return object|bool The updated submission object or false
1726 function process_feedback($formdata=null) {
1727 global $CFG, $USER, $DB;
1728 require_once($CFG->libdir
.'/gradelib.php');
1730 if (!$feedback = data_submitted() or !confirm_sesskey()) { // No incoming data?
1734 ///For save and next, we need to know the userid to save, and the userid to go
1735 ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1736 ///as the userid to store
1737 if ((int)$feedback->saveuserid
!== -1){
1738 $feedback->userid
= $feedback->saveuserid
;
1741 if (!empty($feedback->cancel
)) { // User hit cancel button
1745 $grading_info = grade_get_grades($this->course
->id
, 'mod', 'assignment', $this->assignment
->id
, $feedback->userid
);
1747 // store outcomes if needed
1748 $this->process_outcomes($feedback->userid
);
1750 $submission = $this->get_submission($feedback->userid
, true); // Get or make one
1752 if (!($grading_info->items
[0]->grades
[$feedback->userid
]->locked ||
1753 $grading_info->items
[0]->grades
[$feedback->userid
]->overridden
) ) {
1755 $submission->grade
= $feedback->xgrade
;
1756 $submission->submissioncomment
= $feedback->submissioncomment_editor
['text'];
1757 $submission->teacher
= $USER->id
;
1758 $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1760 $submission->mailed
= 1; // treat as already mailed
1762 $submission->mailed
= 0; // Make sure mail goes out (again, even)
1764 $submission->timemarked
= time();
1766 unset($submission->data1
); // Don't need to update this.
1767 unset($submission->data2
); // Don't need to update this.
1769 if (empty($submission->timemodified
)) { // eg for offline assignments
1770 // $submission->timemodified = time();
1773 $DB->update_record('assignment_submissions', $submission);
1775 // triger grade event
1776 $this->update_grade($submission);
1778 add_to_log($this->course
->id
, 'assignment', 'update grades',
1779 'submissions.php?id='.$this->cm
->id
.'&user='.$feedback->userid
, $feedback->userid
, $this->cm
->id
);
1780 if (!is_null($formdata)) {
1781 if ($this->type
== 'upload' ||
$this->type
== 'uploadsingle') {
1782 $mformdata = $formdata->mform
->get_data();
1783 $mformdata = file_postupdate_standard_filemanager($mformdata, 'files', $formdata->fileui_options
, $this->context
, 'mod_assignment', 'response', $submission->id
);
1792 function process_outcomes($userid) {
1795 if (empty($CFG->enableoutcomes
)) {
1799 require_once($CFG->libdir
.'/gradelib.php');
1801 if (!$formdata = data_submitted() or !confirm_sesskey()) {
1806 $grading_info = grade_get_grades($this->course
->id
, 'mod', 'assignment', $this->assignment
->id
, $userid);
1808 if (!empty($grading_info->outcomes
)) {
1809 foreach($grading_info->outcomes
as $n=>$old) {
1810 $name = 'outcome_'.$n;
1811 if (isset($formdata->{$name}[$userid]) and $old->grades
[$userid]->grade
!= $formdata->{$name}[$userid]) {
1812 $data[$n] = $formdata->{$name}[$userid];
1816 if (count($data) > 0) {
1817 grade_update_outcomes('mod/assignment', $this->course
->id
, 'mod', 'assignment', $this->assignment
->id
, $userid, $data);
1823 * Load the submission object for a particular user
1827 * @param int $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1828 * @param bool $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1829 * @param bool $teachermodified student submission set if false
1830 * @return object|bool The submission or false (if $createnew is false and there is no existing submission).
1832 function get_submission($userid=0, $createnew=false, $teachermodified=false) {
1835 if (empty($userid)) {
1836 $userid = $USER->id
;
1839 $submission = $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment
->id
, 'userid'=>$userid));
1843 } else if (!$createnew) {
1846 $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
1847 $DB->insert_record("assignment_submissions", $newsubmission);
1849 return $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment
->id
, 'userid'=>$userid));
1853 * Check the given submission is complete. Preliminary rows are often created in the assignment_submissions
1854 * table before a submission actually takes place. This function checks to see if the given submission has actually
1857 * @param stdClass $submission The submission we want to check for completion
1858 * @return bool Indicates if the submission was found to be complete
1860 public function is_submitted_with_required_data($submission) {
1861 return $submission->timemodified
;
1865 * Instantiates a new submission object for a given user
1867 * Sets the assignment, userid and times, everything else is set to default values.
1869 * @param int $userid The userid for which we want a submission object
1870 * @param bool $teachermodified student submission set if false
1871 * @return object The submission
1873 function prepare_new_submission($userid, $teachermodified=false) {
1874 $submission = new stdClass();
1875 $submission->assignment
= $this->assignment
->id
;
1876 $submission->userid
= $userid;
1877 $submission->timecreated
= time();
1878 // teachers should not be modifying modified date, except offline assignments
1879 if ($teachermodified) {
1880 $submission->timemodified
= 0;
1882 $submission->timemodified
= $submission->timecreated
;
1884 $submission->numfiles
= 0;
1885 $submission->data1
= '';
1886 $submission->data2
= '';
1887 $submission->grade
= -1;
1888 $submission->submissioncomment
= '';
1889 $submission->format
= 0;
1890 $submission->teacher
= 0;
1891 $submission->timemarked
= 0;
1892 $submission->mailed
= 0;
1897 * Return all assignment submissions by ENROLLED students (even empty)
1899 * @param string $sort optional field names for the ORDER BY in the sql query
1900 * @param string $dir optional specifying the sort direction, defaults to DESC
1901 * @return array The submission objects indexed by id
1903 function get_submissions($sort='', $dir='DESC') {
1904 return assignment_get_all_submissions($this->assignment
, $sort, $dir);
1908 * Counts all complete (real) assignment submissions by enrolled students
1910 * @param int $groupid (optional) If nonzero then count is restricted to this group
1911 * @return int The number of submissions
1913 function count_real_submissions($groupid=0) {
1917 // Grab the context assocated with our course module
1918 $context = get_context_instance(CONTEXT_MODULE
, $this->cm
->id
);
1920 // Get ids of users enrolled in the given course.
1921 list($enroledsql, $params) = get_enrolled_sql($context, 'mod/assignment:view', $groupid);
1922 $params['assignmentid'] = $this->cm
->instance
;
1924 // Get ids of users enrolled in the given course.
1925 return $DB->count_records_sql("SELECT COUNT('x')
1926 FROM {assignment_submissions} s
1927 LEFT JOIN {assignment} a ON a.id = s.assignment
1928 INNER JOIN ($enroledsql) u ON u.id = s.userid
1929 WHERE s.assignment = :assignmentid AND
1930 s.timemodified > 0", $params);
1934 * Alerts teachers by email of new or changed assignments that need grading
1936 * First checks whether the option to email teachers is set for this assignment.
1937 * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1938 * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1942 * @param $submission object The submission that has changed
1945 function email_teachers($submission) {
1948 if (empty($this->assignment
->emailteachers
)) { // No need to do anything
1952 $user = $DB->get_record('user', array('id'=>$submission->userid
));
1954 if ($teachers = $this->get_graders($user)) {
1956 $strassignments = get_string('modulenameplural', 'assignment');
1957 $strassignment = get_string('modulename', 'assignment');
1958 $strsubmitted = get_string('submitted', 'assignment');
1960 foreach ($teachers as $teacher) {
1961 $info = new stdClass();
1962 $info->username
= fullname($user, true);
1963 $info->assignment
= format_string($this->assignment
->name
,true);
1964 $info->url
= $CFG->wwwroot
.'/mod/assignment/submissions.php?id='.$this->cm
->id
;
1965 $info->timeupdated
= userdate($submission->timemodified
, '%c', $teacher->timezone
);
1967 $postsubject = $strsubmitted.': '.$info->username
.' -> '.$this->assignment
->name
;
1968 $posttext = $this->email_teachers_text($info);
1969 $posthtml = ($teacher->mailformat
== 1) ?
$this->email_teachers_html($info) : '';
1971 $eventdata = new stdClass();
1972 $eventdata->modulename
= 'assignment';
1973 $eventdata->userfrom
= $user;
1974 $eventdata->userto
= $teacher;
1975 $eventdata->subject
= $postsubject;
1976 $eventdata->fullmessage
= $posttext;
1977 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
1978 $eventdata->fullmessagehtml
= $posthtml;
1979 $eventdata->smallmessage
= $postsubject;
1981 $eventdata->name
= 'assignment_updates';
1982 $eventdata->component
= 'mod_assignment';
1983 $eventdata->notification
= 1;
1984 $eventdata->contexturl
= $info->url
;
1985 $eventdata->contexturlname
= $info->assignment
;
1987 message_send($eventdata);
1995 * @param string $filearea
1996 * @param array $args
1997 * @param bool $forcedownload whether or not force download
1998 * @param array $options additional options affecting the file serving
2001 function send_file($filearea, $args, $forcedownload, array $options=array()) {
2002 debugging('plugin does not implement file sending', DEBUG_DEVELOPER
);
2007 * Returns a list of teachers that should be grading given submission
2009 * @param object $user
2012 function get_graders($user) {
2016 list($enrolledsql, $params) = get_enrolled_sql($this->context
, 'mod/assignment:grade', 0, true);
2019 JOIN ($enrolledsql) je ON je.id = u.id";
2020 $potgraders = $DB->get_records_sql($sql, $params);
2023 if (groups_get_activity_groupmode($this->cm
) == SEPARATEGROUPS
) { // Separate groups are being used
2024 if ($groups = groups_get_all_groups($this->course
->id
, $user->id
)) { // Try to find all groups
2025 foreach ($groups as $group) {
2026 foreach ($potgraders as $t) {
2027 if ($t->id
== $user->id
) {
2028 continue; // do not send self
2030 if (groups_is_member($group->id
, $t->id
)) {
2031 $graders[$t->id
] = $t;
2036 // user not in group, try to find graders without group
2037 foreach ($potgraders as $t) {
2038 if ($t->id
== $user->id
) {
2039 continue; // do not send self
2041 if (!groups_get_all_groups($this->course
->id
, $t->id
)) { //ugly hack
2042 $graders[$t->id
] = $t;
2047 foreach ($potgraders as $t) {
2048 if ($t->id
== $user->id
) {
2049 continue; // do not send self
2051 $graders[$t->id
] = $t;
2058 * Creates the text content for emails to teachers
2060 * @param $info object The info used by the 'emailteachermail' language string
2063 function email_teachers_text($info) {
2064 $posttext = format_string($this->course
->shortname
, true, array('context' => $this->coursecontext
)).' -> '.
2065 $this->strassignments
.' -> '.
2066 format_string($this->assignment
->name
, true, array('context' => $this->context
))."\n";
2067 $posttext .= '---------------------------------------------------------------------'."\n";
2068 $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
2069 $posttext .= "\n---------------------------------------------------------------------\n";
2074 * Creates the html content for emails to teachers
2076 * @param $info object The info used by the 'emailteachermailhtml' language string
2079 function email_teachers_html($info) {
2081 $posthtml = '<p><font face="sans-serif">'.
2082 '<a href="'.$CFG->wwwroot
.'/course/view.php?id='.$this->course
->id
.'">'.format_string($this->course
->shortname
, true, array('context' => $this->coursecontext
)).'</a> ->'.
2083 '<a href="'.$CFG->wwwroot
.'/mod/assignment/index.php?id='.$this->course
->id
.'">'.$this->strassignments
.'</a> ->'.
2084 '<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>';
2085 $posthtml .= '<hr /><font face="sans-serif">';
2086 $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
2087 $posthtml .= '</font><hr />';
2092 * Produces a list of links to the files uploaded by a user
2094 * @param $userid int optional id of the user. If 0 then $USER->id is used.
2095 * @param $return boolean optional defaults to false. If true the list is returned rather than printed
2096 * @return string optional
2098 function print_user_files($userid=0, $return=false) {
2099 global $CFG, $USER, $OUTPUT;
2102 if (!isloggedin()) {
2105 $userid = $USER->id
;
2110 $submission = $this->get_submission($userid);
2115 $fs = get_file_storage();
2116 $files = $fs->get_area_files($this->context
->id
, 'mod_assignment', 'submission', $submission->id
, "timemodified", false);
2117 if (!empty($files)) {
2118 require_once($CFG->dirroot
. '/mod/assignment/locallib.php');
2119 if ($CFG->enableportfolios
) {
2120 require_once($CFG->libdir
.'/portfoliolib.php');
2121 $button = new portfolio_add_button();
2123 foreach ($files as $file) {
2124 $filename = $file->get_filename();
2125 $mimetype = $file->get_mimetype();
2126 $path = file_encode_url($CFG->wwwroot
.'/pluginfile.php', '/'.$this->context
->id
.'/mod_assignment/submission/'.$submission->id
.'/'.$filename);
2127 $output .= '<a href="'.$path.'" >'.$OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon')).s($filename).'</a>';
2128 if ($CFG->enableportfolios
&& $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
, 'fileid' => $file->get_id()), '/mod/assignment/locallib.php');
2130 $button->set_format_by_file($file);
2131 $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK
);
2134 if ($CFG->enableplagiarism
) {
2135 require_once($CFG->libdir
.'/plagiarismlib.php');
2136 $output .= plagiarism_get_links(array('userid'=>$userid, 'file'=>$file, 'cmid'=>$this->cm
->id
, 'course'=>$this->course
, 'assignment'=>$this->assignment
));
2137 $output .= '<br />';
2140 if ($CFG->enableportfolios
&& count($files) > 1 && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context
)) {
2141 $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm
->id
, 'submissionid' => $submission->id
), '/mod/assignment/locallib.php');
2142 $output .= '<br />' . $button->to_html(PORTFOLIO_ADD_TEXT_LINK
);
2146 $output = '<div class="files">'.$output.'</div>';
2155 * Count the files uploaded by a given user
2157 * @param $itemid int The submission's id as the file's itemid.
2160 function count_user_files($itemid) {
2161 $fs = get_file_storage();
2162 $files = $fs->get_area_files($this->context
->id
, 'mod_assignment', 'submission', $itemid, "id", false);
2163 return count($files);
2167 * Returns true if the student is allowed to submit
2169 * Checks that the assignment has started and, if the option to prevent late
2170 * submissions is set, also checks that the assignment has not yet closed.
2175 if ($this->assignment
->preventlate
&& $this->assignment
->timedue
) {
2176 return ($this->assignment
->timeavailable
<= $time && $time <= $this->assignment
->timedue
);
2178 return ($this->assignment
->timeavailable
<= $time);
2184 * Return true if is set description is hidden till available date
2186 * This is needed by calendar so that hidden descriptions do not
2187 * come up in upcoming events.
2189 * Check that description is hidden till available date
2190 * By default return false
2191 * Assignments types should implement this method if needed
2194 function description_is_hidden() {
2199 * Return an outline of the user's interaction with the assignment
2201 * The default method prints the grade and timemodified
2202 * @param $grade object
2203 * @return object with properties ->info and ->time
2205 function user_outline($grade) {
2207 $result = new stdClass();
2208 $result->info
= get_string('grade').': '.$grade->str_long_grade
;
2209 $result->time
= $grade->dategraded
;
2214 * Print complete information about the user's interaction with the assignment
2216 * @param $user object
2218 function user_complete($user, $grade=null) {
2221 if ($submission = $this->get_submission($user->id
)) {
2223 $fs = get_file_storage();
2225 if ($files = $fs->get_area_files($this->context
->id
, 'mod_assignment', 'submission', $submission->id
, "timemodified", false)) {
2226 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
2227 foreach ($files as $file) {
2228 $countfiles .= "; ".$file->get_filename();
2232 echo $OUTPUT->box_start();
2233 echo get_string("lastmodified").": ";
2234 echo userdate($submission->timemodified
);
2235 echo $this->display_lateness($submission->timemodified
);
2237 $this->print_user_files($user->id
);
2241 $this->view_feedback($submission);
2243 echo $OUTPUT->box_end();
2247 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade
);
2248 if ($grade->str_feedback
) {
2249 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback
);
2252 print_string("notsubmittedyet", "assignment");
2257 * Return a string indicating how late a submission is
2259 * @param $timesubmitted int
2262 function display_lateness($timesubmitted) {
2263 return assignment_display_lateness($timesubmitted, $this->assignment
->timedue
);
2267 * Empty method stub for all delete actions.
2270 //nothing by default
2271 redirect('view.php?id='.$this->cm
->id
);
2275 * Empty custom feedback grading form.
2277 function custom_feedbackform($submission, $return=false) {
2278 //nothing by default
2283 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
2284 * for the course (see resource).
2286 * Given a course_module object, this function returns any "extra" information that may be needed
2287 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
2289 * @param $coursemodule object The coursemodule object (record).
2290 * @return cached_cm_info Object used to customise appearance on course page
2292 function get_coursemodule_info($coursemodule) {
2297 * Plugin cron method - do not use $this here, create new assignment instances if needed.
2301 //no plugin cron by default - override if needed
2305 * Reset all submissions
2307 function reset_userdata($data) {
2310 if (!$DB->count_records('assignment', array('course'=>$data->courseid
, 'assignmenttype'=>$this->type
))) {
2311 return array(); // no assignments of this type present
2314 $componentstr = get_string('modulenameplural', 'assignment');
2317 $typestr = get_string('type'.$this->type
, 'assignment');
2318 // ugly hack to support pluggable assignment type titles...
2319 if($typestr === '[[type'.$this->type
.']]'){
2320 $typestr = get_string('type'.$this->type
, 'assignment_'.$this->type
);
2323 if (!empty($data->reset_assignment_submissions
)) {
2324 $assignmentssql = "SELECT a.id
2326 WHERE a.course=? AND a.assignmenttype=?";
2327 $params = array($data->courseid
, $this->type
);
2329 // now get rid of all submissions and responses
2330 $fs = get_file_storage();
2331 if ($assignments = $DB->get_records_sql($assignmentssql, $params)) {
2332 foreach ($assignments as $assignmentid=>$unused) {
2333 if (!$cm = get_coursemodule_from_instance('assignment', $assignmentid)) {
2336 $context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
2337 $fs->delete_area_files($context->id
, 'mod_assignment', 'submission');
2338 $fs->delete_area_files($context->id
, 'mod_assignment', 'response');
2342 $DB->delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)", $params);
2344 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
2346 if (empty($data->reset_gradebook_grades
)) {
2347 // remove all grades from gradebook
2348 assignment_reset_gradebook($data->courseid
, $this->type
);
2352 /// updating dates - shift may be negative too
2353 if ($data->timeshift
) {
2354 shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift
, $data->courseid
);
2355 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
2362 function portfolio_exportable() {
2367 * base implementation for backing up subtype specific information
2368 * for one single module
2370 * @param filehandle $bf file handle for xml file to write to
2371 * @param mixed $preferences the complete backup preference object
2377 static function backup_one_mod($bf, $preferences, $assignment) {
2382 * base implementation for backing up subtype specific information
2383 * for one single submission
2385 * @param filehandle $bf file handle for xml file to write to
2386 * @param mixed $preferences the complete backup preference object
2387 * @param object $submission the assignment submission db record
2393 static function backup_one_submission($bf, $preferences, $assignment, $submission) {
2398 * base implementation for restoring subtype specific information
2399 * for one single module
2401 * @param array $info the array representing the xml
2402 * @param object $restore the restore preferences
2408 static function restore_one_mod($info, $restore, $assignment) {
2413 * base implementation for restoring subtype specific information
2414 * for one single submission
2416 * @param object $submission the newly created submission
2417 * @param array $info the array representing the xml
2418 * @param object $restore the restore preferences
2424 static function restore_one_submission($info, $restore, $assignment, $submission) {
2428 } ////// End of the assignment_base class
2431 class assignment_grading_form
extends moodleform
{
2432 /** @var stores the advaned grading instance (if used in grading) */
2433 private $advancegradinginstance;
2435 function definition() {
2437 $mform =& $this->_form
;
2439 if (isset($this->_customdata
->advancedgradinginstance
)) {
2440 $this->use_advanced_grading($this->_customdata
->advancedgradinginstance
);
2443 $formattr = $mform->getAttributes();
2444 $formattr['id'] = 'submitform';
2445 $mform->setAttributes($formattr);
2447 $mform->addElement('hidden', 'offset', ($this->_customdata
->offset+
1));
2448 $mform->setType('offset', PARAM_INT
);
2449 $mform->addElement('hidden', 'userid', $this->_customdata
->userid
);
2450 $mform->setType('userid', PARAM_INT
);
2451 $mform->addElement('hidden', 'nextid', $this->_customdata
->nextid
);
2452 $mform->setType('nextid', PARAM_INT
);
2453 $mform->addElement('hidden', 'id', $this->_customdata
->cm
->id
);
2454 $mform->setType('id', PARAM_INT
);
2455 $mform->addElement('hidden', 'sesskey', sesskey());
2456 $mform->setType('sesskey', PARAM_ALPHANUM
);
2457 $mform->addElement('hidden', 'mode', 'grade');
2458 $mform->setType('mode', PARAM_TEXT
);
2459 $mform->addElement('hidden', 'menuindex', "0");
2460 $mform->setType('menuindex', PARAM_INT
);
2461 $mform->addElement('hidden', 'saveuserid', "-1");
2462 $mform->setType('saveuserid', PARAM_INT
);
2463 $mform->addElement('hidden', 'filter', "0");
2464 $mform->setType('filter', PARAM_INT
);
2466 $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata
->user
),
2467 fullname($this->_customdata
->user
, true) . '<br/>' .
2468 userdate($this->_customdata
->submission
->timemodified
) .
2469 $this->_customdata
->lateness
);
2471 $this->add_submission_content();
2472 $this->add_grades_section();
2474 $this->add_feedback_section();
2476 if ($this->_customdata
->submission
->timemarked
) {
2477 $datestring = userdate($this->_customdata
->submission
->timemarked
)." (".format_time(time() - $this->_customdata
->submission
->timemarked
).")";
2478 $mform->addElement('header', 'Last Grade', get_string('lastgrade', 'assignment'));
2479 $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata
->teacher
) ,
2480 fullname($this->_customdata
->teacher
,true).
2481 '<br/>'.$datestring);
2484 $this->add_action_buttons();
2489 * Gets or sets the instance for advanced grading
2491 * @param gradingform_instance $gradinginstance
2493 public function use_advanced_grading($gradinginstance = false) {
2494 if ($gradinginstance !== false) {
2495 $this->advancegradinginstance
= $gradinginstance;
2497 return $this->advancegradinginstance
;
2501 * Add the grades configuration section to the assignment configuration form
2503 function add_grades_section() {
2505 $mform =& $this->_form
;
2506 $attributes = array();
2507 if ($this->_customdata
->gradingdisabled
) {
2508 $attributes['disabled'] ='disabled';
2511 $mform->addElement('header', 'Grades', get_string('grades', 'grades'));
2513 $grademenu = make_grades_menu($this->_customdata
->assignment
->grade
);
2514 if ($gradinginstance = $this->use_advanced_grading()) {
2515 $gradinginstance->get_controller()->set_grade_range($grademenu);
2516 $gradingelement = $mform->addElement('grading', 'advancedgrading', get_string('grade').':', array('gradinginstance' => $gradinginstance));
2517 if ($this->_customdata
->gradingdisabled
) {
2518 $gradingelement->freeze();
2520 $mform->addElement('hidden', 'advancedgradinginstanceid', $gradinginstance->get_id());
2523 // use simple direct grading
2524 $grademenu['-1'] = get_string('nograde');
2526 $mform->addElement('select', 'xgrade', get_string('grade').':', $grademenu, $attributes);
2527 $mform->setDefault('xgrade', $this->_customdata
->submission
->grade
); //@fixme some bug when element called 'grade' makes it break
2528 $mform->setType('xgrade', PARAM_INT
);
2531 if (!empty($this->_customdata
->enableoutcomes
)) {
2532 foreach($this->_customdata
->grading_info
->outcomes
as $n=>$outcome) {
2533 $options = make_grades_menu(-$outcome->scaleid
);
2534 if ($outcome->grades
[$this->_customdata
->submission
->userid
]->locked
) {
2535 $options[0] = get_string('nooutcome', 'grades');
2536 $mform->addElement('static', 'outcome_'.$n.'['.$this->_customdata
->userid
.']', $outcome->name
.':',
2537 $options[$outcome->grades
[$this->_customdata
->submission
->userid
]->grade
]);
2539 $options[''] = get_string('nooutcome', 'grades');
2540 $attributes = array('id' => 'menuoutcome_'.$n );
2541 $mform->addElement('select', 'outcome_'.$n.'['.$this->_customdata
->userid
.']', $outcome->name
.':', $options, $attributes );
2542 $mform->setType('outcome_'.$n.'['.$this->_customdata
->userid
.']', PARAM_INT
);
2543 $mform->setDefault('outcome_'.$n.'['.$this->_customdata
->userid
.']', $outcome->grades
[$this->_customdata
->submission
->userid
]->grade
);
2547 $course_context = get_context_instance(CONTEXT_MODULE
, $this->_customdata
->cm
->id
);
2548 if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
2549 $grade = '<a href="'.$CFG->wwwroot
.'/grade/report/grader/index.php?id='. $this->_customdata
->courseid
.'" >'.
2550 $this->_customdata
->grading_info
->items
[0]->grades
[$this->_customdata
->userid
]->str_grade
. '</a>';
2552 $grade = $this->_customdata
->grading_info
->items
[0]->grades
[$this->_customdata
->userid
]->str_grade
;
2554 $mform->addElement('static', 'finalgrade', get_string('currentgrade', 'assignment').':' ,$grade);
2555 $mform->setType('finalgrade', PARAM_INT
);
2560 * @global core_renderer $OUTPUT
2562 function add_feedback_section() {
2564 $mform =& $this->_form
;
2565 $mform->addElement('header', 'Feed Back', get_string('feedback', 'grades'));
2567 if ($this->_customdata
->gradingdisabled
) {
2568 $mform->addElement('static', 'disabledfeedback', $this->_customdata
->grading_info
->items
[0]->grades
[$this->_customdata
->userid
]->str_feedback
);
2572 $mform->addElement('editor', 'submissioncomment_editor', get_string('feedback', 'assignment').':', null, $this->get_editor_options() );
2573 $mform->setType('submissioncomment_editor', PARAM_RAW
); // to be cleaned before display
2574 $mform->setDefault('submissioncomment_editor', $this->_customdata
->submission
->submissioncomment
);
2575 //$mform->addRule('submissioncomment', get_string('required'), 'required', null, 'client');
2576 switch ($this->_customdata
->assignment
->assignmenttype
) {
2578 case 'uploadsingle' :
2579 $mform->addElement('filemanager', 'files_filemanager', get_string('responsefiles', 'assignment'). ':', null, $this->_customdata
->fileui_options
);
2584 $mform->addElement('hidden', 'mailinfo_h', "0");
2585 $mform->setType('mailinfo_h', PARAM_INT
);
2586 $mform->addElement('checkbox', 'mailinfo',get_string('enablenotification','assignment').
2587 $OUTPUT->help_icon('enablenotification', 'assignment') .':' );
2588 $mform->setType('mailinfo', PARAM_INT
);
2592 function add_action_buttons($cancel = true, $submitlabel = NULL) {
2593 $mform =& $this->_form
;
2594 //if there are more to be graded.
2595 if ($this->_customdata
->nextid
>0) {
2596 $buttonarray=array();
2597 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2598 //@todo: fix accessibility: javascript dependency not necessary
2599 $buttonarray[] = &$mform->createElement('submit', 'saveandnext', get_string('saveandnext'));
2600 $buttonarray[] = &$mform->createElement('submit', 'next', get_string('next'));
2601 $buttonarray[] = &$mform->createElement('cancel');
2603 $buttonarray=array();
2604 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2605 $buttonarray[] = &$mform->createElement('cancel');
2607 $mform->addGroup($buttonarray, 'grading_buttonar', '', array(' '), false);
2608 $mform->closeHeaderBefore('grading_buttonar');
2609 $mform->setType('grading_buttonar', PARAM_RAW
);
2612 function add_submission_content() {
2613 $mform =& $this->_form
;
2614 $mform->addElement('header', 'Submission', get_string('submission', 'assignment'));
2615 $mform->addElement('static', '', '' , $this->_customdata
->submission_content
);
2618 protected function get_editor_options() {
2619 $editoroptions = array();
2620 $editoroptions['component'] = 'mod_assignment';
2621 $editoroptions['filearea'] = 'feedback';
2622 $editoroptions['noclean'] = false;
2623 $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)
2624 $editoroptions['maxbytes'] = $this->_customdata
->maxbytes
;
2625 $editoroptions['context'] = $this->_customdata
->context
;
2626 return $editoroptions;
2629 public function set_data($data) {
2630 $editoroptions = $this->get_editor_options();
2631 if (!isset($data->text
)) {
2634 if (!isset($data->format
)) {
2635 $data->textformat
= FORMAT_HTML
;
2637 $data->textformat
= $data->format
;
2640 if (!empty($this->_customdata
->submission
->id
)) {
2641 $itemid = $this->_customdata
->submission
->id
;
2646 switch ($this->_customdata
->assignment
->assignmenttype
) {
2648 case 'uploadsingle' :
2649 $data = file_prepare_standard_filemanager($data, 'files', $editoroptions, $this->_customdata
->context
, 'mod_assignment', 'response', $itemid);
2655 $data = file_prepare_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata
->context
, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2656 return parent
::set_data($data);
2659 public function get_data() {
2660 $data = parent
::get_data();
2662 if (!empty($this->_customdata
->submission
->id
)) {
2663 $itemid = $this->_customdata
->submission
->id
;
2665 $itemid = null; //TODO: this is wrong, itemid MUST be known when saving files!! (skodak)
2669 $editoroptions = $this->get_editor_options();
2670 switch ($this->_customdata
->assignment
->assignmenttype
) {
2672 case 'uploadsingle' :
2673 $data = file_postupdate_standard_filemanager($data, 'files', $editoroptions, $this->_customdata
->context
, 'mod_assignment', 'response', $itemid);
2678 $data = file_postupdate_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata
->context
, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2681 if ($this->use_advanced_grading() && !isset($data->advancedgrading
)) {
2682 $data->advancedgrading
= null;
2689 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
2692 * Deletes an assignment instance
2694 * This is done by calling the delete_instance() method of the assignment type class
2696 function assignment_delete_instance($id){
2699 if (! $assignment = $DB->get_record('assignment', array('id'=>$id))) {
2703 // fall back to base class if plugin missing
2704 $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2705 if (file_exists($classfile)) {
2706 require_once($classfile);
2707 $assignmentclass = "assignment_$assignment->assignmenttype";
2710 debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
2711 $assignmentclass = "assignment_base";
2714 $ass = new $assignmentclass();
2715 return $ass->delete_instance($assignment);
2720 * Updates an assignment instance
2722 * This is done by calling the update_instance() method of the assignment type class
2724 function assignment_update_instance($assignment){
2727 $assignment->assignmenttype
= clean_param($assignment->assignmenttype
, PARAM_PLUGIN
);
2729 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2730 $assignmentclass = "assignment_$assignment->assignmenttype";
2731 $ass = new $assignmentclass();
2732 return $ass->update_instance($assignment);
2737 * Adds an assignment instance
2739 * This is done by calling the add_instance() method of the assignment type class
2741 * @param stdClass $assignment
2742 * @param mod_assignment_mod_form $mform
2743 * @return int intance id
2745 function assignment_add_instance($assignment, $mform = null) {
2748 $assignment->assignmenttype
= clean_param($assignment->assignmenttype
, PARAM_PLUGIN
);
2750 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2751 $assignmentclass = "assignment_$assignment->assignmenttype";
2752 $ass = new $assignmentclass();
2753 return $ass->add_instance($assignment);
2758 * Returns an outline of a user interaction with an assignment
2760 * This is done by calling the user_outline() method of the assignment type class
2762 function assignment_user_outline($course, $user, $mod, $assignment) {
2765 require_once("$CFG->libdir/gradelib.php");
2766 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2767 $assignmentclass = "assignment_$assignment->assignmenttype";
2768 $ass = new $assignmentclass($mod->id
, $assignment, $mod, $course);
2769 $grades = grade_get_grades($course->id
, 'mod', 'assignment', $assignment->id
, $user->id
);
2770 if (!empty($grades->items
[0]->grades
)) {
2771 return $ass->user_outline(reset($grades->items
[0]->grades
));
2778 * Prints the complete info about a user's interaction with an assignment
2780 * This is done by calling the user_complete() method of the assignment type class
2782 function assignment_user_complete($course, $user, $mod, $assignment) {
2785 require_once("$CFG->libdir/gradelib.php");
2786 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2787 $assignmentclass = "assignment_$assignment->assignmenttype";
2788 $ass = new $assignmentclass($mod->id
, $assignment, $mod, $course);
2789 $grades = grade_get_grades($course->id
, 'mod', 'assignment', $assignment->id
, $user->id
);
2790 if (empty($grades->items
[0]->grades
)) {
2793 $grade = reset($grades->items
[0]->grades
);
2795 return $ass->user_complete($user, $grade);
2799 * Function to be run periodically according to the moodle cron
2801 * Finds all assignment notifications that have yet to be mailed out, and mails them
2803 function assignment_cron () {
2804 global $CFG, $USER, $DB;
2806 /// first execute all crons in plugins
2807 if ($plugins = get_plugin_list('assignment')) {
2808 foreach ($plugins as $plugin=>$dir) {
2809 require_once("$dir/assignment.class.php");
2810 $assignmentclass = "assignment_$plugin";
2811 $ass = new $assignmentclass();
2816 /// Notices older than 1 day will not be mailed. This is to avoid the problem where
2817 /// cron has not been running for a long time, and then suddenly people are flooded
2818 /// with mail from the past few weeks or months
2821 $endtime = $timenow - $CFG->maxeditingtime
;
2822 $starttime = $endtime - 24 * 3600; /// One day earlier
2824 if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2826 $realuser = clone($USER);
2828 foreach ($submissions as $key => $submission) {
2829 $DB->set_field("assignment_submissions", "mailed", "1", array("id"=>$submission->id
));
2834 foreach ($submissions as $submission) {
2836 echo "Processing assignment submission $submission->id\n";
2838 if (! $user = $DB->get_record("user", array("id"=>$submission->userid
))) {
2839 echo "Could not find user $user->id\n";
2843 if (! $course = $DB->get_record("course", array("id"=>$submission->course
))) {
2844 echo "Could not find course $submission->course\n";
2848 /// Override the language and timezone of the "current" user, so that
2849 /// mail is customised for the receiver.
2850 cron_setup_user($user, $course);
2852 $coursecontext = get_context_instance(CONTEXT_COURSE
, $submission->course
);
2853 $courseshortname = format_string($course->shortname
, true, array('context' => $coursecontext));
2854 if (!is_enrolled($coursecontext, $user->id
)) {
2855 echo fullname($user)." not an active participant in " . $courseshortname . "\n";
2859 if (! $teacher = $DB->get_record("user", array("id"=>$submission->teacher
))) {
2860 echo "Could not find teacher $submission->teacher\n";
2864 if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment
, $course->id
)) {
2865 echo "Could not find course module for assignment id $submission->assignment\n";
2869 if (! $mod->visible
) { /// Hold mail notification for hidden assignments until later
2873 $strassignments = get_string("modulenameplural", "assignment");
2874 $strassignment = get_string("modulename", "assignment");
2876 $assignmentinfo = new stdClass();
2877 $assignmentinfo->teacher
= fullname($teacher);
2878 $assignmentinfo->assignment
= format_string($submission->name
,true);
2879 $assignmentinfo->url
= "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2881 $postsubject = "$courseshortname: $strassignments: ".format_string($submission->name
,true);
2882 $posttext = "$courseshortname -> $strassignments -> ".format_string($submission->name
,true)."\n";
2883 $posttext .= "---------------------------------------------------------------------\n";
2884 $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2885 $posttext .= "---------------------------------------------------------------------\n";
2887 if ($user->mailformat
== 1) { // HTML
2888 $posthtml = "<p><font face=\"sans-serif\">".
2889 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$courseshortname</a> ->".
2890 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2891 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name
,true)."</a></font></p>";
2892 $posthtml .= "<hr /><font face=\"sans-serif\">";
2893 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2894 $posthtml .= "</font><hr />";
2899 $eventdata = new stdClass();
2900 $eventdata->modulename
= 'assignment';
2901 $eventdata->userfrom
= $teacher;
2902 $eventdata->userto
= $user;
2903 $eventdata->subject
= $postsubject;
2904 $eventdata->fullmessage
= $posttext;
2905 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
2906 $eventdata->fullmessagehtml
= $posthtml;
2907 $eventdata->smallmessage
= get_string('assignmentmailsmall', 'assignment', $assignmentinfo);
2909 $eventdata->name
= 'assignment_updates';
2910 $eventdata->component
= 'mod_assignment';
2911 $eventdata->notification
= 1;
2912 $eventdata->contexturl
= $assignmentinfo->url
;
2913 $eventdata->contexturlname
= $assignmentinfo->assignment
;
2915 message_send($eventdata);
2925 * Return grade for given user or all users.
2927 * @param stdClass $assignment An assignment instance
2928 * @param int $userid Optional user id, 0 means all users
2929 * @return array An array of grades, false if none
2931 function assignment_get_user_grades($assignment, $userid=0) {
2935 $user = "AND u.id = :userid";
2936 $params = array('userid'=>$userid);
2940 $params['aid'] = $assignment->id
;
2942 $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2943 s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2944 FROM {user} u, {assignment_submissions} s
2945 WHERE u.id = s.userid AND s.assignment = :aid
2948 return $DB->get_records_sql($sql, $params);
2952 * Update activity grades
2955 * @param stdClass $assignment Assignment instance
2956 * @param int $userid specific user only, 0 means all
2957 * @param bool $nullifnone Not used
2959 function assignment_update_grades($assignment, $userid=0, $nullifnone=true) {
2961 require_once($CFG->libdir
.'/gradelib.php');
2963 if ($assignment->grade
== 0) {
2964 assignment_grade_item_update($assignment);
2966 } else if ($grades = assignment_get_user_grades($assignment, $userid)) {
2967 foreach($grades as $k=>$v) {
2968 if ($v->rawgrade
== -1) {
2969 $grades[$k]->rawgrade
= null;
2972 assignment_grade_item_update($assignment, $grades);
2975 assignment_grade_item_update($assignment);
2980 * Update all grades in gradebook.
2982 function assignment_upgrade_grades() {
2985 $sql = "SELECT COUNT('x')
2986 FROM {assignment} a, {course_modules} cm, {modules} m
2987 WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2988 $count = $DB->count_records_sql($sql);
2990 $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
2991 FROM {assignment} a, {course_modules} cm, {modules} m
2992 WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2993 $rs = $DB->get_recordset_sql($sql);
2995 // too much debug output
2996 $pbar = new progress_bar('assignmentupgradegrades', 500, true);
2998 foreach ($rs as $assignment) {
3000 upgrade_set_timeout(60*5); // set up timeout, may also abort execution
3001 assignment_update_grades($assignment);
3002 $pbar->update($i, $count, "Updating Assignment grades ($i/$count).");
3004 upgrade_set_timeout(); // reset to default timeout
3010 * Create grade item for given assignment
3013 * @param stdClass $assignment An assignment instance with extra cmidnumber property
3014 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
3015 * @return int 0 if ok, error code otherwise
3017 function assignment_grade_item_update($assignment, $grades=NULL) {
3019 require_once($CFG->libdir
.'/gradelib.php');
3021 if (!isset($assignment->courseid
)) {
3022 $assignment->courseid
= $assignment->course
;
3025 $params = array('itemname'=>$assignment->name
, 'idnumber'=>$assignment->cmidnumber
);
3027 if ($assignment->grade
> 0) {
3028 $params['gradetype'] = GRADE_TYPE_VALUE
;
3029 $params['grademax'] = $assignment->grade
;
3030 $params['grademin'] = 0;
3032 } else if ($assignment->grade
< 0) {
3033 $params['gradetype'] = GRADE_TYPE_SCALE
;
3034 $params['scaleid'] = -$assignment->grade
;
3037 $params['gradetype'] = GRADE_TYPE_TEXT
; // allow text comments only
3040 if ($grades === 'reset') {
3041 $params['reset'] = true;
3045 return grade_update('mod/assignment', $assignment->courseid
, 'mod', 'assignment', $assignment->id
, 0, $grades, $params);
3049 * Delete grade item for given assignment
3052 * @param object $assignment object
3053 * @return object assignment
3055 function assignment_grade_item_delete($assignment) {
3057 require_once($CFG->libdir
.'/gradelib.php');
3059 if (!isset($assignment->courseid
)) {
3060 $assignment->courseid
= $assignment->course
;
3063 return grade_update('mod/assignment', $assignment->courseid
, 'mod', 'assignment', $assignment->id
, 0, NULL, array('deleted'=>1));
3068 * Serves assignment submissions and other files.
3070 * @package mod_assignment
3072 * @param stdClass $course course object
3073 * @param stdClass $cm course module object
3074 * @param stdClass $context context object
3075 * @param string $filearea file area
3076 * @param array $args extra arguments
3077 * @param bool $forcedownload whether or not force download
3078 * @param array $options additional options affecting the file serving
3079 * @return bool false if file not found, does not return if found - just send the file
3081 function assignment_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
3084 if ($context->contextlevel
!= CONTEXT_MODULE
) {
3088 require_login($course, false, $cm);
3090 if (!$assignment = $DB->get_record('assignment', array('id'=>$cm->instance
))) {
3094 require_once($CFG->dirroot
.'/mod/assignment/type/'.$assignment->assignmenttype
.'/assignment.class.php');
3095 $assignmentclass = 'assignment_'.$assignment->assignmenttype
;
3096 $assignmentinstance = new $assignmentclass($cm->id
, $assignment, $cm, $course);
3098 return $assignmentinstance->send_file($filearea, $args, $forcedownload, $options);
3101 * Checks if a scale is being used by an assignment
3103 * This is used by the backup code to decide whether to back up a scale
3104 * @param $assignmentid int
3105 * @param $scaleid int
3106 * @return boolean True if the scale is used by the assignment
3108 function assignment_scale_used($assignmentid, $scaleid) {
3113 $rec = $DB->get_record('assignment', array('id'=>$assignmentid,'grade'=>-$scaleid));
3115 if (!empty($rec) && !empty($scaleid)) {
3123 * Checks if scale is being used by any instance of assignment
3125 * This is used to find out if scale used anywhere
3126 * @param $scaleid int
3127 * @return boolean True if the scale is used by any assignment
3129 function assignment_scale_used_anywhere($scaleid) {
3132 if ($scaleid and $DB->record_exists('assignment', array('grade'=>-$scaleid))) {
3140 * Make sure up-to-date events are created for all assignment instances
3142 * This standard function will check all instances of this module
3143 * and make sure there are up-to-date events created for each of them.
3144 * If courseid = 0, then every assignment event in the site is checked, else
3145 * only assignment events belonging to the course specified are checked.
3146 * This function is used, in its new format, by restore_refresh_events()
3148 * @param $courseid int optional If zero then all assignments for all courses are covered
3149 * @return boolean Always returns true
3151 function assignment_refresh_events($courseid = 0) {
3154 if ($courseid == 0) {
3155 if (! $assignments = $DB->get_records("assignment")) {
3159 if (! $assignments = $DB->get_records("assignment", array("course"=>$courseid))) {
3163 $moduleid = $DB->get_field('modules', 'id', array('name'=>'assignment'));
3165 foreach ($assignments as $assignment) {
3166 $cm = get_coursemodule_from_id('assignment', $assignment->id
);
3167 $event = new stdClass();
3168 $event->name
= $assignment->name
;
3169 $event->description
= format_module_intro('assignment', $assignment, $cm->id
);
3170 $event->timestart
= $assignment->timedue
;
3172 if ($event->id
= $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id
))) {
3173 update_event($event);
3176 $event->courseid
= $assignment->course
;
3177 $event->groupid
= 0;
3179 $event->modulename
= 'assignment';
3180 $event->instance
= $assignment->id
;
3181 $event->eventtype
= 'due';
3182 $event->timeduration
= 0;
3183 $event->visible
= $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$assignment->id
));
3192 * Print recent activity from all assignments in a given course
3194 * This is used by the recent activity block
3196 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
3197 global $CFG, $USER, $DB, $OUTPUT;
3199 // do not use log table if possible, it may be huge
3201 if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
3202 u.firstname, u.lastname, u.email, u.picture
3203 FROM {assignment_submissions} asb
3204 JOIN {assignment} a ON a.id = asb.assignment
3205 JOIN {course_modules} cm ON cm.instance = a.id
3206 JOIN {modules} md ON md.id = cm.module
3207 JOIN {user} u ON u.id = asb.userid
3208 WHERE asb.timemodified > ? AND
3210 md.name = 'assignment'
3211 ORDER BY asb.timemodified ASC", array($timestart, $course->id
))) {
3215 $modinfo = get_fast_modinfo($course); // reference needed because we might load the groups
3219 foreach($submissions as $submission) {
3220 if (!array_key_exists($submission->cmid
, $modinfo->cms
)) {
3223 $cm = $modinfo->cms
[$submission->cmid
];
3224 if (!$cm->uservisible
) {
3227 if ($submission->userid
== $USER->id
) {
3228 $show[] = $submission;
3232 // the act of sumbitting of assignment may be considered private - only graders will see it if specified
3233 if (empty($CFG->assignment_showrecentsubmissions
)) {
3234 if (!array_key_exists($cm->id
, $grader)) {
3235 $grader[$cm->id
] = has_capability('moodle/grade:viewall', get_context_instance(CONTEXT_MODULE
, $cm->id
));
3237 if (!$grader[$cm->id
]) {
3242 $groupmode = groups_get_activity_groupmode($cm, $course);
3244 if ($groupmode == SEPARATEGROUPS
and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE
, $cm->id
))) {
3245 if (isguestuser()) {
3246 // shortcut - guest user does not belong into any group
3250 if (is_null($modinfo->groups
)) {
3251 $modinfo->groups
= groups_get_user_groups($course->id
); // load all my groups and cache it in modinfo
3254 // this will be slow - show only users that share group with me in this cm
3255 if (empty($modinfo->groups
[$cm->id
])) {
3258 $usersgroups = groups_get_all_groups($course->id
, $submission->userid
, $cm->groupingid
);
3259 if (is_array($usersgroups)) {
3260 $usersgroups = array_keys($usersgroups);
3261 $intersect = array_intersect($usersgroups, $modinfo->groups
[$cm->id
]);
3262 if (empty($intersect)) {
3267 $show[] = $submission;
3274 echo $OUTPUT->heading(get_string('newsubmissions', 'assignment').':', 3);
3276 foreach ($show as $submission) {
3277 $cm = $modinfo->cms
[$submission->cmid
];
3278 $link = $CFG->wwwroot
.'/mod/assignment/view.php?id='.$cm->id
;
3279 print_recent_activity_note($submission->timemodified
, $submission, $cm->name
, $link, false, $viewfullnames);
3287 * Returns all assignments since a given time in specified forum.
3289 function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0) {
3290 global $CFG, $COURSE, $USER, $DB;
3292 if ($COURSE->id
== $courseid) {
3295 $course = $DB->get_record('course', array('id'=>$courseid));
3298 $modinfo = get_fast_modinfo($course);
3300 $cm = $modinfo->cms
[$cmid];
3304 $userselect = "AND u.id = :userid";
3305 $params['userid'] = $userid;
3311 $groupselect = "AND gm.groupid = :groupid";
3312 $groupjoin = "JOIN {groups_members} gm ON gm.userid=u.id";
3313 $params['groupid'] = $groupid;
3319 $params['cminstance'] = $cm->instance
;
3320 $params['timestart'] = $timestart;
3322 $userfields = user_picture
::fields('u', null, 'userid');
3324 if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified,
3326 FROM {assignment_submissions} asb
3327 JOIN {assignment} a ON a.id = asb.assignment
3328 JOIN {user} u ON u.id = asb.userid
3330 WHERE asb.timemodified > :timestart AND a.id = :cminstance
3331 $userselect $groupselect
3332 ORDER BY asb.timemodified ASC", $params)) {
3336 $groupmode = groups_get_activity_groupmode($cm, $course);
3337 $cm_context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
3338 $grader = has_capability('moodle/grade:viewall', $cm_context);
3339 $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
3340 $viewfullnames = has_capability('moodle/site:viewfullnames', $cm_context);
3342 if (is_null($modinfo->groups
)) {
3343 $modinfo->groups
= groups_get_user_groups($course->id
); // load all my groups and cache it in modinfo
3348 foreach($submissions as $submission) {
3349 if ($submission->userid
== $USER->id
) {
3350 $show[] = $submission;
3353 // the act of submitting of assignment may be considered private - only graders will see it if specified
3354 if (empty($CFG->assignment_showrecentsubmissions
)) {
3360 if ($groupmode == SEPARATEGROUPS
and !$accessallgroups) {
3361 if (isguestuser()) {
3362 // shortcut - guest user does not belong into any group
3366 // this will be slow - show only users that share group with me in this cm
3367 if (empty($modinfo->groups
[$cm->id
])) {
3370 $usersgroups = groups_get_all_groups($course->id
, $cm->userid
, $cm->groupingid
);
3371 if (is_array($usersgroups)) {
3372 $usersgroups = array_keys($usersgroups);
3373 $intersect = array_intersect($usersgroups, $modinfo->groups
[$cm->id
]);
3374 if (empty($intersect)) {
3379 $show[] = $submission;
3387 require_once($CFG->libdir
.'/gradelib.php');
3389 foreach ($show as $id=>$submission) {
3390 $userids[] = $submission->userid
;
3393 $grades = grade_get_grades($courseid, 'mod', 'assignment', $cm->instance
, $userids);
3396 $aname = format_string($cm->name
,true);
3397 foreach ($show as $submission) {
3398 $tmpactivity = new stdClass();
3400 $tmpactivity->type
= 'assignment';
3401 $tmpactivity->cmid
= $cm->id
;
3402 $tmpactivity->name
= $aname;
3403 $tmpactivity->sectionnum
= $cm->sectionnum
;
3404 $tmpactivity->timestamp
= $submission->timemodified
;
3407 $tmpactivity->grade
= $grades->items
[0]->grades
[$submission->userid
]->str_long_grade
;
3410 $userfields = explode(',', user_picture
::fields());
3411 foreach ($userfields as $userfield) {
3412 if ($userfield == 'id') {
3413 $tmpactivity->user
->{$userfield} = $submission->userid
; // aliased in SQL above
3415 $tmpactivity->user
->{$userfield} = $submission->{$userfield};
3418 $tmpactivity->user
->fullname
= fullname($submission, $viewfullnames);
3420 $activities[$index++
] = $tmpactivity;
3427 * Print recent activity from all assignments in a given course
3429 * This is used by course/recent.php
3431 function assignment_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
3432 global $CFG, $OUTPUT;
3434 echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
3436 echo "<tr><td class=\"userpicture\" valign=\"top\">";
3437 echo $OUTPUT->user_picture($activity->user
);
3441 $modname = $modnames[$activity->type
];
3442 echo '<div class="title">';
3443 echo "<img src=\"" . $OUTPUT->pix_url('icon', 'assignment') . "\" ".
3444 "class=\"icon\" alt=\"$modname\">";
3445 echo "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id={$activity->cmid}\">{$activity->name}</a>";
3449 if (isset($activity->grade
)) {
3450 echo '<div class="grade">';
3451 echo get_string('grade').': ';
3452 echo $activity->grade
;
3456 echo '<div class="user">';
3457 echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->id}&course=$courseid\">"
3458 ."{$activity->user->fullname}</a> - ".userdate($activity->timestamp
);
3461 echo "</td></tr></table>";
3464 /// GENERIC SQL FUNCTIONS
3467 * Fetch info from logs
3469 * @param $log object with properties ->info (the assignment id) and ->userid
3470 * @return array with assignment name and user firstname and lastname
3472 function assignment_log_info($log) {
3475 return $DB->get_record_sql("SELECT a.name, u.firstname, u.lastname
3476 FROM {assignment} a, {user} u
3477 WHERE a.id = ? AND u.id = ?", array($log->info
, $log->userid
));
3481 * Return list of marked submissions that have not been mailed out for currently enrolled students
3485 function assignment_get_unmailed_submissions($starttime, $endtime) {
3488 return $DB->get_records_sql("SELECT s.*, a.course, a.name
3489 FROM {assignment_submissions} s,
3492 AND s.timemarked <= ?
3493 AND s.timemarked >= ?
3494 AND s.assignment = a.id", array($endtime, $starttime));
3498 * Counts all complete (real) assignment submissions by enrolled students for the given course modeule.
3500 * @deprecated Since Moodle 2.2 MDL-abc - Please do not use this function any more.
3501 * @param cm_info $cm The course module that we wish to perform the count on.
3502 * @param int $groupid (optional) If nonzero then count is restricted to this group
3503 * @return int The number of submissions
3505 function assignment_count_real_submissions($cm, $groupid=0) {
3508 // Grab the assignment type for the given course module
3509 $assignmenttype = $DB->get_field($cm->modname
, 'assignmenttype', array('id' => $cm->instance
), MUST_EXIST
);
3511 // Create the expected class file path and class name for the returned assignemnt type
3512 $filename = "{$CFG->dirroot}/mod/assignment/type/{$assignmenttype}/assignment.class.php";
3513 $classname = "assignment_{$assignmenttype}";
3515 // If the file exists and the class is not already loaded we require the class file
3516 if (file_exists($filename) && !class_exists($classname)) {
3517 require_once($filename);
3519 // If the required class is still not loaded then we revert to assignment base
3520 if (!class_exists($classname)) {
3521 $classname = 'assignment_base';
3523 $instance = new $classname;
3525 // Attach the course module to the assignment type instance and then call the method for counting submissions
3526 $instance->cm
= $cm;
3527 return $instance->count_real_submissions($groupid);
3531 * Return all assignment submissions by ENROLLED students (even empty)
3533 * There are also assignment type methods get_submissions() wich in the default
3534 * implementation simply call this function.
3535 * @param $sort string optional field names for the ORDER BY in the sql query
3536 * @param $dir string optional specifying the sort direction, defaults to DESC
3537 * @return array The submission objects indexed by id
3539 function assignment_get_all_submissions($assignment, $sort="", $dir="DESC") {
3540 /// Return all assignment submissions by ENROLLED students (even empty)
3543 if ($sort == "lastname" or $sort == "firstname") {
3544 $sort = "u.$sort $dir";
3545 } else if (empty($sort)) {
3546 $sort = "a.timemodified DESC";
3548 $sort = "a.$sort $dir";
3551 /* not sure this is needed at all since assignment already has a course define, so this join?
3552 $select = "s.course = '$assignment->course' AND";
3553 if ($assignment->course == SITEID) {
3556 $cm = get_coursemodule_from_instance('assignment', $assignment->id
, $assignment->course
);
3557 $context = context_module
::instance($cm->id
);
3558 list($enroledsql, $params) = get_enrolled_sql($context, 'mod/assignment:submit');
3559 $params['assignmentid'] = $assignment->id
;
3560 return $DB->get_records_sql("SELECT a.*
3561 FROM {assignment_submissions} a
3562 INNER JOIN (". $enroledsql .") u ON u.id = a.userid
3563 WHERE u.id = a.userid
3564 AND a.assignment = :assignmentid
3565 ORDER BY $sort", $params);
3570 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
3571 * for the course (see resource).
3573 * Given a course_module object, this function returns any "extra" information that may be needed
3574 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
3576 * @param $coursemodule object The coursemodule object (record).
3577 * @return cached_cm_info An object on information that the courses will know about (most noticeably, an icon).
3579 function assignment_get_coursemodule_info($coursemodule) {
3582 if (! $assignment = $DB->get_record('assignment', array('id'=>$coursemodule->instance
),
3583 'id, assignmenttype, name, intro, introformat')) {
3587 $libfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
3589 if (file_exists($libfile)) {
3590 require_once($libfile);
3591 $assignmentclass = "assignment_$assignment->assignmenttype";
3592 $ass = new $assignmentclass('staticonly');
3593 if (!($result = $ass->get_coursemodule_info($coursemodule))) {
3594 $result = new cached_cm_info();
3595 $result->name
= $assignment->name
;
3597 if ($coursemodule->showdescription
) {
3598 // Convert intro to html. Do not filter cached version, filters run at display time.
3599 $result->content
= format_module_intro('assignment', $assignment, $coursemodule->id
, false);
3603 debugging('Incorrect assignment type: '.$assignment->assignmenttype
);
3610 /// OTHER GENERAL FUNCTIONS FOR ASSIGNMENTS ///////////////////////////////////////
3613 * Returns an array of installed assignment types indexed and sorted by name
3615 * @return array The index is the name of the assignment type, the value its full name from the language strings
3617 function assignment_types() {
3619 $names = get_plugin_list('assignment');
3620 foreach ($names as $name=>$dir) {
3621 $types[$name] = get_string('type'.$name, 'assignment');
3623 // ugly hack to support pluggable assignment type titles..
3624 if ($types[$name] == '[[type'.$name.']]') {
3625 $types[$name] = get_string('type'.$name, 'assignment_'.$name);
3632 function assignment_print_overview($courses, &$htmlarray) {
3633 global $USER, $CFG, $DB;
3634 require_once($CFG->libdir
.'/gradelib.php');
3636 if (empty($courses) ||
!is_array($courses) ||
count($courses) == 0) {
3640 if (!$assignments = get_all_instances_in_courses('assignment',$courses)) {
3644 $assignmentids = array();
3646 // Do assignment_base::isopen() here without loading the whole thing for speed
3647 foreach ($assignments as $key => $assignment) {
3649 if ($assignment->timedue
) {
3650 if ($assignment->preventlate
) {
3651 $isopen = ($assignment->timeavailable
<= $time && $time <= $assignment->timedue
);
3653 $isopen = ($assignment->timeavailable
<= $time);
3656 if (empty($isopen) ||
empty($assignment->timedue
)) {
3657 unset($assignments[$key]);
3659 $assignmentids[] = $assignment->id
;
3663 if (empty($assignmentids)){
3664 // no assignments to look at - we're done
3668 $strduedate = get_string('duedate', 'assignment');
3669 $strduedateno = get_string('duedateno', 'assignment');
3670 $strgraded = get_string('graded', 'assignment');
3671 $strnotgradedyet = get_string('notgradedyet', 'assignment');
3672 $strnotsubmittedyet = get_string('notsubmittedyet', 'assignment');
3673 $strsubmitted = get_string('submitted', 'assignment');
3674 $strassignment = get_string('modulename', 'assignment');
3675 $strreviewed = get_string('reviewed','assignment');
3678 // NOTE: we do all possible database work here *outside* of the loop to ensure this scales
3680 list($sqlassignmentids, $assignmentidparams) = $DB->get_in_or_equal($assignmentids);
3682 // build up and array of unmarked submissions indexed by assignment id/ userid
3683 // for use where the user has grading rights on assignment
3684 $rs = $DB->get_recordset_sql("SELECT id, assignment, userid
3685 FROM {assignment_submissions}
3686 WHERE teacher = 0 AND timemarked = 0
3687 AND assignment $sqlassignmentids", $assignmentidparams);
3689 $unmarkedsubmissions = array();
3690 foreach ($rs as $rd) {
3691 $unmarkedsubmissions[$rd->assignment
][$rd->userid
] = $rd->id
;
3696 // get all user submissions, indexed by assignment id
3697 $mysubmissions = $DB->get_records_sql("SELECT assignment, timemarked, teacher, grade
3698 FROM {assignment_submissions}
3699 WHERE userid = ? AND
3700 assignment $sqlassignmentids", array_merge(array($USER->id
), $assignmentidparams));
3702 foreach ($assignments as $assignment) {
3703 $grading_info = grade_get_grades($assignment->course
, 'mod', 'assignment', $assignment->id
, $USER->id
);
3704 $final_grade = $grading_info->items
[0]->grades
[$USER->id
];
3706 $str = '<div class="assignment overview"><div class="name">'.$strassignment. ': '.
3707 '<a '.($assignment->visible ?
'':' class="dimmed"').
3708 'title="'.$strassignment.'" href="'.$CFG->wwwroot
.
3709 '/mod/assignment/view.php?id='.$assignment->coursemodule
.'">'.
3710 $assignment->name
.'</a></div>';
3711 if ($assignment->timedue
) {
3712 $str .= '<div class="info">'.$strduedate.': '.userdate($assignment->timedue
).'</div>';
3714 $str .= '<div class="info">'.$strduedateno.'</div>';
3716 $context = get_context_instance(CONTEXT_MODULE
, $assignment->coursemodule
);
3717 if (has_capability('mod/assignment:grade', $context)) {
3719 // count how many people can submit
3720 $submissions = 0; // init
3721 if ($students = get_enrolled_users($context, 'mod/assignment:view', 0, 'u.id')) {
3722 foreach ($students as $student) {
3723 if (isset($unmarkedsubmissions[$assignment->id
][$student->id
])) {
3730 $link = new moodle_url('/mod/assignment/submissions.php', array('id'=>$assignment->coursemodule
));
3731 $str .= '<div class="details"><a href="'.$link.'">'.get_string('submissionsnotgraded', 'assignment', $submissions).'</a></div>';
3734 $str .= '<div class="details">';
3735 if (isset($mysubmissions[$assignment->id
])) {
3737 $submission = $mysubmissions[$assignment->id
];
3739 if ($submission->teacher
== 0 && $submission->timemarked
== 0 && !$final_grade->grade
) {
3740 $str .= $strsubmitted . ', ' . $strnotgradedyet;
3741 } else if ($submission->grade
<= 0 && !$final_grade->grade
) {
3742 $str .= $strsubmitted . ', ' . $strreviewed;
3744 $str .= $strsubmitted . ', ' . $strgraded;
3747 $str .= $strnotsubmittedyet . ' ' . assignment_display_lateness(time(), $assignment->timedue
);
3752 if (empty($htmlarray[$assignment->course
]['assignment'])) {
3753 $htmlarray[$assignment->course
]['assignment'] = $str;
3755 $htmlarray[$assignment->course
]['assignment'] .= $str;
3760 function assignment_display_lateness($timesubmitted, $timedue) {
3764 $time = $timedue - $timesubmitted;
3766 $timetext = get_string('late', 'assignment', format_time($time));
3767 return ' (<span class="late">'.$timetext.'</span>)';
3769 $timetext = get_string('early', 'assignment', format_time($time));
3770 return ' (<span class="early">'.$timetext.'</span>)';
3774 function assignment_get_view_actions() {
3775 return array('view');
3778 function assignment_get_post_actions() {
3779 return array('upload');
3782 function assignment_get_types() {
3786 $type = new stdClass();
3787 $type->modclass
= MOD_CLASS_ACTIVITY
;
3788 $type->type
= "assignment_group_start";
3789 $type->typestr
= '--'.get_string('modulenameplural', 'assignment');
3792 $standardassignments = array('upload','online','uploadsingle','offline');
3793 foreach ($standardassignments as $assignmenttype) {
3794 $type = new stdClass();
3795 $type->modclass
= MOD_CLASS_ACTIVITY
;
3796 $type->type
= "assignment&type=$assignmenttype";
3797 $type->typestr
= get_string("type$assignmenttype", 'assignment');
3801 /// Drop-in extra assignment types
3802 $assignmenttypes = get_list_of_plugins('mod/assignment/type');
3803 foreach ($assignmenttypes as $assignmenttype) {
3804 if (!empty($CFG->{'assignment_hide_'.$assignmenttype})) { // Not wanted
3807 if (!in_array($assignmenttype, $standardassignments)) {
3808 $type = new stdClass();
3809 $type->modclass
= MOD_CLASS_ACTIVITY
;
3810 $type->type
= "assignment&type=$assignmenttype";
3811 $type->typestr
= get_string("type$assignmenttype", 'assignment_'.$assignmenttype);
3816 $type = new stdClass();
3817 $type->modclass
= MOD_CLASS_ACTIVITY
;
3818 $type->type
= "assignment_group_end";
3819 $type->typestr
= '--';
3826 * Removes all grades from gradebook
3828 * @param int $courseid The ID of the course to reset
3829 * @param string $type Optional type of assignment to limit the reset to a particular assignment type
3831 function assignment_reset_gradebook($courseid, $type='') {
3834 $params = array('courseid'=>$courseid);
3836 $type = "AND a.assignmenttype= :type";
3837 $params['type'] = $type;
3840 $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
3841 FROM {assignment} a, {course_modules} cm, {modules} m
3842 WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id AND a.course=:courseid $type";
3844 if ($assignments = $DB->get_records_sql($sql, $params)) {
3845 foreach ($assignments as $assignment) {
3846 assignment_grade_item_update($assignment, 'reset');
3852 * This function is used by the reset_course_userdata function in moodlelib.
3853 * This function will remove all posts from the specified assignment
3854 * and clean up any related data.
3855 * @param $data the data submitted from the reset course.
3856 * @return array status array
3858 function assignment_reset_userdata($data) {
3862 foreach (get_plugin_list('assignment') as $type=>$dir) {
3863 require_once("$dir/assignment.class.php");
3864 $assignmentclass = "assignment_$type";
3865 $ass = new $assignmentclass();
3866 $status = array_merge($status, $ass->reset_userdata($data));
3873 * Implementation of the function for printing the form elements that control
3874 * whether the course reset functionality affects the assignment.
3875 * @param $mform form passed by reference
3877 function assignment_reset_course_form_definition(&$mform) {
3878 $mform->addElement('header', 'assignmentheader', get_string('modulenameplural', 'assignment'));
3879 $mform->addElement('advcheckbox', 'reset_assignment_submissions', get_string('deleteallsubmissions','assignment'));
3883 * Course reset form defaults.
3885 function assignment_reset_course_form_defaults($course) {
3886 return array('reset_assignment_submissions'=>1);
3890 * Returns all other caps used in module
3892 function assignment_get_extra_capabilities() {
3893 return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames', 'moodle/grade:managegradingforms');
3897 * @param string $feature FEATURE_xx constant for requested feature
3898 * @return mixed True if module supports feature, null if doesn't know
3900 function assignment_supports($feature) {
3902 case FEATURE_GROUPS
: return true;
3903 case FEATURE_GROUPINGS
: return true;
3904 case FEATURE_GROUPMEMBERSONLY
: return true;
3905 case FEATURE_MOD_INTRO
: return true;
3906 case FEATURE_COMPLETION_TRACKS_VIEWS
: return true;
3907 case FEATURE_GRADE_HAS_GRADE
: return true;
3908 case FEATURE_GRADE_OUTCOMES
: return true;
3909 case FEATURE_GRADE_HAS_GRADE
: return true;
3910 case FEATURE_BACKUP_MOODLE2
: return true;
3911 case FEATURE_SHOW_DESCRIPTION
: return true;
3912 case FEATURE_ADVANCED_GRADING
: return true;
3914 default: return null;
3919 * Adds module specific settings to the settings block
3921 * @param settings_navigation $settings The settings navigation object
3922 * @param navigation_node $assignmentnode The node to add module settings to
3924 function assignment_extend_settings_navigation(settings_navigation
$settings, navigation_node
$assignmentnode) {
3925 global $PAGE, $DB, $USER, $CFG;
3927 $assignmentrow = $DB->get_record("assignment", array("id" => $PAGE->cm
->instance
));
3928 require_once "$CFG->dirroot/mod/assignment/type/$assignmentrow->assignmenttype/assignment.class.php";
3930 $assignmentclass = 'assignment_'.$assignmentrow->assignmenttype
;
3931 $assignmentinstance = new $assignmentclass($PAGE->cm
->id
, $assignmentrow, $PAGE->cm
, $PAGE->course
);
3935 // Add assignment submission information
3936 if (has_capability('mod/assignment:grade', $PAGE->cm
->context
)) {
3937 if ($allgroups && has_capability('moodle/site:accessallgroups', $PAGE->cm
->context
)) {
3940 $group = groups_get_activity_group($PAGE->cm
);
3942 $link = new moodle_url('/mod/assignment/submissions.php', array('id'=>$PAGE->cm
->id
));
3943 if ($assignmentrow->assignmenttype
== 'offline') {
3944 $string = get_string('viewfeedback', 'assignment');
3945 } else if ($count = $assignmentinstance->count_real_submissions($group)) {
3946 $string = get_string('viewsubmissions', 'assignment', $count);
3948 $string = get_string('noattempts', 'assignment');
3950 $assignmentnode->add($string, $link, navigation_node
::TYPE_SETTING
);
3953 if (is_object($assignmentinstance) && method_exists($assignmentinstance, 'extend_settings_navigation')) {
3954 $assignmentinstance->extend_settings_navigation($assignmentnode);
3959 * generate zip file from array of given files
3960 * @param array $filesforzipping - array of files to pass into archive_to_pathname
3961 * @return path of temp file - note this returned file does not have a .zip extension - it is a temp file.
3963 function assignment_pack_files($filesforzipping) {
3965 //create path for new zip file.
3966 $tempzip = tempnam($CFG->tempdir
.'/', 'assignment_');
3968 $zipper = new zip_packer();
3969 if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
3976 * Lists all file areas current user may browse
3978 * @package mod_assignment
3980 * @param stdClass $course course object
3981 * @param stdClass $cm course module object
3982 * @param stdClass $context context object
3983 * @return array available file areas
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 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'));