86906a913699af1bd533731d8c7be9e880864be7
[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         $gradestr = '<div class="grade">'. get_string("grade").': '.$grade->str_long_grade. '</div>';
336         if (!empty($submission) && $controller = get_grading_manager($this->context, 'mod_assignment', 'submission')->get_active_controller()) {
337             $controller->set_grade_range(make_grades_menu($this->assignment->grade));
338             echo $controller->render_grade($PAGE, $submission->id, $item, $gradestr, has_capability('mod/assignment:grade', $this->context));
339         } else {
340             echo $gradestr;
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                 $filter = optional_param('filter', self::FILTER_ALL, PARAM_INT);
774                 $redirect = new moodle_url('submissions.php',
775                         array('id' => $id, 'offset' => $offset, 'userid' => $nextid,
776                         'mode' => 'single', 'filter' => $filter));
778                 redirect($redirect);
779                 break;
781             case 'singlenosave':
782                 $this->display_submission();
783                 break;
785             default:
786                 echo "something seriously is wrong!!";
787                 break;
788         }
789     }
791     /**
792      * Checks if grading method allows quickgrade mode. At the moment it is hardcoded
793      * that advanced grading methods do not allow quickgrade.
794      *
795      * Assignment type plugins are not allowed to override this method
796      *
797      * @return boolean
798      */
799     public final function quickgrade_mode_allowed() {
800         global $CFG;
801         require_once("$CFG->dirroot/grade/grading/lib.php");
802         if ($controller = get_grading_manager($this->context, 'mod_assignment', 'submission')->get_active_controller()) {
803             return false;
804         }
805         return true;
806     }
808     /**
809      * Helper method updating the listing on the main script from popup using javascript
810      *
811      * @global object
812      * @global object
813      * @param $submission object The submission whose data is to be updated on the main page
814      */
815     function update_main_listing($submission) {
816         global $SESSION, $CFG, $OUTPUT;
818         $output = '';
820         $perpage = get_user_preferences('assignment_perpage', 10);
822         $quickgrade = get_user_preferences('assignment_quickgrade', 0) && $this->quickgrade_mode_allowed();
824         /// Run some Javascript to try and update the parent page
825         $output .= '<script type="text/javascript">'."\n<!--\n";
826         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['submissioncomment'])) {
827             if ($quickgrade){
828                 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid.'").value="'
829                 .trim($submission->submissioncomment).'";'."\n";
830              } else {
831                 $output.= 'opener.document.getElementById("com'.$submission->userid.
832                 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment)), 15)."\";\n";
833             }
834         }
836         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['grade'])) {
837             //echo optional_param('menuindex');
838             if ($quickgrade){
839                 $output.= 'opener.document.getElementById("menumenu'.$submission->userid.
840                 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT).'";'."\n";
841             } else {
842                 $output.= 'opener.document.getElementById("g'.$submission->userid.'").innerHTML="'.
843                 $this->display_grade($submission->grade)."\";\n";
844             }
845         }
846         //need to add student's assignments in there too.
847         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemodified']) &&
848             $submission->timemodified) {
849             $output.= 'opener.document.getElementById("ts'.$submission->userid.
850                  '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid)).userdate($submission->timemodified)."\";\n";
851         }
853         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemarked']) &&
854             $submission->timemarked) {
855             $output.= 'opener.document.getElementById("tt'.$submission->userid.
856                  '").innerHTML="'.userdate($submission->timemarked)."\";\n";
857         }
859         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['status'])) {
860             $output.= 'opener.document.getElementById("up'.$submission->userid.'").className="s1";';
861             $buttontext = get_string('update');
862             $url = new moodle_url('/mod/assignment/submissions.php', array(
863                     'id' => $this->cm->id,
864                     'userid' => $submission->userid,
865                     'mode' => 'single',
866                     'offset' => (optional_param('offset', '', PARAM_INT)-1)));
867             $button = $OUTPUT->action_link($url, $buttontext, new popup_action('click', $url, 'grade'.$submission->userid, array('height' => 450, 'width' => 700)), array('ttile'=>$buttontext));
869             $output .= 'opener.document.getElementById("up'.$submission->userid.'").innerHTML="'.addslashes_js($button).'";';
870         }
872         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $submission->userid);
874         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['finalgrade'])) {
875             $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid.
876             '").innerHTML="'.$grading_info->items[0]->grades[$submission->userid]->str_grade.'";'."\n";
877         }
879         if (!empty($CFG->enableoutcomes) and empty($SESSION->flextable['mod-assignment-submissions']->collapse['outcome'])) {
881             if (!empty($grading_info->outcomes)) {
882                 foreach($grading_info->outcomes as $n=>$outcome) {
883                     if ($outcome->grades[$submission->userid]->locked) {
884                         continue;
885                     }
887                     if ($quickgrade){
888                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.
889                         '").selectedIndex="'.$outcome->grades[$submission->userid]->grade.'";'."\n";
891                     } else {
892                         $options = make_grades_menu(-$outcome->scaleid);
893                         $options[0] = get_string('nooutcome', 'grades');
894                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.'").innerHTML="'.$options[$outcome->grades[$submission->userid]->grade]."\";\n";
895                     }
897                 }
898             }
899         }
901         $output .= "\n-->\n</script>";
902         return $output;
903     }
905     /**
906      *  Return a grade in user-friendly form, whether it's a scale or not
907      *
908      * @global object
909      * @param mixed $grade
910      * @return string User-friendly representation of grade
911      */
912     function display_grade($grade) {
913         global $DB;
915         static $scalegrades = array();   // Cache scales for each assignment - they might have different scales!!
917         if ($this->assignment->grade >= 0) {    // Normal number
918             if ($grade == -1) {
919                 return '-';
920             } else {
921                 return $grade.' / '.$this->assignment->grade;
922             }
924         } else {                                // Scale
925             if (empty($scalegrades[$this->assignment->id])) {
926                 if ($scale = $DB->get_record('scale', array('id'=>-($this->assignment->grade)))) {
927                     $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
928                 } else {
929                     return '-';
930                 }
931             }
932             if (isset($scalegrades[$this->assignment->id][$grade])) {
933                 return $scalegrades[$this->assignment->id][$grade];
934             }
935             return '-';
936         }
937     }
939     /**
940      *  Display a single submission, ready for grading on a popup window
941      *
942      * This default method prints the teacher info and submissioncomment box at the top and
943      * the student info and submission at the bottom.
944      * This method also fetches the necessary data in order to be able to
945      * provide a "Next submission" button.
946      * Calls preprocess_submission() to give assignment type plug-ins a chance
947      * to process submissions before they are graded
948      * This method gets its arguments from the page parameters userid and offset
949      *
950      * @global object
951      * @global object
952      * @param string $extra_javascript
953      */
954     function display_submission($offset=-1,$userid =-1, $display=true) {
955         global $CFG, $DB, $PAGE, $OUTPUT, $USER;
956         require_once($CFG->libdir.'/gradelib.php');
957         require_once($CFG->libdir.'/tablelib.php');
958         require_once("$CFG->dirroot/repository/lib.php");
959         require_once("$CFG->dirroot/grade/grading/lib.php");
960         if ($userid==-1) {
961             $userid = required_param('userid', PARAM_INT);
962         }
963         if ($offset==-1) {
964             $offset = required_param('offset', PARAM_INT);//offset for where to start looking for student.
965         }
966         $filter = optional_param('filter', 0, PARAM_INT);
968         if (!$user = $DB->get_record('user', array('id'=>$userid))) {
969             print_error('nousers');
970         }
972         if (!$submission = $this->get_submission($user->id)) {
973             $submission = $this->prepare_new_submission($userid);
974         }
975         if ($submission->timemodified > $submission->timemarked) {
976             $subtype = 'assignmentnew';
977         } else {
978             $subtype = 'assignmentold';
979         }
981         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
982         $gradingdisabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
984     /// construct SQL, using current offset to find the data of the next student
985         $course     = $this->course;
986         $assignment = $this->assignment;
987         $cm         = $this->cm;
988         $context    = get_context_instance(CONTEXT_MODULE, $cm->id);
990         //reset filter to all for offline assignment
991         if ($assignment->assignmenttype == 'offline' && $filter == self::FILTER_SUBMITTED) {
992             $filter = self::FILTER_ALL;
993         }
994         /// Get all ppl that can submit assignments
996         $currentgroup = groups_get_activity_group($cm);
997         $users = get_enrolled_users($context, 'mod/assignment:submit', $currentgroup, 'u.id');
998         if ($users) {
999             $users = array_keys($users);
1000             // if groupmembersonly used, remove users who are not in any group
1001             if (!empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
1002                 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1003                     $users = array_intersect($users, array_keys($groupingusers));
1004                 }
1005             }
1006         }
1008         $nextid = 0;
1009         $where = '';
1010         if($filter == self::FILTER_SUBMITTED) {
1011             $where .= 's.timemodified > 0 AND ';
1012         } else if($filter == self::FILTER_REQUIRE_GRADING) {
1013             $where .= 's.timemarked < s.timemodified AND ';
1014         }
1016         if ($users) {
1017             $userfields = user_picture::fields('u', array('lastaccess'));
1018             $select = "SELECT $userfields,
1019                               s.id AS submissionid, s.grade, s.submissioncomment,
1020                               s.timemodified, s.timemarked,
1021                               CASE WHEN s.timemarked > 0 AND s.timemarked >= s.timemodified THEN 1
1022                                    ELSE 0 END AS status ";
1024             $sql = 'FROM {user} u '.
1025                    'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1026                    AND s.assignment = '.$this->assignment->id.' '.
1027                    'WHERE '.$where.'u.id IN ('.implode(',', $users).') ';
1029             if ($sort = flexible_table::get_sort_for_table('mod-assignment-submissions')) {
1030                 $sort = 'ORDER BY '.$sort.' ';
1031             }
1032             $auser = $DB->get_records_sql($select.$sql.$sort, null, $offset, 2);
1034             if (is_array($auser) && count($auser)>1) {
1035                 $nextuser = next($auser);
1036                 $nextid = $nextuser->id;
1037             }
1038         }
1040         if ($submission->teacher) {
1041             $teacher = $DB->get_record('user', array('id'=>$submission->teacher));
1042         } else {
1043             global $USER;
1044             $teacher = $USER;
1045         }
1047         $this->preprocess_submission($submission);
1049         $mformdata = new stdClass();
1050         $mformdata->context = $this->context;
1051         $mformdata->maxbytes = $this->course->maxbytes;
1052         $mformdata->courseid = $this->course->id;
1053         $mformdata->teacher = $teacher;
1054         $mformdata->assignment = $assignment;
1055         $mformdata->submission = $submission;
1056         $mformdata->lateness = $this->display_lateness($submission->timemodified);
1057         $mformdata->auser = $auser;
1058         $mformdata->user = $user;
1059         $mformdata->offset = $offset;
1060         $mformdata->userid = $userid;
1061         $mformdata->cm = $this->cm;
1062         $mformdata->grading_info = $grading_info;
1063         $mformdata->enableoutcomes = $CFG->enableoutcomes;
1064         $mformdata->grade = $this->assignment->grade;
1065         $mformdata->gradingdisabled = $gradingdisabled;
1066         $mformdata->nextid = $nextid;
1067         $mformdata->submissioncomment= $submission->submissioncomment;
1068         $mformdata->submissioncommentformat= FORMAT_HTML;
1069         $mformdata->submission_content= $this->print_user_files($user->id,true);
1070         $mformdata->filter = $filter;
1071         $mformdata->mailinfo = get_user_preferences('assignment_mailinfo', 0);
1072          if ($assignment->assignmenttype == 'upload') {
1073             $mformdata->fileui_options = array('subdirs'=>1, 'maxbytes'=>$assignment->maxbytes, 'maxfiles'=>$assignment->var1, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL);
1074         } elseif ($assignment->assignmenttype == 'uploadsingle') {
1075             $mformdata->fileui_options = array('subdirs'=>0, 'maxbytes'=>$CFG->userquota, 'maxfiles'=>1, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL);
1076         }
1077         $advancedgradingwarning = false;
1078         $gradingmanager = get_grading_manager($this->context, 'mod_assignment', 'submission');
1079         if ($gradingmethod = $gradingmanager->get_active_method()) {
1080             $controller = $gradingmanager->get_controller($gradingmethod);
1081             if ($controller->is_form_available()) {
1082                 $itemid = null;
1083                 if (!empty($submission->id)) {
1084                     $itemid = $submission->id;
1085                 }
1086                 if ($gradingdisabled && $itemid) {
1087                     $mformdata->advancedgradinginstance = $controller->get_current_instance($USER->id, $itemid);
1088                 } else if (!$gradingdisabled) {
1089                     $instanceid = optional_param('advancedgradinginstanceid', 0, PARAM_INT);
1090                     $mformdata->advancedgradinginstance = $controller->get_or_create_instance($instanceid, $USER->id, $itemid);
1091                 }
1092             } else {
1093                 $advancedgradingwarning = $controller->form_unavailable_notification();
1094             }
1095         }
1097         $submitform = new mod_assignment_grading_form( null, $mformdata );
1099          if (!$display) {
1100             $ret_data = new stdClass();
1101             $ret_data->mform = $submitform;
1102             if (isset($mformdata->fileui_options)) {
1103                 $ret_data->fileui_options = $mformdata->fileui_options;
1104             }
1105             return $ret_data;
1106         }
1108         if ($submitform->is_cancelled()) {
1109             redirect('submissions.php?id='.$this->cm->id);
1110         }
1112         $submitform->set_data($mformdata);
1114         $PAGE->set_title($this->course->fullname . ': ' .get_string('feedback', 'assignment').' - '.fullname($user, true));
1115         $PAGE->set_heading($this->course->fullname);
1116         $PAGE->navbar->add(get_string('submissions', 'assignment'), new moodle_url('/mod/assignment/submissions.php', array('id'=>$cm->id)));
1117         $PAGE->navbar->add(fullname($user, true));
1119         echo $OUTPUT->header();
1120         echo $OUTPUT->heading(get_string('feedback', 'assignment').': '.fullname($user, true));
1122         // display mform here...
1123         if ($advancedgradingwarning) {
1124             echo $OUTPUT->notification($advancedgradingwarning, 'error');
1125         }
1126         $submitform->display();
1128         $customfeedback = $this->custom_feedbackform($submission, true);
1129         if (!empty($customfeedback)) {
1130             echo $customfeedback;
1131         }
1133         echo $OUTPUT->footer();
1134     }
1136     /**
1137      *  Preprocess submission before grading
1138      *
1139      * Called by display_submission()
1140      * The default type does nothing here.
1141      *
1142      * @param object $submission The submission object
1143      */
1144     function preprocess_submission(&$submission) {
1145     }
1147     /**
1148      *  Display all the submissions ready for grading
1149      *
1150      * @global object
1151      * @global object
1152      * @global object
1153      * @global object
1154      * @param string $message
1155      * @return bool|void
1156      */
1157     function display_submissions($message='') {
1158         global $CFG, $DB, $USER, $DB, $OUTPUT, $PAGE;
1159         require_once($CFG->libdir.'/gradelib.php');
1161         /* first we check to see if the form has just been submitted
1162          * to request user_preference updates
1163          */
1165        $filters = array(self::FILTER_ALL             => get_string('all'),
1166                         self::FILTER_REQUIRE_GRADING => get_string('requiregrading', 'assignment'));
1168         $updatepref = optional_param('updatepref', 0, PARAM_BOOL);
1169         if ($updatepref) {
1170             $perpage = optional_param('perpage', 10, PARAM_INT);
1171             $perpage = ($perpage <= 0) ? 10 : $perpage ;
1172             $filter = optional_param('filter', 0, PARAM_INT);
1173             set_user_preference('assignment_perpage', $perpage);
1174             set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
1175             set_user_preference('assignment_filter', $filter);
1176         }
1178         /* next we get perpage and quickgrade (allow quick grade) params
1179          * from database
1180          */
1181         $perpage    = get_user_preferences('assignment_perpage', 10);
1182         $quickgrade = get_user_preferences('assignment_quickgrade', 0) && $this->quickgrade_mode_allowed();
1183         $filter = get_user_preferences('assignment_filter', 0);
1184         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);
1186         if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
1187             $uses_outcomes = true;
1188         } else {
1189             $uses_outcomes = false;
1190         }
1192         $page    = optional_param('page', 0, PARAM_INT);
1193         $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
1195     /// Some shortcuts to make the code read better
1197         $course     = $this->course;
1198         $assignment = $this->assignment;
1199         $cm         = $this->cm;
1200         $hassubmission = false;
1202         // reset filter to all for offline assignment only.
1203         if ($assignment->assignmenttype == 'offline') {
1204             if ($filter == self::FILTER_SUBMITTED) {
1205                 $filter = self::FILTER_ALL;
1206             }
1207         } else {
1208             $filters[self::FILTER_SUBMITTED] = get_string('submitted', 'assignment');
1209         }
1211         $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
1212         add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->cm->id, $this->assignment->id, $this->cm->id);
1214         $PAGE->set_title(format_string($this->assignment->name,true));
1215         $PAGE->set_heading($this->course->fullname);
1216         echo $OUTPUT->header();
1218         echo '<div class="usersubmissions">';
1220         //hook to allow plagiarism plugins to update status/print links.
1221         plagiarism_update_status($this->course, $this->cm);
1223         $course_context = get_context_instance(CONTEXT_COURSE, $course->id);
1224         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
1225             echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">'
1226                 . get_string('seeallcoursegrades', 'grades') . '</a></div>';
1227         }
1229         if (!empty($message)) {
1230             echo $message;   // display messages here if any
1231         }
1233         $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1235     /// Check to see if groups are being used in this assignment
1237         /// find out current groups mode
1238         $groupmode = groups_get_activity_groupmode($cm);
1239         $currentgroup = groups_get_activity_group($cm, true);
1240         groups_print_activity_menu($cm, $CFG->wwwroot . '/mod/assignment/submissions.php?id=' . $this->cm->id);
1242         /// Print quickgrade form around the table
1243         if ($quickgrade) {
1244             $formattrs = array();
1245             $formattrs['action'] = new moodle_url('/mod/assignment/submissions.php');
1246             $formattrs['id'] = 'fastg';
1247             $formattrs['method'] = 'post';
1249             echo html_writer::start_tag('form', $formattrs);
1250             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'id',      'value'=> $this->cm->id));
1251             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'mode',    'value'=> 'fastgrade'));
1252             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'page',    'value'=> $page));
1253             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=> sesskey()));
1254         }
1256         /// Get all ppl that are allowed to submit assignments
1257         list($esql, $params) = get_enrolled_sql($context, 'mod/assignment:submit', $currentgroup);
1259         if ($filter == self::FILTER_ALL) {
1260             $sql = "SELECT u.id FROM {user} u ".
1261                    "LEFT JOIN ($esql) eu ON eu.id=u.id ".
1262                    "WHERE u.deleted = 0 AND eu.id=u.id ";
1263         } else {
1264             $wherefilter = ' AND s.assignment = '. $this->assignment->id;
1265             $assignmentsubmission = "LEFT JOIN {assignment_submissions} s ON (u.id = s.userid) ";
1266             if($filter == self::FILTER_SUBMITTED) {
1267                 $wherefilter .= ' AND s.timemodified > 0 ';
1268             } else if($filter == self::FILTER_REQUIRE_GRADING && $assignment->assignmenttype != 'offline') {
1269                 $wherefilter .= ' AND s.timemarked < s.timemodified ';
1270             } else { // require grading for offline assignment
1271                 $assignmentsubmission = "";
1272                 $wherefilter = "";
1273             }
1275             $sql = "SELECT u.id FROM {user} u ".
1276                    "LEFT JOIN ($esql) eu ON eu.id=u.id ".
1277                    $assignmentsubmission.
1278                    "WHERE u.deleted = 0 AND eu.id=u.id ".
1279                    $wherefilter;
1280         }
1282         $users = $DB->get_records_sql($sql, $params);
1283         if (!empty($users)) {
1284             if($assignment->assignmenttype == 'offline' && $filter == self::FILTER_REQUIRE_GRADING) {
1285                 //remove users who has submitted their assignment
1286                 foreach ($this->get_submissions() as $submission) {
1287                     if (array_key_exists($submission->userid, $users)) {
1288                         unset($users[$submission->userid]);
1289                     }
1290                 }
1291             }
1292             $users = array_keys($users);
1293         }
1295         // if groupmembersonly used, remove users who are not in any group
1296         if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
1297             if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1298                 $users = array_intersect($users, array_keys($groupingusers));
1299             }
1300         }
1302         $extrafields = get_extra_user_fields($context);
1303         $tablecolumns = array_merge(array('picture', 'fullname'), $extrafields,
1304                 array('grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade'));
1305         if ($uses_outcomes) {
1306             $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
1307         }
1309         $extrafieldnames = array();
1310         foreach ($extrafields as $field) {
1311             $extrafieldnames[] = get_user_field_name($field);
1312         }
1313         $tableheaders = array_merge(
1314                 array('', get_string('fullnameuser')),
1315                 $extrafieldnames,
1316                 array(
1317                     get_string('grade'),
1318                     get_string('comment', 'assignment'),
1319                     get_string('lastmodified').' ('.get_string('submission', 'assignment').')',
1320                     get_string('lastmodified').' ('.get_string('grade').')',
1321                     get_string('status'),
1322                     get_string('finalgrade', 'grades'),
1323                 ));
1324         if ($uses_outcomes) {
1325             $tableheaders[] = get_string('outcome', 'grades');
1326         }
1328         require_once($CFG->libdir.'/tablelib.php');
1329         $table = new flexible_table('mod-assignment-submissions');
1331         $table->define_columns($tablecolumns);
1332         $table->define_headers($tableheaders);
1333         $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;currentgroup='.$currentgroup);
1335         $table->sortable(true, 'lastname');//sorted by lastname by default
1336         $table->collapsible(true);
1337         $table->initialbars(true);
1339         $table->column_suppress('picture');
1340         $table->column_suppress('fullname');
1342         $table->column_class('picture', 'picture');
1343         $table->column_class('fullname', 'fullname');
1344         foreach ($extrafields as $field) {
1345             $table->column_class($field, $field);
1346         }
1347         $table->column_class('grade', 'grade');
1348         $table->column_class('submissioncomment', 'comment');
1349         $table->column_class('timemodified', 'timemodified');
1350         $table->column_class('timemarked', 'timemarked');
1351         $table->column_class('status', 'status');
1352         $table->column_class('finalgrade', 'finalgrade');
1353         if ($uses_outcomes) {
1354             $table->column_class('outcome', 'outcome');
1355         }
1357         $table->set_attribute('cellspacing', '0');
1358         $table->set_attribute('id', 'attempts');
1359         $table->set_attribute('class', 'submissions');
1360         $table->set_attribute('width', '100%');
1362         $table->no_sorting('finalgrade');
1363         $table->no_sorting('outcome');
1365         // Start working -- this is necessary as soon as the niceties are over
1366         $table->setup();
1368         /// Construct the SQL
1369         list($where, $params) = $table->get_sql_where();
1370         if ($where) {
1371             $where .= ' AND ';
1372         }
1374         if ($filter == self::FILTER_SUBMITTED) {
1375            $where .= 's.timemodified > 0 AND ';
1376         } else if($filter == self::FILTER_REQUIRE_GRADING) {
1377             $where = '';
1378             if ($assignment->assignmenttype != 'offline') {
1379                $where .= 's.timemarked < s.timemodified AND ';
1380             }
1381         }
1383         if ($sort = $table->get_sql_sort()) {
1384             $sort = ' ORDER BY '.$sort;
1385         }
1387         $ufields = user_picture::fields('u', $extrafields);
1388         if (!empty($users)) {
1389             $select = "SELECT $ufields,
1390                               s.id AS submissionid, s.grade, s.submissioncomment,
1391                               s.timemodified, s.timemarked,
1392                               CASE WHEN s.timemarked > 0 AND s.timemarked >= s.timemodified THEN 1
1393                                    ELSE 0 END AS status ";
1395             $sql = 'FROM {user} u '.
1396                    'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1397                     AND s.assignment = '.$this->assignment->id.' '.
1398                    'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1400             $ausers = $DB->get_records_sql($select.$sql.$sort, $params, $table->get_page_start(), $table->get_page_size());
1402             $table->pagesize($perpage, count($users));
1404             ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1405             $offset = $page * $perpage;
1406             $strupdate = get_string('update');
1407             $strgrade  = get_string('grade');
1408             $grademenu = make_grades_menu($this->assignment->grade);
1410             if ($ausers !== false) {
1411                 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
1412                 $endposition = $offset + $perpage;
1413                 $currentposition = 0;
1414                 foreach ($ausers as $auser) {
1415                     if ($currentposition == $offset && $offset < $endposition) {
1416                         $final_grade = $grading_info->items[0]->grades[$auser->id];
1417                         $grademax = $grading_info->items[0]->grademax;
1418                         $final_grade->formatted_grade = round($final_grade->grade,2) .' / ' . round($grademax,2);
1419                         $locked_overridden = 'locked';
1420                         if ($final_grade->overridden) {
1421                             $locked_overridden = 'overridden';
1422                         }
1424                         // TODO add here code if advanced grading grade must be reviewed => $auser->status=0
1426                         $picture = $OUTPUT->user_picture($auser);
1428                         if (empty($auser->submissionid)) {
1429                             $auser->grade = -1; //no submission yet
1430                         }
1432                         if (!empty($auser->submissionid)) {
1433                             $hassubmission = true;
1434                         ///Prints student answer and student modified date
1435                         ///attach file or print link to student answer, depending on the type of the assignment.
1436                         ///Refer to print_student_answer in inherited classes.
1437                             if ($auser->timemodified > 0) {
1438                                 $studentmodified = '<div id="ts'.$auser->id.'">'.$this->print_student_answer($auser->id)
1439                                                  . userdate($auser->timemodified).'</div>';
1440                             } else {
1441                                 $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1442                             }
1443                         ///Print grade, dropdown or text
1444                             if ($auser->timemarked > 0) {
1445                                 $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
1447                                 if ($final_grade->locked or $final_grade->overridden) {
1448                                     $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1449                                 } else if ($quickgrade) {
1450                                     $attributes = array();
1451                                     $attributes['tabindex'] = $tabindex++;
1452                                     $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1453                                     $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
1454                                 } else {
1455                                     $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1456                                 }
1458                             } else {
1459                                 $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1460                                 if ($final_grade->locked or $final_grade->overridden) {
1461                                     $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1462                                 } else if ($quickgrade) {
1463                                     $attributes = array();
1464                                     $attributes['tabindex'] = $tabindex++;
1465                                     $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1466                                     $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1467                                 } else {
1468                                     $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1469                                 }
1470                             }
1471                         ///Print Comment
1472                             if ($final_grade->locked or $final_grade->overridden) {
1473                                 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';
1475                             } else if ($quickgrade) {
1476                                 $comment = '<div id="com'.$auser->id.'">'
1477                                          . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1478                                          . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1479                             } else {
1480                                 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
1481                             }
1482                         } else {
1483                             $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1484                             $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1485                             $status          = '<div id="st'.$auser->id.'">&nbsp;</div>';
1487                             if ($final_grade->locked or $final_grade->overridden) {
1488                                 $grade = '<div id="g'.$auser->id.'">'.$final_grade->formatted_grade . '</div>';
1489                                 $hassubmission = true;
1490                             } else if ($quickgrade) {   // allow editing
1491                                 $attributes = array();
1492                                 $attributes['tabindex'] = $tabindex++;
1493                                 $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1494                                 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1495                                 $hassubmission = true;
1496                             } else {
1497                                 $grade = '<div id="g'.$auser->id.'">-</div>';
1498                             }
1500                             if ($final_grade->locked or $final_grade->overridden) {
1501                                 $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
1502                             } else if ($quickgrade) {
1503                                 $comment = '<div id="com'.$auser->id.'">'
1504                                          . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1505                                          . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1506                             } else {
1507                                 $comment = '<div id="com'.$auser->id.'">&nbsp;</div>';
1508                             }
1509                         }
1511                         if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
1512                             $auser->status = 0;
1513                         } else {
1514                             $auser->status = 1;
1515                         }
1517                         $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
1519                         ///No more buttons, we use popups ;-).
1520                         $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1521                                    . '&amp;userid='.$auser->id.'&amp;mode=single'.'&amp;filter='.$filter.'&amp;offset='.$offset++;
1523                         $button = $OUTPUT->action_link($popup_url, $buttontext);
1525                         $status  = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
1527                         $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';
1529                         $outcomes = '';
1531                         if ($uses_outcomes) {
1533                             foreach($grading_info->outcomes as $n=>$outcome) {
1534                                 $outcomes .= '<div class="outcome"><label>'.$outcome->name.'</label>';
1535                                 $options = make_grades_menu(-$outcome->scaleid);
1537                                 if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
1538                                     $options[0] = get_string('nooutcome', 'grades');
1539                                     $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
1540                                 } else {
1541                                     $attributes = array();
1542                                     $attributes['tabindex'] = $tabindex++;
1543                                     $attributes['id'] = 'outcome_'.$n.'_'.$auser->id;
1544                                     $outcomes .= ' '.html_writer::select($options, 'outcome_'.$n.'['.$auser->id.']', $outcome->grades[$auser->id]->grade, array(0=>get_string('nooutcome', 'grades')), $attributes);
1545                                 }
1546                                 $outcomes .= '</div>';
1547                             }
1548                         }
1550                         $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>';
1551                         $extradata = array();
1552                         foreach ($extrafields as $field) {
1553                             $extradata[] = $auser->{$field};
1554                         }
1555                         $row = array_merge(array($picture, $userlink), $extradata,
1556                                 array($grade, $comment, $studentmodified, $teachermodified,
1557                                 $status, $finalgrade));
1558                         if ($uses_outcomes) {
1559                             $row[] = $outcomes;
1560                         }
1561                         $table->add_data($row);
1562                     }
1563                     $currentposition++;
1564                 }
1565                 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)
1566                     echo html_writer::start_tag('div', array('class' => 'mod-assignment-download-link'));
1567                     echo html_writer::link(new moodle_url('/mod/assignment/submissions.php', array('id' => $this->cm->id, 'download' => 'zip')), get_string('downloadall', 'assignment'));
1568                     echo html_writer::end_tag('div');
1569                 }
1570                 $table->print_html();  /// Print the whole table
1571             } else {
1572                 if ($filter == self::FILTER_SUBMITTED) {
1573                     echo html_writer::tag('div', get_string('nosubmisson', 'assignment'), array('class'=>'nosubmisson'));
1574                 } else if ($filter == self::FILTER_REQUIRE_GRADING) {
1575                     echo html_writer::tag('div', get_string('norequiregrading', 'assignment'), array('class'=>'norequiregrading'));
1576                 }
1577             }
1578         }
1580         /// Print quickgrade form around the table
1581         if ($quickgrade && $table->started_output && !empty($users)){
1582             $mailinfopref = false;
1583             if (get_user_preferences('assignment_mailinfo', 1)) {
1584                 $mailinfopref = true;
1585             }
1586             $emailnotification =  html_writer::checkbox('mailinfo', 1, $mailinfopref, get_string('enablenotification','assignment'));
1588             $emailnotification .= $OUTPUT->help_icon('enablenotification', 'assignment');
1589             echo html_writer::tag('div', $emailnotification, array('class'=>'emailnotification'));
1591             $savefeedback = html_writer::empty_tag('input', array('type'=>'submit', 'name'=>'fastg', 'value'=>get_string('saveallfeedback', 'assignment')));
1592             echo html_writer::tag('div', $savefeedback, array('class'=>'fastgbutton'));
1594             echo html_writer::end_tag('form');
1595         } else if ($quickgrade) {
1596             echo html_writer::end_tag('form');
1597         }
1599         echo '</div>';
1600         /// End of fast grading form
1602         /// Mini form for setting user preference
1604         $formaction = new moodle_url('/mod/assignment/submissions.php', array('id'=>$this->cm->id));
1605         $mform = new MoodleQuickForm('optionspref', 'post', $formaction, '', array('class'=>'optionspref'));
1607         $mform->addElement('hidden', 'updatepref');
1608         $mform->setDefault('updatepref', 1);
1609         $mform->addElement('header', 'qgprefs', get_string('optionalsettings', 'assignment'));
1610         $mform->addElement('select', 'filter', get_string('show'),  $filters);
1612         $mform->setDefault('filter', $filter);
1614         $mform->addElement('text', 'perpage', get_string('pagesize', 'assignment'), array('size'=>1));
1615         $mform->setDefault('perpage', $perpage);
1617         if ($this->quickgrade_mode_allowed()) {
1618             $mform->addElement('checkbox', 'quickgrade', get_string('quickgrade','assignment'));
1619             $mform->setDefault('quickgrade', $quickgrade);
1620             $mform->addHelpButton('quickgrade', 'quickgrade', 'assignment');
1621         }
1623         $mform->addElement('submit', 'savepreferences', get_string('savepreferences'));
1625         $mform->display();
1627         echo $OUTPUT->footer();
1628     }
1630     /**
1631      * If the form was cancelled ('Cancel' or 'Next' was pressed), call cancel method
1632      * from advanced grading (if applicable) and returns true
1633      * If the form was submitted, validates it and returns false if validation did not pass.
1634      * If validation passes, preprocess advanced grading (if applicable) and returns true.
1635      *
1636      * Note to the developers: This is NOT the correct way to implement advanced grading
1637      * in grading form. The assignment grading was written long time ago and unfortunately
1638      * does not fully use the mforms. Usually function is_validated() is called to
1639      * validate the form and get_data() is called to get the data from the form.
1640      *
1641      * Here we have to push the calculated grade to $_POST['xgrade'] because further processing
1642      * of the form gets the data not from form->get_data(), but from $_POST (using statement
1643      * like  $feedback = data_submitted() )
1644      */
1645     protected function validate_and_preprocess_feedback() {
1646         global $USER, $CFG;
1647         require_once($CFG->libdir.'/gradelib.php');
1648         if (!($feedback = data_submitted()) || !isset($feedback->userid) || !isset($feedback->offset)) {
1649             return true;      // No incoming data, nothing to validate
1650         }
1651         $userid = required_param('userid', PARAM_INT);
1652         $offset = required_param('offset', PARAM_INT);
1653         $gradinginfo = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($userid));
1654         $gradingdisabled = $gradinginfo->items[0]->grades[$userid]->locked || $gradinginfo->items[0]->grades[$userid]->overridden;
1655         if ($gradingdisabled) {
1656             return true;
1657         }
1658         $submissiondata = $this->display_submission($offset, $userid, false);
1659         $mform = $submissiondata->mform;
1660         $gradinginstance = $mform->use_advanced_grading();
1661         if (optional_param('cancel', false, PARAM_BOOL) || optional_param('next', false, PARAM_BOOL)) {
1662             // form was cancelled
1663             if ($gradinginstance) {
1664                 $gradinginstance->cancel();
1665             }
1666         } else if ($mform->is_submitted()) {
1667             // form was submitted (= a submit button other than 'cancel' or 'next' has been clicked)
1668             if (!$mform->is_validated()) {
1669                 return false;
1670             }
1671             // preprocess advanced grading here
1672             if ($gradinginstance) {
1673                 $data = $mform->get_data();
1674                 // create submission if it did not exist yet because we need submission->id for storing the grading instance
1675                 $submission = $this->get_submission($userid, true);
1676                 $_POST['xgrade'] = $gradinginstance->submit_and_get_grade($data->advancedgrading, $submission->id);
1677             }
1678         }
1679         return true;
1680     }
1682     /**
1683      *  Process teacher feedback submission
1684      *
1685      * This is called by submissions() when a grading even has taken place.
1686      * It gets its data from the submitted form.
1687      *
1688      * @global object
1689      * @global object
1690      * @global object
1691      * @return object|bool The updated submission object or false
1692      */
1693     function process_feedback($formdata=null) {
1694         global $CFG, $USER, $DB;
1695         require_once($CFG->libdir.'/gradelib.php');
1697         if (!$feedback = data_submitted() or !confirm_sesskey()) {      // No incoming data?
1698             return false;
1699         }
1701         ///For save and next, we need to know the userid to save, and the userid to go
1702         ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1703         ///as the userid to store
1704         if ((int)$feedback->saveuserid !== -1){
1705             $feedback->userid = $feedback->saveuserid;
1706         }
1708         if (!empty($feedback->cancel)) {          // User hit cancel button
1709             return false;
1710         }
1712         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);
1714         // store outcomes if needed
1715         $this->process_outcomes($feedback->userid);
1717         $submission = $this->get_submission($feedback->userid, true);  // Get or make one
1719         if (!($grading_info->items[0]->grades[$feedback->userid]->locked ||
1720             $grading_info->items[0]->grades[$feedback->userid]->overridden) ) {
1722             $submission->grade      = $feedback->xgrade;
1723             $submission->submissioncomment    = $feedback->submissioncomment_editor['text'];
1724             $submission->teacher    = $USER->id;
1725             $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1726             if (!$mailinfo) {
1727                 $submission->mailed = 1;       // treat as already mailed
1728             } else {
1729                 $submission->mailed = 0;       // Make sure mail goes out (again, even)
1730             }
1731             $submission->timemarked = time();
1733             unset($submission->data1);  // Don't need to update this.
1734             unset($submission->data2);  // Don't need to update this.
1736             if (empty($submission->timemodified)) {   // eg for offline assignments
1737                 // $submission->timemodified = time();
1738             }
1740             $DB->update_record('assignment_submissions', $submission);
1742             // triger grade event
1743             $this->update_grade($submission);
1745             add_to_log($this->course->id, 'assignment', 'update grades',
1746                        'submissions.php?id='.$this->cm->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
1747              if (!is_null($formdata)) {
1748                     if ($this->type == 'upload' || $this->type == 'uploadsingle') {
1749                         $mformdata = $formdata->mform->get_data();
1750                         $mformdata = file_postupdate_standard_filemanager($mformdata, 'files', $formdata->fileui_options, $this->context, 'mod_assignment', 'response', $submission->id);
1751                     }
1752              }
1753         }
1755         return $submission;
1757     }
1759     function process_outcomes($userid) {
1760         global $CFG, $USER;
1762         if (empty($CFG->enableoutcomes)) {
1763             return;
1764         }
1766         require_once($CFG->libdir.'/gradelib.php');
1768         if (!$formdata = data_submitted() or !confirm_sesskey()) {
1769             return;
1770         }
1772         $data = array();
1773         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
1775         if (!empty($grading_info->outcomes)) {
1776             foreach($grading_info->outcomes as $n=>$old) {
1777                 $name = 'outcome_'.$n;
1778                 if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
1779                     $data[$n] = $formdata->{$name}[$userid];
1780                 }
1781             }
1782         }
1783         if (count($data) > 0) {
1784             grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1785         }
1787     }
1789     /**
1790      * Load the submission object for a particular user
1791      *
1792      * @global object
1793      * @global object
1794      * @param $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1795      * @param $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1796      * @param bool $teachermodified student submission set if false
1797      * @return object The submission
1798      */
1799     function get_submission($userid=0, $createnew=false, $teachermodified=false) {
1800         global $USER, $DB;
1802         if (empty($userid)) {
1803             $userid = $USER->id;
1804         }
1806         $submission = $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1808         if ($submission || !$createnew) {
1809             return $submission;
1810         }
1811         $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
1812         $DB->insert_record("assignment_submissions", $newsubmission);
1814         return $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1815     }
1817     /**
1818      * Instantiates a new submission object for a given user
1819      *
1820      * Sets the assignment, userid and times, everything else is set to default values.
1821      *
1822      * @param int $userid The userid for which we want a submission object
1823      * @param bool $teachermodified student submission set if false
1824      * @return object The submission
1825      */
1826     function prepare_new_submission($userid, $teachermodified=false) {
1827         $submission = new stdClass();
1828         $submission->assignment   = $this->assignment->id;
1829         $submission->userid       = $userid;
1830         $submission->timecreated = time();
1831         // teachers should not be modifying modified date, except offline assignments
1832         if ($teachermodified) {
1833             $submission->timemodified = 0;
1834         } else {
1835             $submission->timemodified = $submission->timecreated;
1836         }
1837         $submission->numfiles     = 0;
1838         $submission->data1        = '';
1839         $submission->data2        = '';
1840         $submission->grade        = -1;
1841         $submission->submissioncomment      = '';
1842         $submission->format       = 0;
1843         $submission->teacher      = 0;
1844         $submission->timemarked   = 0;
1845         $submission->mailed       = 0;
1846         return $submission;
1847     }
1849     /**
1850      * Return all assignment submissions by ENROLLED students (even empty)
1851      *
1852      * @param string $sort optional field names for the ORDER BY in the sql query
1853      * @param string $dir optional specifying the sort direction, defaults to DESC
1854      * @return array The submission objects indexed by id
1855      */
1856     function get_submissions($sort='', $dir='DESC') {
1857         return assignment_get_all_submissions($this->assignment, $sort, $dir);
1858     }
1860     /**
1861      * Counts all real assignment submissions by ENROLLED students (not empty ones)
1862      *
1863      * @param int $groupid optional If nonzero then count is restricted to this group
1864      * @return int The number of submissions
1865      */
1866     function count_real_submissions($groupid=0) {
1867         return assignment_count_real_submissions($this->cm, $groupid);
1868     }
1870     /**
1871      * Alerts teachers by email of new or changed assignments that need grading
1872      *
1873      * First checks whether the option to email teachers is set for this assignment.
1874      * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1875      * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1876      *
1877      * @global object
1878      * @global object
1879      * @param $submission object The submission that has changed
1880      * @return void
1881      */
1882     function email_teachers($submission) {
1883         global $CFG, $DB;
1885         if (empty($this->assignment->emailteachers)) {          // No need to do anything
1886             return;
1887         }
1889         $user = $DB->get_record('user', array('id'=>$submission->userid));
1891         if ($teachers = $this->get_graders($user)) {
1893             $strassignments = get_string('modulenameplural', 'assignment');
1894             $strassignment  = get_string('modulename', 'assignment');
1895             $strsubmitted  = get_string('submitted', 'assignment');
1897             foreach ($teachers as $teacher) {
1898                 $info = new stdClass();
1899                 $info->username = fullname($user, true);
1900                 $info->assignment = format_string($this->assignment->name,true);
1901                 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
1902                 $info->timeupdated = userdate($submission->timemodified, '%c', $teacher->timezone);
1904                 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1905                 $posttext = $this->email_teachers_text($info);
1906                 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
1908                 $eventdata = new stdClass();
1909                 $eventdata->modulename       = 'assignment';
1910                 $eventdata->userfrom         = $user;
1911                 $eventdata->userto           = $teacher;
1912                 $eventdata->subject          = $postsubject;
1913                 $eventdata->fullmessage      = $posttext;
1914                 $eventdata->fullmessageformat = FORMAT_PLAIN;
1915                 $eventdata->fullmessagehtml  = $posthtml;
1916                 $eventdata->smallmessage     = $postsubject;
1918                 $eventdata->name            = 'assignment_updates';
1919                 $eventdata->component       = 'mod_assignment';
1920                 $eventdata->notification    = 1;
1921                 $eventdata->contexturl      = $info->url;
1922                 $eventdata->contexturlname  = $info->assignment;
1924                 message_send($eventdata);
1925             }
1926         }
1927     }
1929     /**
1930      * @param string $filearea
1931      * @param array $args
1932      * @return bool
1933      */
1934     function send_file($filearea, $args) {
1935         debugging('plugin does not implement file sending', DEBUG_DEVELOPER);
1936         return false;
1937     }
1939     /**
1940      * Returns a list of teachers that should be grading given submission
1941      *
1942      * @param object $user
1943      * @return array
1944      */
1945     function get_graders($user) {
1946         //potential graders
1947         $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false);
1949         $graders = array();
1950         if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) {   // Separate groups are being used
1951             if ($groups = groups_get_all_groups($this->course->id, $user->id)) {  // Try to find all groups
1952                 foreach ($groups as $group) {
1953                     foreach ($potgraders as $t) {
1954                         if ($t->id == $user->id) {
1955                             continue; // do not send self
1956                         }
1957                         if (groups_is_member($group->id, $t->id)) {
1958                             $graders[$t->id] = $t;
1959                         }
1960                     }
1961                 }
1962             } else {
1963                 // user not in group, try to find graders without group
1964                 foreach ($potgraders as $t) {
1965                     if ($t->id == $user->id) {
1966                         continue; // do not send self
1967                     }
1968                     if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
1969                         $graders[$t->id] = $t;
1970                     }
1971                 }
1972             }
1973         } else {
1974             foreach ($potgraders as $t) {
1975                 if ($t->id == $user->id) {
1976                     continue; // do not send self
1977                 }
1978                 $graders[$t->id] = $t;
1979             }
1980         }
1981         return $graders;
1982     }
1984     /**
1985      * Creates the text content for emails to teachers
1986      *
1987      * @param $info object The info used by the 'emailteachermail' language string
1988      * @return string
1989      */
1990     function email_teachers_text($info) {
1991         $posttext  = format_string($this->course->shortname, true, array('context' => $this->coursecontext)).' -> '.
1992                      $this->strassignments.' -> '.
1993                      format_string($this->assignment->name, true, array('context' => $this->context))."\n";
1994         $posttext .= '---------------------------------------------------------------------'."\n";
1995         $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
1996         $posttext .= "\n---------------------------------------------------------------------\n";
1997         return $posttext;
1998     }
2000      /**
2001      * Creates the html content for emails to teachers
2002      *
2003      * @param $info object The info used by the 'emailteachermailhtml' language string
2004      * @return string
2005      */
2006     function email_teachers_html($info) {
2007         global $CFG;
2008         $posthtml  = '<p><font face="sans-serif">'.
2009                      '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname, true, array('context' => $this->coursecontext)).'</a> ->'.
2010                      '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
2011                      '<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>';
2012         $posthtml .= '<hr /><font face="sans-serif">';
2013         $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
2014         $posthtml .= '</font><hr />';
2015         return $posthtml;
2016     }
2018     /**
2019      * Produces a list of links to the files uploaded by a user
2020      *
2021      * @param $userid int optional id of the user. If 0 then $USER->id is used.
2022      * @param $return boolean optional defaults to false. If true the list is returned rather than printed
2023      * @return string optional
2024      */
2025     function print_user_files($userid=0, $return=false) {
2026         global $CFG, $USER, $OUTPUT;
2028         if (!$userid) {
2029             if (!isloggedin()) {
2030                 return '';
2031             }
2032             $userid = $USER->id;
2033         }
2035         $output = '';
2037         $submission = $this->get_submission($userid);
2038         if (!$submission) {
2039             return $output;
2040         }
2042         $fs = get_file_storage();
2043         $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false);
2044         if (!empty($files)) {
2045             require_once($CFG->dirroot . '/mod/assignment/locallib.php');
2046             if ($CFG->enableportfolios) {
2047                 require_once($CFG->libdir.'/portfoliolib.php');
2048                 $button = new portfolio_add_button();
2049             }
2050             foreach ($files as $file) {
2051                 $filename = $file->get_filename();
2052                 $mimetype = $file->get_mimetype();
2053                 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/mod_assignment/submission/'.$submission->id.'/'.$filename);
2054                 $output .= '<a href="'.$path.'" ><img src="'.$OUTPUT->pix_url(file_mimetype_icon($mimetype)).'" class="icon" alt="'.$mimetype.'" />'.s($filename).'</a>';
2055                 if ($CFG->enableportfolios && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
2056                     $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id, 'submissionid' => $submission->id, 'fileid' => $file->get_id()), '/mod/assignment/locallib.php');
2057                     $button->set_format_by_file($file);
2058                     $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
2059                 }
2061                 if ($CFG->enableplagiarism) {
2062                     require_once($CFG->libdir.'/plagiarismlib.php');
2063                     $output .= plagiarism_get_links(array('userid'=>$userid, 'file'=>$file, 'cmid'=>$this->cm->id, 'course'=>$this->course, 'assignment'=>$this->assignment));
2064                     $output .= '<br />';
2065                 }
2066             }
2067             if ($CFG->enableportfolios && count($files) > 1  && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
2068                 $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id, 'submissionid' => $submission->id), '/mod/assignment/locallib.php');
2069                 $output .= '<br />'  . $button->to_html(PORTFOLIO_ADD_TEXT_LINK);
2070             }
2071         }
2073         $output = '<div class="files">'.$output.'</div>';
2075         if ($return) {
2076             return $output;
2077         }
2078         echo $output;
2079     }
2081     /**
2082      * Count the files uploaded by a given user
2083      *
2084      * @param $itemid int The submission's id as the file's itemid.
2085      * @return int
2086      */
2087     function count_user_files($itemid) {
2088         $fs = get_file_storage();
2089         $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $itemid, "id", false);
2090         return count($files);
2091     }
2093     /**
2094      * Returns true if the student is allowed to submit
2095      *
2096      * Checks that the assignment has started and, if the option to prevent late
2097      * submissions is set, also checks that the assignment has not yet closed.
2098      * @return boolean
2099      */
2100     function isopen() {
2101         $time = time();
2102         if ($this->assignment->preventlate && $this->assignment->timedue) {
2103             return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
2104         } else {
2105             return ($this->assignment->timeavailable <= $time);
2106         }
2107     }
2110     /**
2111      * Return true if is set description is hidden till available date
2112      *
2113      * This is needed by calendar so that hidden descriptions do not
2114      * come up in upcoming events.
2115      *
2116      * Check that description is hidden till available date
2117      * By default return false
2118      * Assignments types should implement this method if needed
2119      * @return boolen
2120      */
2121     function description_is_hidden() {
2122         return false;
2123     }
2125     /**
2126      * Return an outline of the user's interaction with the assignment
2127      *
2128      * The default method prints the grade and timemodified
2129      * @param $grade object
2130      * @return object with properties ->info and ->time
2131      */
2132     function user_outline($grade) {
2134         $result = new stdClass();
2135         $result->info = get_string('grade').': '.$grade->str_long_grade;
2136         $result->time = $grade->dategraded;
2137         return $result;
2138     }
2140     /**
2141      * Print complete information about the user's interaction with the assignment
2142      *
2143      * @param $user object
2144      */
2145     function user_complete($user, $grade=null) {
2146         global $OUTPUT;
2148         if ($submission = $this->get_submission($user->id)) {
2150             $fs = get_file_storage();
2152             if ($files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false)) {
2153                 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
2154                 foreach ($files as $file) {
2155                     $countfiles .= "; ".$file->get_filename();
2156                 }
2157             }
2159             echo $OUTPUT->box_start();
2160             echo get_string("lastmodified").": ";
2161             echo userdate($submission->timemodified);
2162             echo $this->display_lateness($submission->timemodified);
2164             $this->print_user_files($user->id);
2166             echo '<br />';
2168             $this->view_feedback($submission);
2170             echo $OUTPUT->box_end();
2172         } else {
2173             if ($grade) {
2174                 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
2175                 if ($grade->str_feedback) {
2176                     echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
2177                 }
2178             }
2179             print_string("notsubmittedyet", "assignment");
2180         }
2181     }
2183     /**
2184      * Return a string indicating how late a submission is
2185      *
2186      * @param $timesubmitted int
2187      * @return string
2188      */
2189     function display_lateness($timesubmitted) {
2190         return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
2191     }
2193     /**
2194      * Empty method stub for all delete actions.
2195      */
2196     function delete() {
2197         //nothing by default
2198         redirect('view.php?id='.$this->cm->id);
2199     }
2201     /**
2202      * Empty custom feedback grading form.
2203      */
2204     function custom_feedbackform($submission, $return=false) {
2205         //nothing by default
2206         return '';
2207     }
2209     /**
2210      * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
2211      * for the course (see resource).
2212      *
2213      * Given a course_module object, this function returns any "extra" information that may be needed
2214      * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
2215      *
2216      * @param $coursemodule object The coursemodule object (record).
2217      * @return cached_cm_info Object used to customise appearance on course page
2218      */
2219     function get_coursemodule_info($coursemodule) {
2220         return null;
2221     }
2223     /**
2224      * Plugin cron method - do not use $this here, create new assignment instances if needed.
2225      * @return void
2226      */
2227     function cron() {
2228         //no plugin cron by default - override if needed
2229     }
2231     /**
2232      * Reset all submissions
2233      */
2234     function reset_userdata($data) {
2235         global $CFG, $DB;
2237         if (!$DB->count_records('assignment', array('course'=>$data->courseid, 'assignmenttype'=>$this->type))) {
2238             return array(); // no assignments of this type present
2239         }
2241         $componentstr = get_string('modulenameplural', 'assignment');
2242         $status = array();
2244         $typestr = get_string('type'.$this->type, 'assignment');
2245         // ugly hack to support pluggable assignment type titles...
2246         if($typestr === '[[type'.$this->type.']]'){
2247             $typestr = get_string('type'.$this->type, 'assignment_'.$this->type);
2248         }
2250         if (!empty($data->reset_assignment_submissions)) {
2251             $assignmentssql = "SELECT a.id
2252                                  FROM {assignment} a
2253                                 WHERE a.course=? AND a.assignmenttype=?";
2254             $params = array($data->courseid, $this->type);
2256             // now get rid of all submissions and responses
2257             $fs = get_file_storage();
2258             if ($assignments = $DB->get_records_sql($assignmentssql, $params)) {
2259                 foreach ($assignments as $assignmentid=>$unused) {
2260                     if (!$cm = get_coursemodule_from_instance('assignment', $assignmentid)) {
2261                         continue;
2262                     }
2263                     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2264                     $fs->delete_area_files($context->id, 'mod_assignment', 'submission');
2265                     $fs->delete_area_files($context->id, 'mod_assignment', 'response');
2266                 }
2267             }
2269             $DB->delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)", $params);
2271             $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
2273             if (empty($data->reset_gradebook_grades)) {
2274                 // remove all grades from gradebook
2275                 assignment_reset_gradebook($data->courseid, $this->type);
2276             }
2277         }
2279         /// updating dates - shift may be negative too
2280         if ($data->timeshift) {
2281             shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
2282             $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
2283         }
2285         return $status;
2286     }
2289     function portfolio_exportable() {
2290         return false;
2291     }
2293     /**
2294      * base implementation for backing up subtype specific information
2295      * for one single module
2296      *
2297      * @param filehandle $bf file handle for xml file to write to
2298      * @param mixed $preferences the complete backup preference object
2299      *
2300      * @return boolean
2301      *
2302      * @static
2303      */
2304     static function backup_one_mod($bf, $preferences, $assignment) {
2305         return true;
2306     }
2308     /**
2309      * base implementation for backing up subtype specific information
2310      * for one single submission
2311      *
2312      * @param filehandle $bf file handle for xml file to write to
2313      * @param mixed $preferences the complete backup preference object
2314      * @param object $submission the assignment submission db record
2315      *
2316      * @return boolean
2317      *
2318      * @static
2319      */
2320     static function backup_one_submission($bf, $preferences, $assignment, $submission) {
2321         return true;
2322     }
2324     /**
2325      * base implementation for restoring subtype specific information
2326      * for one single module
2327      *
2328      * @param array  $info the array representing the xml
2329      * @param object $restore the restore preferences
2330      *
2331      * @return boolean
2332      *
2333      * @static
2334      */
2335     static function restore_one_mod($info, $restore, $assignment) {
2336         return true;
2337     }
2339     /**
2340      * base implementation for restoring subtype specific information
2341      * for one single submission
2342      *
2343      * @param object $submission the newly created submission
2344      * @param array  $info the array representing the xml
2345      * @param object $restore the restore preferences
2346      *
2347      * @return boolean
2348      *
2349      * @static
2350      */
2351     static function restore_one_submission($info, $restore, $assignment, $submission) {
2352         return true;
2353     }
2355 } ////// End of the assignment_base class
2358 class mod_assignment_grading_form extends moodleform {
2359     /** @var stores the advaned grading instance (if used in grading) */
2360     private $advancegradinginstance;
2362     function definition() {
2363         global $OUTPUT;
2364         $mform =& $this->_form;
2366         if (isset($this->_customdata->advancedgradinginstance)) {
2367             $this->use_advanced_grading($this->_customdata->advancedgradinginstance);
2368         }
2370         $formattr = $mform->getAttributes();
2371         $formattr['id'] = 'submitform';
2372         $mform->setAttributes($formattr);
2373         // hidden params
2374         $mform->addElement('hidden', 'offset', ($this->_customdata->offset+1));
2375         $mform->setType('offset', PARAM_INT);
2376         $mform->addElement('hidden', 'userid', $this->_customdata->userid);
2377         $mform->setType('userid', PARAM_INT);
2378         $mform->addElement('hidden', 'nextid', $this->_customdata->nextid);
2379         $mform->setType('nextid', PARAM_INT);
2380         $mform->addElement('hidden', 'id', $this->_customdata->cm->id);
2381         $mform->setType('id', PARAM_INT);
2382         $mform->addElement('hidden', 'sesskey', sesskey());
2383         $mform->setType('sesskey', PARAM_ALPHANUM);
2384         $mform->addElement('hidden', 'mode', 'grade');
2385         $mform->setType('mode', PARAM_TEXT);
2386         $mform->addElement('hidden', 'menuindex', "0");
2387         $mform->setType('menuindex', PARAM_INT);
2388         $mform->addElement('hidden', 'saveuserid', "-1");
2389         $mform->setType('saveuserid', PARAM_INT);
2390         $mform->addElement('hidden', 'filter', "0");
2391         $mform->setType('filter', PARAM_INT);
2393         $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->user),
2394                                                 fullname($this->_customdata->user, true) . '<br/>' .
2395                                                 userdate($this->_customdata->submission->timemodified) .
2396                                                 $this->_customdata->lateness );
2398         $this->add_submission_content();
2399         $this->add_grades_section();
2401         $this->add_feedback_section();
2403         if ($this->_customdata->submission->timemarked) {
2404             $datestring = userdate($this->_customdata->submission->timemarked)."&nbsp; (".format_time(time() - $this->_customdata->submission->timemarked).")";
2405             $mform->addElement('header', 'Last Grade', get_string('lastgrade', 'assignment'));
2406             $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->teacher) ,
2407                                                     fullname($this->_customdata->teacher,true).
2408                                                     '<br/>'.$datestring);
2409         }
2410         // buttons
2411         $this->add_action_buttons();
2413     }
2415     /**
2416      * Gets or sets the instance for advanced grading
2417      *
2418      * @param gradingform_instance $gradinginstance
2419      */
2420     public function use_advanced_grading($gradinginstance = false) {
2421         if ($gradinginstance !== false) {
2422             $this->advancegradinginstance = $gradinginstance;
2423         }
2424         return $this->advancegradinginstance;
2425     }
2427     function add_grades_section() {
2428         global $CFG;
2429         $mform =& $this->_form;
2430         $attributes = array();
2431         if ($this->_customdata->gradingdisabled) {
2432             $attributes['disabled'] ='disabled';
2433         }
2435         $mform->addElement('header', 'Grades', get_string('grades', 'grades'));
2437         $grademenu = make_grades_menu($this->_customdata->assignment->grade);
2438         if ($gradinginstance = $this->use_advanced_grading()) {
2439             $gradinginstance->get_controller()->set_grade_range($grademenu);
2440             $gradingelement = $mform->addElement('grading', 'advancedgrading', get_string('grade').':', array('gradinginstance' => $gradinginstance));
2441             if ($this->_customdata->gradingdisabled) {
2442                 $gradingelement->freeze();
2443             } else {
2444                 $mform->addElement('hidden', 'advancedgradinginstanceid', $gradinginstance->get_id());
2445             }
2446         } else {
2447             // use simple direct grading
2448             $grademenu['-1'] = get_string('nograde');
2450             $mform->addElement('select', 'xgrade', get_string('grade').':', $grademenu, $attributes);
2451             $mform->setDefault('xgrade', $this->_customdata->submission->grade ); //@fixme some bug when element called 'grade' makes it break
2452             $mform->setType('xgrade', PARAM_INT);
2453         }
2455         if (!empty($this->_customdata->enableoutcomes)) {
2456             foreach($this->_customdata->grading_info->outcomes as $n=>$outcome) {
2457                 $options = make_grades_menu(-$outcome->scaleid);
2458                 if ($outcome->grades[$this->_customdata->submission->userid]->locked) {
2459                     $options[0] = get_string('nooutcome', 'grades');
2460                     $mform->addElement('static', 'outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->name.':',
2461                             $options[$outcome->grades[$this->_customdata->submission->userid]->grade]);
2462                 } else {
2463                     $options[''] = get_string('nooutcome', 'grades');
2464                     $attributes = array('id' => 'menuoutcome_'.$n );
2465                     $mform->addElement('select', 'outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->name.':', $options, $attributes );
2466                     $mform->setType('outcome_'.$n.'['.$this->_customdata->userid.']', PARAM_INT);
2467                     $mform->setDefault('outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->grades[$this->_customdata->submission->userid]->grade );
2468                 }
2469             }
2470         }
2471         $course_context = get_context_instance(CONTEXT_MODULE , $this->_customdata->cm->id);
2472         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
2473             $grade = '<a href="'.$CFG->wwwroot.'/grade/report/grader/index.php?id='. $this->_customdata->courseid .'" >'.
2474                         $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade . '</a>';
2475         }else{
2476             $grade = $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade;
2477         }
2478         $mform->addElement('static', 'finalgrade', get_string('currentgrade', 'assignment').':' ,$grade);
2479         $mform->setType('finalgrade', PARAM_INT);
2480     }
2482     /**
2483      *
2484      * @global core_renderer $OUTPUT
2485      */
2486     function add_feedback_section() {
2487         global $OUTPUT;
2488         $mform =& $this->_form;
2489         $mform->addElement('header', 'Feed Back', get_string('feedback', 'grades'));
2491         if ($this->_customdata->gradingdisabled) {
2492             $mform->addElement('static', 'disabledfeedback', $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_feedback );
2493         } else {
2494             // visible elements
2496             $mform->addElement('editor', 'submissioncomment_editor', get_string('feedback', 'assignment').':', null, $this->get_editor_options() );
2497             $mform->setType('submissioncomment_editor', PARAM_RAW); // to be cleaned before display
2498             $mform->setDefault('submissioncomment_editor', $this->_customdata->submission->submissioncomment);
2499             //$mform->addRule('submissioncomment', get_string('required'), 'required', null, 'client');
2500             switch ($this->_customdata->assignment->assignmenttype) {
2501                 case 'upload' :
2502                 case 'uploadsingle' :
2503                     $mform->addElement('filemanager', 'files_filemanager', get_string('responsefiles', 'assignment'). ':', null, $this->_customdata->fileui_options);
2504                     break;
2505                 default :
2506                     break;
2507             }
2508             $mform->addElement('hidden', 'mailinfo_h', "0");
2509             $mform->setType('mailinfo_h', PARAM_INT);
2510             $mform->addElement('checkbox', 'mailinfo',get_string('enablenotification','assignment').
2511             $OUTPUT->help_icon('enablenotification', 'assignment') .':' );
2512             $mform->setType('mailinfo', PARAM_INT);
2513         }
2514     }
2516     function add_action_buttons() {
2517         $mform =& $this->_form;
2518         //if there are more to be graded.
2519         if ($this->_customdata->nextid>0) {
2520             $buttonarray=array();
2521             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2522             //@todo: fix accessibility: javascript dependency not necessary
2523             $buttonarray[] = &$mform->createElement('submit', 'saveandnext', get_string('saveandnext'));
2524             $buttonarray[] = &$mform->createElement('submit', 'next', get_string('next'));
2525             $buttonarray[] = &$mform->createElement('cancel');
2526         } else {
2527             $buttonarray=array();
2528             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2529             $buttonarray[] = &$mform->createElement('cancel');
2530         }
2531         $mform->addGroup($buttonarray, 'grading_buttonar', '', array(' '), false);
2532         $mform->closeHeaderBefore('grading_buttonar');
2533         $mform->setType('grading_buttonar', PARAM_RAW);
2534     }
2536     function add_submission_content() {
2537         $mform =& $this->_form;
2538         $mform->addElement('header', 'Submission', get_string('submission', 'assignment'));
2539         $mform->addElement('static', '', '' , $this->_customdata->submission_content );
2540     }
2542     protected function get_editor_options() {
2543         $editoroptions = array();
2544         $editoroptions['component'] = 'mod_assignment';
2545         $editoroptions['filearea'] = 'feedback';
2546         $editoroptions['noclean'] = false;
2547         $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)
2548         $editoroptions['maxbytes'] = $this->_customdata->maxbytes;
2549         $editoroptions['context'] = $this->_customdata->context;
2550         return $editoroptions;
2551     }
2553     public function set_data($data) {
2554         $editoroptions = $this->get_editor_options();
2555         if (!isset($data->text)) {
2556             $data->text = '';
2557         }
2558         if (!isset($data->format)) {
2559             $data->textformat = FORMAT_HTML;
2560         } else {
2561             $data->textformat = $data->format;
2562         }
2564         if (!empty($this->_customdata->submission->id)) {
2565             $itemid = $this->_customdata->submission->id;
2566         } else {
2567             $itemid = null;
2568         }
2570         switch ($this->_customdata->assignment->assignmenttype) {
2571                 case 'upload' :
2572                 case 'uploadsingle' :
2573                     $data = file_prepare_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2574                     break;
2575                 default :
2576                     break;
2577         }
2579         $data = file_prepare_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2580         return parent::set_data($data);
2581     }
2583     public function get_data() {
2584         $data = parent::get_data();
2586         if (!empty($this->_customdata->submission->id)) {
2587             $itemid = $this->_customdata->submission->id;
2588         } else {
2589             $itemid = null; //TODO: this is wrong, itemid MUST be known when saving files!! (skodak)
2590         }
2592         if ($data) {
2593             $editoroptions = $this->get_editor_options();
2594             switch ($this->_customdata->assignment->assignmenttype) {
2595                 case 'upload' :
2596                 case 'uploadsingle' :
2597                     $data = file_postupdate_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2598                     break;
2599                 default :
2600                     break;
2601             }
2602             $data = file_postupdate_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2603         }
2605         if ($this->use_advanced_grading() && !isset($data->advancedgrading)) {
2606             $data->advancedgrading = null;
2607         }
2609         return $data;
2610     }
2613 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
2615 /**
2616  * Deletes an assignment instance
2617  *
2618  * This is done by calling the delete_instance() method of the assignment type class
2619  */
2620 function assignment_delete_instance($id){
2621     global $CFG, $DB;
2623     if (! $assignment = $DB->get_record('assignment', array('id'=>$id))) {
2624         return false;
2625     }
2627     // fall back to base class if plugin missing
2628     $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2629     if (file_exists($classfile)) {
2630         require_once($classfile);
2631         $assignmentclass = "assignment_$assignment->assignmenttype";
2633     } else {
2634         debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
2635         $assignmentclass = "assignment_base";
2636     }
2638     $ass = new $assignmentclass();
2639     return $ass->delete_instance($assignment);
2643 /**
2644  * Updates an assignment instance
2645  *
2646  * This is done by calling the update_instance() method of the assignment type class
2647  */
2648 function assignment_update_instance($assignment){
2649     global $CFG;
2651     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_PLUGIN);
2653     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2654     $assignmentclass = "assignment_$assignment->assignmenttype";
2655     $ass = new $assignmentclass();
2656     return $ass->update_instance($assignment);
2660 /**
2661  * Adds an assignment instance
2662  *
2663  * This is done by calling the add_instance() method of the assignment type class
2664  */
2665 function assignment_add_instance($assignment) {
2666     global $CFG;
2668     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_PLUGIN);
2670     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2671     $assignmentclass = "assignment_$assignment->assignmenttype";
2672     $ass = new $assignmentclass();
2673     return $ass->add_instance($assignment);
2677 /**
2678  * Returns an outline of a user interaction with an assignment
2679  *
2680  * This is done by calling the user_outline() method of the assignment type class
2681  */
2682 function assignment_user_outline($course, $user, $mod, $assignment) {
2683     global $CFG;
2685     require_once("$CFG->libdir/gradelib.php");
2686     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2687     $assignmentclass = "assignment_$assignment->assignmenttype";
2688     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2689     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2690     if (!empty($grades->items[0]->grades)) {
2691         return $ass->user_outline(reset($grades->items[0]->grades));
2692     } else {
2693         return null;
2694     }
2697 /**
2698  * Prints the complete info about a user's interaction with an assignment
2699  *
2700  * This is done by calling the user_complete() method of the assignment type class
2701  */
2702 function assignment_user_complete($course, $user, $mod, $assignment) {
2703     global $CFG;
2705     require_once("$CFG->libdir/gradelib.php");
2706     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2707     $assignmentclass = "assignment_$assignment->assignmenttype";
2708     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2709     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2710     if (empty($grades->items[0]->grades)) {
2711         $grade = false;
2712     } else {
2713         $grade = reset($grades->items[0]->grades);
2714     }
2715     return $ass->user_complete($user, $grade);
2718 /**
2719  * Function to be run periodically according to the moodle cron
2720  *
2721  * Finds all assignment notifications that have yet to be mailed out, and mails them
2722  */
2723 function assignment_cron () {
2724     global $CFG, $USER, $DB;
2726     /// first execute all crons in plugins
2727     if ($plugins = get_plugin_list('assignment')) {
2728         foreach ($plugins as $plugin=>$dir) {
2729             require_once("$dir/assignment.class.php");
2730             $assignmentclass = "assignment_$plugin";
2731             $ass = new $assignmentclass();
2732             $ass->cron();
2733         }
2734     }
2736     /// Notices older than 1 day will not be mailed.  This is to avoid the problem where
2737     /// cron has not been running for a long time, and then suddenly people are flooded
2738     /// with mail from the past few weeks or months
2740     $timenow   = time();
2741     $endtime   = $timenow - $CFG->maxeditingtime;
2742     $starttime = $endtime - 24 * 3600;   /// One day earlier
2744     if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2746         $realuser = clone($USER);
2748         foreach ($submissions as $key => $submission) {
2749             $DB->set_field("assignment_submissions", "mailed", "1", array("id"=>$submission->id));
2750         }
2752         $timenow = time();
2754         foreach ($submissions as $submission) {
2756             echo "Processing assignment submission $submission->id\n";
2758             if (! $user = $DB->get_record("user", array("id"=>$submission->userid))) {
2759                 echo "Could not find user $user->id\n";
2760                 continue;
2761             }
2763             if (! $course = $DB->get_record("course", array("id"=>$submission->course))) {
2764                 echo "Could not find course $submission->course\n";
2765                 continue;
2766             }
2768             /// Override the language and timezone of the "current" user, so that
2769             /// mail is customised for the receiver.
2770             cron_setup_user($user, $course);
2772             $coursecontext = get_context_instance(CONTEXT_COURSE, $submission->course);
2773             $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
2774             if (!is_enrolled($coursecontext, $user->id)) {
2775                 echo fullname($user)." not an active participant in " . $courseshortname . "\n";
2776                 continue;
2777             }
2779             if (! $teacher = $DB->get_record("user", array("id"=>$submission->teacher))) {
2780                 echo "Could not find teacher $submission->teacher\n";
2781                 continue;
2782             }
2784             if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2785                 echo "Could not find course module for assignment id $submission->assignment\n";
2786                 continue;
2787             }
2789             if (! $mod->visible) {    /// Hold mail notification for hidden assignments until later
2790                 continue;
2791             }
2793             $strassignments = get_string("modulenameplural", "assignment");
2794             $strassignment  = get_string("modulename", "assignment");
2796             $assignmentinfo = new stdClass();
2797             $assignmentinfo->teacher = fullname($teacher);
2798             $assignmentinfo->assignment = format_string($submission->name,true);
2799             $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2801             $postsubject = "$courseshortname: $strassignments: ".format_string($submission->name,true);
2802             $posttext  = "$courseshortname -> $strassignments -> ".format_string($submission->name,true)."\n";
2803             $posttext .= "---------------------------------------------------------------------\n";
2804             $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2805             $posttext .= "---------------------------------------------------------------------\n";
2807             if ($user->mailformat == 1) {  // HTML
2808                 $posthtml = "<p><font face=\"sans-serif\">".
2809                 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$courseshortname</a> ->".
2810                 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2811                 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2812                 $posthtml .= "<hr /><font face=\"sans-serif\">";
2813                 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2814                 $posthtml .= "</font><hr />";
2815             } else {
2816                 $posthtml = "";
2817             }
2819             $eventdata = new stdClass();
2820             $eventdata->modulename       = 'assignment';
2821             $eventdata->userfrom         = $teacher;
2822             $eventdata->userto           = $user;
2823             $eventdata->subject          = $postsubject;
2824             $eventdata->fullmessage      = $posttext;
2825             $eventdata->fullmessageformat = FORMAT_PLAIN;
2826             $eventdata->fullmessagehtml  = $posthtml;
2827             $eventdata->smallmessage     = get_string('assignmentmailsmall', 'assignment', $assignmentinfo);
2829             $eventdata->name            = 'assignment_updates';
2830             $eventdata->component       = 'mod_assignment';
2831             $eventdata->notification    = 1;
2832             $eventdata->contexturl      = $assignmentinfo->url;
2833             $eventdata->contexturlname  = $assignmentinfo->assignment;
2835             message_send($eventdata);
2836         }
2838         cron_setup_user();
2839     }
2841     return true;
2844 /**
2845  * Return grade for given user or all users.
2846  *
2847  * @param int $assignmentid id of assignment
2848  * @param int $userid optional user id, 0 means all users
2849  * @return array array of grades, false if none
2850  */
2851 function assignment_get_user_grades($assignment, $userid=0) {
2852     global $CFG, $DB;
2854     if ($userid) {
2855         $user = "AND u.id = :userid";
2856         $params = array('userid'=>$userid);
2857     } else {
2858         $user = "";
2859     }
2860     $params['aid'] = $assignment->id;
2862     $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2863                    s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2864               FROM {user} u, {assignment_submissions} s
2865              WHERE u.id = s.userid AND s.assignment = :aid
2866                    $user";
2868     return $DB->get_records_sql($sql, $params);
2871 /**
2872  * Update activity grades
2873  *
2874  * @param object $assignment
2875  * @param int $userid specific user only, 0 means all
2876  */
2877 function assignment_update_grades($assignment, $userid=0, $nullifnone=true) {
2878     global $CFG, $DB;
2879     require_once($CFG->libdir.'/gradelib.php');
2881     if ($assignment->grade == 0) {
2882         assignment_grade_item_update($assignment);
2884     } else if ($grades = assignment_get_user_grades($assignment, $userid)) {
2885         foreach($grades as $k=>$v) {
2886             if ($v->rawgrade == -1) {
2887                 $grades[$k]->rawgrade = null;
2888             }
2889         }
2890         assignment_grade_item_update($assignment, $grades);
2892     } else {
2893         assignment_grade_item_update($assignment);
2894     }
2897 /**
2898  * Update all grades in gradebook.
2899  */
2900 function assignment_upgrade_grades() {
2901     global $DB;
2903     $sql = "SELECT COUNT('x')
2904               FROM {assignment} a, {course_modules} cm, {modules} m
2905              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2906     $count = $DB->count_records_sql($sql);
2908     $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
2909               FROM {assignment} a, {course_modules} cm, {modules} m
2910              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2911     $rs = $DB->get_recordset_sql($sql);
2912     if ($rs->valid()) {
2913         // too much debug output
2914         $pbar = new progress_bar('assignmentupgradegrades', 500, true);
2915         $i=0;
2916         foreach ($rs as $assignment) {
2917             $i++;
2918             upgrade_set_timeout(60*5); // set up timeout, may also abort execution
2919             assignment_update_grades($assignment);
2920             $pbar->update($i, $count, "Updating Assignment grades ($i/$count).");
2921         }
2922         upgrade_set_timeout(); // reset to default timeout
2923     }
2924     $rs->close();
2927 /**
2928  * Create grade item for given assignment
2929  *
2930  * @param object $assignment object with extra cmidnumber
2931  * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
2932  * @return int 0 if ok, error code otherwise
2933  */
2934 function assignment_grade_item_update($assignment, $grades=NULL) {
2935     global $CFG;
2936     require_once($CFG->libdir.'/gradelib.php');
2938     if (!isset($assignment->courseid)) {
2939         $assignment->courseid = $assignment->course;
2940     }
2942     $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
2944     if ($assignment->grade > 0) {
2945         $params['gradetype'] = GRADE_TYPE_VALUE;
2946         $params['grademax']  = $assignment->grade;
2947         $params['grademin']  = 0;
2949     } else if ($assignment->grade < 0) {
2950         $params['gradetype'] = GRADE_TYPE_SCALE;
2951         $params['scaleid']   = -$assignment->grade;
2953     } else {
2954         $params['gradetype'] = GRADE_TYPE_TEXT; // allow text comments only
2955     }
2957     if ($grades  === 'reset') {
2958         $params['reset'] = true;
2959         $grades = NULL;
2960     }
2962     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades, $params);
2965 /**
2966  * Delete grade item for given assignment
2967  *
2968  * @param object $assignment object
2969  * @return object assignment
2970  */
2971 function assignment_grade_item_delete($assignment) {
2972     global $CFG;
2973     require_once($CFG->libdir.'/gradelib.php');
2975     if (!isset($assignment->courseid)) {
2976         $assignment->courseid = $assignment->course;
2977     }
2979     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
2982 /**
2983  * Returns the users with data in one assignment (students and teachers)
2984  *
2985  * @todo: deprecated - to be deleted in 2.2
2986  *
2987  * @param $assignmentid int
2988  * @return array of user objects
2989  */
2990 function assignment_get_participants($assignmentid) {
2991     global $CFG, $DB;
2993     //Get students
2994     $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2995                                         FROM {user} u,
2996                                              {assignment_submissions} a
2997                                        WHERE a.assignment = ? and
2998                                              u.id = a.userid", array($assignmentid));
2999     //Get teachers
3000     $teachers = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
3001                                         FROM {user} u,
3002                                              {assignment_submissions} a
3003                                        WHERE a.assignment = ? and
3004                                              u.id = a.teacher", array($assignmentid));
3006     //Add teachers to students
3007     if ($teachers) {
3008         foreach ($teachers as $teacher) {
3009             $students[$teacher->id] = $teacher;
3010         }
3011     }
3012     //Return students array (it contains an array of unique users)
3013     return ($students);
3016 /**
3017  * Serves assignment submissions and other files.
3018  *
3019  * @param object $course
3020  * @param object $cm
3021  * @param object $context
3022  * @param string $filearea
3023  * @param array $args
3024  * @param bool $forcedownload
3025  * @return bool false if file not found, does not return if found - just send the file
3026  */
3027 function assignment_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) {
3028     global $CFG, $DB;
3030     if ($context->contextlevel != CONTEXT_MODULE) {
3031         return false;
3032     }
3034     require_login($course, false, $cm);
3036     if (!$assignment = $DB->get_record('assignment', array('id'=>$cm->instance))) {
3037         return false;
3038     }
3040     require_once($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
3041     $assignmentclass = 'assignment_'.$assignment->assignmenttype;
3042     $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm, $course);
3044     return $assignmentinstance->send_file($filearea, $args);
3046 /**
3047  * Checks if a scale is being used by an assignment
3048  *
3049  * This is used by the backup code to decide whether to back up a scale
3050  * @param $assignmentid int
3051  * @param $scaleid int
3052  * @return boolean True if the scale is used by the assignment
3053  */
3054 function assignment_scale_used($assignmentid, $scaleid) {
3055     global $DB;
3057     $return = false;
3059     $rec = $DB->get_record('assignment', array('id'=>$assignmentid,'grade'=>-$scaleid));
3061     if (!empty($rec) && !empty($scaleid)) {
3062         $return = true;
3063     }
3065     return $return;
3068 /**
3069  * Checks if scale is being used by any instance of assignment
3070  *
3071  * This is used to find out if scale used anywhere
3072  * @param $scaleid int
3073  * @return boolean True if the scale is used by any assignment
3074  */
3075 function assignment_scale_used_anywhere($scaleid) {
3076     global $DB;
3078     if ($scaleid and $DB->record_exists('assignment', array('grade'=>-$scaleid))) {
3079         return true;
3080     } else {
3081         return false;
3082     }
3085 /**
3086  * Make sure up-to-date events are created for all assignment instances
3087  *
3088  * This standard function will check all instances of this module
3089  * and make sure there are up-to-date events created for each of them.
3090  * If courseid = 0, then every assignment event in the site is checked, else
3091  * only assignment events belonging to the course specified are checked.
3092  * This function is used, in its new format, by restore_refresh_events()
3093  *
3094  * @param $courseid int optional If zero then all assignments for all courses are covered
3095  * @return boolean Always returns true
3096  */
3097 function assignment_refresh_events($courseid = 0) {
3098     global $DB;
3100     if ($courseid == 0) {
3101         if (! $assignments = $DB->get_records("assignment")) {
3102             return true;
3103         }
3104     } else {
3105         if (! $assignments = $DB->get_records("assignment", array("course"=>$courseid))) {
3106             return true;
3107         }
3108     }
3109     $moduleid = $DB->get_field('modules', 'id', array('name'=>'assignment'));
3111     foreach ($assignments as $assignment) {
3112         $cm = get_coursemodule_from_id('assignment', $assignment->id);
3113         $event = new stdClass();
3114         $event->name        = $assignment->name;
3115         $event->description = format_module_intro('assignment', $assignment, $cm->id);
3116         $event->timestart   = $assignment->timedue;
3118         if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
3119             update_event($event);
3121         } else {
3122             $event->courseid    = $assignment->course;
3123             $event->groupid     = 0;
3124             $event->userid      = 0;
3125             $event->modulename  = 'assignment';
3126             $event->instance    = $assignment->id;
3127             $event->eventtype   = 'due';
3128             $event->timeduration = 0;
3129             $event->visible     = $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$assignment->id));
3130             add_event($event);
3131         }
3133     }
3134     return true;
3137 /**
3138  * Print recent activity from all assignments in a given course
3139  *
3140  * This is used by the recent activity block
3141  */
3142 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
3143     global $CFG, $USER, $DB, $OUTPUT;
3145     // do not use log table if possible, it may be huge
3147     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
3148                                                      u.firstname, u.lastname, u.email, u.picture
3149                                                 FROM {assignment_submissions} asb
3150                                                      JOIN {assignment} a      ON a.id = asb.assignment
3151                                                      JOIN {course_modules} cm ON cm.instance = a.id
3152                                                      JOIN {modules} md        ON md.id = cm.module
3153                                                      JOIN {user} u            ON u.id = asb.userid
3154                                                WHERE asb.timemodified > ? AND
3155                                                      a.course = ? AND
3156                                                      md.name = 'assignment'
3157                                             ORDER BY asb.timemodified ASC", array($timestart, $course->id))) {
3158          return false;
3159     }
3161     $modinfo =& get_fast_modinfo($course); // reference needed because we might load the groups
3162     $show    = array();
3163     $grader  = array();
3165     foreach($submissions as $submission) {
3166         if (!array_key_exists($submission->cmid, $modinfo->cms)) {
3167             continue;
3168         }
3169         $cm = $modinfo->cms[$submission->cmid];
3170         if (!$cm->uservisible) {
3171             continue;
3172         }
3173         if ($submission->userid == $USER->id) {
3174             $show[] = $submission;
3175             continue;
3176         }
3178         // the act of sumbitting of assignment may be considered private - only graders will see it if specified
3179         if (empty($CFG->assignment_showrecentsubmissions)) {
3180             if (!array_key_exists($cm->id, $grader)) {
3181                 $grader[$cm->id] = has_capability('moodle/grade:viewall', get_context_instance(CONTEXT_MODULE, $cm->id));
3182             }
3183             if (!$grader[$cm->id]) {
3184                 continue;
3185             }
3186         }
3188         $groupmode = groups_get_activity_groupmode($cm, $course);
3190         if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
3191             if (isguestuser()) {
3192                 // shortcut - guest user does not belong into any group
3193                 continue;
3194             }
3196             if (is_null($modinfo->groups)) {
3197                 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
3198             }
3200             // this will be slow - show only users that share group with me in this cm
3201             if (empty($modinfo->groups[$cm->id])) {
3202                 continue;
3203             }
3204             $usersgroups =  groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
3205             if (is_array($usersgroups)) {
3206                 $usersgroups = array_keys($usersgroups);
3207                 $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
3208                 if (empty($intersect)) {
3209                     continue;
3210                 }
3211             }
3212         }
3213         $show[] = $submission;
3214     }
3216     if (empty($show)) {
3217         return false;
3218     }
3220     echo $OUTPUT->heading(get_string('newsubmissions', 'assignment').':', 3);
3222     foreach ($show as $submission) {
3223         $cm = $modinfo->cms[$submission->cmid];
3224         $link = $CFG->wwwroot.'/mod/assignment/view.php?id='.$cm->id;
3225         print_recent_activity_note($submission->timemodified, $submission, $cm->name, $link, false, $viewfullnames);
3226     }
3228     return true;
3232 /**
3233  * Returns all assignments since a given time in specified forum.
3234  */
3235 function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0)  {
3236     global $CFG, $COURSE, $USER, $DB;
3238     if ($COURSE->id == $courseid) {
3239         $course = $COURSE;
3240     } else {
3241         $course = $DB->get_record('course', array('id'=>$courseid));
3242     }
3244     $modinfo =& get_fast_modinfo($course);
3246     $cm = $modinfo->cms[$cmid];
3248     $params = array();
3249     if ($userid) {
3250         $userselect = "AND u.id = :userid";
3251         $params['userid'] = $userid;
3252     } else {
3253         $userselect = "";
3254     }
3256     if ($groupid) {
3257         $groupselect = "AND gm.groupid = :groupid";
3258         $groupjoin   = "JOIN {groups_members} gm ON  gm.userid=u.id";
3259         $params['groupid'] = $groupid;
3260     } else {
3261         $groupselect = "";
3262         $groupjoin   = "";
3263     }
3265     $params['cminstance'] = $cm->instance;
3266     $params['timestart'] = $timestart;
3268     $userfields = user_picture::fields('u', null, 'userid');
3270     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified,
3271                                                      $userfields
3272                                                 FROM {assignment_submissions} asb
3273                                                 JOIN {assignment} a      ON a.id = asb.assignment
3274                                                 JOIN {user} u            ON u.id = asb.userid
3275                                           $groupjoin
3276                                                WHERE asb.timemodified > :timestart AND a.id = :cminstance
3277                                                      $userselect $groupselect
3278                                             ORDER BY asb.timemodified ASC", $params)) {
3279          return;
3280     }
3282     $groupmode       = groups_get_activity_groupmode($cm, $course);
3283     $cm_context      = get_context_instance(CONTEXT_MODULE, $cm->id);
3284     $grader          = has_capability('moodle/grade:viewall', $cm_context);
3285     $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
3286     $viewfullnames   = has_capability('moodle/site:viewfullnames', $cm_context);
3288     if (is_null($modinfo->groups)) {
3289         $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
3290     }
3292     $show = array();
3294     foreach($submissions as $submission) {
3295         if ($submission->userid == $USER->id) {
3296             $show[] = $submission;
3297             continue;
3298         }
3299         // the act of submitting of assignment may be considered private - only graders will see it if specified
3300         if (empty($CFG->assignment_showrecentsubmissions)) {
3301             if (!$grader) {
3302                 continue;
3303             }
3304         }
3306         if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
3307             if (isguestuser()) {
3308                 // shortcut - guest user does not belong into any group
3309                 continue;
3310             }
3312             // this will be slow - show only users that share group with me in this cm
3313             if (empty($modinfo->groups[$cm->id])) {
3314                 continue;
3315             }
3316             $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
3317             if (is_array($usersgroups)) {
3318                 $usersgroups = array_keys($usersgroups);
3319                 $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
3320                 if (empty($intersect)) {
3321                     continue;
3322                 }
3323             }
3324         }
3325         $show[] = $submission;
3326     }
3328     if (empty($show)) {
3329         return;
3330     }
3332     if ($grader) {
3333         require_once($CFG->libdir.'/gradelib.php');
3334         $userids = array();
3335         foreach ($show as $id=>$submission) {
3336             $userids[] = $submission->userid;
3338         }
3339         $grades = grade_get_grades($courseid, 'mod', 'assignment', $cm->instance, $userids);
3340     }
3342     $aname = format_string($cm->name,true);
3343     foreach ($show as $submission) {
3344         $tmpactivity = new stdClass();
3346         $tmpactivity->type         = 'assignment';
3347         $tmpactivity->cmid         = $cm->id;
3348         $tmpactivity->name         = $aname;
3349         $tmpactivity->sectionnum   = $cm->sectionnum;
3350         $tmpactivity->timestamp    = $submission->timemodified;
3352         if ($grader) {
3353             $tmpactivity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
3354         }
3356         $userfields = explode(',', user_picture::fields());
3357         foreach ($userfields as $userfield) {
3358             if ($userfield == 'id') {
3359                 $tmpactivity->user->{$userfield} = $submission->userid; // aliased in SQL above
3360             } else {
3361                 $tmpactivity->user->{$userfield} = $submission->{$userfield};
3362             }
3363         }
3364         $tmpactivity->user->fullname = fullname($submission, $viewfullnames);
3366         $activities[$index++] = $tmpactivity;
3367     }
3369     return;
3372 /**
3373  * Print recent activity from all assignments in a given course
3374  *
3375  * This is used by course/recent.php
3376  */
3377 function assignment_print_recent_mod_activity($activity, $courseid, $detail, $modnames)  {
3378     global $CFG, $OUTPUT;
3380     echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
3382     echo "<tr><td class=\"userpicture\" valign=\"top\">";
3383     echo $OUTPUT->user_picture($activity->user);
3384     echo "</td><td>";
3386     if ($detail) {
3387         $modname = $modnames[$activity->type];
3388         echo '<div class="title">';
3389         echo "<img src=\"" . $OUTPUT->pix_url('icon', 'assignment') . "\" ".
3390              "class=\"icon\" alt=\"$modname\">";
3391         echo "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id={$activity->cmid}\">{$activity->name}</a>";
3392         echo '</div>';
3393     }
3395     if (isset($activity->grade)) {
3396         echo '<div class="grade">';
3397         echo get_string('grade').': ';
3398         echo $activity->grade;
3399         echo '</div>';
3400     }
3402     echo '<div class="user">';
3403     echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->id}&amp;course=$courseid\">"
3404          ."{$activity->user->fullname}</a>  - ".userdate($activity->timestamp);
3405     echo '</div>';
3407     echo "</td></tr></table>";
3410 /// GENERIC SQL FUNCTIONS
3412 /**
3413  * Fetch info from logs
3414  *
3415  * @param $log object with properties ->info (the assignment id) and ->userid
3416  * @return array with assignment name and user firstname and lastname
3417  */
3418 function assignment_log_info($log) {
3419     global $CFG, $DB;
3421     return $DB->get_record_sql("SELECT a.name, u.firstname, u.lastname
3422                                   FROM {assignment} a, {user} u
3423                                  WHERE a.id = ? AND u.id = ?", array($log->info, $log->userid));
3426 /**
3427  * Return list of marked submissions that have not been mailed out for currently enrolled students
3428  *
3429  * @return array
3430  */
3431 function assignment_get_unmailed_submissions($starttime, $endtime) {
3432     global $CFG, $DB;
3434     return $DB->get_records_sql("SELECT s.*, a.course, a.name
3435                                    FROM {assignment_submissions} s,
3436                                         {assignment} a
3437                                   WHERE s.mailed = 0
3438                                         AND s.timemarked <= ?
3439                                         AND s.timemarked >= ?
3440                                         AND s.assignment = a.id", array($endtime, $starttime));
3443 /**
3444  * Counts all real assignment submissions by ENROLLED students (not empty ones)
3445  *
3446  * There are also assignment type methods count_real_submissions() which in the default
3447  * implementation simply call this function.
3448  * @param $groupid int optional If nonzero then count is restricted to this group
3449  * @return int The number of submissions
3450  */
3451 function assignment_count_real_submissions($cm, $groupid=0) {
3452     global $CFG, $DB;
3454     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
3456     // this is all the users with this capability set, in this context or higher
3457     if ($users = get_enrolled_users($context, 'mod/assignment:view', $groupid, 'u.id')) {
3458         $users = array_keys($users);
3459     }
3461     // if groupmembersonly used, remove users who are not in any group
3462     if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
3463         if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
3464             $users = array_intersect($users, array_keys($groupingusers));
3465         }
3466     }
3468     if (empty($users)) {
3469         return 0;
3470     }
3472     $userlists = implode(',', $users);
3474     return $DB->count_records_sql("SELECT COUNT('x')
3475                                      FROM {assignment_submissions}
3476                                     WHERE assignment = ? AND
3477                                           timemodified > 0 AND
3478                                           userid IN ($userlists)", array($cm->instance));
3482 /**
3483  * Return all assignment submissions by ENROLLED students (even empty)
3484  *
3485  * There are also assignment type methods get_submissions() wich in the default
3486  * implementation simply call this function.
3487  * @param $sort string optional field names for the ORDER BY in the sql query
3488  * @param $dir string optional specifying the sort direction, defaults to DESC
3489  * @return array The submission objects indexed by id
3490  */
3491 function assignment_get_all_submissions($assignment, $sort="", $dir="DESC") {
3492 /// Return all assignment submissions by ENROLLED students (even empty)
3493     global $CFG, $DB;
3495     if ($sort == "lastname" or $sort == "firstname") {
3496         $sort = "u.$sort $dir";
3497     } else if (empty($sort)) {
3498         $sort = "a.timemodified DESC";
3499     } else {
3500         $sort = "a.$sort $dir";
3501     }
3503     /* not sure this is needed at all since assignment already has a course define, so this join?
3504     $select = "s.course = '$assignment->course' AND";
3505     if ($assignment->course == SITEID) {
3506         $select = '';
3507     }*/
3509     return $DB->get_records_sql("SELECT a.*
3510                                    FROM {assignment_submissions} a, {user} u
3511                                   WHERE u.id = a.userid
3512                                         AND a.assignment = ?
3513                                ORDER BY $sort", array($assignment->id));
3517 /**
3518  * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
3519  * for the course (see resource).
3520  *
3521  * Given a course_module object, this function returns any "extra" information that may be needed
3522  * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
3523  *
3524  * @param $coursemodule object The coursemodule object (record).
3525  * @return cached_cm_info An object on information that the courses will know about (most noticeably, an icon).
3526  */
3527 function assignment_get_coursemodule_info($coursemodule) {
3528     global $CFG, $DB;
3530     if (! $assignment = $DB->get_record('assignment', array('id'=>$coursemodule->instance),
3531             'id, assignmenttype, name, intro, introformat')) {
3532         return false;
3533     }
3535     $libfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
3537     if (file_exists($libfile)) {
3538         require_once($libfile);
3539         $assignmentclass = "assignment_$assignment->assignmenttype";
3540         $ass = new $assignmentclass('staticonly');
3541         if (!($result = $ass->get_coursemodule_info($coursemodule))) {
3542             $result = new cached_cm_info();
3543             $result->name = $assignment->name;
3544         }
3545         if ($coursemodule->showdescription) {
3546             // Convert intro to html. Do not filter cached version, filters run at display time.
3547             $result->content = format_module_intro('assignment', $assignment, $coursemodule->id, false);
3548         }
3549         return $result;
3550     } else {
3551         debugging('Incorrect assignment type: '.$assignment->assignmenttype);
3552         return false;
3553     }
3558 /// OTHER GENERAL FUNCTIONS FOR ASSIGNMENTS  ///////////////////////////////////////
3560 /**
3561  * Returns an array of installed assignment types indexed and sorted by name
3562  *
3563  * @return array The index is the name of the assignment type, the value its full name from the language strings
3564  */
3565 function assignment_types() {
3566     $types = array();
3567     $names = get_plugin_list('assignment');
3568     foreach ($names as $name=>$dir) {
3569         $types[$name] = get_string('type'.$name, 'assignment');
3571         // ugly hack to support pluggable assignment type titles..
3572         if ($types[$name] == '[[type'.$name.']]') {
3573             $types[$name] = get_string('type'.$name, 'assignment_'.$name);
3574         }
3575     }
3576     asort($types);
3577     return $types;
3580 function assignment_print_overview($courses, &$htmlarray) {
3581     global $USER, $CFG, $DB;
3583     if (empty($courses) || !is_array($courses) || count($courses) == 0) {
3584         return array();
3585     }
3587     if (!$assignments = get_all_instances_in_courses('assignment',$courses)) {
3588         return;
3589     }
3591     $assignmentids = array();
3593     // Do assignment_base::isopen() here without loading the whole thing for speed
3594     foreach ($assignments as $key => $assignment) {
3595         $time = time();
3596         if ($assignment->timedue) {
3597             if ($assignment->preventlate) {
3598                 $isopen = ($assignment->timeavailable <= $time && $time <= $assignment->timedue);
3599             } else {
3600                 $isopen = ($assignment->timeavailable <= $time);
3601             }
3602         }
3603         if (empty($isopen) || empty($assignment->timedue)) {
3604             unset($assignments[$key]);
3605         } else {
3606             $assignmentids[] = $assignment->id;
3607         }
3608     }
3610     if (empty($assignmentids)){
3611         // no assignments to look at - we're done
3612         return true;
3613     }
3615     $strduedate = get_string('duedate', 'assignment');
3616     $strduedateno = get_string('duedateno', 'assignment');
3617     $strgraded = get_string('graded', 'assignment');
3618     $strnotgradedyet = get_string('notgradedyet', 'assignment');
3619     $strnotsubmittedyet = get_string('notsubmittedyet', 'assignment');
3620     $strsubmitted = get_string('submitted', 'assignment');
3621     $strassignment = get_string('modulename', 'assignment');
3622     $strreviewed = get_string('reviewed','assignment');
3625     // NOTE: we do all possible database work here *outside* of the loop to ensure this scales
3626     //
3627     list($sqlassignmentids, $assignmentidparams) = $DB->get_in_or_equal($assignmentids);
3629     // build up and array of unmarked submissions indexed by assignment id/ userid
3630     // for use where the user has grading rights on assignment
3631     $rs = $DB->get_recordset_sql("SELECT id, assignment, userid
3632                             FROM {assignment_submissions}
3633                             WHERE teacher = 0 AND timemarked = 0
3634                             AND assignment $sqlassignmentids", $assignmentidparams);
3636     $unmarkedsubmissions = array();
3637     foreach ($rs as $rd) {
3638         $unmarkedsubmissions[$rd->assignment][$rd->userid] = $rd->id;
3639     }
3640     $rs->close();
3643     // get all user submissions, indexed by assignment id
3644     $mysubmissions = $DB->get_records_sql("SELECT assignment, timemarked, teacher, grade
3645                                       FROM {assignment_submissions}
3646                                       WHERE userid = ? AND
3647                                       assignment $sqlassignmentids", array_merge(array($USER->id), $assignmentidparams));
3649     foreach ($assignments as $assignment) {
3650         $str = '<div class="assignment overview"><div class="name">'.$strassignment. ': '.
3651                '<a '.($assignment->visible ? '':' class="dimmed"').
3652                'title="'.$strassignment.'" href="'.$CFG->wwwroot.
3653                '/mod/assignment/view.php?id='.$assignment->coursemodule.'">'.
3654                $assignment->name.'</a></div>';
3655         if ($assignment->timedue) {
3656             $str .= '<div class="info">'.$strduedate.': '.userdate($assignment->timedue).'</div>';
3657         } else {
3658             $str .= '<div class="info">'.$strduedateno.'</div>';
3659         }
3660         $context = get_context_instance(CONTEXT_MODULE, $assignment->coursemodule);
3661         if (has_capability('mod/assignment:grade', $context)) {
3663             // count how many people can submit
3664             $submissions = 0; // init
3665             if ($students = get_enrolled_users($context, 'mod/assignment:view', 0, 'u.id')) {
3666                 foreach ($students as $student) {
3667                     if (isset($unmarkedsubmissions[$assignment->id][$student->id])) {
3668                         $submissions++;
3669                     }
3670                 }
3671             }
3673             if ($submissions) {
3674                 $link = new moodle_url('/mod/assignment/submissions.php', array('id'=>$assignment->coursemodule));
3675                 $str .= '<div class="details"><a href="'.$link.'">'.get_string('submissionsnotgraded', 'assignment', $submissions).'</a></div>';
3676             }
3677         } else {
3678             $str .= '<div class="details">';
3679             if (isset($mysubmissions[$assignment->id])) {
3681                 $submission = $mysubmissions[$assignment->id];
3683                 if ($submission->teacher == 0 && $submission->timemarked == 0) {
3684                     $str .= $strsubmitted . ', ' . $strnotgradedyet;
3685                 } else if ($submission->grade <= 0) {
3686                     $str .= $strsubmitted . ', ' . $strreviewed;
3687                 } else {
3688                     $str .= $strsubmitted . ', ' . $strgraded;
3689                 }
3690             } else {
3691                 $str .= $strnotsubmittedyet . ' ' . assignment_display_lateness(time(), $assignment->timedue);
3692             }
3693             $str .= '</div>';
3694         }
3695         $str .= '</div>';
3696         if (empty($htmlarray[$assignment->course]['assignment'])) {
3697             $htmlarray[$assignment->course]['assignment'] = $str;
3698         } else {
3699             $htmlarray[$assignment->course]['assignment'] .= $str;
3700         }
3701     }
3704 function assignment_display_lateness($timesubmitted, $timedue) {
3705     if (!$timedue) {
3706         return '';
3707     }
3708     $time = $timedue - $timesubmitted;
3709     if ($time < 0) {
3710         $timetext = get_string('late', 'assignment', format_time($time));
3711         return ' (<span class="late">'.$timetext.'</span>)';
3712     } else {
3713         $timetext = get_string('early', 'assignment', format_time($time));
3714         return ' (<span class="early">'.$timetext.'</span>)';
3715     }
3718 function assignment_get_view_actions() {
3719     return array('view');
3722 function assignment_get_post_actions() {
3723     return array('upload');
3726 function assignment_get_types() {
3727     global $CFG;
3728     $types = array();
3730     $type = new stdClass();
3731     $type->modclass = MOD_CLASS_ACTIVITY;
3732     $type->type = "assignment_group_start";
3733     $type->typestr = '--'.get_string('modulenameplural', 'assignment');
3734     $types[] = $type;
3736     $standardassignments = array('upload','online','uploadsingle','offline');
3737     foreach ($standardassignments as $assignmenttype) {
3738         $type = new stdClass();
3739         $type->modclass = MOD_CLASS_ACTIVITY;
3740         $type->type = "assignment&amp;type=$assignmenttype";
3741         $type->typestr = get_string("type$assignmenttype", 'assignment');
3742         $types[] = $type;
3743     }
3745     /// Drop-in extra assignment types
3746     $assignmenttypes = get_list_of_plugins('mod/assignment/type');
3747     foreach ($assignmenttypes as $assignmenttype) {
3748         if (!empty($CFG->{'assignment_hide_'.$assignmenttype})) {  // Not wanted
3749             continue;
3750         }
3751         if (!in_array($assignmenttype, $standardassignments)) {
3752             $type = new stdClass();
3753             $type->modclass = MOD_CLASS_ACTIVITY;
3754             $type->type = "assignment&amp;type=$assignmenttype";
3755             $type->typestr = get_string("type$assignmenttype", 'assignment_'.$assignmenttype);
3756             $types[] = $type;
3757         }
3758     }
3760     $type = new stdClass();
3761     $type->modclass = MOD_CLASS_ACTIVITY;
3762     $type->type = "assignment_group_end";
3763     $type->typestr = '--';
3764     $types[] = $type;
3766     return $types;
3769 /**
3770  * Removes all grades from gradebook
3771  * @param int $courseid
3772  * @param string optional type
3773  */
3774 function assignment_reset_gradebook($courseid, $type='') {
3775     global $CFG, $DB;
3777     $params = array('courseid'=>$courseid);
3778     if ($type) {
3779         $type = "AND a.assignmenttype= :type";
3780         $params['type'] = $type;
3781     }
3783     $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
3784               FROM {assignment} a, {course_modules} cm, {modules} m
3785              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id AND a.course=:courseid $type";
3787     if ($assignments = $DB->get_records_sql($sql, $params)) {
3788         foreach ($assignments as $assignment) {
3789             assignment_grade_item_update($assignment, 'reset');
3790         }
3791     }
3794 /**
3795  * This function is used by the reset_course_userdata function in moodlelib.
3796  * This function will remove all posts from the specified assignment
3797  * and clean up any related data.
3798  * @param $data the data submitted from the reset course.
3799  * @return array status array
3800  */
3801 function assignment_reset_userdata($data) {
3802     global $CFG;
3804     $status = array();
3805     foreach (get_plugin_list('assignment') as $type=>$dir) {
3806         require_once("$dir/assignment.class.php");
3807         $assignmentclass = "assignment_$type";
3808         $ass = new $assignmentclass();
3809         $status = array_merge($status, $ass->reset_userdata($data));
3810     }
3812     return $status;
3815 /**
3816  * Implementation of the function for printing the form elements that control
3817  * whether the course reset functionality affects the assignment.
3818  * @param $mform form passed by reference
3819  */
3820 function assignment_reset_course_form_definition(&$mform) {
3821     $mform->addElement('header', 'assignmentheader', get_string('modulenameplural', 'assignment'));
3822     $mform->addElement('advcheckbox', 'reset_assignment_submissions', get_string('deleteallsubmissions','assignment'));
3825 /**
3826  * Course reset form defaults.
3827  */
3828 function assignment_reset_course_form_defaults($course) {
3829     return array('reset_assignment_submissions'=>1);
3832 /**
3833  * Returns all other caps used in module
3834  */
3835 function assignment_get_extra_capabilities() {
3836     return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames', 'moodle/grade:managegradingforms');
3839 /**
3840  * @param string $feature FEATURE_xx constant for requested feature
3841  * @return mixed True if module supports feature, null if doesn't know
3842  */
3843 function assignment_supports($feature) {
3844     switch($feature) {
3845         case FEATURE_GROUPS:                  return true;
3846         case FEATURE_GROUPINGS:               return true;
3847         case FEATURE_GROUPMEMBERSONLY:        return true;
3848         case FEATURE_MOD_INTRO:               return true;
3849         case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
3850         case FEATURE_GRADE_HAS_GRADE:         return true;
3851         case FEATURE_GRADE_OUTCOMES:          return true;
3852         case FEATURE_GRADE_HAS_GRADE:         return true;
3853         case FEATURE_BACKUP_MOODLE2:          return true;
3854         case FEATURE_SHOW_DESCRIPTION:        return true;
3855         case FEATURE_ADVANCED_GRADING:        return true;
3857         default: return null;
3858     }
3861 /**
3862  * Adds module specific settings to the settings block
3863  *
3864  * @param settings_navigation $settings The settings navigation object
3865  * @param navigation_node $assignmentnode The node to add module settings to
3866  */
3867 function assignment_extend_settings_navigation(settings_navigation $settings, navigation_node $assignmentnode) {
3868     global $PAGE, $DB, $USER, $CFG;
3870     $assignmentrow = $DB->get_record("assignment", array("id" => $PAGE->cm->instance));
3871     require_once "$CFG->dirroot/mod/assignment/type/$assignmentrow->assignmenttype/assignment.class.php";
3873     $assignmentclass = 'assignment_'.$assignmentrow->assignmenttype;
3874     $assignmentinstance = new $assignmentclass($PAGE->cm->id, $assignmentrow, $PAGE->cm, $PAGE->course);
3876     $allgroups = false;
3878     // Add assignment submission information
3879     if (has_capability('mod/assignment:grade', $PAGE->cm->context)) {
3880         if ($allgroups && has_capability('moodle/site:accessallgroups', $PAGE->cm->context)) {
3881             $group = 0;
3882         } else {
3883             $group = groups_get_activity_group($PAGE->cm);
3884         }
3885         $link = new moodle_url('/mod/assignment/submissions.php', array('id'=>$PAGE->cm->id));
3886         if ($assignmentrow->assignmenttype == 'offline') {
3887             $string = get_string('viewfeedback', 'assignment');
3888         } else if ($count = $assignmentinstance->count_real_submissions($group)) {
3889             $string = get_string('viewsubmissions', 'assignment', $count);
3890         } else {
3891             $string = get_string('noattempts', 'assignment');
3892         }
3893         $assignmentnode->add($string, $link, navigation_node::TYPE_SETTING);
3894     }
3896     if (is_object($assignmentinstance) && method_exists($assignmentinstance, 'extend_settings_navigation')) {
3897         $assignmentinstance->extend_settings_navigation($assignmentnode);
3898     }
3901 /**
3902  * generate zip file from array of given files
3903  * @param array $filesforzipping - array of files to pass into archive_to_pathname
3904  * @return path of temp file - note this returned file does not have a .zip extension - it is a temp file.
3905  */
3906 function assignment_pack_files($filesforzipping) {
3907         global $CFG;
3908         //create path for new zip file.
3909     &n