fabb44d66d3c5508684312573e4d4e46fc27c7a6
[moodle.git] / mod / assignment / lib.php
1 <?PHP
3 // This file is part of Moodle - http://moodle.org/
4 //
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.
9 //
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.
14 //
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/>.
18 /**
19  * assignment_base is the base class for assignment types
20  *
21  * This class provides all the functionality for an assignment
22  *
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
26  */
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);
40 /**
41  * Standard base class for all assignment submodules (assignment types).
42  *
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
46  */
47 class assignment_base {
49     const FILTER_ALL             = 0;
50     const FILTER_SUBMITTED       = 1;
51     const FILTER_REQUIRE_GRADING = 2;
53     /** @var object */
54     var $cm;
55     /** @var object */
56     var $course;
57     /** @var stdClass */
58     var $coursecontext;
59     /** @var object */
60     var $assignment;
61     /** @var string */
62     var $strassignment;
63     /** @var string */
64     var $strassignments;
65     /** @var string */
66     var $strsubmissions;
67     /** @var string */
68     var $strlastmodified;
69     /** @var string */
70     var $pagetitle;
71     /** @var bool */
72     var $usehtmleditor;
73     /**
74      * @todo document this var
75      */
76     var $defaultformat;
77     /**
78      * @todo document this var
79      */
80     var $context;
81     /** @var string */
82     var $type;
84     /**
85      * Constructor for the base assignment class
86      *
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.
91      *
92      * @global object
93      * @global object
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
98      */
99     function assignment_base($cmid='staticonly', $assignment=NULL, $cm=NULL, $course=NULL) {
100         global $COURSE, $DB;
102         if ($cmid == 'staticonly') {
103             //use static functions only!
104             return;
105         }
107         global $CFG;
109         if ($cm) {
110             $this->cm = $cm;
111         } else if (! $this->cm = get_coursemodule_from_id('assignment', $cmid)) {
112             print_error('invalidcoursemodule');
113         }
115         $this->context = get_context_instance(CONTEXT_MODULE, $this->cm->id);
117         if ($course) {
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');
123         }
124         $this->coursecontext = get_context_instance(CONTEXT_COURSE, $this->course->id);
125         $courseshortname = format_text($this->course->shortname, true, array('context' => $this->coursecontext));
127         if ($assignment) {
128             $this->assignment = $assignment;
129         } else if (! $this->assignment = $DB->get_record('assignment', array('id'=>$this->cm->instance))) {
130             print_error('invalidid', 'assignment');
131         }
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();
147     }
149     /**
150      * Display the assignment, used by view.php
151      *
152      * This in turn calls the methods producing individual parts of the page
153      */
154     function view() {
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();
164         $this->view_intro();
166         $this->view_dates();
168         $this->view_feedback();
170         $this->view_footer();
171     }
173     /**
174      * Display the header and top of a page
175      *
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
180      *
181      * @global object
182      * @param string $subpage Description of subpage to be used in navigation trail
183      */
184     function view_header($subpage='') {
185         global $CFG, $PAGE, $OUTPUT;
187         if ($subpage) {
188             $PAGE->navbar->add($subpage);
189         }
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     }
203     /**
204      * Display the assignment intro
205      *
206      * This will most likely be extended by assignment type plug-ins
207      * The default implementation prints the assignment description in a box
208      */
209     function view_intro() {
210         global $OUTPUT;
211         echo $OUTPUT->box_start('generalbox boxaligncenter', 'intro');
212         echo format_module_intro('assignment', $this->assignment, $this->cm->id);
213         echo $OUTPUT->box_end();
214         plagiarism_print_disclosure($this->cm->id);
215     }
217     /**
218      * Display the assignment dates
219      *
220      * Prints the assignment start and end dates in a box.
221      * This will be suitable for most assignment types
222      */
223     function view_dates() {
224         global $OUTPUT;
225         if (!$this->assignment->timeavailable && !$this->assignment->timedue) {
226             return;
227         }
229         echo $OUTPUT->box_start('generalbox boxaligncenter', 'dates');
230         echo '<table>';
231         if ($this->assignment->timeavailable) {
232             echo '<tr><td class="c0">'.get_string('availabledate','assignment').':</td>';
233             echo '    <td class="c1">'.userdate($this->assignment->timeavailable).'</td></tr>';
234         }
235         if ($this->assignment->timedue) {
236             echo '<tr><td class="c0">'.get_string('duedate','assignment').':</td>';
237             echo '    <td class="c1">'.userdate($this->assignment->timedue).'</td></tr>';
238         }
239         echo '</table>';
240         echo $OUTPUT->box_end();
241     }
244     /**
245      * Display the bottom and footer of a page
246      *
247      * This default method just prints the footer.
248      * This will be suitable for most assignment types
249      */
250     function view_footer() {
251         global $OUTPUT;
252         echo $OUTPUT->footer();
253     }
255     /**
256      * Display the feedback to the student
257      *
258      * This default method prints the teacher picture and name, date when marked,
259      * grade and teacher submissioncomment.
260      * If advanced grading is used the method render_grade from the
261      * advanced grading controller is called to display the grade.
262      *
263      * @global object
264      * @global object
265      * @global object
266      * @param object $submission The submission object or NULL in which case it will be loaded
267      */
268     function view_feedback($submission=NULL) {
269         global $USER, $CFG, $DB, $OUTPUT, $PAGE;
270         require_once($CFG->libdir.'/gradelib.php');
271         require_once("$CFG->dirroot/grade/grading/lib.php");
273         if (!$submission) { /// Get submission for this assignment
274             $userid = $USER->id;
275             $submission = $this->get_submission($userid);
276         } else {
277             $userid = $submission->userid;
278         }
279         // Check the user can submit
280         $canviewfeedback = ($userid == $USER->id && has_capability('mod/assignment:submit', $this->context, $USER->id, false));
281         // If not then check if the user still has the view cap and has a previous submission
282         $canviewfeedback = $canviewfeedback || (!empty($submission) && $submission->userid == $USER->id && has_capability('mod/assignment:view', $this->context));
283         // Or if user can grade (is a teacher or admin)
284         $canviewfeedback = $canviewfeedback || has_capability('mod/assignment:grade', $this->context);
286         if (!$canviewfeedback) {
287             // can not view or submit assignments -> no feedback
288             return;
289         }
291         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
292         $item = $grading_info->items[0];
293         $grade = $item->grades[$userid];
295         if ($grade->hidden or $grade->grade === false) { // hidden or error
296             return;
297         }
299         if ($grade->grade === null and empty($grade->str_feedback)) {   /// Nothing to show yet
300             return;
301         }
303         $graded_date = $grade->dategraded;
304         $graded_by   = $grade->usermodified;
306     /// We need the teacher info
307         if (!$teacher = $DB->get_record('user', array('id'=>$graded_by))) {
308             print_error('cannotfindteacher');
309         }
311     /// Print the feedback
312         echo $OUTPUT->heading(get_string('feedbackfromteacher', 'assignment', fullname($teacher)));
314         echo '<table cellspacing="0" class="feedback">';
316         echo '<tr>';
317         echo '<td class="left picture">';
318         if ($teacher) {
319             echo $OUTPUT->user_picture($teacher);
320         }
321         echo '</td>';
322         echo '<td class="topic">';
323         echo '<div class="from">';
324         if ($teacher) {
325             echo '<div class="fullname">'.fullname($teacher).'</div>';
326         }
327         echo '<div class="time">'.userdate($graded_date).'</div>';
328         echo '</div>';
329         echo '</td>';
330         echo '</tr>';
332         echo '<tr>';
333         echo '<td class="left side">&nbsp;</td>';
334         echo '<td class="content">';
335         $grade_str = '<div class="grade">'. get_string("grade").': '.$grade->str_long_grade. '</div>';
336         if (!empty($submission) && $controller = get_grading_manager($this->context, 'mod_assignment', 'submission')->get_active_controller()) {
337             $controller->set_grade_range(make_grades_menu($this->assignment->grade));
338             echo $controller->render_grade($PAGE, $submission->id, $item, $grade_str, has_capability('mod/assignment:grade', $this->context));
339         } else {
340             echo $grade_str;
341         }
342         echo '<div class="clearer"></div>';
344         echo '<div class="comment">';
345         echo $grade->str_feedback;
346         echo '</div>';
347         echo '</tr>';
349          if ($this->type == 'uploadsingle') { //@TODO: move to overload view_feedback method in the class or is uploadsingle merging into upload?
350             $responsefiles = $this->print_responsefiles($submission->userid, true);
351             if (!empty($responsefiles)) {
352                 echo '<tr>';
353                 echo '<td class="left side">&nbsp;</td>';
354                 echo '<td class="content">';
355                 echo $responsefiles;
356                 echo '</tr>';
357             }
358          }
360         echo '</table>';
361     }
363     /**
364      * Returns a link with info about the state of the assignment submissions
365      *
366      * This is used by view_header to put this link at the top right of the page.
367      * For teachers it gives the number of submitted assignments with a link
368      * For students it gives the time of their submission.
369      * This will be suitable for most assignment types.
370      *
371      * @global object
372      * @global object
373      * @param bool $allgroup print all groups info if user can access all groups, suitable for index.php
374      * @return string
375      */
376     function submittedlink($allgroups=false) {
377         global $USER;
378         global $CFG;
380         $submitted = '';
381         $urlbase = "{$CFG->wwwroot}/mod/assignment/";
383         $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
384         if (has_capability('mod/assignment:grade', $context)) {
385             if ($allgroups and has_capability('moodle/site:accessallgroups', $context)) {
386                 $group = 0;
387             } else {
388                 $group = groups_get_activity_group($this->cm);
389             }
390             if ($this->type == 'offline') {
391                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
392                              get_string('viewfeedback', 'assignment').'</a>';
393             } else if ($count = $this->count_real_submissions($group)) {
394                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
395                              get_string('viewsubmissions', 'assignment', $count).'</a>';
396             } else {
397                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
398                              get_string('noattempts', 'assignment').'</a>';
399             }
400         } else {
401             if (isloggedin()) {
402                 if ($submission = $this->get_submission($USER->id)) {
403                     if ($submission->timemodified) {
404                         if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
405                             $submitted = '<span class="early">'.userdate($submission->timemodified).'</span>';
406                         } else {
407                             $submitted = '<span class="late">'.userdate($submission->timemodified).'</span>';
408                         }
409                     }
410                 }
411             }
412         }
414         return $submitted;
415     }
418     /**
419      * @todo Document this function
420      */
421     function setup_elements(&$mform) {
423     }
425     /**
426      * Any preprocessing needed for the settings form for
427      * this assignment type
428      *
429      * @param array $default_values - array to fill in with the default values
430      *      in the form 'formelement' => 'value'
431      * @param object $form - the form that is to be displayed
432      * @return none
433      */
434     function form_data_preprocessing(&$default_values, $form) {
435     }
437     /**
438      * Any extra validation checks needed for the settings
439      * form for this assignment type
440      *
441      * See lib/formslib.php, 'validation' function for details
442      */
443     function form_validation($data, $files) {
444         return array();
445     }
447     /**
448      * Create a new assignment activity
449      *
450      * Given an object containing all the necessary data,
451      * (defined by the form in mod_form.php) this function
452      * will create a new instance and return the id number
453      * of the new instance.
454      * The due data is added to the calendar
455      * This is common to all assignment types.
456      *
457      * @global object
458      * @global object
459      * @param object $assignment The data from the form on mod_form.php
460      * @return int The id of the assignment
461      */
462     function add_instance($assignment) {
463         global $COURSE, $DB;
465         $assignment->timemodified = time();
466         $assignment->courseid = $assignment->course;
468         $returnid = $DB->insert_record("assignment", $assignment);
469         $assignment->id = $returnid;
471         if ($assignment->timedue) {
472             $event = new stdClass();
473             $event->name        = $assignment->name;
474             $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
475             $event->courseid    = $assignment->course;
476             $event->groupid     = 0;
477             $event->userid      = 0;
478             $event->modulename  = 'assignment';
479             $event->instance    = $returnid;
480             $event->eventtype   = 'due';
481             $event->timestart   = $assignment->timedue;
482             $event->timeduration = 0;
484             calendar_event::create($event);
485         }
487         assignment_grade_item_update($assignment);
489         return $returnid;
490     }
492     /**
493      * Deletes an assignment activity
494      *
495      * Deletes all database records, files and calendar events for this assignment.
496      *
497      * @global object
498      * @global object
499      * @param object $assignment The assignment to be deleted
500      * @return boolean False indicates error
501      */
502     function delete_instance($assignment) {
503         global $CFG, $DB;
505         $assignment->courseid = $assignment->course;
507         $result = true;
509         // now get rid of all files
510         $fs = get_file_storage();
511         if ($cm = get_coursemodule_from_instance('assignment', $assignment->id)) {
512             $context = get_context_instance(CONTEXT_MODULE, $cm->id);
513             $fs->delete_area_files($context->id);
514         }
516         if (! $DB->delete_records('assignment_submissions', array('assignment'=>$assignment->id))) {
517             $result = false;
518         }
520         if (! $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
521             $result = false;
522         }
524         if (! $DB->delete_records('assignment', array('id'=>$assignment->id))) {
525             $result = false;
526         }
527         $mod = $DB->get_field('modules','id',array('name'=>'assignment'));
529         assignment_grade_item_delete($assignment);
531         return $result;
532     }
534     /**
535      * Updates a new assignment activity
536      *
537      * Given an object containing all the necessary data,
538      * (defined by the form in mod_form.php) this function
539      * will update the assignment instance and return the id number
540      * The due date is updated in the calendar
541      * This is common to all assignment types.
542      *
543      * @global object
544      * @global object
545      * @param object $assignment The data from the form on mod_form.php
546      * @return bool success
547      */
548     function update_instance($assignment) {
549         global $COURSE, $DB;
551         $assignment->timemodified = time();
553         $assignment->id = $assignment->instance;
554         $assignment->courseid = $assignment->course;
556         $DB->update_record('assignment', $assignment);
558         if ($assignment->timedue) {
559             $event = new stdClass();
561             if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
563                 $event->name        = $assignment->name;
564                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
565                 $event->timestart   = $assignment->timedue;
567                 $calendarevent = calendar_event::load($event->id);
568                 $calendarevent->update($event);
569             } else {
570                 $event = new stdClass();
571                 $event->name        = $assignment->name;
572                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
573                 $event->courseid    = $assignment->course;
574                 $event->groupid     = 0;
575                 $event->userid      = 0;
576                 $event->modulename  = 'assignment';
577                 $event->instance    = $assignment->id;
578                 $event->eventtype   = 'due';
579                 $event->timestart   = $assignment->timedue;
580                 $event->timeduration = 0;
582                 calendar_event::create($event);
583             }
584         } else {
585             $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id));
586         }
588         // get existing grade item
589         assignment_grade_item_update($assignment);
591         return true;
592     }
594     /**
595      * Update grade item for this submission.
596      */
597     function update_grade($submission) {
598         assignment_update_grades($this->assignment, $submission->userid);
599     }
601     /**
602      * Top-level function for handling of submissions called by submissions.php
603      *
604      * This is for handling the teacher interaction with the grading interface
605      * This should be suitable for most assignment types.
606      *
607      * @global object
608      * @param string $mode Specifies the kind of teacher interaction taking place
609      */
610     function submissions($mode) {
611         ///The main switch is changed to facilitate
612         ///1) Batch fast grading
613         ///2) Skip to the next one on the popup
614         ///3) Save and Skip to the next one on the popup
616         //make user global so we can use the id
617         global $USER, $OUTPUT, $DB, $PAGE;
619         $mailinfo = optional_param('mailinfo', null, PARAM_BOOL);
621         if (optional_param('next', null, PARAM_BOOL)) {
622             $mode='next';
623         }
624         if (optional_param('saveandnext', null, PARAM_BOOL)) {
625             $mode='saveandnext';
626         }
628         if (is_null($mailinfo)) {
629             if (optional_param('sesskey', null, PARAM_BOOL)) {
630                 set_user_preference('assignment_mailinfo', $mailinfo);
631             } else {
632                 $mailinfo = get_user_preferences('assignment_mailinfo', 0);
633             }
634         } else {
635             set_user_preference('assignment_mailinfo', $mailinfo);
636         }
638         if (!($this->validate_and_preprocess_feedback())) {
639             // form was submitted ('Save' or 'Save and next' was pressed, but validation failed)
640             $this->display_submission();
641             return;
642         }
644         switch ($mode) {
645             case 'grade':                         // We are in a main window grading
646                 if ($submission = $this->process_feedback()) {
647                     $this->display_submissions(get_string('changessaved'));
648                 } else {
649                     $this->display_submissions();
650                 }
651                 break;
653             case 'single':                        // We are in a main window displaying one submission
654                 if ($submission = $this->process_feedback()) {
655                     $this->display_submissions(get_string('changessaved'));
656                 } else {
657                     $this->display_submission();
658                 }
659                 break;
661             case 'all':                          // Main window, display everything
662                 $this->display_submissions();
663                 break;
665             case 'fastgrade':
666                 ///do the fast grading stuff  - this process should work for all 3 subclasses
667                 $grading    = false;
668                 $commenting = false;
669                 $col        = false;
670                 if (isset($_POST['submissioncomment'])) {
671                     $col = 'submissioncomment';
672                     $commenting = true;
673                 }
674                 if (isset($_POST['menu'])) {
675                     $col = 'menu';
676                     $grading = true;
677                 }
678                 if (!$col) {
679                     //both submissioncomment and grade columns collapsed..
680                     $this->display_submissions();
681                     break;
682                 }
684                 foreach ($_POST[$col] as $id => $unusedvalue){
686                     $id = (int)$id; //clean parameter name
688                     $this->process_outcomes($id);
690                     if (!$submission = $this->get_submission($id)) {
691                         $submission = $this->prepare_new_submission($id);
692                         $newsubmission = true;
693                     } else {
694                         $newsubmission = false;
695                     }
696                     unset($submission->data1);  // Don't need to update this.
697                     unset($submission->data2);  // Don't need to update this.
699                     //for fast grade, we need to check if any changes take place
700                     $updatedb = false;
702                     if ($grading) {
703                         $grade = $_POST['menu'][$id];
704                         $updatedb = $updatedb || ($submission->grade != $grade);
705                         $submission->grade = $grade;
706                     } else {
707                         if (!$newsubmission) {
708                             unset($submission->grade);  // Don't need to update this.
709                         }
710                     }
711                     if ($commenting) {
712                         $commentvalue = trim($_POST['submissioncomment'][$id]);
713                         $updatedb = $updatedb || ($submission->submissioncomment != $commentvalue);
714                         $submission->submissioncomment = $commentvalue;
715                     } else {
716                         unset($submission->submissioncomment);  // Don't need to update this.
717                     }
719                     $submission->teacher    = $USER->id;
720                     if ($updatedb) {
721                         $submission->mailed = (int)(!$mailinfo);
722                     }
724                     $submission->timemarked = time();
726                     //if it is not an update, we don't change the last modified time etc.
727                     //this will also not write into database if no submissioncomment and grade is entered.
729                     if ($updatedb){
730                         if ($newsubmission) {
731                             if (!isset($submission->submissioncomment)) {
732                                 $submission->submissioncomment = '';
733                             }
734                             $sid = $DB->insert_record('assignment_submissions', $submission);
735                             $submission->id = $sid;
736                         } else {
737                             $DB->update_record('assignment_submissions', $submission);
738                         }
740                         // trigger grade event
741                         $this->update_grade($submission);
743                         //add to log only if updating
744                         add_to_log($this->course->id, 'assignment', 'update grades',
745                                    'submissions.php?id='.$this->cm->id.'&user='.$submission->userid,
746                                    $submission->userid, $this->cm->id);
747                     }
749                 }
751                 $message = $OUTPUT->notification(get_string('changessaved'), 'notifysuccess');
753                 $this->display_submissions($message);
754                 break;
757             case 'saveandnext':
758                 ///We are in pop up. save the current one and go to the next one.
759                 //first we save the current changes
760                 if ($submission = $this->process_feedback()) {
761                     //print_heading(get_string('changessaved'));
762                     //$extra_javascript = $this->update_main_listing($submission);
763                 }
765             case 'next':
766                 /// We are currently in pop up, but we want to skip to next one without saving.
767                 ///    This turns out to be similar to a single case
768                 /// The URL used is for the next submission.
769                 $offset = required_param('offset', PARAM_INT);
770                 $nextid = required_param('nextid', PARAM_INT);
771                 $id = required_param('id', PARAM_INT);
772                 $offset = (int)$offset+1;
773                 //$this->display_submission($offset+1 , $nextid);
774                 redirect('submissions.php?id='.$id.'&userid='. $nextid . '&mode=single&offset='.$offset);
775                 break;
777             case 'singlenosave':
778                 $this->display_submission();
779                 break;
781             default:
782                 echo "something seriously is wrong!!";
783                 break;
784         }
785     }
787     /**
788      * Checks if grading method allows quickgrade mode. At the moment it is hardcoded
789      * that advanced grading methods do not allow quickgrade.
790      *
791      * Assignment type plugins are not allowed to override this method
792      *
793      * @return boolean
794      */
795     public final function quickgrade_mode_allowed() {
796         global $CFG;
797         require_once("$CFG->dirroot/grade/grading/lib.php");
798         if ($controller = get_grading_manager($this->context, 'mod_assignment', 'submission')->get_active_controller()) {
799             return false;
800         }
801         return true;
802     }
804     /**
805      * Helper method updating the listing on the main script from popup using javascript
806      *
807      * @global object
808      * @global object
809      * @param $submission object The submission whose data is to be updated on the main page
810      */
811     function update_main_listing($submission) {
812         global $SESSION, $CFG, $OUTPUT;
814         $output = '';
816         $perpage = get_user_preferences('assignment_perpage', 10);
818         $quickgrade = get_user_preferences('assignment_quickgrade', 0) && $this->quickgrade_mode_allowed();
820         /// Run some Javascript to try and update the parent page
821         $output .= '<script type="text/javascript">'."\n<!--\n";
822         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['submissioncomment'])) {
823             if ($quickgrade){
824                 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid.'").value="'
825                 .trim($submission->submissioncomment).'";'."\n";
826              } else {
827                 $output.= 'opener.document.getElementById("com'.$submission->userid.
828                 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment)), 15)."\";\n";
829             }
830         }
832         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['grade'])) {
833             //echo optional_param('menuindex');
834             if ($quickgrade){
835                 $output.= 'opener.document.getElementById("menumenu'.$submission->userid.
836                 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT).'";'."\n";
837             } else {
838                 $output.= 'opener.document.getElementById("g'.$submission->userid.'").innerHTML="'.
839                 $this->display_grade($submission->grade)."\";\n";
840             }
841         }
842         //need to add student's assignments in there too.
843         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemodified']) &&
844             $submission->timemodified) {
845             $output.= 'opener.document.getElementById("ts'.$submission->userid.
846                  '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid)).userdate($submission->timemodified)."\";\n";
847         }
849         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemarked']) &&
850             $submission->timemarked) {
851             $output.= 'opener.document.getElementById("tt'.$submission->userid.
852                  '").innerHTML="'.userdate($submission->timemarked)."\";\n";
853         }
855         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['status'])) {
856             $output.= 'opener.document.getElementById("up'.$submission->userid.'").className="s1";';
857             $buttontext = get_string('update');
858             $url = new moodle_url('/mod/assignment/submissions.php', array(
859                     'id' => $this->cm->id,
860                     'userid' => $submission->userid,
861                     'mode' => 'single',
862                     'offset' => (optional_param('offset', '', PARAM_INT)-1)));
863             $button = $OUTPUT->action_link($url, $buttontext, new popup_action('click', $url, 'grade'.$submission->userid, array('height' => 450, 'width' => 700)), array('ttile'=>$buttontext));
865             $output .= 'opener.document.getElementById("up'.$submission->userid.'").innerHTML="'.addslashes_js($button).'";';
866         }
868         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $submission->userid);
870         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['finalgrade'])) {
871             $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid.
872             '").innerHTML="'.$grading_info->items[0]->grades[$submission->userid]->str_grade.'";'."\n";
873         }
875         if (!empty($CFG->enableoutcomes) and empty($SESSION->flextable['mod-assignment-submissions']->collapse['outcome'])) {
877             if (!empty($grading_info->outcomes)) {
878                 foreach($grading_info->outcomes as $n=>$outcome) {
879                     if ($outcome->grades[$submission->userid]->locked) {
880                         continue;
881                     }
883                     if ($quickgrade){
884                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.
885                         '").selectedIndex="'.$outcome->grades[$submission->userid]->grade.'";'."\n";
887                     } else {
888                         $options = make_grades_menu(-$outcome->scaleid);
889                         $options[0] = get_string('nooutcome', 'grades');
890                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.'").innerHTML="'.$options[$outcome->grades[$submission->userid]->grade]."\";\n";
891                     }
893                 }
894             }
895         }
897         $output .= "\n-->\n</script>";
898         return $output;
899     }
901     /**
902      *  Return a grade in user-friendly form, whether it's a scale or not
903      *
904      * @global object
905      * @param mixed $grade
906      * @return string User-friendly representation of grade
907      */
908     function display_grade($grade) {
909         global $DB;
911         static $scalegrades = array();   // Cache scales for each assignment - they might have different scales!!
913         if ($this->assignment->grade >= 0) {    // Normal number
914             if ($grade == -1) {
915                 return '-';
916             } else {
917                 return $grade.' / '.$this->assignment->grade;
918             }
920         } else {                                // Scale
921             if (empty($scalegrades[$this->assignment->id])) {
922                 if ($scale = $DB->get_record('scale', array('id'=>-($this->assignment->grade)))) {
923                     $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
924                 } else {
925                     return '-';
926                 }
927             }
928             if (isset($scalegrades[$this->assignment->id][$grade])) {
929                 return $scalegrades[$this->assignment->id][$grade];
930             }
931             return '-';
932         }
933     }
935     /**
936      *  Display a single submission, ready for grading on a popup window
937      *
938      * This default method prints the teacher info and submissioncomment box at the top and
939      * the student info and submission at the bottom.
940      * This method also fetches the necessary data in order to be able to
941      * provide a "Next submission" button.
942      * Calls preprocess_submission() to give assignment type plug-ins a chance
943      * to process submissions before they are graded
944      * This method gets its arguments from the page parameters userid and offset
945      *
946      * @global object
947      * @global object
948      * @param string $extra_javascript
949      */
950     function display_submission($offset=-1,$userid =-1, $display=true) {
951         global $CFG, $DB, $PAGE, $OUTPUT, $USER;
952         require_once($CFG->libdir.'/gradelib.php');
953         require_once($CFG->libdir.'/tablelib.php');
954         require_once("$CFG->dirroot/repository/lib.php");
955         require_once("$CFG->dirroot/grade/grading/lib.php");
956         if ($userid==-1) {
957             $userid = required_param('userid', PARAM_INT);
958         }
959         if ($offset==-1) {
960             $offset = required_param('offset', PARAM_INT);//offset for where to start looking for student.
961         }
962         $filter = optional_param('filter', 0, PARAM_INT);
964         if (!$user = $DB->get_record('user', array('id'=>$userid))) {
965             print_error('nousers');
966         }
968         if (!$submission = $this->get_submission($user->id)) {
969             $submission = $this->prepare_new_submission($userid);
970         }
971         if ($submission->timemodified > $submission->timemarked) {
972             $subtype = 'assignmentnew';
973         } else {
974             $subtype = 'assignmentold';
975         }
977         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
978         $gradingdisabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
980     /// construct SQL, using current offset to find the data of the next student
981         $course     = $this->course;
982         $assignment = $this->assignment;
983         $cm         = $this->cm;
984         $context    = get_context_instance(CONTEXT_MODULE, $cm->id);
986         //reset filter to all for offline assignment
987         if ($assignment->assignmenttype == 'offline' && $filter == self::FILTER_SUBMITTED) {
988             $filter = self::FILTER_ALL;
989         }
990         /// Get all ppl that can submit assignments
992         $currentgroup = groups_get_activity_group($cm);
993         $users = get_enrolled_users($context, 'mod/assignment:submit', $currentgroup, 'u.id');
994         if ($users) {
995             $users = array_keys($users);
996             // if groupmembersonly used, remove users who are not in any group
997             if (!empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
998                 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
999                     $users = array_intersect($users, array_keys($groupingusers));
1000                 }
1001             }
1002         }
1004         $nextid = 0;
1005         $where = '';
1006         if($filter == self::FILTER_SUBMITTED) {
1007             $where .= 's.timemodified > 0 AND ';
1008         } else if($filter == self::FILTER_REQUIRE_GRADING) {
1009             $where .= 's.timemarked < s.timemodified AND ';
1010         }
1012         if ($users) {
1013             $userfields = user_picture::fields('u', array('lastaccess'));
1014             $select = "SELECT $userfields,
1015                               s.id AS submissionid, s.grade, s.submissioncomment,
1016                               s.timemodified, s.timemarked ";
1017             $sql = 'FROM {user} u '.
1018                    'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1019                    AND s.assignment = '.$this->assignment->id.' '.
1020                    'WHERE '.$where.'u.id IN ('.implode(',', $users).') ';
1022             if ($sort = flexible_table::get_sort_for_table('mod-assignment-submissions')) {
1023                 $sort = 'ORDER BY '.$sort.' ';
1024             }
1025             $auser = $DB->get_records_sql($select.$sql.$sort, null, $offset, 2);
1027             if (is_array($auser) && count($auser)>1) {
1028                 $nextuser = next($auser);
1029             /// Calculate user status
1030                 $nextuser->status = ($nextuser->timemarked > 0) && ($nextuser->timemarked >= $nextuser->timemodified);
1031                 $nextid = $nextuser->id;
1032             }
1033         }
1035         if ($submission->teacher) {
1036             $teacher = $DB->get_record('user', array('id'=>$submission->teacher));
1037         } else {
1038             global $USER;
1039             $teacher = $USER;
1040         }
1042         $this->preprocess_submission($submission);
1044         $mformdata = new stdClass();
1045         $mformdata->context = $this->context;
1046         $mformdata->maxbytes = $this->course->maxbytes;
1047         $mformdata->courseid = $this->course->id;
1048         $mformdata->teacher = $teacher;
1049         $mformdata->assignment = $assignment;
1050         $mformdata->submission = $submission;
1051         $mformdata->lateness = $this->display_lateness($submission->timemodified);
1052         $mformdata->auser = $auser;
1053         $mformdata->user = $user;
1054         $mformdata->offset = $offset;
1055         $mformdata->userid = $userid;
1056         $mformdata->cm = $this->cm;
1057         $mformdata->grading_info = $grading_info;
1058         $mformdata->enableoutcomes = $CFG->enableoutcomes;
1059         $mformdata->grade = $this->assignment->grade;
1060         $mformdata->gradingdisabled = $gradingdisabled;
1061         $mformdata->nextid = $nextid;
1062         $mformdata->submissioncomment= $submission->submissioncomment;
1063         $mformdata->submissioncommentformat= FORMAT_HTML;
1064         $mformdata->submission_content= $this->print_user_files($user->id,true);
1065         $mformdata->filter = $filter;
1066         $mformdata->mailinfo = get_user_preferences('assignment_mailinfo', 0);
1067          if ($assignment->assignmenttype == 'upload') {
1068             $mformdata->fileui_options = array('subdirs'=>1, 'maxbytes'=>$assignment->maxbytes, 'maxfiles'=>$assignment->var1, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL);
1069         } elseif ($assignment->assignmenttype == 'uploadsingle') {
1070             $mformdata->fileui_options = array('subdirs'=>0, 'maxbytes'=>$CFG->userquota, 'maxfiles'=>1, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL);
1071         }
1072         $advancedgradingwarning = false;
1073         $gradingmanager = get_grading_manager($this->context, 'mod_assignment', 'submission');
1074         if ($gradingmethod = $gradingmanager->get_active_method()) {
1075             $controller = $gradingmanager->get_controller($gradingmethod);
1076             if ($controller->is_form_available()) {
1077                 $itemid = null;
1078                 if (!empty($submission->id)) {
1079                     $itemid = $submission->id;
1080                 }
1081                 if ($gradingdisabled && $itemid) {
1082                     $mformdata->advancedgradinginstance = $controller->get_current_instance($USER->id, $itemid);
1083                 } else if (!$gradingdisabled) {
1084                     $instanceid = optional_param('advancedgradinginstanceid', 0, PARAM_INT);
1085                     $mformdata->advancedgradinginstance = $controller->get_or_create_instance($instanceid, $USER->id, $itemid);
1086                 }
1087             } else {
1088                 $advancedgradingwarning = $controller->form_unavailable_notification();
1089             }
1090         }
1092         $submitform = new mod_assignment_grading_form( null, $mformdata );
1094          if (!$display) {
1095             $ret_data = new stdClass();
1096             $ret_data->mform = $submitform;
1097             if (isset($mformdata->fileui_options)) {
1098                 $ret_data->fileui_options = $mformdata->fileui_options;
1099             }
1100             return $ret_data;
1101         }
1103         if ($submitform->is_cancelled()) {
1104             redirect('submissions.php?id='.$this->cm->id);
1105         }
1107         $submitform->set_data($mformdata);
1109         $PAGE->set_title($this->course->fullname . ': ' .get_string('feedback', 'assignment').' - '.fullname($user, true));
1110         $PAGE->set_heading($this->course->fullname);
1111         $PAGE->navbar->add(get_string('submissions', 'assignment'), new moodle_url('/mod/assignment/submissions.php', array('id'=>$cm->id)));
1112         $PAGE->navbar->add(fullname($user, true));
1114         echo $OUTPUT->header();
1115         echo $OUTPUT->heading(get_string('feedback', 'assignment').': '.fullname($user, true));
1117         // display mform here...
1118         if ($advancedgradingwarning) {
1119             echo $OUTPUT->notification($advancedgradingwarning, 'error');
1120         }
1121         $submitform->display();
1123         $customfeedback = $this->custom_feedbackform($submission, true);
1124         if (!empty($customfeedback)) {
1125             echo $customfeedback;
1126         }
1128         echo $OUTPUT->footer();
1129     }
1131     /**
1132      *  Preprocess submission before grading
1133      *
1134      * Called by display_submission()
1135      * The default type does nothing here.
1136      *
1137      * @param object $submission The submission object
1138      */
1139     function preprocess_submission(&$submission) {
1140     }
1142     /**
1143      *  Display all the submissions ready for grading
1144      *
1145      * @global object
1146      * @global object
1147      * @global object
1148      * @global object
1149      * @param string $message
1150      * @return bool|void
1151      */
1152     function display_submissions($message='') {
1153         global $CFG, $DB, $USER, $DB, $OUTPUT, $PAGE;
1154         require_once($CFG->libdir.'/gradelib.php');
1156         /* first we check to see if the form has just been submitted
1157          * to request user_preference updates
1158          */
1160        $filters = array(self::FILTER_ALL             => get_string('all'),
1161                         self::FILTER_REQUIRE_GRADING => get_string('requiregrading', 'assignment'));
1163         $updatepref = optional_param('updatepref', 0, PARAM_BOOL);
1164         if ($updatepref) {
1165             $perpage = optional_param('perpage', 10, PARAM_INT);
1166             $perpage = ($perpage <= 0) ? 10 : $perpage ;
1167             $filter = optional_param('filter', 0, PARAM_INT);
1168             set_user_preference('assignment_perpage', $perpage);
1169             set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
1170             set_user_preference('assignment_filter', $filter);
1171         }
1173         /* next we get perpage and quickgrade (allow quick grade) params
1174          * from database
1175          */
1176         $perpage    = get_user_preferences('assignment_perpage', 10);
1177         $quickgrade = get_user_preferences('assignment_quickgrade', 0) && $this->quickgrade_mode_allowed();
1178         $filter = get_user_preferences('assignment_filter', 0);
1179         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);
1181         if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
1182             $uses_outcomes = true;
1183         } else {
1184             $uses_outcomes = false;
1185         }
1187         $page    = optional_param('page', 0, PARAM_INT);
1188         $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
1190     /// Some shortcuts to make the code read better
1192         $course     = $this->course;
1193         $assignment = $this->assignment;
1194         $cm         = $this->cm;
1195         $hassubmission = false;
1197         // reset filter to all for offline assignment only.
1198         if ($assignment->assignmenttype == 'offline') {
1199             if ($filter == self::FILTER_SUBMITTED) {
1200                 $filter = self::FILTER_ALL;
1201             }
1202         } else {
1203             $filters[self::FILTER_SUBMITTED] = get_string('submitted', 'assignment');
1204         }
1206         $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
1207         add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->cm->id, $this->assignment->id, $this->cm->id);
1209         $PAGE->set_title(format_string($this->assignment->name,true));
1210         $PAGE->set_heading($this->course->fullname);
1211         echo $OUTPUT->header();
1213         echo '<div class="usersubmissions">';
1215         //hook to allow plagiarism plugins to update status/print links.
1216         plagiarism_update_status($this->course, $this->cm);
1218         $course_context = get_context_instance(CONTEXT_COURSE, $course->id);
1219         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
1220             echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">'
1221                 . get_string('seeallcoursegrades', 'grades') . '</a></div>';
1222         }
1224         if (!empty($message)) {
1225             echo $message;   // display messages here if any
1226         }
1228         $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1230     /// Check to see if groups are being used in this assignment
1232         /// find out current groups mode
1233         $groupmode = groups_get_activity_groupmode($cm);
1234         $currentgroup = groups_get_activity_group($cm, true);
1235         groups_print_activity_menu($cm, $CFG->wwwroot . '/mod/assignment/submissions.php?id=' . $this->cm->id);
1237         /// Print quickgrade form around the table
1238         if ($quickgrade) {
1239             $formattrs = array();
1240             $formattrs['action'] = new moodle_url('/mod/assignment/submissions.php');
1241             $formattrs['id'] = 'fastg';
1242             $formattrs['method'] = 'post';
1244             echo html_writer::start_tag('form', $formattrs);
1245             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'id',      'value'=> $this->cm->id));
1246             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'mode',    'value'=> 'fastgrade'));
1247             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'page',    'value'=> $page));
1248             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=> sesskey()));
1249         }
1251         /// Get all ppl that are allowed to submit assignments
1252         list($esql, $params) = get_enrolled_sql($context, 'mod/assignment:submit', $currentgroup);
1254         if ($filter == self::FILTER_ALL) {
1255             $sql = "SELECT u.id FROM {user} u ".
1256                    "LEFT JOIN ($esql) eu ON eu.id=u.id ".
1257                    "WHERE u.deleted = 0 AND eu.id=u.id ";
1258         } else {
1259             $wherefilter = ' AND s.assignment = '. $this->assignment->id;
1260             $assignmentsubmission = "LEFT JOIN {assignment_submissions} s ON (u.id = s.userid) ";
1261             if($filter == self::FILTER_SUBMITTED) {
1262                 $wherefilter .= ' AND s.timemodified > 0 ';
1263             } else if($filter == self::FILTER_REQUIRE_GRADING && $assignment->assignmenttype != 'offline') {
1264                 $wherefilter .= ' AND s.timemarked < s.timemodified ';
1265             } else { // require grading for offline assignment
1266                 $assignmentsubmission = "";
1267                 $wherefilter = "";
1268             }
1270             $sql = "SELECT u.id FROM {user} u ".
1271                    "LEFT JOIN ($esql) eu ON eu.id=u.id ".
1272                    $assignmentsubmission.
1273                    "WHERE u.deleted = 0 AND eu.id=u.id ".
1274                    $wherefilter;
1275         }
1277         $users = $DB->get_records_sql($sql, $params);
1278         if (!empty($users)) {
1279             if($assignment->assignmenttype == 'offline' && $filter == self::FILTER_REQUIRE_GRADING) {
1280                 //remove users who has submitted their assignment
1281                 foreach ($this->get_submissions() as $submission) {
1282                     if (array_key_exists($submission->userid, $users)) {
1283                         unset($users[$submission->userid]);
1284                     }
1285                 }
1286             }
1287             $users = array_keys($users);
1288         }
1290         // if groupmembersonly used, remove users who are not in any group
1291         if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
1292             if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1293                 $users = array_intersect($users, array_keys($groupingusers));
1294             }
1295         }
1297         $tablecolumns = array('picture', 'fullname', 'grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade');
1298         if ($uses_outcomes) {
1299             $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
1300         }
1302         $tableheaders = array('',
1303                               get_string('fullnameuser'),
1304                               get_string('grade'),
1305                               get_string('comment', 'assignment'),
1306                               get_string('lastmodified').' ('.get_string('submission', 'assignment').')',
1307                               get_string('lastmodified').' ('.get_string('grade').')',
1308                               get_string('status'),
1309                               get_string('finalgrade', 'grades'));
1310         if ($uses_outcomes) {
1311             $tableheaders[] = get_string('outcome', 'grades');
1312         }
1314         require_once($CFG->libdir.'/tablelib.php');
1315         $table = new flexible_table('mod-assignment-submissions');
1317         $table->define_columns($tablecolumns);
1318         $table->define_headers($tableheaders);
1319         $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;currentgroup='.$currentgroup);
1321         $table->sortable(true, 'lastname');//sorted by lastname by default
1322         $table->collapsible(true);
1323         $table->initialbars(true);
1325         $table->column_suppress('picture');
1326         $table->column_suppress('fullname');
1328         $table->column_class('picture', 'picture');
1329         $table->column_class('fullname', 'fullname');
1330         $table->column_class('grade', 'grade');
1331         $table->column_class('submissioncomment', 'comment');
1332         $table->column_class('timemodified', 'timemodified');
1333         $table->column_class('timemarked', 'timemarked');
1334         $table->column_class('status', 'status');
1335         $table->column_class('finalgrade', 'finalgrade');
1336         if ($uses_outcomes) {
1337             $table->column_class('outcome', 'outcome');
1338         }
1340         $table->set_attribute('cellspacing', '0');
1341         $table->set_attribute('id', 'attempts');
1342         $table->set_attribute('class', 'submissions');
1343         $table->set_attribute('width', '100%');
1345         $table->no_sorting('finalgrade');
1346         $table->no_sorting('outcome');
1348         // Start working -- this is necessary as soon as the niceties are over
1349         $table->setup();
1351         /// Construct the SQL
1352         list($where, $params) = $table->get_sql_where();
1353         if ($where) {
1354             $where .= ' AND ';
1355         }
1357         if ($filter == self::FILTER_SUBMITTED) {
1358            $where .= 's.timemodified > 0 AND ';
1359         } else if($filter == self::FILTER_REQUIRE_GRADING) {
1360             $where = '';
1361             if ($assignment->assignmenttype != 'offline') {
1362                $where .= 's.timemarked < s.timemodified AND ';
1363             }
1364         }
1366         if ($sort = $table->get_sql_sort()) {
1367             $sort = ' ORDER BY '.$sort;
1368         }
1370         $ufields = user_picture::fields('u');
1371         if (!empty($users)) {
1372             $select = "SELECT $ufields,
1373                               s.id AS submissionid, s.grade, s.submissioncomment,
1374                               s.timemodified, s.timemarked ";
1375             $sql = 'FROM {user} u '.
1376                    'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1377                     AND s.assignment = '.$this->assignment->id.' '.
1378                    'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1380             $ausers = $DB->get_records_sql($select.$sql.$sort, $params, $table->get_page_start(), $table->get_page_size());
1382             $table->pagesize($perpage, count($users));
1384             ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1385             $offset = $page * $perpage;
1386             $strupdate = get_string('update');
1387             $strgrade  = get_string('grade');
1388             $grademenu = make_grades_menu($this->assignment->grade);
1390             if ($ausers !== false) {
1391                 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
1392                 $endposition = $offset + $perpage;
1393                 $currentposition = 0;
1394                 foreach ($ausers as $auser) {
1395                     if ($currentposition == $offset && $offset < $endposition) {
1396                         $final_grade = $grading_info->items[0]->grades[$auser->id];
1397                         $grademax = $grading_info->items[0]->grademax;
1398                         $final_grade->formatted_grade = round($final_grade->grade,2) .' / ' . round($grademax,2);
1399                         $locked_overridden = 'locked';
1400                         if ($final_grade->overridden) {
1401                             $locked_overridden = 'overridden';
1402                         }
1404                     /// Calculate user status
1405                         $auser->status = ($auser->timemarked > 0) && ($auser->timemarked >= $auser->timemodified);
1406                         // TODO add here code if advanced grading grade must be reviewed => $auser->status=0
1407                         $picture = $OUTPUT->user_picture($auser);
1409                         if (empty($auser->submissionid)) {
1410                             $auser->grade = -1; //no submission yet
1411                         }
1413                         if (!empty($auser->submissionid)) {
1414                             $hassubmission = true;
1415                         ///Prints student answer and student modified date
1416                         ///attach file or print link to student answer, depending on the type of the assignment.
1417                         ///Refer to print_student_answer in inherited classes.
1418                             if ($auser->timemodified > 0) {
1419                                 $studentmodified = '<div id="ts'.$auser->id.'">'.$this->print_student_answer($auser->id)
1420                                                  . userdate($auser->timemodified).'</div>';
1421                             } else {
1422                                 $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1423                             }
1424                         ///Print grade, dropdown or text
1425                             if ($auser->timemarked > 0) {
1426                                 $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
1428                                 if ($final_grade->locked or $final_grade->overridden) {
1429                                     $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1430                                 } else if ($quickgrade) {
1431                                     $attributes = array();
1432                                     $attributes['tabindex'] = $tabindex++;
1433                                     $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1434                                     $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
1435                                 } else {
1436                                     $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1437                                 }
1439                             } else {
1440                                 $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1441                                 if ($final_grade->locked or $final_grade->overridden) {
1442                                     $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1443                                 } else if ($quickgrade) {
1444                                     $attributes = array();
1445                                     $attributes['tabindex'] = $tabindex++;
1446                                     $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1447                                     $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1448                                 } else {
1449                                     $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1450                                 }
1451                             }
1452                         ///Print Comment
1453                             if ($final_grade->locked or $final_grade->overridden) {
1454                                 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';
1456                             } else if ($quickgrade) {
1457                                 $comment = '<div id="com'.$auser->id.'">'
1458                                          . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1459                                          . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1460                             } else {
1461                                 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
1462                             }
1463                         } else {
1464                             $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1465                             $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1466                             $status          = '<div id="st'.$auser->id.'">&nbsp;</div>';
1468                             if ($final_grade->locked or $final_grade->overridden) {
1469                                 $grade = '<div id="g'.$auser->id.'">'.$final_grade->formatted_grade . '</div>';
1470                                 $hassubmission = true;
1471                             } else if ($quickgrade) {   // allow editing
1472                                 $attributes = array();
1473                                 $attributes['tabindex'] = $tabindex++;
1474                                 $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1475                                 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1476                                 $hassubmission = true;
1477                             } else {
1478                                 $grade = '<div id="g'.$auser->id.'">-</div>';
1479                             }
1481                             if ($final_grade->locked or $final_grade->overridden) {
1482                                 $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
1483                             } else if ($quickgrade) {
1484                                 $comment = '<div id="com'.$auser->id.'">'
1485                                          . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1486                                          . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1487                             } else {
1488                                 $comment = '<div id="com'.$auser->id.'">&nbsp;</div>';
1489                             }
1490                         }
1492                         if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
1493                             $auser->status = 0;
1494                         } else {
1495                             $auser->status = 1;
1496                         }
1498                         $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
1500                         ///No more buttons, we use popups ;-).
1501                         $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1502                                    . '&amp;userid='.$auser->id.'&amp;mode=single'.'&amp;filter='.$filter.'&amp;offset='.$offset++;
1504                         $button = $OUTPUT->action_link($popup_url, $buttontext);
1506                         $status  = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
1508                         $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';
1510                         $outcomes = '';
1512                         if ($uses_outcomes) {
1514                             foreach($grading_info->outcomes as $n=>$outcome) {
1515                                 $outcomes .= '<div class="outcome"><label>'.$outcome->name.'</label>';
1516                                 $options = make_grades_menu(-$outcome->scaleid);
1518                                 if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
1519                                     $options[0] = get_string('nooutcome', 'grades');
1520                                     $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
1521                                 } else {
1522                                     $attributes = array();
1523                                     $attributes['tabindex'] = $tabindex++;
1524                                     $attributes['id'] = 'outcome_'.$n.'_'.$auser->id;
1525                                     $outcomes .= ' '.html_writer::select($options, 'outcome_'.$n.'['.$auser->id.']', $outcome->grades[$auser->id]->grade, array(0=>get_string('nooutcome', 'grades')), $attributes);
1526                                 }
1527                                 $outcomes .= '</div>';
1528                             }
1529                         }
1531                         $userlink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $auser->id . '&amp;course=' . $course->id . '">' . fullname($auser, has_capability('moodle/site:viewfullnames', $this->context)) . '</a>';
1532                         $row = array($picture, $userlink, $grade, $comment, $studentmodified, $teachermodified, $status, $finalgrade);
1533                         if ($uses_outcomes) {
1534                             $row[] = $outcomes;
1535                         }
1536                         $table->add_data($row);
1537                     }
1538                     $currentposition++;
1539                 }
1540                 if ($hassubmission && ($this->assignment->assignmenttype=='upload' || $this->assignment->assignmenttype=='online' || $this->assignment->assignmenttype=='uploadsingle')) { //TODO: this is an ugly hack, where is the plugin spirit? (skodak)
1541                     echo html_writer::start_tag('div', array('class' => 'mod-assignment-download-link'));
1542                     echo html_writer::link(new moodle_url('/mod/assignment/submissions.php', array('id' => $this->cm->id, 'download' => 'zip')), get_string('downloadall', 'assignment'));
1543                     echo html_writer::end_tag('div');
1544                 }
1545                 $table->print_html();  /// Print the whole table
1546             } else {
1547                 if ($filter == self::FILTER_SUBMITTED) {
1548                     echo html_writer::tag('div', get_string('nosubmisson', 'assignment'), array('class'=>'nosubmisson'));
1549                 } else if ($filter == self::FILTER_REQUIRE_GRADING) {
1550                     echo html_writer::tag('div', get_string('norequiregrading', 'assignment'), array('class'=>'norequiregrading'));
1551                 }
1552             }
1553         }
1555         /// Print quickgrade form around the table
1556         if ($quickgrade && $table->started_output && !empty($users)){
1557             $mailinfopref = false;
1558             if (get_user_preferences('assignment_mailinfo', 1)) {
1559                 $mailinfopref = true;
1560             }
1561             $emailnotification =  html_writer::checkbox('mailinfo', 1, $mailinfopref, get_string('enablenotification','assignment'));
1563             $emailnotification .= $OUTPUT->help_icon('enablenotification', 'assignment');
1564             echo html_writer::tag('div', $emailnotification, array('class'=>'emailnotification'));
1566             $savefeedback = html_writer::empty_tag('input', array('type'=>'submit', 'name'=>'fastg', 'value'=>get_string('saveallfeedback', 'assignment')));
1567             echo html_writer::tag('div', $savefeedback, array('class'=>'fastgbutton'));
1569             echo html_writer::end_tag('form');
1570         } else if ($quickgrade) {
1571             echo html_writer::end_tag('form');
1572         }
1574         echo '</div>';
1575         /// End of fast grading form
1577         /// Mini form for setting user preference
1579         $formaction = new moodle_url('/mod/assignment/submissions.php', array('id'=>$this->cm->id));
1580         $mform = new MoodleQuickForm('optionspref', 'post', $formaction, '', array('class'=>'optionspref'));
1582         $mform->addElement('hidden', 'updatepref');
1583         $mform->setDefault('updatepref', 1);
1584         $mform->addElement('header', 'qgprefs', get_string('optionalsettings', 'assignment'));
1585         $mform->addElement('select', 'filter', get_string('show'),  $filters);
1587         $mform->setDefault('filter', $filter);
1589         $mform->addElement('text', 'perpage', get_string('pagesize', 'assignment'), array('size'=>1));
1590         $mform->setDefault('perpage', $perpage);
1592         if ($this->quickgrade_mode_allowed()) {
1593             $mform->addElement('checkbox', 'quickgrade', get_string('quickgrade','assignment'));
1594             $mform->setDefault('quickgrade', $quickgrade);
1595             $mform->addHelpButton('quickgrade', 'quickgrade', 'assignment');
1596         }
1598         $mform->addElement('submit', 'savepreferences', get_string('savepreferences'));
1600         $mform->display();
1602         echo $OUTPUT->footer();
1603     }
1605     /**
1606      * If the form was cancelled ('Cancel' or 'Next' was pressed), call cancel method
1607      * from advanced grading (if applicable) and returns true
1608      * If the form was submitted, validates it and returns false if validation did not pass.
1609      * If validation passes, preprocess advanced grading (if applicable) and returns true.
1610      */
1611     function validate_and_preprocess_feedback() {
1612         global $USER, $CFG;
1613         require_once($CFG->libdir.'/gradelib.php');
1614         if (!($feedback = data_submitted()) || !isset($feedback->userid) || !isset($feedback->offset)) {
1615             return true;      // No incoming data, nothing to validate
1616         }
1617         $userid = required_param('userid', PARAM_INT);
1618         $offset = required_param('offset', PARAM_INT);
1619         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($userid));
1620         $gradingdisabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
1621         if ($gradingdisabled) {
1622             return true;
1623         }
1624         $submissiondata = $this->display_submission($offset, $userid, false);
1625         $mform = $submissiondata->mform;
1626         $gradinginstance = $mform->use_advanced_grading();
1627         if (optional_param('cancel', false, PARAM_BOOL) || optional_param('next', false, PARAM_BOOL)) {
1628             // form was cancelled
1629             if ($gradinginstance) {
1630                 $gradinginstance->cancel();
1631             }
1632         } else if ($mform->is_submitted()) {
1633             // form was submitted (= a submit button other than 'cancel' or 'next' has been clicked)
1634             if (!$mform->is_validated()) {
1635                 return false;
1636             }
1637             // preprocess advanced grading here
1638             if ($gradinginstance) {
1639                 $data = $mform->get_data();
1640                 // create submission if it did not exist yet because we need submission->id for storing the grading instance
1641                 $submission = $this->get_submission($userid, true);
1642                 $_POST['xgrade'] = $gradinginstance->submit_and_get_grade($data->advancedgrading, $submission->id);
1643             }
1644         }
1645         return true;
1646     }
1648     /**
1649      *  Process teacher feedback submission
1650      *
1651      * This is called by submissions() when a grading even has taken place.
1652      * It gets its data from the submitted form.
1653      *
1654      * @global object
1655      * @global object
1656      * @global object
1657      * @return object|bool The updated submission object or false
1658      */
1659     function process_feedback($formdata=null) {
1660         global $CFG, $USER, $DB;
1661         require_once($CFG->libdir.'/gradelib.php');
1663         if (!$feedback = data_submitted() or !confirm_sesskey()) {      // No incoming data?
1664             return false;
1665         }
1667         ///For save and next, we need to know the userid to save, and the userid to go
1668         ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1669         ///as the userid to store
1670         if ((int)$feedback->saveuserid !== -1){
1671             $feedback->userid = $feedback->saveuserid;
1672         }
1674         if (!empty($feedback->cancel)) {          // User hit cancel button
1675             return false;
1676         }
1678         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);
1680         // store outcomes if needed
1681         $this->process_outcomes($feedback->userid);
1683         $submission = $this->get_submission($feedback->userid, true);  // Get or make one
1685         if (!($grading_info->items[0]->grades[$feedback->userid]->locked ||
1686             $grading_info->items[0]->grades[$feedback->userid]->overridden) ) {
1688             $submission->grade      = $feedback->xgrade;
1689             $submission->submissioncomment    = $feedback->submissioncomment_editor['text'];
1690             $submission->teacher    = $USER->id;
1691             $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1692             if (!$mailinfo) {
1693                 $submission->mailed = 1;       // treat as already mailed
1694             } else {
1695                 $submission->mailed = 0;       // Make sure mail goes out (again, even)
1696             }
1697             $submission->timemarked = time();
1699             unset($submission->data1);  // Don't need to update this.
1700             unset($submission->data2);  // Don't need to update this.
1702             if (empty($submission->timemodified)) {   // eg for offline assignments
1703                 // $submission->timemodified = time();
1704             }
1706             $DB->update_record('assignment_submissions', $submission);
1708             // triger grade event
1709             $this->update_grade($submission);
1711             add_to_log($this->course->id, 'assignment', 'update grades',
1712                        'submissions.php?id='.$this->cm->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
1713              if (!is_null($formdata)) {
1714                     if ($this->type == 'upload' || $this->type == 'uploadsingle') {
1715                         $mformdata = $formdata->mform->get_data();
1716                         $mformdata = file_postupdate_standard_filemanager($mformdata, 'files', $formdata->fileui_options, $this->context, 'mod_assignment', 'response', $submission->id);
1717                     }
1718              }
1719         }
1721         return $submission;
1723     }
1725     function process_outcomes($userid) {
1726         global $CFG, $USER;
1728         if (empty($CFG->enableoutcomes)) {
1729             return;
1730         }
1732         require_once($CFG->libdir.'/gradelib.php');
1734         if (!$formdata = data_submitted() or !confirm_sesskey()) {
1735             return;
1736         }
1738         $data = array();
1739         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
1741         if (!empty($grading_info->outcomes)) {
1742             foreach($grading_info->outcomes as $n=>$old) {
1743                 $name = 'outcome_'.$n;
1744                 if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
1745                     $data[$n] = $formdata->{$name}[$userid];
1746                 }
1747             }
1748         }
1749         if (count($data) > 0) {
1750             grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1751         }
1753     }
1755     /**
1756      * Load the submission object for a particular user
1757      *
1758      * @global object
1759      * @global object
1760      * @param $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1761      * @param $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1762      * @param bool $teachermodified student submission set if false
1763      * @return object The submission
1764      */
1765     function get_submission($userid=0, $createnew=false, $teachermodified=false) {
1766         global $USER, $DB;
1768         if (empty($userid)) {
1769             $userid = $USER->id;
1770         }
1772         $submission = $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1774         if ($submission || !$createnew) {
1775             return $submission;
1776         }
1777         $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
1778         $DB->insert_record("assignment_submissions", $newsubmission);
1780         return $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1781     }
1783     /**
1784      * Instantiates a new submission object for a given user
1785      *
1786      * Sets the assignment, userid and times, everything else is set to default values.
1787      *
1788      * @param int $userid The userid for which we want a submission object
1789      * @param bool $teachermodified student submission set if false
1790      * @return object The submission
1791      */
1792     function prepare_new_submission($userid, $teachermodified=false) {
1793         $submission = new stdClass();
1794         $submission->assignment   = $this->assignment->id;
1795         $submission->userid       = $userid;
1796         $submission->timecreated = time();
1797         // teachers should not be modifying modified date, except offline assignments
1798         if ($teachermodified) {
1799             $submission->timemodified = 0;
1800         } else {
1801             $submission->timemodified = $submission->timecreated;
1802         }
1803         $submission->numfiles     = 0;
1804         $submission->data1        = '';
1805         $submission->data2        = '';
1806         $submission->grade        = -1;
1807         $submission->submissioncomment      = '';
1808         $submission->format       = 0;
1809         $submission->teacher      = 0;
1810         $submission->timemarked   = 0;
1811         $submission->mailed       = 0;
1812         return $submission;
1813     }
1815     /**
1816      * Return all assignment submissions by ENROLLED students (even empty)
1817      *
1818      * @param string $sort optional field names for the ORDER BY in the sql query
1819      * @param string $dir optional specifying the sort direction, defaults to DESC
1820      * @return array The submission objects indexed by id
1821      */
1822     function get_submissions($sort='', $dir='DESC') {
1823         return assignment_get_all_submissions($this->assignment, $sort, $dir);
1824     }
1826     /**
1827      * Counts all real assignment submissions by ENROLLED students (not empty ones)
1828      *
1829      * @param int $groupid optional If nonzero then count is restricted to this group
1830      * @return int The number of submissions
1831      */
1832     function count_real_submissions($groupid=0) {
1833         return assignment_count_real_submissions($this->cm, $groupid);
1834     }
1836     /**
1837      * Alerts teachers by email of new or changed assignments that need grading
1838      *
1839      * First checks whether the option to email teachers is set for this assignment.
1840      * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1841      * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1842      *
1843      * @global object
1844      * @global object
1845      * @param $submission object The submission that has changed
1846      * @return void
1847      */
1848     function email_teachers($submission) {
1849         global $CFG, $DB;
1851         if (empty($this->assignment->emailteachers)) {          // No need to do anything
1852             return;
1853         }
1855         $user = $DB->get_record('user', array('id'=>$submission->userid));
1857         if ($teachers = $this->get_graders($user)) {
1859             $strassignments = get_string('modulenameplural', 'assignment');
1860             $strassignment  = get_string('modulename', 'assignment');
1861             $strsubmitted  = get_string('submitted', 'assignment');
1863             foreach ($teachers as $teacher) {
1864                 $info = new stdClass();
1865                 $info->username = fullname($user, true);
1866                 $info->assignment = format_string($this->assignment->name,true);
1867                 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
1868                 $info->timeupdated = strftime('%c',$submission->timemodified);
1870                 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1871                 $posttext = $this->email_teachers_text($info);
1872                 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
1874                 $eventdata = new stdClass();
1875                 $eventdata->modulename       = 'assignment';
1876                 $eventdata->userfrom         = $user;
1877                 $eventdata->userto           = $teacher;
1878                 $eventdata->subject          = $postsubject;
1879                 $eventdata->fullmessage      = $posttext;
1880                 $eventdata->fullmessageformat = FORMAT_PLAIN;
1881                 $eventdata->fullmessagehtml  = $posthtml;
1882                 $eventdata->smallmessage     = $postsubject;
1884                 $eventdata->name            = 'assignment_updates';
1885                 $eventdata->component       = 'mod_assignment';
1886                 $eventdata->notification    = 1;
1887                 $eventdata->contexturl      = $info->url;
1888                 $eventdata->contexturlname  = $info->assignment;
1890                 message_send($eventdata);
1891             }
1892         }
1893     }
1895     /**
1896      * @param string $filearea
1897      * @param array $args
1898      * @return bool
1899      */
1900     function send_file($filearea, $args) {
1901         debugging('plugin does not implement file sending', DEBUG_DEVELOPER);
1902         return false;
1903     }
1905     /**
1906      * Returns a list of teachers that should be grading given submission
1907      *
1908      * @param object $user
1909      * @return array
1910      */
1911     function get_graders($user) {
1912         //potential graders
1913         $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false);
1915         $graders = array();
1916         if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) {   // Separate groups are being used
1917             if ($groups = groups_get_all_groups($this->course->id, $user->id)) {  // Try to find all groups
1918                 foreach ($groups as $group) {
1919                     foreach ($potgraders as $t) {
1920                         if ($t->id == $user->id) {
1921                             continue; // do not send self
1922                         }
1923                         if (groups_is_member($group->id, $t->id)) {
1924                             $graders[$t->id] = $t;
1925                         }
1926                     }
1927                 }
1928             } else {
1929                 // user not in group, try to find graders without group
1930                 foreach ($potgraders as $t) {
1931                     if ($t->id == $user->id) {
1932                         continue; // do not send self
1933                     }
1934                     if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
1935                         $graders[$t->id] = $t;
1936                     }
1937                 }
1938             }
1939         } else {
1940             foreach ($potgraders as $t) {
1941                 if ($t->id == $user->id) {
1942                     continue; // do not send self
1943                 }
1944                 $graders[$t->id] = $t;
1945             }
1946         }
1947         return $graders;
1948     }
1950     /**
1951      * Creates the text content for emails to teachers
1952      *
1953      * @param $info object The info used by the 'emailteachermail' language string
1954      * @return string
1955      */
1956     function email_teachers_text($info) {
1957         $posttext  = format_string($this->course->shortname, true, array('context' => $this->coursecontext)).' -> '.
1958                      $this->strassignments.' -> '.
1959                      format_string($this->assignment->name, true, array('context' => $this->context))."\n";
1960         $posttext .= '---------------------------------------------------------------------'."\n";
1961         $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
1962         $posttext .= "\n---------------------------------------------------------------------\n";
1963         return $posttext;
1964     }
1966      /**
1967      * Creates the html content for emails to teachers
1968      *
1969      * @param $info object The info used by the 'emailteachermailhtml' language string
1970      * @return string
1971      */
1972     function email_teachers_html($info) {
1973         global $CFG;
1974         $posthtml  = '<p><font face="sans-serif">'.
1975                      '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname, true, array('context' => $this->coursecontext)).'</a> ->'.
1976                      '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
1977                      '<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>';
1978         $posthtml .= '<hr /><font face="sans-serif">';
1979         $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
1980         $posthtml .= '</font><hr />';
1981         return $posthtml;
1982     }
1984     /**
1985      * Produces a list of links to the files uploaded by a user
1986      *
1987      * @param $userid int optional id of the user. If 0 then $USER->id is used.
1988      * @param $return boolean optional defaults to false. If true the list is returned rather than printed
1989      * @return string optional
1990      */
1991     function print_user_files($userid=0, $return=false) {
1992         global $CFG, $USER, $OUTPUT;
1994         if (!$userid) {
1995             if (!isloggedin()) {
1996                 return '';
1997             }
1998             $userid = $USER->id;
1999         }
2001         $output = '';
2003         $submission = $this->get_submission($userid);
2004         if (!$submission) {
2005             return $output;
2006         }
2008         $fs = get_file_storage();
2009         $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false);
2010         if (!empty($files)) {
2011             require_once($CFG->dirroot . '/mod/assignment/locallib.php');
2012             if ($CFG->enableportfolios) {
2013                 require_once($CFG->libdir.'/portfoliolib.php');
2014                 $button = new portfolio_add_button();
2015             }
2016             foreach ($files as $file) {
2017                 $filename = $file->get_filename();
2018                 $mimetype = $file->get_mimetype();
2019                 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/mod_assignment/submission/'.$submission->id.'/'.$filename);
2020                 $output .= '<a href="'.$path.'" ><img src="'.$OUTPUT->pix_url(file_mimetype_icon($mimetype)).'" class="icon" alt="'.$mimetype.'" />'.s($filename).'</a>';
2021                 if ($CFG->enableportfolios && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
2022                     $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id, 'submissionid' => $submission->id, 'fileid' => $file->get_id()), '/mod/assignment/locallib.php');
2023                     $button->set_format_by_file($file);
2024                     $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
2025                 }
2027                 if ($CFG->enableplagiarism) {
2028                     require_once($CFG->libdir.'/plagiarismlib.php');
2029                     $output .= plagiarism_get_links(array('userid'=>$userid, 'file'=>$file, 'cmid'=>$this->cm->id, 'course'=>$this->course, 'assignment'=>$this->assignment));
2030                     $output .= '<br />';
2031                 }
2032             }
2033             if ($CFG->enableportfolios && count($files) > 1  && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
2034                 $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id, 'submissionid' => $submission->id), '/mod/assignment/locallib.php');
2035                 $output .= '<br />'  . $button->to_html(PORTFOLIO_ADD_TEXT_LINK);
2036             }
2037         }
2039         $output = '<div class="files">'.$output.'</div>';
2041         if ($return) {
2042             return $output;
2043         }
2044         echo $output;
2045     }
2047     /**
2048      * Count the files uploaded by a given user
2049      *
2050      * @param $itemid int The submission's id as the file's itemid.
2051      * @return int
2052      */
2053     function count_user_files($itemid) {
2054         $fs = get_file_storage();
2055         $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $itemid, "id", false);
2056         return count($files);
2057     }
2059     /**
2060      * Returns true if the student is allowed to submit
2061      *
2062      * Checks that the assignment has started and, if the option to prevent late
2063      * submissions is set, also checks that the assignment has not yet closed.
2064      * @return boolean
2065      */
2066     function isopen() {
2067         $time = time();
2068         if ($this->assignment->preventlate && $this->assignment->timedue) {
2069             return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
2070         } else {
2071             return ($this->assignment->timeavailable <= $time);
2072         }
2073     }
2076     /**
2077      * Return true if is set description is hidden till available date
2078      *
2079      * This is needed by calendar so that hidden descriptions do not
2080      * come up in upcoming events.
2081      *
2082      * Check that description is hidden till available date
2083      * By default return false
2084      * Assignments types should implement this method if needed
2085      * @return boolen
2086      */
2087     function description_is_hidden() {
2088         return false;
2089     }
2091     /**
2092      * Return an outline of the user's interaction with the assignment
2093      *
2094      * The default method prints the grade and timemodified
2095      * @param $grade object
2096      * @return object with properties ->info and ->time
2097      */
2098     function user_outline($grade) {
2100         $result = new stdClass();
2101         $result->info = get_string('grade').': '.$grade->str_long_grade;
2102         $result->time = $grade->dategraded;
2103         return $result;
2104     }
2106     /**
2107      * Print complete information about the user's interaction with the assignment
2108      *
2109      * @param $user object
2110      */
2111     function user_complete($user, $grade=null) {
2112         global $OUTPUT;
2114         if ($submission = $this->get_submission($user->id)) {
2116             $fs = get_file_storage();
2118             if ($files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false)) {
2119                 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
2120                 foreach ($files as $file) {
2121                     $countfiles .= "; ".$file->get_filename();
2122                 }
2123             }
2125             echo $OUTPUT->box_start();
2126             echo get_string("lastmodified").": ";
2127             echo userdate($submission->timemodified);
2128             echo $this->display_lateness($submission->timemodified);
2130             $this->print_user_files($user->id);
2132             echo '<br />';
2134             $this->view_feedback($submission);
2136             echo $OUTPUT->box_end();
2138         } else {
2139             if ($grade) {
2140                 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
2141                 if ($grade->str_feedback) {
2142                     echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
2143                 }
2144             }
2145             print_string("notsubmittedyet", "assignment");
2146         }
2147     }
2149     /**
2150      * Return a string indicating how late a submission is
2151      *
2152      * @param $timesubmitted int
2153      * @return string
2154      */
2155     function display_lateness($timesubmitted) {
2156         return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
2157     }
2159     /**
2160      * Empty method stub for all delete actions.
2161      */
2162     function delete() {
2163         //nothing by default
2164         redirect('view.php?id='.$this->cm->id);
2165     }
2167     /**
2168      * Empty custom feedback grading form.
2169      */
2170     function custom_feedbackform($submission, $return=false) {
2171         //nothing by default
2172         return '';
2173     }
2175     /**
2176      * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
2177      * for the course (see resource).
2178      *
2179      * Given a course_module object, this function returns any "extra" information that may be needed
2180      * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
2181      *
2182      * @param $coursemodule object The coursemodule object (record).
2183      * @return cached_cm_info Object used to customise appearance on course page
2184      */
2185     function get_coursemodule_info($coursemodule) {
2186         return null;
2187     }
2189     /**
2190      * Plugin cron method - do not use $this here, create new assignment instances if needed.
2191      * @return void
2192      */
2193     function cron() {
2194         //no plugin cron by default - override if needed
2195     }
2197     /**
2198      * Reset all submissions
2199      */
2200     function reset_userdata($data) {
2201         global $CFG, $DB;
2203         if (!$DB->count_records('assignment', array('course'=>$data->courseid, 'assignmenttype'=>$this->type))) {
2204             return array(); // no assignments of this type present
2205         }
2207         $componentstr = get_string('modulenameplural', 'assignment');
2208         $status = array();
2210         $typestr = get_string('type'.$this->type, 'assignment');
2211         // ugly hack to support pluggable assignment type titles...
2212         if($typestr === '[[type'.$this->type.']]'){
2213             $typestr = get_string('type'.$this->type, 'assignment_'.$this->type);
2214         }
2216         if (!empty($data->reset_assignment_submissions)) {
2217             $assignmentssql = "SELECT a.id
2218                                  FROM {assignment} a
2219                                 WHERE a.course=? AND a.assignmenttype=?";
2220             $params = array($data->courseid, $this->type);
2222             // now get rid of all submissions and responses
2223             $fs = get_file_storage();
2224             if ($assignments = $DB->get_records_sql($assignmentssql, $params)) {
2225                 foreach ($assignments as $assignmentid=>$unused) {
2226                     if (!$cm = get_coursemodule_from_instance('assignment', $assignmentid)) {
2227                         continue;
2228                     }
2229                     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2230                     $fs->delete_area_files($context->id, 'mod_assignment', 'submission');
2231                     $fs->delete_area_files($context->id, 'mod_assignment', 'response');
2232                 }
2233             }
2235             $DB->delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)", $params);
2237             $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
2239             if (empty($data->reset_gradebook_grades)) {
2240                 // remove all grades from gradebook
2241                 assignment_reset_gradebook($data->courseid, $this->type);
2242             }
2243         }
2245         /// updating dates - shift may be negative too
2246         if ($data->timeshift) {
2247             shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
2248             $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
2249         }
2251         return $status;
2252     }
2255     function portfolio_exportable() {
2256         return false;
2257     }
2259     /**
2260      * base implementation for backing up subtype specific information
2261      * for one single module
2262      *
2263      * @param filehandle $bf file handle for xml file to write to
2264      * @param mixed $preferences the complete backup preference object
2265      *
2266      * @return boolean
2267      *
2268      * @static
2269      */
2270     static function backup_one_mod($bf, $preferences, $assignment) {
2271         return true;
2272     }
2274     /**
2275      * base implementation for backing up subtype specific information
2276      * for one single submission
2277      *
2278      * @param filehandle $bf file handle for xml file to write to
2279      * @param mixed $preferences the complete backup preference object
2280      * @param object $submission the assignment submission db record
2281      *
2282      * @return boolean
2283      *
2284      * @static
2285      */
2286     static function backup_one_submission($bf, $preferences, $assignment, $submission) {
2287         return true;
2288     }
2290     /**
2291      * base implementation for restoring subtype specific information
2292      * for one single module
2293      *
2294      * @param array  $info the array representing the xml
2295      * @param object $restore the restore preferences
2296      *
2297      * @return boolean
2298      *
2299      * @static
2300      */
2301     static function restore_one_mod($info, $restore, $assignment) {
2302         return true;
2303     }
2305     /**
2306      * base implementation for restoring subtype specific information
2307      * for one single submission
2308      *
2309      * @param object $submission the newly created submission
2310      * @param array  $info the array representing the xml
2311      * @param object $restore the restore preferences
2312      *
2313      * @return boolean
2314      *
2315      * @static
2316      */
2317     static function restore_one_submission($info, $restore, $assignment, $submission) {
2318         return true;
2319     }
2321 } ////// End of the assignment_base class
2324 class mod_assignment_grading_form extends moodleform {
2326     function definition() {
2327         global $OUTPUT;
2328         $mform =& $this->_form;
2330         if (isset($this->_customdata->advancedgradinginstance)) {
2331             $this->use_advanced_grading($this->_customdata->advancedgradinginstance);
2332         }
2334         $formattr = $mform->getAttributes();
2335         $formattr['id'] = 'submitform';
2336         $mform->setAttributes($formattr);
2337         // hidden params
2338         $mform->addElement('hidden', 'offset', ($this->_customdata->offset+1));
2339         $mform->setType('offset', PARAM_INT);
2340         $mform->addElement('hidden', 'userid', $this->_customdata->userid);
2341         $mform->setType('userid', PARAM_INT);
2342         $mform->addElement('hidden', 'nextid', $this->_customdata->nextid);
2343         $mform->setType('nextid', PARAM_INT);
2344         $mform->addElement('hidden', 'id', $this->_customdata->cm->id);
2345         $mform->setType('id', PARAM_INT);
2346         $mform->addElement('hidden', 'sesskey', sesskey());
2347         $mform->setType('sesskey', PARAM_ALPHANUM);
2348         $mform->addElement('hidden', 'mode', 'grade');
2349         $mform->setType('mode', PARAM_TEXT);
2350         $mform->addElement('hidden', 'menuindex', "0");
2351         $mform->setType('menuindex', PARAM_INT);
2352         $mform->addElement('hidden', 'saveuserid', "-1");
2353         $mform->setType('saveuserid', PARAM_INT);
2354         $mform->addElement('hidden', 'filter', "0");
2355         $mform->setType('filter', PARAM_INT);
2357         $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->user),
2358                                                 fullname($this->_customdata->user, true) . '<br/>' .
2359                                                 userdate($this->_customdata->submission->timemodified) .
2360                                                 $this->_customdata->lateness );
2362         $this->add_submission_content();
2363         $this->add_grades_section();
2365         $this->add_feedback_section();
2367         if ($this->_customdata->submission->timemarked) {
2368             $datestring = userdate($this->_customdata->submission->timemarked)."&nbsp; (".format_time(time() - $this->_customdata->submission->timemarked).")";
2369             $mform->addElement('header', 'Last Grade', get_string('lastgrade', 'assignment'));
2370             $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->teacher) ,
2371                                                     fullname($this->_customdata->teacher,true).
2372                                                     '<br/>'.$datestring);
2373         }
2374         // buttons
2375         $this->add_action_buttons();
2377     }
2379     private $advancegradinginstance;
2380     /**
2381      * Gets or sets the instance for advanced grading
2382      *
2383      * @param gradingform_instance $gradinginstance
2384      */
2385     public function use_advanced_grading($gradinginstance = false) {
2386         if ($gradinginstance !== false) {
2387             $this->advancegradinginstance = $gradinginstance;
2388         }
2389         return $this->advancegradinginstance;
2390     }
2392     function add_grades_section() {
2393         global $CFG;
2394         $mform =& $this->_form;
2395         $attributes = array();
2396         if ($this->_customdata->gradingdisabled) {
2397             $attributes['disabled'] ='disabled';
2398         }
2400         $mform->addElement('header', 'Grades', get_string('grades', 'grades'));
2402         $grademenu = make_grades_menu($this->_customdata->assignment->grade);
2403         if ($gradinginstance = $this->use_advanced_grading()) {
2404             $gradinginstance->get_controller()->set_grade_range($grademenu);
2405             $gradingelement = $mform->addElement('grading', 'advancedgrading', get_string('grade').':', array('gradinginstance' => $gradinginstance));
2406             if ($this->_customdata->gradingdisabled) {
2407                 $gradingelement->freeze();
2408             } else {
2409                 $mform->addElement('hidden', 'advancedgradinginstanceid', $gradinginstance->get_id());
2410             }
2411         } else {
2412             // use simple direct grading
2413             $grademenu['-1'] = get_string('nograde');
2415             $mform->addElement('select', 'xgrade', get_string('grade').':', $grademenu, $attributes);
2416             $mform->setDefault('xgrade', $this->_customdata->submission->grade ); //@fixme some bug when element called 'grade' makes it break
2417             $mform->setType('xgrade', PARAM_INT);
2418         }
2420         if (!empty($this->_customdata->enableoutcomes)) {
2421             foreach($this->_customdata->grading_info->outcomes as $n=>$outcome) {
2422                 $options = make_grades_menu(-$outcome->scaleid);
2423                 if ($outcome->grades[$this->_customdata->submission->userid]->locked) {
2424                     $options[0] = get_string('nooutcome', 'grades');
2425                     $mform->addElement('static', 'outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->name.':',
2426                             $options[$outcome->grades[$this->_customdata->submission->userid]->grade]);
2427                 } else {
2428                     $options[''] = get_string('nooutcome', 'grades');
2429                     $attributes = array('id' => 'menuoutcome_'.$n );
2430                     $mform->addElement('select', 'outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->name.':', $options, $attributes );
2431                     $mform->setType('outcome_'.$n.'['.$this->_customdata->userid.']', PARAM_INT);
2432                     $mform->setDefault('outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->grades[$this->_customdata->submission->userid]->grade );
2433                 }
2434             }
2435         }
2436         $course_context = get_context_instance(CONTEXT_MODULE , $this->_customdata->cm->id);
2437         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
2438             $grade = '<a href="'.$CFG->wwwroot.'/grade/report/grader/index.php?id='. $this->_customdata->courseid .'" >'.
2439                         $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade . '</a>';
2440         }else{
2441             $grade = $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade;
2442         }
2443         $mform->addElement('static', 'finalgrade', get_string('currentgrade', 'assignment').':' ,$grade);
2444         $mform->setType('finalgrade', PARAM_INT);
2445     }
2447     /**
2448      *
2449      * @global core_renderer $OUTPUT
2450      */
2451     function add_feedback_section() {
2452         global $OUTPUT;
2453         $mform =& $this->_form;
2454         $mform->addElement('header', 'Feed Back', get_string('feedback', 'grades'));
2456         if ($this->_customdata->gradingdisabled) {
2457             $mform->addElement('static', 'disabledfeedback', $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_feedback );
2458         } else {
2459             // visible elements
2461             $mform->addElement('editor', 'submissioncomment_editor', get_string('feedback', 'assignment').':', null, $this->get_editor_options() );
2462             $mform->setType('submissioncomment_editor', PARAM_RAW); // to be cleaned before display
2463             $mform->setDefault('submissioncomment_editor', $this->_customdata->submission->submissioncomment);
2464             //$mform->addRule('submissioncomment', get_string('required'), 'required', null, 'client');
2465             switch ($this->_customdata->assignment->assignmenttype) {
2466                 case 'upload' :
2467                 case 'uploadsingle' :
2468                     $mform->addElement('filemanager', 'files_filemanager', get_string('responsefiles', 'assignment'). ':', null, $this->_customdata->fileui_options);
2469                     break;
2470                 default :
2471                     break;
2472             }
2473             $mform->addElement('hidden', 'mailinfo_h', "0");
2474             $mform->setType('mailinfo_h', PARAM_INT);
2475             $mform->addElement('checkbox', 'mailinfo',get_string('enablenotification','assignment').
2476             $OUTPUT->help_icon('enablenotification', 'assignment') .':' );
2477             $mform->setType('mailinfo', PARAM_INT);
2478         }
2479     }
2481     function add_action_buttons() {
2482         $mform =& $this->_form;
2483         //if there are more to be graded.
2484         if ($this->_customdata->nextid>0) {
2485             $buttonarray=array();
2486             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2487             //@todo: fix accessibility: javascript dependency not necessary
2488             $buttonarray[] = &$mform->createElement('submit', 'saveandnext', get_string('saveandnext'));
2489             $buttonarray[] = &$mform->createElement('submit', 'next', get_string('next'));
2490             $buttonarray[] = &$mform->createElement('cancel');
2491         } else {
2492             $buttonarray=array();
2493             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2494             $buttonarray[] = &$mform->createElement('cancel');
2495         }
2496         $mform->addGroup($buttonarray, 'grading_buttonar', '', array(' '), false);
2497         $mform->closeHeaderBefore('grading_buttonar');
2498         $mform->setType('grading_buttonar', PARAM_RAW);
2499     }
2501     function add_submission_content() {
2502         $mform =& $this->_form;
2503         $mform->addElement('header', 'Submission', get_string('submission', 'assignment'));
2504         $mform->addElement('static', '', '' , $this->_customdata->submission_content );
2505     }
2507     protected function get_editor_options() {
2508         $editoroptions = array();
2509         $editoroptions['component'] = 'mod_assignment';
2510         $editoroptions['filearea'] = 'feedback';
2511         $editoroptions['noclean'] = false;
2512         $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)
2513         $editoroptions['maxbytes'] = $this->_customdata->maxbytes;
2514         $editoroptions['context'] = $this->_customdata->context;
2515         return $editoroptions;
2516     }
2518     public function set_data($data) {
2519         $editoroptions = $this->get_editor_options();
2520         if (!isset($data->text)) {
2521             $data->text = '';
2522         }
2523         if (!isset($data->format)) {
2524             $data->textformat = FORMAT_HTML;
2525         } else {
2526             $data->textformat = $data->format;
2527         }
2529         if (!empty($this->_customdata->submission->id)) {
2530             $itemid = $this->_customdata->submission->id;
2531         } else {
2532             $itemid = null;
2533         }
2535         switch ($this->_customdata->assignment->assignmenttype) {
2536                 case 'upload' :
2537                 case 'uploadsingle' :
2538                     $data = file_prepare_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2539                     break;
2540                 default :
2541                     break;
2542         }
2544         $data = file_prepare_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2545         return parent::set_data($data);
2546     }
2548     public function get_data() {
2549         $data = parent::get_data();
2551         if (!empty($this->_customdata->submission->id)) {
2552             $itemid = $this->_customdata->submission->id;
2553         } else {
2554             $itemid = null; //TODO: this is wrong, itemid MUST be known when saving files!! (skodak)
2555         }
2557         if ($data) {
2558             $editoroptions = $this->get_editor_options();
2559             switch ($this->_customdata->assignment->assignmenttype) {
2560                 case 'upload' :
2561                 case 'uploadsingle' :
2562                     $data = file_postupdate_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2563                     break;
2564                 default :
2565                     break;
2566             }
2567             $data = file_postupdate_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2568         }
2570         if ($this->use_advanced_grading() && !isset($data->advancedgrading)) {
2571             $data->advancedgrading = null;
2572         }
2574         return $data;
2575     }
2578 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
2580 /**
2581  * Deletes an assignment instance
2582  *
2583  * This is done by calling the delete_instance() method of the assignment type class
2584  */
2585 function assignment_delete_instance($id){
2586     global $CFG, $DB;
2588     if (! $assignment = $DB->get_record('assignment', array('id'=>$id))) {
2589         return false;
2590     }
2592     // fall back to base class if plugin missing
2593     $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2594     if (file_exists($classfile)) {
2595         require_once($classfile);
2596         $assignmentclass = "assignment_$assignment->assignmenttype";
2598     } else {
2599         debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
2600         $assignmentclass = "assignment_base";
2601     }
2603     $ass = new $assignmentclass();
2604     return $ass->delete_instance($assignment);
2608 /**
2609  * Updates an assignment instance
2610  *
2611  * This is done by calling the update_instance() method of the assignment type class
2612  */
2613 function assignment_update_instance($assignment){
2614     global $CFG;
2616     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_PLUGIN);
2618     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2619     $assignmentclass = "assignment_$assignment->assignmenttype";
2620     $ass = new $assignmentclass();
2621     return $ass->update_instance($assignment);
2625 /**
2626  * Adds an assignment instance
2627  *
2628  * This is done by calling the add_instance() method of the assignment type class
2629  */
2630 function assignment_add_instance($assignment) {
2631     global $CFG;
2633     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_PLUGIN);
2635     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2636     $assignmentclass = "assignment_$assignment->assignmenttype";
2637     $ass = new $assignmentclass();
2638     return $ass->add_instance($assignment);
2642 /**
2643  * Returns an outline of a user interaction with an assignment
2644  *
2645  * This is done by calling the user_outline() method of the assignment type class
2646  */
2647 function assignment_user_outline($course, $user, $mod, $assignment) {
2648     global $CFG;
2650     require_once("$CFG->libdir/gradelib.php");
2651     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2652     $assignmentclass = "assignment_$assignment->assignmenttype";
2653     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2654     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2655     if (!empty($grades->items[0]->grades)) {
2656         return $ass->user_outline(reset($grades->items[0]->grades));
2657     } else {
2658         return null;
2659     }
2662 /**
2663  * Prints the complete info about a user's interaction with an assignment
2664  *
2665  * This is done by calling the user_complete() method of the assignment type class
2666  */
2667 function assignment_user_complete($course, $user, $mod, $assignment) {
2668     global $CFG;
2670     require_once("$CFG->libdir/gradelib.php");
2671     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2672     $assignmentclass = "assignment_$assignment->assignmenttype";
2673     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2674     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2675     if (empty($grades->items[0]->grades)) {
2676         $grade = false;
2677     } else {
2678         $grade = reset($grades->items[0]->grades);
2679     }
2680     return $ass->user_complete($user, $grade);
2683 /**
2684  * Function to be run periodically according to the moodle cron
2685  *
2686  * Finds all assignment notifications that have yet to be mailed out, and mails them
2687  */
2688 function assignment_cron () {
2689     global $CFG, $USER, $DB;
2691     /// first execute all crons in plugins
2692     if ($plugins = get_plugin_list('assignment')) {
2693         foreach ($plugins as $plugin=>$dir) {
2694             require_once("$dir/assignment.class.php");
2695             $assignmentclass = "assignment_$plugin";
2696             $ass = new $assignmentclass();
2697             $ass->cron();
2698         }
2699     }
2701     /// Notices older than 1 day will not be mailed.  This is to avoid the problem where
2702     /// cron has not been running for a long time, and then suddenly people are flooded
2703     /// with mail from the past few weeks or months
2705     $timenow   = time();
2706     $endtime   = $timenow - $CFG->maxeditingtime;
2707     $starttime = $endtime - 24 * 3600;   /// One day earlier
2709     if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2711         $realuser = clone($USER);
2713         foreach ($submissions as $key => $submission) {
2714             $DB->set_field("assignment_submissions", "mailed", "1", array("id"=>$submission->id));
2715         }
2717         $timenow = time();
2719         foreach ($submissions as $submission) {
2721             echo "Processing assignment submission $submission->id\n";
2723             if (! $user = $DB->get_record("user", array("id"=>$submission->userid))) {
2724                 echo "Could not find user $user->id\n";
2725                 continue;
2726             }
2728             if (! $course = $DB->get_record("course", array("id"=>$submission->course))) {
2729                 echo "Could not find course $submission->course\n";
2730                 continue;
2731             }
2733             /// Override the language and timezone of the "current" user, so that
2734             /// mail is customised for the receiver.
2735             cron_setup_user($user, $course);
2737             $coursecontext = get_context_instance(CONTEXT_COURSE, $submission->course);
2738             $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
2739             if (!is_enrolled($coursecontext, $user->id)) {
2740                 echo fullname($user)." not an active participant in " . $courseshortname . "\n";
2741                 continue;
2742             }
2744             if (! $teacher = $DB->get_record("user", array("id"=>$submission->teacher))) {
2745                 echo "Could not find teacher $submission->teacher\n";
2746                 continue;
2747             }
2749             if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2750                 echo "Could not find course module for assignment id $submission->assignment\n";
2751                 continue;
2752             }
2754             if (! $mod->visible) {    /// Hold mail notification for hidden assignments until later
2755                 continue;
2756             }
2758             $strassignments = get_string("modulenameplural", "assignment");
2759             $strassignment  = get_string("modulename", "assignment");
2761             $assignmentinfo = new stdClass();
2762             $assignmentinfo->teacher = fullname($teacher);
2763             $assignmentinfo->assignment = format_string($submission->name,true);
2764             $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2766             $postsubject = "$courseshortname: $strassignments: ".format_string($submission->name,true);
2767             $posttext  = "$courseshortname -> $strassignments -> ".format_string($submission->name,true)."\n";
2768             $posttext .= "---------------------------------------------------------------------\n";
2769             $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2770             $posttext .= "---------------------------------------------------------------------\n";
2772             if ($user->mailformat == 1) {  // HTML
2773                 $posthtml = "<p><font face=\"sans-serif\">".
2774                 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$courseshortname</a> ->".
2775                 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2776                 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2777                 $posthtml .= "<hr /><font face=\"sans-serif\">";
2778                 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2779                 $posthtml .= "</font><hr />";
2780             } else {
2781                 $posthtml = "";
2782             }
2784             $eventdata = new stdClass();
2785             $eventdata->modulename       = 'assignment';
2786             $eventdata->userfrom         = $teacher;
2787             $eventdata->userto           = $user;
2788             $eventdata->subject          = $postsubject;
2789             $eventdata->fullmessage      = $posttext;
2790             $eventdata->fullmessageformat = FORMAT_PLAIN;
2791             $eventdata->fullmessagehtml  = $posthtml;
2792             $eventdata->smallmessage     = get_string('assignmentmailsmall', 'assignment', $assignmentinfo);
2794             $eventdata->name            = 'assignment_updates';
2795             $eventdata->component       = 'mod_assignment';
2796             $eventdata->notification    = 1;
2797             $eventdata->contexturl      = $assignmentinfo->url;
2798             $eventdata->contexturlname  = $assignmentinfo->assignment;
2800             message_send($eventdata);
2801         }
2803         cron_setup_user();
2804     }
2806     return true;
2809 /**
2810  * Return grade for given user or all users.
2811  *
2812  * @param int $assignmentid id of assignment
2813  * @param int $userid optional user id, 0 means all users
2814  * @return array array of grades, false if none
2815  */
2816 function assignment_get_user_grades($assignment, $userid=0) {
2817     global $CFG, $DB;
2819     if ($userid) {
2820         $user = "AND u.id = :userid";
2821         $params = array('userid'=>$userid);
2822     } else {
2823         $user = "";
2824     }
2825     $params['aid'] = $assignment->id;
2827     $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2828                    s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2829               FROM {user} u, {assignment_submissions} s
2830              WHERE u.id = s.userid AND s.assignment = :aid
2831                    $user";
2833     return $DB->get_records_sql($sql, $params);
2836 /**
2837  * Update activity grades
2838  *
2839  * @param object $assignment
2840  * @param int $userid specific user only, 0 means all
2841  */
2842 function assignment_update_grades($assignment, $userid=0, $nullifnone=true) {
2843     global $CFG, $DB;
2844     require_once($CFG->libdir.'/gradelib.php');
2846     if ($assignment->grade == 0) {
2847         assignment_grade_item_update($assignment);
2849     } else if ($grades = assignment_get_user_grades($assignment, $userid)) {
2850         foreach($grades as $k=>$v) {
2851             if ($v->rawgrade == -1) {
2852                 $grades[$k]->rawgrade = null;
2853             }
2854         }
2855         assignment_grade_item_update($assignment, $grades);
2857     } else {
2858         assignment_grade_item_update($assignment);
2859     }
2862 /**
2863  * Update all grades in gradebook.
2864  */
2865 function assignment_upgrade_grades() {
2866     global $DB;
2868     $sql = "SELECT COUNT('x')
2869               FROM {assignment} a, {course_modules} cm, {modules} m
2870              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2871     $count = $DB->count_records_sql($sql);
2873     $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
2874               FROM {assignment} a, {course_modules} cm, {modules} m
2875              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2876     $rs = $DB->get_recordset_sql($sql);
2877     if ($rs->valid()) {
2878         // too much debug output
2879         $pbar = new progress_bar('assignmentupgradegrades', 500, true);
2880         $i=0;
2881         foreach ($rs as $assignment) {
2882             $i++;
2883             upgrade_set_timeout(60*5); // set up timeout, may also abort execution
2884             assignment_update_grades($assignment);
2885             $pbar->update($i, $count, "Updating Assignment grades ($i/$count).");
2886         }
2887         upgrade_set_timeout(); // reset to default timeout
2888     }
2889     $rs->close();
2892 /**
2893  * Create grade item for given assignment
2894  *
2895  * @param object $assignment object with extra cmidnumber
2896  * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
2897  * @return int 0 if ok, error code otherwise
2898  */
2899 function assignment_grade_item_update($assignment, $grades=NULL) {
2900     global $CFG;
2901     require_once($CFG->libdir.'/gradelib.php');
2903     if (!isset($assignment->courseid)) {
2904         $assignment->courseid = $assignment->course;
2905     }
2907     $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
2909     if ($assignment->grade > 0) {
2910         $params['gradetype'] = GRADE_TYPE_VALUE;
2911         $params['grademax']  = $assignment->grade;
2912         $params['grademin']  = 0;
2914     } else if ($assignment->grade < 0) {
2915         $params['gradetype'] = GRADE_TYPE_SCALE;
2916         $params['scaleid']   = -$assignment->grade;
2918     } else {
2919         $params['gradetype'] = GRADE_TYPE_TEXT; // allow text comments only
2920     }
2922     if ($grades  === 'reset') {
2923         $params['reset'] = true;
2924         $grades = NULL;
2925     }
2927     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades, $params);
2930 /**
2931  * Delete grade item for given assignment
2932  *
2933  * @param object $assignment object
2934  * @return object assignment
2935  */
2936 function assignment_grade_item_delete($assignment) {
2937     global $CFG;
2938     require_once($CFG->libdir.'/gradelib.php');
2940     if (!isset($assignment->courseid)) {
2941         $assignment->courseid = $assignment->course;
2942     }
2944     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
2947 /**
2948  * Returns the users with data in one assignment (students and teachers)
2949  *
2950  * @todo: deprecated - to be deleted in 2.2
2951  *
2952  * @param $assignmentid int
2953  * @return array of user objects
2954  */
2955 function assignment_get_participants($assignmentid) {
2956     global $CFG, $DB;
2958     //Get students
2959     $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2960                                         FROM {user} u,
2961                                              {assignment_submissions} a
2962                                        WHERE a.assignment = ? and
2963                                              u.id = a.userid", array($assignmentid));
2964     //Get teachers
2965     $teachers = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2966                                         FROM {user} u,
2967                                              {assignment_submissions} a
2968                                        WHERE a.assignment = ? and
2969                                              u.id = a.teacher", array($assignmentid));
2971     //Add teachers to students
2972     if ($teachers) {
2973         foreach ($teachers as $teacher) {
2974             $students[$teacher->id] = $teacher;
2975         }
2976     }
2977     //Return students array (it contains an array of unique users)
2978     return ($students);
2981 /**
2982  * Serves assignment submissions and other files.
2983  *
2984  * @param object $course
2985  * @param object $cm
2986  * @param object $context
2987  * @param string $filearea
2988  * @param array $args
2989  * @param bool $forcedownload
2990  * @return bool false if file not found, does not return if found - just send the file
2991  */
2992 function assignment_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) {
2993     global $CFG, $DB;
2995     if ($context->contextlevel != CONTEXT_MODULE) {
2996         return false;
2997     }
2999     require_login($course, false, $cm);
3001     if (!$assignment = $DB->get_record('assignment', array('id'=>$cm->instance))) {
3002         return false;
3003     }
3005     require_once($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
3006     $assignmentclass = 'assignment_'.$assignment->assignmenttype;
3007     $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm, $course);
3009     return $assignmentinstance->send_file($filearea, $args);
3011 /**
3012  * Checks if a scale is being used by an assignment
3013  *
3014  * This is used by the backup code to decide whether to back up a scale
3015  * @param $assignmentid int
3016  * @param $scaleid int
3017  * @return boolean True if the scale is used by the assignment
3018  */
3019 function assignment_scale_used($assignmentid, $scaleid) {
3020     global $DB;
3022     $return = false;
3024     $rec = $DB->get_record('assignment', array('id'=>$assignmentid,'grade'=>-$scaleid));
3026     if (!empty($rec) && !empty($scaleid)) {
3027         $return = true;
3028     }
3030     return $return;
3033 /**
3034  * Checks if scale is being used by any instance of assignment
3035  *
3036  * This is used to find out if scale used anywhere
3037  * @param $scaleid int
3038  * @return boolean True if the scale is used by any assignment
3039  */
3040 function assignment_scale_used_anywhere($scaleid) {
3041     global $DB;
3043     if ($scaleid and $DB->record_exists('assignment', array('grade'=>-$scaleid))) {
3044         return true;
3045     } else {
3046         return false;
3047     }
3050 /**
3051  * Make sure up-to-date events are created for all assignment instances
3052  *
3053  * This standard function will check all instances of this module
3054  * and make sure there are up-to-date events created for each of them.
3055  * If courseid = 0, then every assignment event in the site is checked, else
3056  * only assignment events belonging to the course specified are checked.
3057  * This function is used, in its new format, by restore_refresh_events()
3058  *
3059  * @param $courseid int optional If zero then all assignments for all courses are covered
3060  * @return boolean Always returns true
3061  */
3062 function assignment_refresh_events($courseid = 0) {
3063     global $DB;
3065     if ($courseid == 0) {
3066         if (! $assignments = $DB->get_records("assignment")) {
3067             return true;
3068         }
3069     } else {
3070         if (! $assignments = $DB->get_records("assignment", array("course"=>$courseid))) {
3071             return true;
3072         }
3073     }
3074     $moduleid = $DB->get_field('modules', 'id', array('name'=>'assignment'));
3076     foreach ($assignments as $assignment) {
3077         $cm = get_coursemodule_from_id('assignment', $assignment->id);
3078         $event = new stdClass();
3079         $event->name        = $assignment->name;
3080         $event->description = format_module_intro('assignment', $assignment, $cm->id);
3081         $event->timestart   = $assignment->timedue;
3083         if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
3084             update_event($event);
3086         } else {
3087             $event->courseid    = $assignment->course;
3088             $event->groupid     = 0;
3089             $event->userid      = 0;
3090             $event->modulename  = 'assignment';
3091             $event->instance    = $assignment->id;
3092             $event->eventtype   = 'due';
3093             $event->timeduration = 0;
3094             $event->visible     = $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$assignment->id));
3095             add_event($event);
3096         }
3098     }
3099     return true;
3102 /**
3103  * Print recent activity from all assignments in a given course
3104  *
3105  * This is used by the recent activity block
3106  */
3107 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
3108     global $CFG, $USER, $DB, $OUTPUT;
3110     // do not use log table if possible, it may be huge
3112     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
3113                                                      u.firstname, u.lastname, u.email, u.picture
3114                                                 FROM {assignment_submissions} asb
3115                                                      JOIN {assignment} a      ON a.id = asb.assignment
3116                                                      JOIN {course_modules} cm ON cm.instance = a.id
3117                                                      JOIN {modules} md        ON md.id = cm.module
3118                                                      JOIN {user} u            ON u.id = asb.userid
3119                                                WHERE asb.timemodified > ? AND
3120                                                      a.course = ? AND
3121                                                      md.name = 'assignment'
3122                                             ORDER BY asb.timemodified ASC", array($timestart, $course->id))) {
3123          return false;
3124     }
3126     $modinfo =& get_fast_modinfo($course); // reference needed because we might load the groups
3127     $show    = array();
3128     $grader  = array();
3130     foreach($submissions as $submission) {
3131         if (!array_key_exists($submission->cmid, $modinfo->cms)) {
3132             continue;
3133         }
3134         $cm = $modinfo->cms[$submission->cmid];
3135         if (!$cm->uservisible) {
3136             continue;
3137         }
3138         if ($submission->userid == $USER->id) {
3139             $show[] = $submission;
3140             continue;
3141         }
3143         // the act of sumbitting of assignment may be considered private - only graders will see it if specified
3144         if (empty($CFG->assignment_showrecentsubmissions)) {
3145             if (!array_key_exists($cm->id, $grader)) {
3146                 $grader[$cm->id] = has_capability('moodle/grade:viewall', get_context_instance(CONTEXT_MODULE, $cm->id));
3147             }
3148             if (!$grader[$cm->id]) {
3149                 continue;
3150             }
3151         }
3153         $groupmode = groups_get_activity_groupmode($cm, $course);
3155         if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
3156             if (isguestuser()) {
3157                 // shortcut - guest user does not belong into any group
3158                 continue;
3159             }
3161             if (is_null($modinfo->groups)) {
3162                 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
3163             }
3165             // this will be slow - show only users that share group with me in this cm
3166             if (empty($modinfo->groups[$cm->id])) {
3167                 continue;
3168             }
3169             $usersgroups =  groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
3170             if (is_array($usersgroups)) {
3171                 $usersgroups = array_keys($usersgroups);
3172                 $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
3173                 if (empty($intersect)) {
3174                     continue;
3175                 }
3176             }
3177         }
3178         $show[] = $submission;
3179     }
3181     if (empty($show)) {
3182         return false;
3183     }
3185     echo $OUTPUT->heading(get_string('newsubmissions', 'assignment').':', 3);
3187     foreach ($show as $submission) {
3188         $cm = $modinfo->cms[$submission->cmid];
3189         $link = $CFG->wwwroot.'/mod/assignment/view.php?id='.$cm->id;
3190         print_recent_activity_note($submission->timemodified, $submission, $cm->name, $link, false, $viewfullnames);
3191     }
3193     return true;
3197 /**
3198  * Returns all assignments since a given time in specified forum.
3199  */
3200 function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0)  {
3201     global $CFG, $COURSE, $USER, $DB;
3203     if ($COURSE->id == $courseid) {
3204         $course = $COURSE;
3205     } else {
3206         $course = $DB->get_record('course', array('id'=>$courseid));
3207     }
3209     $modinfo =& get_fast_modinfo($course);
3211     $cm = $modinfo->cms[$cmid];
3213     $params = array();
3214     if ($userid) {
3215         $userselect = "AND u.id = :userid";
3216         $params['userid'] = $userid;
3217     } else {
3218         $userselect = "";
3219     }
3221     if ($groupid) {
3222         $groupselect = "AND gm.groupid = :groupid";
3223         $groupjoin   = "JOIN {groups_members} gm ON  gm.userid=u.id";
3224         $params['groupid'] = $groupid;
3225     } else {
3226         $groupselect = "";
3227         $groupjoin   = "";
3228     }
3230     $params['cminstance'] = $cm->instance;
3231     $params['timestart'] = $timestart;
3233     $userfields = user_picture::fields('u', null, 'userid');
3235     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified,
3236                                                      $userfields
3237                                                 FROM {assignment_submissions} asb
3238                                                 JOIN {assignment} a      ON a.id = asb.assignment
3239                                                 JOIN {user} u            ON u.id = asb.userid
3240                                           $groupjoin
3241                                                WHERE asb.timemodified > :timestart AND a.id = :cminstance
3242                                                      $userselect $groupselect
3243                                             ORDER BY asb.timemodified ASC", $params)) {
3244          return;
3245     }
3247     $groupmode       = groups_get_activity_groupmode($cm, $course);
3248     $cm_context      = get_context_instance(CONTEXT_MODULE, $cm->id);
3249     $grader          = has_capability('moodle/grade:viewall', $cm_context);
3250     $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
3251     $viewfullnames   = has_capability('moodle/site:viewfullnames', $cm_context);
3253     if (is_null($modinfo->groups)) {
3254         $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
3255     }
3257     $show = array();
3259     foreach($submissions as $submission) {
3260         if ($submission->userid == $USER->id) {
3261             $show[] = $submission;
3262             continue;
3263         }
3264         // the act of submitting of assignment may be considered private - only graders will see it if specified
3265         if (empty($CFG->assignment_showrecentsubmissions)) {
3266             if (!$grader) {
3267                 continue;
3268             }
3269         }
3271         if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
3272             if (isguestuser()) {
3273                 // shortcut - guest user does not belong into any group
3274                 continue;
3275             }
3277             // this will be slow - show only users that share group with me in this cm
3278             if (empty($modinfo->groups[$cm->id])) {
3279                 continue;
3280             }
3281             $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
3282             if (is_array($usersgroups)) {
3283                 $usersgroups = array_keys($usersgroups);
3284                 $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
3285                 if (empty($intersect)) {
3286                     continue;
3287                 }
3288             }
3289         }
3290         $show[] = $submission;
3291     }
3293     if (empty($show)) {
3294         return;
3295     }
3297     if ($grader) {
3298         require_once($CFG->libdir.'/gradelib.php');
3299         $userids = array();
3300         foreach ($show as $id=>$submission) {
3301             $userids[] = $submission->userid;
3303         }
3304         $grades = grade_get_grades($courseid, 'mod', 'assignment', $cm->instance, $userids);
3305     }
3307     $aname = format_string($cm->name,true);
3308     foreach ($show as $submission) {
3309         $tmpactivity = new stdClass();
3311         $tmpactivity->type         = 'assignment';
3312         $tmpactivity->cmid         = $cm->id;
3313         $tmpactivity->name         = $aname;
3314         $tmpactivity->sectionnum   = $cm->sectionnum;
3315         $tmpactivity->timestamp    = $submission->timemodified;
3317         if ($grader) {
3318             $tmpactivity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
3319         }
3321         $userfields = explode(',', user_picture::fields());
3322         foreach ($userfields as $userfield) {
3323             if ($userfield == 'id') {
3324                 $tmpactivity->user->{$userfield} = $submission->userid; // aliased in SQL above
3325             } else {
3326                 $tmpactivity->user->{$userfield} = $submission->{$userfield};
3327             }
3328         }
3329         $tmpactivity->user->fullname = fullname($submission, $viewfullnames);
3331         $activities[$index++] = $tmpactivity;
3332     }
3334     return;
3337 /**
3338  * Print recent activity from all assignments in a given course
3339  *
3340  * This is used by course/recent.php
3341  */
3342 function assignment_print_recent_mod_activity($activity, $courseid, $detail, $modnames)  {
3343     global $CFG, $OUTPUT;
3345     echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
3347     echo "<tr><td class=\"userpicture\" valign=\"top\">";
3348     echo $OUTPUT->user_picture($activity->user);
3349     echo "</td><td>";
3351     if ($detail) {
3352         $modname = $modnames[$activity->type];
3353         echo '<div class="title">';
3354         echo "<img src=\"" . $OUTPUT->pix_url('icon', 'assignment') . "\" ".
3355              "class=\"icon\" alt=\"$modname\">";
3356         echo "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id={$activity->cmid}\">{$activity->name}</a>";
3357         echo '</div>';
3358     }
3360     if (isset($activity->grade)) {
3361         echo '<div class="grade">';
3362         echo get_string('grade').': ';
3363         echo $activity->grade;
3364         echo '</div>';
3365     }
3367     echo '<div class="user">';
3368     echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->id}&amp;course=$courseid\">"
3369          ."{$activity->user->fullname}</a>  - ".userdate($activity->timestamp);
3370     echo '</div>';
3372     echo "</td></tr></table>";
3375 /// GENERIC SQL FUNCTIONS
3377 /**
3378  * Fetch info from logs
3379  *
3380  * @param $log object with properties ->info (the assignment id) and ->userid
3381  * @return array with assignment name and user firstname and lastname
3382  */
3383 function assignment_log_info($log) {
3384     global $CFG, $DB;
3386     return $DB->get_record_sql("SELECT a.name, u.firstname, u.lastname
3387                                   FROM {assignment} a, {user} u
3388                                  WHERE a.id = ? AND u.id = ?", array($log->info, $log->userid));
3391 /**
3392  * Return list of marked submissions that have not been mailed out for currently enrolled students
3393  *
3394  * @return array
3395  */
3396 function assignment_get_unmailed_submissions($starttime, $endtime) {
3397     global $CFG, $DB;
3399     return $DB->get_records_sql("SELECT s.*, a.course, a.name
3400                                    FROM {assignment_submissions} s,
3401                                         {assignment} a
3402                                   WHERE s.mailed = 0
3403                                         AND s.timemarked <= ?
3404                                         AND s.timemarked >= ?
3405                                         AND s.assignment = a.id", array($endtime, $starttime));
3408 /**
3409  * Counts all real assignment submissions by ENROLLED students (not empty ones)
3410  *
3411  * There are also assignment type methods count_real_submissions() which in the default
3412  * implementation simply call this function.
3413  * @param $groupid int optional If nonzero then count is restricted to this group
3414  * @return int The number of submissions
3415  */
3416 function assignment_count_real_submissions($cm, $groupid=0) {
3417     global $CFG, $DB;
3419     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
3421     // this is all the users with this capability set, in this context or higher
3422     if ($users = get_enrolled_users($context, 'mod/assignment:view', $groupid, 'u.id')) {
3423         $users = array_keys($users);
3424     }
3426     // if groupmembersonly used, remove users who are not in any group
3427     if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
3428         if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
3429             $users = array_intersect($users, array_keys($groupingusers));
3430         }
3431     }
3433     if (empty($users)) {
3434         return 0;
3435     }
3437     $userlists = implode(',', $users);
3439     return $DB->count_records_sql("SELECT COUNT('x')
3440                                      FROM {assignment_submissions}
3441                                     WHERE assignment = ? AND
3442                                           timemodified > 0 AND
3443                                           userid IN ($userlists)", array($cm->instance));
3447 /**
3448  * Return all assignment submissions by ENROLLED students (even empty)
3449  *
3450  * There are also assignment type methods get_submissions() wich in the default
3451  * implementation simply call this function.
3452  * @param $sort string optional field names for the ORDER BY in the sql query
3453  * @param $dir string optional specifying the sort direction, defaults to DESC
3454  * @return array The submission objects indexed by id
3455  */
3456 function assignment_get_all_submissions($assignment, $sort="", $dir="DESC") {
3457 /// Return all assignment submissions by ENROLLED students (even empty)
3458     global $CFG, $DB;
3460     if ($sort == "lastname" or $sort == "firstname") {
3461         $sort = "u.$sort $dir";
3462     } else if (empty($sort)) {
3463         $sort = "a.timemodified DESC";
3464     } else {
3465         $sort = "a.$sort $dir";
3466     }
3468     /* not sure this is needed at all since assignment already has a course define, so this join?
3469     $select = "s.course = '$assignment->course' AND";
3470     if ($assignment->course == SITEID) {
3471         $select = '';
3472     }*/
3474     return $DB->get_records_sql("SELECT a.*
3475                                    FROM {assignment_submissions} a, {user} u
3476                                   WHERE u.id = a.userid
3477                                         AND a.assignment = ?
3478                                ORDER BY $sort", array($assignment->id));
3482 /**
3483  * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
3484  * for the course (see resource).
3485  *
3486  * Given a course_module object, this function returns any "extra" information that may be needed
3487  * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
3488  *
3489  * @param $coursemodule object The coursemodule object (record).
3490  * @return cached_cm_info An object on information that the courses will know about (most noticeably, an icon).
3491  */
3492 function assignment_get_coursemodule_info($coursemodule) {
3493     global $CFG, $DB;
3495     if (! $assignment = $DB->get_record('assignment', array('id'=>$coursemodule->instance),
3496             'id, assignmenttype, name, intro, introformat')) {
3497         return false;
3498     }
3500     $libfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
3502     if (file_exists($libfile)) {
3503         require_once($libfile);
3504         $assignmentclass = "assignment_$assignment->assignmenttype";
3505         $ass = new $assignmentclass('staticonly');
3506         if (!($result = $ass->get_coursemodule_info($coursemodule))) {
3507             $result = new cached_cm_info();
3508             $result->name = $assignment->name;
3509         }
3510         if ($coursemodule->showdescription) {
3511             // Convert intro to html. Do not filter cached version, filters run at display time.
3512             $info->content = format_module_intro('assignment', $assignment, $coursemodule->id, false);
3513         }
3514         return $result;
3515     } else {
3516         debugging('Incorrect assignment type: '.$assignment->assignmenttype);
3517         return false;
3518     }
3523 /// OTHER GENERAL FUNCTIONS FOR ASSIGNMENTS  ///////////////////////////////////////
3525 /**
3526  * Returns an array of installed assignment types indexed and sorted by name
3527  *
3528  * @return array The index is the name of the assignment type, the value its full name from the language strings
3529  */
3530 function assignment_types() {
3531     $types = array();
3532     $names = get_plugin_list('assignment');
3533     foreach ($names as $name=>$dir) {
3534         $types[$name] = get_string('type'.$name, 'assignment');
3536         // ugly hack to support pluggable assignment type titles..
3537         if ($types[$name] == '[[type'.$name.']]') {
3538             $types[$name] = get_string('type'.$name, 'assignment_'.$name);
3539         }
3540     }
3541     asort($types);
3542     return $types;
3545 function assignment_print_overview($courses, &$htmlarray) {
3546     global $USER, $CFG, $DB;
3548     if (empty($courses) || !is_array($courses) || count($courses) == 0) {
3549         return array();
3550     }
3552     if (!$assignments = get_all_instances_in_courses('assignment',$courses)) {
3553         return;
3554     }
3556     $assignmentids = array();
3558     // Do assignment_base::isopen() here without loading the whole thing for speed
3559     foreach ($assignments as $key => $assignment) {
3560         $time = time();
3561         if ($assignment->timedue) {
3562             if ($assignment->preventlate) {
3563                 $isopen = ($assignment->timeavailable <= $time && $time <= $assignment->timedue);
3564             } else {
3565                 $isopen = ($assignment->timeavailable <= $time);
3566             }
3567         }
3568         if (empty($isopen) || empty($assignment->timedue)) {
3569             unset($assignments[$key]);
3570         } else {
3571             $assignmentids[] = $assignment->id;
3572         }
3573     }
3575     if (empty($assignmentids)){
3576         // no assignments to look at - we're done
3577         return true;
3578     }
3580     $strduedate = get_string('duedate', 'assignment');
3581     $strduedateno = get_string('duedateno', 'assignment');
3582     $strgraded = get_string('graded', 'assignment');
3583     $strnotgradedyet = get_string('notgradedyet', 'assignment');
3584     $strnotsubmittedyet = get_string('notsubmittedyet', 'assignment');
3585     $strsubmitted = get_string('submitted', 'assignment');
3586     $strassignment = get_string('modulename', 'assignment');
3587     $strreviewed = get_string('reviewed','assignment');
3590     // NOTE: we do all possible database work here *outside* of the loop to ensure this scales
3591     //
3592     list($sqlassignmentids, $assignmentidparams) = $DB->get_in_or_equal($assignmentids);
3594     // build up and array of unmarked submissions indexed by assignment id/ userid
3595     // for use where the user has grading rights on assignment
3596     $rs = $DB->get_recordset_sql("SELECT id, assignment, userid
3597                             FROM {assignment_submissions}
3598                             WHERE teacher = 0 AND timemarked = 0
3599                             AND assignment $sqlassignmentids", $assignmentidparams);
3601     $unmarkedsubmissions = array();
3602     foreach ($rs as $rd) {
3603         $unmarkedsubmissions[$rd->assignment][$rd->userid] = $rd->id;
3604     }
3605     $rs->close();
3608     // get all user submissions, indexed by assignment id
3609     $mysubmissions = $DB->get_records_sql("SELECT assignment, timemarked, teacher, grade
3610                                       FROM {assignment_submissions}
3611                                       WHERE userid = ? AND
3612                                       assignment $sqlassignmentids", array_merge(array($USER->id), $assignmentidparams));
3614     foreach ($assignments as $assignment) {
3615         $str = '<div class="assignment overview"><div class="name">'.$strassignment. ': '.
3616                '<a '.($assignment->visible ? '':' class="dimmed"').
3617                'title="'.$strassignment.'" href="'.$CFG->wwwroot.
3618                '/mod/assignment/view.php?id='.$assignment->coursemodule.'">'.
3619                $assignment->name.'</a></div>';
3620         if ($assignment->timedue) {
3621             $str .= '<div class="info">'.$strduedate.': '.userdate($assignment->timedue).'</div>';
3622         } else {
3623             $str .= '<div class="info">'.$strduedateno.'</div>';
3624         }
3625         $context = get_context_instance(CONTEXT_MODULE, $assignment->coursemodule);
3626         if (has_capability('mod/assignment:grade', $context)) {
3628             // count how many people can submit
3629             $submissions = 0; // init
3630             if ($students = get_enrolled_users($context, 'mod/assignment:view', 0, 'u.id')) {
3631                 foreach ($students as $student) {
3632                     if (isset($unmarkedsubmissions[$assignment->id][$student->id])) {
3633                         $submissions++;
3634                     }
3635                 }
3636             }
3638             if ($submissions) {
3639                 $link = new moodle_url('/mod/assignment/submissions.php', array('id'=>$assignment->coursemodule));
3640                 $str .= '<div class="details"><a href="'.$link.'">'.get_string('submissionsnotgraded', 'assignment', $submissions).'</a></div>';
3641             }
3642         } else {
3643             $str .= '<div class="details">';
3644             if (isset($mysubmissions[$assignment->id])) {
3646                 $submission = $mysubmissions[$assignment->id];
3648                 if ($submission->teacher == 0 && $submission->timemarked == 0) {
3649                     $str .= $strsubmitted . ', ' . $strnotgradedyet;
3650                 } else if ($submission->grade <= 0) {
3651                     $str .= $strsubmitted . ', ' . $strreviewed;
3652                 } else {
3653                     $str .= $strsubmitted . ', ' . $strgraded;
3654                 }
3655             } else {
3656                 $str .= $strnotsubmittedyet . ' ' . assignment_display_lateness(time(), $assignment->timedue);
3657             }
3658             $str .= '</div>';
3659         }
3660         $str .= '</div>';
3661         if (empty($htmlarray[$assignment->course]['assignment'])) {
3662             $htmlarray[$assignment->course]['assignment'] = $str;
3663         } else {
3664             $htmlarray[$assignment->course]['assignment'] .= $str;
3665         }
3666     }
3669 function assignment_display_lateness($timesubmitted, $timedue) {
3670     if (!$timedue) {
3671         return '';
3672     }
3673     $time = $timedue - $timesubmitted;
3674     if ($time < 0) {
3675         $timetext = get_string('late', 'assignment', format_time($time));
3676         return ' (<span class="late">'.$timetext.'</span>)';
3677     } else {
3678         $timetext = get_string('early', 'assignment', format_time($time));
3679         return ' (<span class="early">'.$timetext.'</span>)';
3680     }
3683 function assignment_get_view_actions() {
3684     return array('view');
3687 function assignment_get_post_actions() {
3688     return array('upload');
3691 function assignment_get_types() {
3692     global $CFG;
3693     $types = array();
3695     $type = new stdClass();
3696     $type->modclass = MOD_CLASS_ACTIVITY;
3697     $type->type = "assignment_group_start";
3698     $type->typestr = '--'.get_string('modulenameplural', 'assignment');
3699     $types[] = $type;
3701     $standardassignments = array('upload','online','uploadsingle','offline');
3702     foreach ($standardassignments as $assignmenttype) {
3703         $type = new stdClass();
3704         $type->modclass = MOD_CLASS_ACTIVITY;
3705         $type->type = "assignment&amp;type=$assignmenttype";
3706         $type->typestr = get_string("type$assignmenttype", 'assignment');
3707         $types[] = $type;
3708     }
3710     /// Drop-in extra assignment types
3711     $assignmenttypes = get_list_of_plugins('mod/assignment/type');
3712     foreach ($assignmenttypes as $assignmenttype) {
3713         if (!empty($CFG->{'assignment_hide_'.$assignmenttype})) {  // Not wanted
3714             continue;
3715         }
3716         if (!in_array($assignmenttype, $standardassignments)) {
3717             $type = new stdClass();
3718             $type->modclass = MOD_CLASS_ACTIVITY;
3719             $type->type = "assignment&amp;type=$assignmenttype";
3720             $type->typestr = get_string("type$assignmenttype", 'assignment_'.$assignmenttype);
3721             $types[] = $type;
3722         }
3723     }
3725     $type = new stdClass();
3726     $type->modclass = MOD_CLASS_ACTIVITY;
3727     $type->type = "assignment_group_end";
3728     $type->typestr = '--';
3729     $types[] = $type;
3731     return $types;
3734 /**
3735  * Removes all grades from gradebook
3736  * @param int $courseid
3737  * @param string optional type
3738  */
3739 function assignment_reset_gradebook($courseid, $type='') {
3740     global $CFG, $DB;
3742     $params = array('courseid'=>$courseid);
3743     if ($type) {
3744         $type = "AND a.assignmenttype= :type";
3745         $params['type'] = $type;
3746     }
3748     $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
3749               FROM {assignment} a, {course_modules} cm, {modules} m
3750              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id AND a.course=:courseid $type";
3752     if ($assignments = $DB->get_records_sql($sql, $params)) {
3753         foreach ($assignments as $assignment) {
3754             assignment_grade_item_update($assignment, 'reset');
3755         }
3756     }
3759 /**
3760  * This function is used by the reset_course_userdata function in moodlelib.
3761  * This function will remove all posts from the specified assignment
3762  * and clean up any related data.
3763  * @param $data the data submitted from the reset course.
3764  * @return array status array
3765  */
3766 function assignment_reset_userdata($data) {
3767     global $CFG;
3769     $status = array();
3770     foreach (get_plugin_list('assignment') as $type=>$dir) {
3771         require_once("$dir/assignment.class.php");
3772         $assignmentclass = "assignment_$type";
3773         $ass = new $assignmentclass();
3774         $status = array_merge($status, $ass->reset_userdata($data));
3775     }
3777     return $status;
3780 /**
3781  * Implementation of the function for printing the form elements that control
3782  * whether the course reset functionality affects the assignment.
3783  * @param $mform form passed by reference
3784  */
3785 function assignment_reset_course_form_definition(&$mform) {
3786     $mform->addElement('header', 'assignmentheader', get_string('modulenameplural', 'assignment'));
3787     $mform->addElement('advcheckbox', 'reset_assignment_submissions', get_string('deleteallsubmissions','assignment'));
3790 /**
3791  * Course reset form defaults.
3792  */
3793 function assignment_reset_course_form_defaults($course) {
3794     return array('reset_assignment_submissions'=>1);
3797 /**
3798  * Returns all other caps used in module
3799  */
3800 function assignment_get_extra_capabilities() {
3801     return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames');
3804 /**
3805  * @param string $feature FEATURE_xx constant for requested feature
3806  * @return mixed True if module supports feature, null if doesn't know
3807  */
3808 function assignment_supports($feature) {
3809     switch($feature) {
3810         case FEATURE_GROUPS:                  return true;
3811         case FEATURE_GROUPINGS:               return true;
3812         case FEATURE_GROUPMEMBERSONLY:        return true;
3813         case FEATURE_MOD_INTRO:               return true;
3814         case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
3815         case FEATURE_GRADE_HAS_GRADE:         return true;
3816         case FEATURE_GRADE_OUTCOMES:          return true;
3817         case FEATURE_GRADE_HAS_GRADE:         return true;
3818         case FEATURE_BACKUP_MOODLE2:          return true;
3819         case FEATURE_SHOW_DESCRIPTION:        return true;
3820         case FEATURE_ADVANCED_GRADING:        return true;
3822         default: return null;
3823     }
3826 /**
3827  * Adds module specific settings to the settings block
3828  *
3829  * @param settings_navigation $settings The settings navigation object
3830  * @param navigation_node $assignmentnode The node to add module settings to
3831  */
3832 function assignment_extend_settings_navigation(settings_navigation $settings, navigation_node $assignmentnode) {
3833     global $PAGE, $DB, $USER, $CFG;
3835     $assignmentrow = $DB->get_record("assignment", array("id" => $PAGE->cm->instance));
3836     require_once "$CFG->dirroot/mod/assignment/type/$assignmentrow->assignmenttype/assignment.class.php";
3838     $assignmentclass = 'assignment_'.$assignmentrow->assignmenttype;
3839     $assignmentinstance = new $assignmentclass($PAGE->cm->id, $assignmentrow, $PAGE->cm, $PAGE->course);
3841     $allgroups = false;
3843     // Add assignment submission information
3844     if (has_capability('mod/assignment:grade', $PAGE->cm->context)) {
3845         if ($allgroups && has_capability('moodle/site:accessallgroups', $PAGE->cm->context)) {
3846             $group = 0;
3847         } else {
3848             $group = groups_get_activity_group($PAGE->cm);
3849         }
3850         $link = new moodle_url('/mod/assignment/submissions.php', array('id'=>$PAGE->cm->id));
3851         if ($assignmentrow->assignmenttype == 'offline') {
3852             $string = get_string('viewfeedback', 'assignment');
3853         } else if ($count = $assignmentinstance->count_real_submissions($group)) {
3854             $string = get_string('viewsubmissions', 'assignment', $count);
3855         } else {
3856             $string = get_string('noattempts', 'assignment');
3857         }
3858         $assignmentnode->add($string, $link, navigation_node::TYPE_SETTING);
3859     }
3861     if (is_object($assignmentinstance) && method_exists($assignmentinstance, 'extend_settings_navigation')) {
3862         $assignmentinstance->extend_settings_navigation($assignmentnode);
3863     }
3866 /**
3867  * generate zip file from array of given files
3868  * @param array $filesforzipping - array of files to pass into archive_to_pathname
3869  * @return path of temp file - note this returned file does not have a .zip extension - it is a temp file.
3870  */
3871 function assignment_pack_files($filesforzipping) {
3872         global $CFG;
3873         //create path for new zip file.
3874         $tempzip = tempnam($CFG->tempdir.'/', 'assignment_');
3875         //zip files
3876         $zipper = new zip_packer();
3877         if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
3878             return $tempzip;
3879         }
3880         return false;
3883 /**
3884  * Lists all file areas current user may browse
3885  *
3886  * @param object $course
3887  * @param object $cm
3888  * @param object $context
3889  * @return array
3890  */
3891 function assignment_get_file_areas($course, $cm, $context) {
3892     $areas = array();
3893     if (has_capability('moodle/course:managefiles', $context)) {
3894         $areas['submission'] = get_string('assignmentsubmission', 'assignment');
3895     }
3896     return $areas;
3899 /**
3900  * Return a list of page types
3901  * @param string $pagetype current page type
3902  * @param stdClass $parentcontext Block's parent context
3903  * @param stdClass $currentcontext Current context of block
3904  */
3905 function assignment_page_type_list($pagetype, $parentcontext, $currentcontext) {
3906     $module_pagetype = array(
3907         'mod-assignment-*'=>get_string('page-mod-assignment-x', 'assignment'),
3908         'mod-assignment-view'=>get_string('page-mod-assignment-view', 'assignment'),
3909         'mod-assignment-submissions'=>get_string('page-mod-assignment-submissions', 'assignment')
3910     );
3911     return $module_pagetype;
3914 /**
3915  * Lists all gradable areas for the advanced grading methods gramework
3916  *
3917  * @return array
3918  */
3919 function assignment_g