Assignment MDL-7206 - download all submissions as a zip - finally pushing this into...
[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     /** @var object */
50     var $cm;
51     /** @var object */
52     var $course;
53     /** @var object */
54     var $assignment;
55     /** @var string */
56     var $strassignment;
57     /** @var string */
58     var $strassignments;
59     /** @var string */
60     var $strsubmissions;
61     /** @var string */
62     var $strlastmodified;
63     /** @var string */
64     var $pagetitle;
65     /** @var bool */
66     var $usehtmleditor;
67     /**
68      * @todo document this var
69      */
70     var $defaultformat;
71     /**
72      * @todo document this var
73      */
74     var $context;
75     /** @var string */
76     var $type;
78     /**
79      * Constructor for the base assignment class
80      *
81      * Constructor for the base assignment class.
82      * If cmid is set create the cm, course, assignment objects.
83      * If the assignment is hidden and the user is not a teacher then
84      * this prints a page header and notice.
85      *
86      * @global object
87      * @global object
88      * @param int $cmid the current course module id - not set for new assignments
89      * @param object $assignment usually null, but if we have it we pass it to save db access
90      * @param object $cm usually null, but if we have it we pass it to save db access
91      * @param object $course usually null, but if we have it we pass it to save db access
92      */
93     function assignment_base($cmid='staticonly', $assignment=NULL, $cm=NULL, $course=NULL) {
94         global $COURSE, $DB;
96         if ($cmid == 'staticonly') {
97             //use static functions only!
98             return;
99         }
101         global $CFG;
103         if ($cm) {
104             $this->cm = $cm;
105         } else if (! $this->cm = get_coursemodule_from_id('assignment', $cmid)) {
106             print_error('invalidcoursemodule');
107         }
109         $this->context = get_context_instance(CONTEXT_MODULE, $this->cm->id);
111         if ($course) {
112             $this->course = $course;
113         } else if ($this->cm->course == $COURSE->id) {
114             $this->course = $COURSE;
115         } else if (! $this->course = $DB->get_record('course', array('id'=>$this->cm->course))) {
116             print_error('invalidid', 'assignment');
117         }
119         if ($assignment) {
120             $this->assignment = $assignment;
121         } else if (! $this->assignment = $DB->get_record('assignment', array('id'=>$this->cm->instance))) {
122             print_error('invalidid', 'assignment');
123         }
125         $this->assignment->cmidnumber = $this->cm->id;     // compatibility with modedit assignment obj
126         $this->assignment->courseid   = $this->course->id; // compatibility with modedit assignment obj
128         $this->strassignment = get_string('modulename', 'assignment');
129         $this->strassignments = get_string('modulenameplural', 'assignment');
130         $this->strsubmissions = get_string('submissions', 'assignment');
131         $this->strlastmodified = get_string('lastmodified');
132         $this->pagetitle = strip_tags($this->course->shortname.': '.$this->strassignment.': '.format_string($this->assignment->name,true));
134         // visibility handled by require_login() with $cm parameter
135         // get current group only when really needed
137     /// Set up things for a HTML editor if it's needed
138         if ($this->usehtmleditor = can_use_html_editor()) {
139             $this->defaultformat = FORMAT_HTML;
140         } else {
141             $this->defaultformat = FORMAT_MOODLE;
142         }
143     }
145     /**
146      * Display the assignment, used by view.php
147      *
148      * This in turn calls the methods producing individual parts of the page
149      */
150     function view() {
152         $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
153         require_capability('mod/assignment:view', $context);
155         add_to_log($this->course->id, "assignment", "view", "view.php?id={$this->cm->id}",
156                    $this->assignment->id, $this->cm->id);
158         $this->view_header();
160         $this->view_intro();
162         $this->view_dates();
164         $this->view_feedback();
166         $this->view_footer();
167     }
169     /**
170      * Display the header and top of a page
171      *
172      * (this doesn't change much for assignment types)
173      * This is used by the view() method to print the header of view.php but
174      * it can be used on other pages in which case the string to denote the
175      * page in the navigation trail should be passed as an argument
176      *
177      * @global object
178      * @param string $subpage Description of subpage to be used in navigation trail
179      */
180     function view_header($subpage='') {
181         global $CFG, $PAGE, $OUTPUT;
183         if ($subpage) {
184             $PAGE->navbar->add($subpage);
185         }
187         $PAGE->set_title($this->pagetitle);
188         $PAGE->set_heading($this->course->fullname);
190         echo $OUTPUT->header();
192         groups_print_activity_menu($this->cm, $CFG->wwwroot . '/mod/assignment/view.php?id=' . $this->cm->id);
194         echo '<div class="reportlink">'.$this->submittedlink().'</div>';
195         echo '<div class="clearer"></div>';
196     }
199     /**
200      * Display the assignment intro
201      *
202      * This will most likely be extended by assignment type plug-ins
203      * The default implementation prints the assignment description in a box
204      */
205     function view_intro() {
206         global $OUTPUT;
207         echo $OUTPUT->box_start('generalbox boxaligncenter', 'intro');
208         echo format_module_intro('assignment', $this->assignment, $this->cm->id);
209         echo $OUTPUT->box_end();
210     }
212     /**
213      * Display the assignment dates
214      *
215      * Prints the assignment start and end dates in a box.
216      * This will be suitable for most assignment types
217      */
218     function view_dates() {
219         global $OUTPUT;
220         if (!$this->assignment->timeavailable && !$this->assignment->timedue) {
221             return;
222         }
224         echo $OUTPUT->box_start('generalbox boxaligncenter', 'dates');
225         echo '<table>';
226         if ($this->assignment->timeavailable) {
227             echo '<tr><td class="c0">'.get_string('availabledate','assignment').':</td>';
228             echo '    <td class="c1">'.userdate($this->assignment->timeavailable).'</td></tr>';
229         }
230         if ($this->assignment->timedue) {
231             echo '<tr><td class="c0">'.get_string('duedate','assignment').':</td>';
232             echo '    <td class="c1">'.userdate($this->assignment->timedue).'</td></tr>';
233         }
234         echo '</table>';
235         echo $OUTPUT->box_end();
236     }
239     /**
240      * Display the bottom and footer of a page
241      *
242      * This default method just prints the footer.
243      * This will be suitable for most assignment types
244      */
245     function view_footer() {
246         global $OUTPUT;
247         echo $OUTPUT->footer();
248     }
250     /**
251      * Display the feedback to the student
252      *
253      * This default method prints the teacher picture and name, date when marked,
254      * grade and teacher submissioncomment.
255      *
256      * @global object
257      * @global object
258      * @global object
259      * @param object $submission The submission object or NULL in which case it will be loaded
260      */
261     function view_feedback($submission=NULL) {
262         global $USER, $CFG, $DB, $OUTPUT;
263         require_once($CFG->libdir.'/gradelib.php');
265         if (!has_capability('mod/assignment:submit', $this->context, $USER->id, false)) {
266             // can not submit assignments -> no feedback
267             return;
268         }
270         if (!$submission) { /// Get submission for this assignment
271             $submission = $this->get_submission($USER->id);
272         }
274         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $USER->id);
275         $item = $grading_info->items[0];
276         $grade = $item->grades[$USER->id];
278         if ($grade->hidden or $grade->grade === false) { // hidden or error
279             return;
280         }
282         if ($grade->grade === null and empty($grade->str_feedback)) {   /// Nothing to show yet
283             return;
284         }
286         $graded_date = $grade->dategraded;
287         $graded_by   = $grade->usermodified;
289     /// We need the teacher info
290         if (!$teacher = $DB->get_record('user', array('id'=>$graded_by))) {
291             print_error('cannotfindteacher');
292         }
294     /// Print the feedback
295         echo $OUTPUT->heading(get_string('feedbackfromteacher', 'assignment', fullname($teacher)));
297         echo '<table cellspacing="0" class="feedback">';
299         echo '<tr>';
300         echo '<td class="left picture">';
301         if ($teacher) {
302             echo $OUTPUT->user_picture($teacher);
303         }
304         echo '</td>';
305         echo '<td class="topic">';
306         echo '<div class="from">';
307         if ($teacher) {
308             echo '<div class="fullname">'.fullname($teacher).'</div>';
309         }
310         echo '<div class="time">'.userdate($graded_date).'</div>';
311         echo '</div>';
312         echo '</td>';
313         echo '</tr>';
315         echo '<tr>';
316         echo '<td class="left side">&nbsp;</td>';
317         echo '<td class="content">';
318         echo '<div class="grade">';
319         echo get_string("grade").': '.$grade->str_long_grade;
320         echo '</div>';
321         echo '<div class="clearer"></div>';
323         echo '<div class="comment">';
324         echo $grade->str_feedback;
325         echo '</div>';
326         echo '</tr>';
328         echo '</table>';
329     }
331     /**
332      * Returns a link with info about the state of the assignment submissions
333      *
334      * This is used by view_header to put this link at the top right of the page.
335      * For teachers it gives the number of submitted assignments with a link
336      * For students it gives the time of their submission.
337      * This will be suitable for most assignment types.
338      *
339      * @global object
340      * @global object
341      * @param bool $allgroup print all groups info if user can access all groups, suitable for index.php
342      * @return string
343      */
344     function submittedlink($allgroups=false) {
345         global $USER;
346         global $CFG;
348         $submitted = '';
349         $urlbase = "{$CFG->wwwroot}/mod/assignment/";
351         $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
352         if (has_capability('mod/assignment:grade', $context)) {
353             if ($allgroups and has_capability('moodle/site:accessallgroups', $context)) {
354                 $group = 0;
355             } else {
356                 $group = groups_get_activity_group($this->cm);
357             }
358             if ($count = $this->count_real_submissions($group)) {
359                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
360                              get_string('viewsubmissions', 'assignment', $count).'</a>';
361             } else {
362                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
363                              get_string('noattempts', 'assignment').'</a>';
364             }
365         } else {
366             if (isloggedin()) {
367                 if ($submission = $this->get_submission($USER->id)) {
368                     if ($submission->timemodified) {
369                         if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
370                             $submitted = '<span class="early">'.userdate($submission->timemodified).'</span>';
371                         } else {
372                             $submitted = '<span class="late">'.userdate($submission->timemodified).'</span>';
373                         }
374                     }
375                 }
376             }
377         }
379         return $submitted;
380     }
383     /**
384      * @todo Document this function
385      */
386     function setup_elements(&$mform) {
388     }
390     /**
391      * Create a new assignment activity
392      *
393      * Given an object containing all the necessary data,
394      * (defined by the form in mod_form.php) this function
395      * will create a new instance and return the id number
396      * of the new instance.
397      * The due data is added to the calendar
398      * This is common to all assignment types.
399      *
400      * @global object
401      * @global object
402      * @param object $assignment The data from the form on mod_form.php
403      * @return int The id of the assignment
404      */
405     function add_instance($assignment) {
406         global $COURSE, $DB;
408         $assignment->timemodified = time();
409         $assignment->courseid = $assignment->course;
411         if ($returnid = $DB->insert_record("assignment", $assignment)) {
412             $assignment->id = $returnid;
414             if ($assignment->timedue) {
415                 $event = new object();
416                 $event->name        = $assignment->name;
417                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
418                 $event->courseid    = $assignment->course;
419                 $event->groupid     = 0;
420                 $event->userid      = 0;
421                 $event->modulename  = 'assignment';
422                 $event->instance    = $returnid;
423                 $event->eventtype   = 'due';
424                 $event->timestart   = $assignment->timedue;
425                 $event->timeduration = 0;
427                 calendar_event::create($event);
428             }
430             assignment_grade_item_update($assignment);
432         }
435         return $returnid;
436     }
438     /**
439      * Deletes an assignment activity
440      *
441      * Deletes all database records, files and calendar events for this assignment.
442      *
443      * @global object
444      * @global object
445      * @param object $assignment The assignment to be deleted
446      * @return boolean False indicates error
447      */
448     function delete_instance($assignment) {
449         global $CFG, $DB;
451         $assignment->courseid = $assignment->course;
453         $result = true;
455         // now get rid of all files
456         $fs = get_file_storage();
457         if ($cm = get_coursemodule_from_instance('assignment', $assignment->id)) {
458             $context = get_context_instance(CONTEXT_MODULE, $cm->id);
459             $fs->delete_area_files($context->id);
460         }
462         if (! $DB->delete_records('assignment_submissions', array('assignment'=>$assignment->id))) {
463             $result = false;
464         }
466         if (! $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
467             $result = false;
468         }
470         if (! $DB->delete_records('assignment', array('id'=>$assignment->id))) {
471             $result = false;
472         }
474         assignment_grade_item_delete($assignment);
476         return $result;
477     }
479     /**
480      * Updates a new assignment activity
481      *
482      * Given an object containing all the necessary data,
483      * (defined by the form in mod_form.php) this function
484      * will update the assignment instance and return the id number
485      * The due date is updated in the calendar
486      * This is common to all assignment types.
487      *
488      * @global object
489      * @global object
490      * @param object $assignment The data from the form on mod_form.php
491      * @return int The assignment id
492      */
493     function update_instance($assignment) {
494         global $COURSE, $DB;
496         $assignment->timemodified = time();
498         $assignment->id = $assignment->instance;
499         $assignment->courseid = $assignment->course;
501         $DB->update_record('assignment', $assignment);
503         if ($assignment->timedue) {
504             $event = new object();
506             if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
508                 $event->name        = $assignment->name;
509                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
510                 $event->timestart   = $assignment->timedue;
512                 $calendarevent = calendar_event::load($event->id);
513                 $calendarevent->update($event);
514             } else {
515                 $event = new object();
516                 $event->name        = $assignment->name;
517                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
518                 $event->courseid    = $assignment->course;
519                 $event->groupid     = 0;
520                 $event->userid      = 0;
521                 $event->modulename  = 'assignment';
522                 $event->instance    = $assignment->id;
523                 $event->eventtype   = 'due';
524                 $event->timestart   = $assignment->timedue;
525                 $event->timeduration = 0;
527                 calendar_event::create($event);
528             }
529         } else {
530             $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id));
531         }
533         // get existing grade item
534         assignment_grade_item_update($assignment);
536         return true;
537     }
539     /**
540      * Update grade item for this submission.
541      */
542     function update_grade($submission) {
543         assignment_update_grades($this->assignment, $submission->userid);
544     }
546     /**
547      * Top-level function for handling of submissions called by submissions.php
548      *
549      * This is for handling the teacher interaction with the grading interface
550      * This should be suitable for most assignment types.
551      *
552      * @global object
553      * @param string $mode Specifies the kind of teacher interaction taking place
554      */
555     function submissions($mode) {
556         ///The main switch is changed to facilitate
557         ///1) Batch fast grading
558         ///2) Skip to the next one on the popup
559         ///3) Save and Skip to the next one on the popup
561         //make user global so we can use the id
562         global $USER, $OUTPUT, $DB, $PAGE;
564         $mailinfo = optional_param('mailinfo', null, PARAM_BOOL);
565         if (is_null($mailinfo)) {
566             $mailinfo = get_user_preferences('assignment_mailinfo', 0);
567         } else {
568             set_user_preference('assignment_mailinfo', $mailinfo);
569         }
571         switch ($mode) {
572             case 'grade':                         // We are in a popup window grading
573                 if ($submission = $this->process_feedback()) {
574                     //IE needs proper header with encoding
575                     $PAGE->set_title(get_string('feedback', 'assignment').':'.format_string($this->assignment->name));
576                     echo $OUTPUT->header();
577                     echo $OUTPUT->heading(get_string('changessaved'));
578                     print $this->update_main_listing($submission);
579                 }
580                 close_window();
581                 break;
583             case 'single':                        // We are in a popup window displaying submission
584                 $this->display_submission();
585                 break;
587             case 'all':                          // Main window, display everything
588                 $this->display_submissions();
589                 break;
591             case 'fastgrade':
592                 ///do the fast grading stuff  - this process should work for all 3 subclasses
594                 $grading    = false;
595                 $commenting = false;
596                 $col        = false;
597                 if (isset($_POST['submissioncomment'])) {
598                     $col = 'submissioncomment';
599                     $commenting = true;
600                 }
601                 if (isset($_POST['menu'])) {
602                     $col = 'menu';
603                     $grading = true;
604                 }
605                 if (!$col) {
606                     //both submissioncomment and grade columns collapsed..
607                     $this->display_submissions();
608                     break;
609                 }
611                 foreach ($_POST[$col] as $id => $unusedvalue){
613                     $id = (int)$id; //clean parameter name
615                     $this->process_outcomes($id);
617                     if (!$submission = $this->get_submission($id)) {
618                         $submission = $this->prepare_new_submission($id);
619                         $newsubmission = true;
620                     } else {
621                         $newsubmission = false;
622                     }
623                     unset($submission->data1);  // Don't need to update this.
624                     unset($submission->data2);  // Don't need to update this.
626                     //for fast grade, we need to check if any changes take place
627                     $updatedb = false;
629                     if ($grading) {
630                         $grade = $_POST['menu'][$id];
631                         $updatedb = $updatedb || ($submission->grade != $grade);
632                         $submission->grade = $grade;
633                     } else {
634                         if (!$newsubmission) {
635                             unset($submission->grade);  // Don't need to update this.
636                         }
637                     }
638                     if ($commenting) {
639                         $commentvalue = trim($_POST['submissioncomment'][$id]);
640                         $updatedb = $updatedb || ($submission->submissioncomment != $commentvalue);
641                         $submission->submissioncomment = $commentvalue;
642                     } else {
643                         unset($submission->submissioncomment);  // Don't need to update this.
644                     }
646                     $submission->teacher    = $USER->id;
647                     if ($updatedb) {
648                         $submission->mailed = (int)(!$mailinfo);
649                     }
651                     $submission->timemarked = time();
653                     //if it is not an update, we don't change the last modified time etc.
654                     //this will also not write into database if no submissioncomment and grade is entered.
656                     if ($updatedb){
657                         if ($newsubmission) {
658                             if (!isset($submission->submissioncomment)) {
659                                 $submission->submissioncomment = '';
660                             }
661                             $sid = $DB->insert_record('assignment_submissions', $submission);
662                             $submission->id = $sid;
663                         } else {
664                             $DB->update_record('assignment_submissions', $submission);
665                         }
667                         // triger grade event
668                         $this->update_grade($submission);
670                         //add to log only if updating
671                         add_to_log($this->course->id, 'assignment', 'update grades',
672                                    'submissions.php?id='.$this->assignment->id.'&user='.$submission->userid,
673                                    $submission->userid, $this->cm->id);
674                     }
676                 }
678                 $message = $OUTPUT->notification(get_string('changessaved'), 'notifysuccess');
680                 $this->display_submissions($message);
681                 break;
684             case 'next':
685                 /// We are currently in pop up, but we want to skip to next one without saving.
686                 ///    This turns out to be similar to a single case
687                 /// The URL used is for the next submission.
689                 $this->display_submission();
690                 break;
692             case 'saveandnext':
693                 ///We are in pop up. save the current one and go to the next one.
694                 //first we save the current changes
695                 if ($submission = $this->process_feedback()) {
696                     //print_heading(get_string('changessaved'));
697                     $extra_javascript = $this->update_main_listing($submission);
698                 }
700                 //then we display the next submission
701                 $this->display_submission($extra_javascript);
702                 break;
704             default:
705                 echo "something seriously is wrong!!";
706                 break;
707         }
708     }
710     /**
711      * Helper method updating the listing on the main script from popup using javascript
712      *
713      * @global object
714      * @global object
715      * @param $submission object The submission whose data is to be updated on the main page
716      */
717     function update_main_listing($submission) {
718         global $SESSION, $CFG, $OUTPUT;
720         $output = '';
722         $perpage = get_user_preferences('assignment_perpage', 10);
724         $quickgrade = get_user_preferences('assignment_quickgrade', 0);
726         /// Run some Javascript to try and update the parent page
727         $output .= '<script type="text/javascript">'."\n<!--\n";
728         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['submissioncomment'])) {
729             if ($quickgrade){
730                 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid.'").value="'
731                 .trim($submission->submissioncomment).'";'."\n";
732              } else {
733                 $output.= 'opener.document.getElementById("com'.$submission->userid.
734                 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment)), 15)."\";\n";
735             }
736         }
738         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['grade'])) {
739             //echo optional_param('menuindex');
740             if ($quickgrade){
741                 $output.= 'opener.document.getElementById("menumenu'.$submission->userid.
742                 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT).'";'."\n";
743             } else {
744                 $output.= 'opener.document.getElementById("g'.$submission->userid.'").innerHTML="'.
745                 $this->display_grade($submission->grade)."\";\n";
746             }
747         }
748         //need to add student's assignments in there too.
749         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemodified']) &&
750             $submission->timemodified) {
751             $output.= 'opener.document.getElementById("ts'.$submission->userid.
752                  '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid)).userdate($submission->timemodified)."\";\n";
753         }
755         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemarked']) &&
756             $submission->timemarked) {
757             $output.= 'opener.document.getElementById("tt'.$submission->userid.
758                  '").innerHTML="'.userdate($submission->timemarked)."\";\n";
759         }
761         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['status'])) {
762             $output.= 'opener.document.getElementById("up'.$submission->userid.'").className="s1";';
763             $buttontext = get_string('update');
764             $url = new moodle_url('/mod/assignment/submissions.php', array(
765                     'id' => $this->cm->id,
766                     'userid' => $submission->userid,
767                     'mode' => 'single',
768                     'offset' => (optional_param('offset', '', PARAM_INT)-1)));
769             $button = $OUTPUT->action_link($url, $buttontext, new popup_action('click', $url, 'grade'.$submission->userid, array('height' => 450, 'width' => 700)), array('ttile'=>$buttontext));
771             $output .= 'opener.document.getElementById("up'.$submission->userid.'").innerHTML="'.addslashes_js($button).'";';
772         }
774         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $submission->userid);
776         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['finalgrade'])) {
777             $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid.
778             '").innerHTML="'.$grading_info->items[0]->grades[$submission->userid]->str_grade.'";'."\n";
779         }
781         if (!empty($CFG->enableoutcomes) and empty($SESSION->flextable['mod-assignment-submissions']->collapse['outcome'])) {
783             if (!empty($grading_info->outcomes)) {
784                 foreach($grading_info->outcomes as $n=>$outcome) {
785                     if ($outcome->grades[$submission->userid]->locked) {
786                         continue;
787                     }
789                     if ($quickgrade){
790                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.
791                         '").selectedIndex="'.$outcome->grades[$submission->userid]->grade.'";'."\n";
793                     } else {
794                         $options = make_grades_menu(-$outcome->scaleid);
795                         $options[0] = get_string('nooutcome', 'grades');
796                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.'").innerHTML="'.$options[$outcome->grades[$submission->userid]->grade]."\";\n";
797                     }
799                 }
800             }
801         }
803         $output .= "\n-->\n</script>";
804         return $output;
805     }
807     /**
808      *  Return a grade in user-friendly form, whether it's a scale or not
809      *
810      * @global object
811      * @param mixed $grade
812      * @return string User-friendly representation of grade
813      */
814     function display_grade($grade) {
815         global $DB;
817         static $scalegrades = array();   // Cache scales for each assignment - they might have different scales!!
819         if ($this->assignment->grade >= 0) {    // Normal number
820             if ($grade == -1) {
821                 return '-';
822             } else {
823                 return $grade.' / '.$this->assignment->grade;
824             }
826         } else {                                // Scale
827             if (empty($scalegrades[$this->assignment->id])) {
828                 if ($scale = $DB->get_record('scale', array('id'=>-($this->assignment->grade)))) {
829                     $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
830                 } else {
831                     return '-';
832                 }
833             }
834             if (isset($scalegrades[$this->assignment->id][$grade])) {
835                 return $scalegrades[$this->assignment->id][$grade];
836             }
837             return '-';
838         }
839     }
841     /**
842      *  Display a single submission, ready for grading on a popup window
843      *
844      * This default method prints the teacher info and submissioncomment box at the top and
845      * the student info and submission at the bottom.
846      * This method also fetches the necessary data in order to be able to
847      * provide a "Next submission" button.
848      * Calls preprocess_submission() to give assignment type plug-ins a chance
849      * to process submissions before they are graded
850      * This method gets its arguments from the page parameters userid and offset
851      *
852      * @global object
853      * @global object
854      * @param string $extra_javascript
855      */
856     function display_submission($extra_javascript = '') {
857         global $CFG, $DB, $PAGE, $OUTPUT;
858         require_once($CFG->libdir.'/gradelib.php');
859         require_once($CFG->libdir.'/tablelib.php');
861         $userid = required_param('userid', PARAM_INT);
862         $offset = required_param('offset', PARAM_INT);//offset for where to start looking for student.
864         if (!$user = $DB->get_record('user', array('id'=>$userid))) {
865             print_error('nousers');
866         }
868         if (!$submission = $this->get_submission($user->id)) {
869             $submission = $this->prepare_new_submission($userid);
870         }
871         if ($submission->timemodified > $submission->timemarked) {
872             $subtype = 'assignmentnew';
873         } else {
874             $subtype = 'assignmentold';
875         }
877         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
878         $disabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
880     /// construct SQL, using current offset to find the data of the next student
881         $course     = $this->course;
882         $assignment = $this->assignment;
883         $cm         = $this->cm;
884         $context    = get_context_instance(CONTEXT_MODULE, $cm->id);
886         /// Get all ppl that can submit assignments
888         $currentgroup = groups_get_activity_group($cm);
889         if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $currentgroup, '', false)) {
890             $users = array_keys($users);
891         }
893         // if groupmembersonly used, remove users who are not in any group
894         if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
895             if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
896                 $users = array_intersect($users, array_keys($groupingusers));
897             }
898         }
900         $nextid = 0;
902         if ($users) {
903             $select = 'SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt,
904                               s.id AS submissionid, s.grade, s.submissioncomment,
905                               s.timemodified, s.timemarked,
906                               COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ';
907             $sql = 'FROM {user} u '.
908                    'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
909                                                                       AND s.assignment = '.$this->assignment->id.' '.
910                    'WHERE u.id IN ('.implode(',', $users).') ';
912             if ($sort = flexible_table::get_sort_for_table('mod-assignment-submissions')) {
913                 $sort = 'ORDER BY '.$sort.' ';
914             }
916             $auser = $DB->get_records_sql($select.$sql.$sort, null, $offset+1, 1);
917             if (is_array($auser) && count($auser)>0) {
918                 $nextuser = array_shift($auser);
919             /// Calculate user status
920                 $nextuser->status = ($nextuser->timemarked > 0) && ($nextuser->timemarked >= $nextuser->timemodified);
921                 $nextid = $nextuser->id;
922             }
923         }
925         $PAGE->set_title(get_string('feedback', 'assignment').':'.fullname($user, true).':'.format_string($this->assignment->name));
926         echo $OUTPUT->header();
928         /// Print any extra javascript needed for saveandnext
929         echo $extra_javascript;
930         echo html_writer::script(js_writer::function_call('initNext', array($nextid, $userid)));
932         echo '<table cellspacing="0" class="feedback '.$subtype.'" >';
934         ///Start of teacher info row
936         echo '<tr>';
937         echo '<td class="picture teacher">';
938         if ($submission->teacher) {
939             $teacher = $DB->get_record('user', array('id'=>$submission->teacher));
940         } else {
941             global $USER;
942             $teacher = $USER;
943         }
944         echo $OUTPUT->user_picture($teacher);
945         echo '</td>';
946         echo '<td class="content">';
947         echo '<form id="submitform" action="submissions.php" method="post">';
948         echo '<div>'; // xhtml compatibility - invisiblefieldset was breaking layout here
949         echo '<input type="hidden" name="offset" value="'.($offset+1).'" />';
950         echo '<input type="hidden" name="userid" value="'.$userid.'" />';
951         echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
952         echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
953         echo '<input type="hidden" name="mode" value="grade" />';
954         echo '<input type="hidden" name="menuindex" value="0" />';//selected menu index
956         //new hidden field, initialized to -1.
957         echo '<input type="hidden" name="saveuserid" value="-1" />';
959         if ($submission->timemarked) {
960             echo '<div class="from">';
961             echo '<div class="fullname">'.fullname($teacher, true).'</div>';
962             echo '<div class="time">'.userdate($submission->timemarked).'</div>';
963             echo '</div>';
964         }
965         echo '<div class="grade"><label for="menugrade">'.get_string('grade').'</label> ';
966         $attributes = array();
967         $attributes['disabled'] = $disabled ? 'disabled' : null;
968         echo html_writer::select(make_grades_menu($this->assignment->grade),'grade', $submission->grade, array(-1=>get_string('nograde')), $attributes);
969         echo '</div>';
971         echo '<div class="clearer"></div>';
972         echo '<div class="finalgrade">'.get_string('finalgrade', 'grades').': '.$grading_info->items[0]->grades[$userid]->str_grade.'</div>';
973         echo '<div class="clearer"></div>';
975         if (!empty($CFG->enableoutcomes)) {
976             foreach($grading_info->outcomes as $n=>$outcome) {
977                 echo '<div class="outcome"><label for="menuoutcome_'.$n.'">'.$outcome->name.'</label> ';
978                 $options = make_grades_menu(-$outcome->scaleid);
979                 if ($outcome->grades[$submission->userid]->locked) {
980                     $options[0] = get_string('nooutcome', 'grades');
981                     echo $options[$outcome->grades[$submission->userid]->grade];
982                 } else {
983                     echo html_writer::select($options, 'outcome_'.$n.'['.$userid.']', $outcome->grades[$submission->userid]->grade, get_string('nooutcome', 'grades'), array('id' => 'menuoutcome_'.$n));
984                 }
985                 echo '</div>';
986                 echo '<div class="clearer"></div>';
987             }
988         }
991         $this->preprocess_submission($submission);
993         if ($disabled) {
994             echo '<div class="disabledfeedback">'.$grading_info->items[0]->grades[$userid]->str_feedback.'</div>';
996         } else {
997             print_textarea($this->usehtmleditor, 14, 58, 0, 0, 'submissioncomment', $submission->submissioncomment, $this->course->id);
998             if ($this->usehtmleditor) {
999                 echo '<input type="hidden" name="format" value="'.FORMAT_HTML.'" />';
1000             } else {
1001                 echo '<div class="format">';
1002                 echo html_writer::select(format_text_menu(), "format", $submission->format, false);
1003                 echo $OUTPUT->old_help_icon("textformat", get_string("helpformatting"));
1004                 echo '</div>';
1005             }
1006         }
1008         $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? 'checked="checked"' : '';
1010         ///Print Buttons in Single View
1011         echo '<input type="hidden" name="mailinfo" value="0" />';
1012         echo '<input type="checkbox" id="mailinfo" name="mailinfo" value="1" '.$lastmailinfo.' /><label for="mailinfo">'.get_string('enableemailnotification','assignment').'</label>';
1013         echo '<div class="buttons">';
1014         echo '<input type="submit" name="submit" value="'.get_string('savechanges').'" onclick = "document.getElementById(\'submitform\').menuindex.value = document.getElementById(\'submitform\').grade.selectedIndex" />';
1015         echo '<input type="submit" name="cancel" value="'.get_string('cancel').'" />';
1016         //if there are more to be graded.
1017         if ($nextid) {
1018             echo '<input type="submit" name="saveandnext" value="'.get_string('saveandnext').'" onclick="saveNext()" />';
1019             echo '<input type="submit" name="next" value="'.get_string('next').'" onclick="setNext();" />';
1020         }
1021         echo '</div>';
1022         echo '</div></form>';
1024         $customfeedback = $this->custom_feedbackform($submission, true);
1025         if (!empty($customfeedback)) {
1026             echo $customfeedback;
1027         }
1029         echo '</td></tr>';
1031         ///End of teacher info row, Start of student info row
1032         echo '<tr>';
1033         echo '<td class="picture user">';
1034         echo $OUTPUT->user_picture($user);
1035         echo '</td>';
1036         echo '<td class="topic">';
1037         echo '<div class="from">';
1038         echo '<div class="fullname">'.fullname($user, true).'</div>';
1039         if ($submission->timemodified) {
1040             echo '<div class="time">'.userdate($submission->timemodified).
1041                                      $this->display_lateness($submission->timemodified).'</div>';
1042         }
1043         echo '</div>';
1044         $this->print_user_files($user->id);
1045         echo '</td>';
1046         echo '</tr>';
1048         ///End of student info row
1050         echo '</table>';
1052         echo $OUTPUT->footer();
1053     }
1055     /**
1056      *  Preprocess submission before grading
1057      *
1058      * Called by display_submission()
1059      * The default type does nothing here.
1060      *
1061      * @param object $submission The submission object
1062      */
1063     function preprocess_submission(&$submission) {
1064     }
1066     /**
1067      *  Display all the submissions ready for grading
1068      *
1069      * @global object
1070      * @global object
1071      * @global object
1072      * @global object
1073      * @param string $message
1074      * @return bool|void
1075      */
1076     function display_submissions($message='') {
1077         global $CFG, $DB, $USER, $DB, $OUTPUT, $PAGE;
1078         require_once($CFG->libdir.'/gradelib.php');
1080         /* first we check to see if the form has just been submitted
1081          * to request user_preference updates
1082          */
1084         if (isset($_POST['updatepref'])){
1085             $perpage = optional_param('perpage', 10, PARAM_INT);
1086             $perpage = ($perpage <= 0) ? 10 : $perpage ;
1087             set_user_preference('assignment_perpage', $perpage);
1088             set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
1089         }
1091         /* next we get perpage and quickgrade (allow quick grade) params
1092          * from database
1093          */
1094         $perpage    = get_user_preferences('assignment_perpage', 10);
1096         $quickgrade = get_user_preferences('assignment_quickgrade', 0);
1098         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);
1100         if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
1101             $uses_outcomes = true;
1102         } else {
1103             $uses_outcomes = false;
1104         }
1106         $page    = optional_param('page', 0, PARAM_INT);
1107         $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
1109     /// Some shortcuts to make the code read better
1111         $course     = $this->course;
1112         $assignment = $this->assignment;
1113         $cm         = $this->cm;
1115         $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
1116         add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->cm->id, $this->assignment->id, $this->cm->id);
1117         $PAGE->navbar->add($this->strsubmissions);
1118         $PAGE->set_title(format_string($this->assignment->name,true));
1119         echo $OUTPUT->header();
1121         $course_context = get_context_instance(CONTEXT_COURSE, $course->id);
1122         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
1123             echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">'
1124                 . get_string('seeallcoursegrades', 'grades') . '</a></div>';
1125         }
1127         if (!empty($message)) {
1128             echo $message;   // display messages here if any
1129         }
1131         $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1133     /// Check to see if groups are being used in this assignment
1135         /// find out current groups mode
1136         $groupmode = groups_get_activity_groupmode($cm);
1137         $currentgroup = groups_get_activity_group($cm, true);
1138         groups_print_activity_menu($cm, $CFG->wwwroot . '/mod/assignment/submissions.php?id=' . $this->cm->id);
1140         /// Get all ppl that are allowed to submit assignments
1141         if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $currentgroup, '', false)) {
1142             $users = array_keys($users);
1143         }
1145         // if groupmembersonly used, remove users who are not in any group
1146         if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
1147             if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1148                 $users = array_intersect($users, array_keys($groupingusers));
1149             }
1150         }
1152         $tablecolumns = array('picture', 'fullname', 'grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade');
1153         if ($uses_outcomes) {
1154             $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
1155         }
1157         $tableheaders = array('',
1158                               get_string('fullname'),
1159                               get_string('grade'),
1160                               get_string('comment', 'assignment'),
1161                               get_string('lastmodified').' ('.get_string('submission', 'assignment').')',
1162                               get_string('lastmodified').' ('.get_string('grade').')',
1163                               get_string('status'),
1164                               get_string('finalgrade', 'grades'));
1165         if ($uses_outcomes) {
1166             $tableheaders[] = get_string('outcome', 'grades');
1167         }
1169         require_once($CFG->libdir.'/tablelib.php');
1170         $table = new flexible_table('mod-assignment-submissions');
1172         $table->define_columns($tablecolumns);
1173         $table->define_headers($tableheaders);
1174         $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;currentgroup='.$currentgroup);
1176         $table->sortable(true, 'lastname');//sorted by lastname by default
1177         $table->collapsible(true);
1178         $table->initialbars(true);
1180         $table->column_suppress('picture');
1181         $table->column_suppress('fullname');
1183         $table->column_class('picture', 'picture');
1184         $table->column_class('fullname', 'fullname');
1185         $table->column_class('grade', 'grade');
1186         $table->column_class('submissioncomment', 'comment');
1187         $table->column_class('timemodified', 'timemodified');
1188         $table->column_class('timemarked', 'timemarked');
1189         $table->column_class('status', 'status');
1190         $table->column_class('finalgrade', 'finalgrade');
1191         if ($uses_outcomes) {
1192             $table->column_class('outcome', 'outcome');
1193         }
1195         $table->set_attribute('cellspacing', '0');
1196         $table->set_attribute('id', 'attempts');
1197         $table->set_attribute('class', 'submissions');
1198         $table->set_attribute('width', '100%');
1199         //$table->set_attribute('align', 'center');
1201         $table->no_sorting('finalgrade');
1202         $table->no_sorting('outcome');
1204         // Start working -- this is necessary as soon as the niceties are over
1205         $table->setup();
1207         if (empty($users)) {
1208             echo $OUTPUT->heading(get_string('nosubmitusers','assignment'));
1209             return true;
1210         }
1211         if ($this->assignment->assignmenttype=='upload' || $this->assignment->assignmenttype=='online' || $this->assignment->assignmenttype=='uploadsingle') {
1212             echo '<div style="text-align:right"><a href="submissions.php?id='.$this->cm->id.'&amp;download=zip">'.get_string('downloadall', 'assignment').'</div>';
1213         }
1214     /// Construct the SQL
1216         if ($where = $table->get_sql_where()) {
1217             $where .= ' AND ';
1218         }
1220         if ($sort = $table->get_sql_sort()) {
1221             $sort = ' ORDER BY '.$sort;
1222         }
1224         $select = 'SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt,
1225                           s.id AS submissionid, s.grade, s.submissioncomment,
1226                           s.timemodified, s.timemarked,
1227                           COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ';
1228         $sql = 'FROM {user} u '.
1229                'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1230                                                                   AND s.assignment = '.$this->assignment->id.' '.
1231                'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1233         $table->pagesize($perpage, count($users));
1235         ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1236         $offset = $page * $perpage;
1238         $strupdate = get_string('update');
1239         $strgrade  = get_string('grade');
1240         $grademenu = make_grades_menu($this->assignment->grade);
1242         if (($ausers = $DB->get_records_sql($select.$sql.$sort, null, $table->get_page_start(), $table->get_page_size())) !== false) {
1243             $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
1244             foreach ($ausers as $auser) {
1245                 $final_grade = $grading_info->items[0]->grades[$auser->id];
1246                 $grademax = $grading_info->items[0]->grademax;
1247                 $final_grade->formatted_grade = round($final_grade->grade,2) .' / ' . round($grademax,2);
1248                 $locked_overridden = 'locked';
1249                 if ($final_grade->overridden) {
1250                     $locked_overridden = 'overridden';
1251                 }
1253             /// Calculate user status
1254                 $auser->status = ($auser->timemarked > 0) && ($auser->timemarked >= $auser->timemodified);
1255                 $picture = $OUTPUT->user_picture($auser);
1257                 if (empty($auser->submissionid)) {
1258                     $auser->grade = -1; //no submission yet
1259                 }
1261                 if (!empty($auser->submissionid)) {
1262                 ///Prints student answer and student modified date
1263                 ///attach file or print link to student answer, depending on the type of the assignment.
1264                 ///Refer to print_student_answer in inherited classes.
1265                     if ($auser->timemodified > 0) {
1266                         $studentmodified = '<div id="ts'.$auser->id.'">'.$this->print_student_answer($auser->id)
1267                                          . userdate($auser->timemodified).'</div>';
1268                     } else {
1269                         $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1270                     }
1271                 ///Print grade, dropdown or text
1272                     if ($auser->timemarked > 0) {
1273                         $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
1275                         if ($final_grade->locked or $final_grade->overridden) {
1276                             $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1277                         } else if ($quickgrade) {
1278                             $attributes = array();
1279                             $attributes['tabindex'] = $tabindex++;
1280                             $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1281                             $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
1282                         } else {
1283                             $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1284                         }
1286                     } else {
1287                         $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1288                         if ($final_grade->locked or $final_grade->overridden) {
1289                             $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1290                         } else if ($quickgrade) {
1291                             $attributes = array();
1292                             $attributes['tabindex'] = $tabindex++;
1293                             $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1294                             $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1295                         } else {
1296                             $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1297                         }
1298                     }
1299                 ///Print Comment
1300                     if ($final_grade->locked or $final_grade->overridden) {
1301                         $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';
1303                     } else if ($quickgrade) {
1304                         $comment = '<div id="com'.$auser->id.'">'
1305                                  . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1306                                  . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1307                     } else {
1308                         $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
1309                     }
1310                 } else {
1311                     $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1312                     $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1313                     $status          = '<div id="st'.$auser->id.'">&nbsp;</div>';
1315                     if ($final_grade->locked or $final_grade->overridden) {
1316                         $grade = '<div id="g'.$auser->id.'">'.$final_grade->formatted_grade . '</div>';
1317                     } else if ($quickgrade) {   // allow editing
1318                         $attributes = array();
1319                         $attributes['tabindex'] = $tabindex++;
1320                         $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1321                         $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1322                     } else {
1323                         $grade = '<div id="g'.$auser->id.'">-</div>';
1324                     }
1326                     if ($final_grade->locked or $final_grade->overridden) {
1327                         $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
1328                     } else if ($quickgrade) {
1329                         $comment = '<div id="com'.$auser->id.'">'
1330                                  . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1331                                  . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1332                     } else {
1333                         $comment = '<div id="com'.$auser->id.'">&nbsp;</div>';
1334                     }
1335                 }
1337                 if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
1338                     $auser->status = 0;
1339                 } else {
1340                     $auser->status = 1;
1341                 }
1343                 $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
1345                 ///No more buttons, we use popups ;-).
1346                 $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1347                            . '&userid='.$auser->id.'&mode=single'.'&offset='.$offset++;
1349                 $action = new popup_action('click', $popup_url, 'grade'.$auser->id, array('height' => 600, 'width' => 700));
1350                 $button = $OUTPUT->action_link($popup_url, $buttontext, $action);
1352                 $status  = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
1354                 $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';
1356                 $outcomes = '';
1358                 if ($uses_outcomes) {
1360                     foreach($grading_info->outcomes as $n=>$outcome) {
1361                         $outcomes .= '<div class="outcome"><label>'.$outcome->name.'</label>';
1362                         $options = make_grades_menu(-$outcome->scaleid);
1364                         if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
1365                             $options[0] = get_string('nooutcome', 'grades');
1366                             $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
1367                         } else {
1368                             $attributes = array();
1369                             $attributes['tabindex'] = $tabindex++;
1370                             $attributes['id'] = 'outcome_'.$n.'_'.$auser->id;
1371                             $outcomes .= ' '.html_writer::select($options, 'outcome_'.$n.'['.$auser->id.']', $outcome->grades[$auser->id]->grade, array(0=>get_string('nooutcome', 'grades')), $attributes);
1372                         }
1373                         $outcomes .= '</div>';
1374                     }
1375                 }
1377                 $userlink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $auser->id . '&amp;course=' . $course->id . '">' . fullname($auser) . '</a>';
1378                 $row = array($picture, $userlink, $grade, $comment, $studentmodified, $teachermodified, $status, $finalgrade);
1379                 if ($uses_outcomes) {
1380                     $row[] = $outcomes;
1381                 }
1383                 $table->add_data($row);
1384             }
1385         }
1387         /// Print quickgrade form around the table
1388         if ($quickgrade){
1389             echo '<form action="submissions.php" id="fastg" method="post">';
1390             echo '<div>';
1391             echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
1392             echo '<input type="hidden" name="mode" value="fastgrade" />';
1393             echo '<input type="hidden" name="page" value="'.$page.'" />';
1394             echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1395             echo '</div>';
1396         }
1398         $table->print_html();  /// Print the whole table
1400         if ($quickgrade){
1401             $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? 'checked="checked"' : '';
1402             echo '<div class="fgcontrols">';
1403             echo '<div class="emailnotification">';
1404             echo '<label for="mailinfo">'.get_string('enableemailnotification','assignment').'</label>';
1405             echo '<input type="hidden" name="mailinfo" value="0" />';
1406             echo '<input type="checkbox" id="mailinfo" name="mailinfo" value="1" '.$lastmailinfo.' />';
1407             echo $OUTPUT->old_help_icon('emailnotification', get_string('enableemailnotification', 'assignment'), 'assignment').'</p></div>';
1408             echo '</div>';
1409             echo '<div class="fastgbutton"><input type="submit" name="fastg" value="'.get_string('saveallfeedback', 'assignment').'" /></div>';
1410             echo '</div>';
1411             echo '</form>';
1412         }
1413         /// End of fast grading form
1415         /// Mini form for setting user preference
1416         echo '<div class="qgprefs">';
1417         echo '<form id="options" action="submissions.php?id='.$this->cm->id.'" method="post"><div>';
1418         echo '<input type="hidden" name="updatepref" value="1" />';
1419         echo '<table id="optiontable">';
1420         echo '<tr><td>';
1421         echo '<label for="perpage">'.get_string('pagesize','assignment').'</label>';
1422         echo '</td>';
1423         echo '<td>';
1424         echo '<input type="text" id="perpage" name="perpage" size="1" value="'.$perpage.'" />';
1425         echo $OUTPUT->old_help_icon('pagesize', get_string('pagesize','assignment'), 'assignment');
1426         echo '</td></tr>';
1427         echo '<tr><td>';
1428         echo '<label for="quickgrade">'.get_string('quickgrade','assignment').'</label>';
1429         echo '</td>';
1430         echo '<td>';
1431         $checked = $quickgrade ? 'checked="checked"' : '';
1432         echo '<input type="checkbox" id="quickgrade" name="quickgrade" value="1" '.$checked.' />';
1433         echo $OUTPUT->old_help_icon('quickgrade', get_string('quickgrade', 'assignment'), 'assignment').'</p></div>';
1434         echo '</td></tr>';
1435         echo '<tr><td colspan="2">';
1436         echo '<input type="submit" value="'.get_string('savepreferences').'" />';
1437         echo '</td></tr></table>';
1438         echo '</div></form></div>';
1439         ///End of mini form
1440         echo $OUTPUT->footer();
1441     }
1443     /**
1444      *  Process teacher feedback submission
1445      *
1446      * This is called by submissions() when a grading even has taken place.
1447      * It gets its data from the submitted form.
1448      *
1449      * @global object
1450      * @global object
1451      * @global object
1452      * @return object|bool The updated submission object or false
1453      */
1454     function process_feedback() {
1455         global $CFG, $USER, $DB;
1456         require_once($CFG->libdir.'/gradelib.php');
1458         if (!$feedback = data_submitted() or !confirm_sesskey()) {      // No incoming data?
1459             return false;
1460         }
1462         ///For save and next, we need to know the userid to save, and the userid to go
1463         ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1464         ///as the userid to store
1465         if ((int)$feedback->saveuserid !== -1){
1466             $feedback->userid = $feedback->saveuserid;
1467         }
1469         if (!empty($feedback->cancel)) {          // User hit cancel button
1470             return false;
1471         }
1473         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);
1475         // store outcomes if needed
1476         $this->process_outcomes($feedback->userid);
1478         $submission = $this->get_submission($feedback->userid, true);  // Get or make one
1480         if (!$grading_info->items[0]->grades[$feedback->userid]->locked and
1481             !$grading_info->items[0]->grades[$feedback->userid]->overridden) {
1483             $submission->grade      = $feedback->grade;
1484             $submission->submissioncomment    = $feedback->submissioncomment;
1485             $submission->format     = $feedback->format;
1486             $submission->teacher    = $USER->id;
1487             $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1488             if (!$mailinfo) {
1489                 $submission->mailed = 1;       // treat as already mailed
1490             } else {
1491                 $submission->mailed = 0;       // Make sure mail goes out (again, even)
1492             }
1493             $submission->timemarked = time();
1495             unset($submission->data1);  // Don't need to update this.
1496             unset($submission->data2);  // Don't need to update this.
1498             if (empty($submission->timemodified)) {   // eg for offline assignments
1499                 // $submission->timemodified = time();
1500             }
1502             $DB->update_record('assignment_submissions', $submission);
1504             // triger grade event
1505             $this->update_grade($submission);
1507             add_to_log($this->course->id, 'assignment', 'update grades',
1508                        'submissions.php?id='.$this->assignment->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
1509         }
1511         return $submission;
1513     }
1515     function process_outcomes($userid) {
1516         global $CFG, $USER;
1518         if (empty($CFG->enableoutcomes)) {
1519             return;
1520         }
1522         require_once($CFG->libdir.'/gradelib.php');
1524         if (!$formdata = data_submitted() or !confirm_sesskey()) {
1525             return;
1526         }
1528         $data = array();
1529         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
1531         if (!empty($grading_info->outcomes)) {
1532             foreach($grading_info->outcomes as $n=>$old) {
1533                 $name = 'outcome_'.$n;
1534                 if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
1535                     $data[$n] = $formdata->{$name}[$userid];
1536                 }
1537             }
1538         }
1539         if (count($data) > 0) {
1540             grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1541         }
1543     }
1545     /**
1546      * Load the submission object for a particular user
1547      *
1548      * @global object
1549      * @global object
1550      * @param $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1551      * @param $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1552      * @param bool $teachermodified student submission set if false
1553      * @return object The submission
1554      */
1555     function get_submission($userid=0, $createnew=false, $teachermodified=false) {
1556         global $USER, $DB;
1558         if (empty($userid)) {
1559             $userid = $USER->id;
1560         }
1562         $submission = $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1564         if ($submission || !$createnew) {
1565             return $submission;
1566         }
1567         $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
1568         $DB->insert_record("assignment_submissions", $newsubmission);
1570         return $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1571     }
1573     /**
1574      * Instantiates a new submission object for a given user
1575      *
1576      * Sets the assignment, userid and times, everything else is set to default values.
1577      *
1578      * @param int $userid The userid for which we want a submission object
1579      * @param bool $teachermodified student submission set if false
1580      * @return object The submission
1581      */
1582     function prepare_new_submission($userid, $teachermodified=false) {
1583         $submission = new Object;
1584         $submission->assignment   = $this->assignment->id;
1585         $submission->userid       = $userid;
1586         $submission->timecreated = time();
1587         // teachers should not be modifying modified date, except offline assignments
1588         if ($teachermodified) {
1589             $submission->timemodified = 0;
1590         } else {
1591             $submission->timemodified = $submission->timecreated;
1592         }
1593         $submission->numfiles     = 0;
1594         $submission->data1        = '';
1595         $submission->data2        = '';
1596         $submission->grade        = -1;
1597         $submission->submissioncomment      = '';
1598         $submission->format       = 0;
1599         $submission->teacher      = 0;
1600         $submission->timemarked   = 0;
1601         $submission->mailed       = 0;
1602         return $submission;
1603     }
1605     /**
1606      * Return all assignment submissions by ENROLLED students (even empty)
1607      *
1608      * @param string $sort optional field names for the ORDER BY in the sql query
1609      * @param string $dir optional specifying the sort direction, defaults to DESC
1610      * @return array The submission objects indexed by id
1611      */
1612     function get_submissions($sort='', $dir='DESC') {
1613         return assignment_get_all_submissions($this->assignment, $sort, $dir);
1614     }
1616     /**
1617      * Counts all real assignment submissions by ENROLLED students (not empty ones)
1618      *
1619      * @param int $groupid optional If nonzero then count is restricted to this group
1620      * @return int The number of submissions
1621      */
1622     function count_real_submissions($groupid=0) {
1623         return assignment_count_real_submissions($this->cm, $groupid);
1624     }
1626     /**
1627      * Alerts teachers by email of new or changed assignments that need grading
1628      *
1629      * First checks whether the option to email teachers is set for this assignment.
1630      * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1631      * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1632      *
1633      * @global object
1634      * @global object
1635      * @param $submission object The submission that has changed
1636      * @return void
1637      */
1638     function email_teachers($submission) {
1639         global $CFG, $DB;
1641         if (empty($this->assignment->emailteachers)) {          // No need to do anything
1642             return;
1643         }
1645         $user = $DB->get_record('user', array('id'=>$submission->userid));
1647         if ($teachers = $this->get_graders($user)) {
1649             $strassignments = get_string('modulenameplural', 'assignment');
1650             $strassignment  = get_string('modulename', 'assignment');
1651             $strsubmitted  = get_string('submitted', 'assignment');
1653             foreach ($teachers as $teacher) {
1654                 $info = new object();
1655                 $info->username = fullname($user, true);
1656                 $info->assignment = format_string($this->assignment->name,true);
1657                 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
1659                 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1660                 $posttext = $this->email_teachers_text($info);
1661                 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
1663                 $eventdata = new object();
1664                 $eventdata->modulename       = 'assignment';
1665                 $eventdata->userfrom         = $user;
1666                 $eventdata->userto           = $teacher;
1667                 $eventdata->subject          = $postsubject;
1668                 $eventdata->fullmessage      = $posttext;
1669                 $eventdata->fullmessageformat = FORMAT_PLAIN;
1670                 $eventdata->fullmessagehtml  = $posthtml;
1671                 $eventdata->smallmessage     = '';
1672                 message_send($eventdata);
1673             }
1674         }
1675     }
1677     /**
1678      * @param string $filearea
1679      * @param array $args
1680      * @return bool
1681      */
1682     function send_file($filearea, $args) {
1683         debugging('plugin does not implement file sending', DEBUG_DEVELOPER);
1684         return false;
1685     }
1687     /**
1688      * Returns a list of teachers that should be grading given submission
1689      *
1690      * @param object $user
1691      * @return array
1692      */
1693     function get_graders($user) {
1694         //potential graders
1695         $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false);
1697         $graders = array();
1698         if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) {   // Separate groups are being used
1699             if ($groups = groups_get_all_groups($this->course->id, $user->id)) {  // Try to find all groups
1700                 foreach ($groups as $group) {
1701                     foreach ($potgraders as $t) {
1702                         if ($t->id == $user->id) {
1703                             continue; // do not send self
1704                         }
1705                         if (groups_is_member($group->id, $t->id)) {
1706                             $graders[$t->id] = $t;
1707                         }
1708                     }
1709                 }
1710             } else {
1711                 // user not in group, try to find graders without group
1712                 foreach ($potgraders as $t) {
1713                     if ($t->id == $user->id) {
1714                         continue; // do not send self
1715                     }
1716                     if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
1717                         $graders[$t->id] = $t;
1718                     }
1719                 }
1720             }
1721         } else {
1722             foreach ($potgraders as $t) {
1723                 if ($t->id == $user->id) {
1724                     continue; // do not send self
1725                 }
1726                 $graders[$t->id] = $t;
1727             }
1728         }
1729         return $graders;
1730     }
1732     /**
1733      * Creates the text content for emails to teachers
1734      *
1735      * @param $info object The info used by the 'emailteachermail' language string
1736      * @return string
1737      */
1738     function email_teachers_text($info) {
1739         $posttext  = format_string($this->course->shortname).' -> '.$this->strassignments.' -> '.
1740                      format_string($this->assignment->name)."\n";
1741         $posttext .= '---------------------------------------------------------------------'."\n";
1742         $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
1743         $posttext .= "\n---------------------------------------------------------------------\n";
1744         return $posttext;
1745     }
1747      /**
1748      * Creates the html content for emails to teachers
1749      *
1750      * @param $info object The info used by the 'emailteachermailhtml' language string
1751      * @return string
1752      */
1753     function email_teachers_html($info) {
1754         global $CFG;
1755         $posthtml  = '<p><font face="sans-serif">'.
1756                      '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname).'</a> ->'.
1757                      '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
1758                      '<a href="'.$CFG->wwwroot.'/mod/assignment/view.php?id='.$this->cm->id.'">'.format_string($this->assignment->name).'</a></font></p>';
1759         $posthtml .= '<hr /><font face="sans-serif">';
1760         $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
1761         $posthtml .= '</font><hr />';
1762         return $posthtml;
1763     }
1765     /**
1766      * Produces a list of links to the files uploaded by a user
1767      *
1768      * @param $userid int optional id of the user. If 0 then $USER->id is used.
1769      * @param $return boolean optional defaults to false. If true the list is returned rather than printed
1770      * @return string optional
1771      */
1772     function print_user_files($userid=0, $return=false) {
1773         global $CFG, $USER, $OUTPUT;
1775         if (!$userid) {
1776             if (!isloggedin()) {
1777                 return '';
1778             }
1779             $userid = $USER->id;
1780         }
1782         $output = '';
1784         $fs = get_file_storage();
1785         $browser = get_file_browser();
1787         $found = false;
1789         if ($files = $fs->get_area_files($this->context->id, 'assignment_submission', $userid, "timemodified", false)) {
1790             require_once($CFG->libdir.'/portfoliolib.php');
1791             require_once($CFG->dirroot . '/mod/assignment/locallib.php');
1792             $button = new portfolio_add_button();
1793             foreach ($files as $file) {
1794                 $filename = $file->get_filename();
1795                 $found = true;
1796                 $mimetype = $file->get_mimetype();
1797                 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/assignment_submission/'.$userid.'/'.$filename);
1798                 $output .= '<a href="'.$path.'" ><img src="'.$OUTPUT->pix_url(file_mimetype_icon($mimetype)).'" class="icon" alt="'.$mimetype.'" />'.s($filename).'</a>';
1799                 if ($this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1800                     $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id, 'fileid' => $file->get_id()), '/mod/assignment/locallib.php');
1801                     $button->set_format_by_file($file);
1802                     $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
1803                 }
1804                 $output .= '<br />';
1805             }
1806             if (count($files) > 1  && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1807                 $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id), '/mod/assignment/locallib.php');
1808                 $output .= '<br />'  . $button->to_html();
1809             }
1810         }
1812         $output = '<div class="files">'.$output.'</div>';
1814         if ($return) {
1815             return $output;
1816         }
1817         echo $output;
1818     }
1820     /**
1821      * Count the files uploaded by a given user
1822      *
1823      * @param $userid int The user id
1824      * @return int
1825      */
1826     function count_user_files($userid) {
1827         $fs = get_file_storage();
1828         $files = $fs->get_area_files($this->context->id, 'assignment_submission', $userid, "id", false);
1829         return count($files);
1830     }
1832     /**
1833      * Returns true if the student is allowed to submit
1834      *
1835      * Checks that the assignment has started and, if the option to prevent late
1836      * submissions is set, also checks that the assignment has not yet closed.
1837      * @return boolean
1838      */
1839     function isopen() {
1840         $time = time();
1841         if ($this->assignment->preventlate && $this->assignment->timedue) {
1842             return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
1843         } else {
1844             return ($this->assignment->timeavailable <= $time);
1845         }
1846     }
1849     /**
1850      * Return true if is set description is hidden till available date
1851      *
1852      * This is needed by calendar so that hidden descriptions do not
1853      * come up in upcoming events.
1854      *
1855      * Check that description is hidden till available date
1856      * By default return false
1857      * Assignments types should implement this method if needed
1858      * @return boolen
1859      */
1860     function description_is_hidden() {
1861         return false;
1862     }
1864     /**
1865      * Return an outline of the user's interaction with the assignment
1866      *
1867      * The default method prints the grade and timemodified
1868      * @param $grade object
1869      * @return object with properties ->info and ->time
1870      */
1871     function user_outline($grade) {
1873         $result = new object();
1874         $result->info = get_string('grade').': '.$grade->str_long_grade;
1875         $result->time = $grade->dategraded;
1876         return $result;
1877     }
1879     /**
1880      * Print complete information about the user's interaction with the assignment
1881      *
1882      * @param $user object
1883      */
1884     function user_complete($user, $grade=null) {
1885         global $OUTPUT;
1886         if ($grade) {
1887             echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
1888             if ($grade->str_feedback) {
1889                 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
1890             }
1891         }
1893         if ($submission = $this->get_submission($user->id)) {
1895             $fs = get_file_storage();
1896             $browser = get_file_browser();
1898             if ($files = $fs->get_area_files($this->context->id, 'assignment_submission', $user->id, "timemodified", false)) {
1899                 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
1900                 foreach ($files as $file) {
1901                     $countfiles .= "; ".$file->get_filename();
1902                 }
1903             }
1905             echo $OUTPUT->box_start();
1906             echo get_string("lastmodified").": ";
1907             echo userdate($submission->timemodified);
1908             echo $this->display_lateness($submission->timemodified);
1910             $this->print_user_files($user->id);
1912             echo '<br />';
1914             $this->view_feedback($submission);
1916             echo $OUTPUT->box_end();
1918         } else {
1919             print_string("notsubmittedyet", "assignment");
1920         }
1921     }
1923     /**
1924      * Return a string indicating how late a submission is
1925      *
1926      * @param $timesubmitted int
1927      * @return string
1928      */
1929     function display_lateness($timesubmitted) {
1930         return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
1931     }
1933     /**
1934      * Empty method stub for all delete actions.
1935      */
1936     function delete() {
1937         //nothing by default
1938         redirect('view.php?id='.$this->cm->id);
1939     }
1941     /**
1942      * Empty custom feedback grading form.
1943      */
1944     function custom_feedbackform($submission, $return=false) {
1945         //nothing by default
1946         return '';
1947     }
1949     /**
1950      * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
1951      * for the course (see resource).
1952      *
1953      * Given a course_module object, this function returns any "extra" information that may be needed
1954      * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
1955      *
1956      * @param $coursemodule object The coursemodule object (record).
1957      * @return object An object on information that the coures will know about (most noticeably, an icon).
1958      *
1959      */
1960     function get_coursemodule_info($coursemodule) {
1961         return false;
1962     }
1964     /**
1965      * Plugin cron method - do not use $this here, create new assignment instances if needed.
1966      * @return void
1967      */
1968     function cron() {
1969         //no plugin cron by default - override if needed
1970     }
1972     /**
1973      * Reset all submissions
1974      */
1975     function reset_userdata($data) {
1976         global $CFG, $DB;
1978         if (!$DB->count_records('assignment', array('course'=>$data->courseid, 'assignmenttype'=>$this->type))) {
1979             return array(); // no assignments of this type present
1980         }
1982         $componentstr = get_string('modulenameplural', 'assignment');
1983         $status = array();
1985         $typestr = get_string('type'.$this->type, 'assignment');
1986         // ugly hack to support pluggable assignment type titles...
1987         if($typestr === '[[type'.$this->type.']]'){
1988             $typestr = get_string('type'.$this->type, 'assignment_'.$this->type);
1989         }
1991         if (!empty($data->reset_assignment_submissions)) {
1992             $assignmentssql = "SELECT a.id
1993                                  FROM {assignment} a
1994                                 WHERE a.course=? AND a.assignmenttype=?";
1995             $params = array($data->courseid, $this->type);
1997             // now get rid of all submissions and responses
1998             $fs = get_file_storage();
1999             if ($assignments = $DB->get_records_sql($assignmentssql, $params)) {
2000                 foreach ($assignments as $assignmentid=>$unused) {
2001                     if (!$cm = get_coursemodule_from_instance('assignment', $assignmentid)) {
2002                         continue;
2003                     }
2004                     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2005                     $fs->delete_area_files($context->id, 'assignment_submission');
2006                     $fs->delete_area_files($context->id, 'assignment_response');
2007                 }
2008             }
2010             $DB->delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)", $params);
2012             $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
2014             if (empty($data->reset_gradebook_grades)) {
2015                 // remove all grades from gradebook
2016                 assignment_reset_gradebook($data->courseid, $this->type);
2017             }
2018         }
2020         /// updating dates - shift may be negative too
2021         if ($data->timeshift) {
2022             shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
2023             $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
2024         }
2026         return $status;
2027     }
2030     function portfolio_exportable() {
2031         return false;
2032     }
2034     /**
2035      * base implementation for backing up subtype specific information
2036      * for one single module
2037      *
2038      * @param filehandle $bf file handle for xml file to write to
2039      * @param mixed $preferences the complete backup preference object
2040      *
2041      * @return boolean
2042      *
2043      * @static
2044      */
2045     static function backup_one_mod($bf, $preferences, $assignment) {
2046         return true;
2047     }
2049     /**
2050      * base implementation for backing up subtype specific information
2051      * for one single submission
2052      *
2053      * @param filehandle $bf file handle for xml file to write to
2054      * @param mixed $preferences the complete backup preference object
2055      * @param object $submission the assignment submission db record
2056      *
2057      * @return boolean
2058      *
2059      * @static
2060      */
2061     static function backup_one_submission($bf, $preferences, $assignment, $submission) {
2062         return true;
2063     }
2065     /**
2066      * base implementation for restoring subtype specific information
2067      * for one single module
2068      *
2069      * @param array  $info the array representing the xml
2070      * @param object $restore the restore preferences
2071      *
2072      * @return boolean
2073      *
2074      * @static
2075      */
2076     static function restore_one_mod($info, $restore, $assignment) {
2077         return true;
2078     }
2080     /**
2081      * base implementation for restoring subtype specific information
2082      * for one single submission
2083      *
2084      * @param object $submission the newly created submission
2085      * @param array  $info the array representing the xml
2086      * @param object $restore the restore preferences
2087      *
2088      * @return boolean
2089      *
2090      * @static
2091      */
2092     static function restore_one_submission($info, $restore, $assignment, $submission) {
2093         return true;
2094     }
2096 } ////// End of the assignment_base class
2098 /**
2099  * @package   mod-assignment
2100  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
2101  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2102  */
2103 class mod_assignment_upload_file_form extends moodleform {
2104     function definition() {
2105         $mform = $this->_form;
2106         $instance = $this->_customdata;
2108         //TODO: improve upload size checking
2109         $mform->setMaxFileSize($instance->assignment->maxbytes);
2111         // visible elements
2112         $mform->addElement('file', 'newfile', get_string('uploadafile'));
2114         // hidden params
2115         $mform->addElement('hidden', 'id', $instance->cm->id);
2116         $mform->setType('id', PARAM_INT);
2117         $mform->addElement('hidden', 'action', 'uploadfile');
2118         $mform->setType('action', PARAM_ALPHA);
2120         // buttons
2121         $this->add_action_buttons(false, get_string('uploadthisfile'));
2122     }
2126 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
2128 /**
2129  * Deletes an assignment instance
2130  *
2131  * This is done by calling the delete_instance() method of the assignment type class
2132  */
2133 function assignment_delete_instance($id){
2134     global $CFG, $DB;
2136     if (! $assignment = $DB->get_record('assignment', array('id'=>$id))) {
2137         return false;
2138     }
2140     // fall back to base class if plugin missing
2141     $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2142     if (file_exists($classfile)) {
2143         require_once($classfile);
2144         $assignmentclass = "assignment_$assignment->assignmenttype";
2146     } else {
2147         debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
2148         $assignmentclass = "assignment_base";
2149     }
2151     $ass = new $assignmentclass();
2152     return $ass->delete_instance($assignment);
2156 /**
2157  * Updates an assignment instance
2158  *
2159  * This is done by calling the update_instance() method of the assignment type class
2160  */
2161 function assignment_update_instance($assignment){
2162     global $CFG;
2164     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2166     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2167     $assignmentclass = "assignment_$assignment->assignmenttype";
2168     $ass = new $assignmentclass();
2169     return $ass->update_instance($assignment);
2173 /**
2174  * Adds an assignment instance
2175  *
2176  * This is done by calling the add_instance() method of the assignment type class
2177  */
2178 function assignment_add_instance($assignment) {
2179     global $CFG;
2181     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2183     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2184     $assignmentclass = "assignment_$assignment->assignmenttype";
2185     $ass = new $assignmentclass();
2186     return $ass->add_instance($assignment);
2190 /**
2191  * Returns an outline of a user interaction with an assignment
2192  *
2193  * This is done by calling the user_outline() method of the assignment type class
2194  */
2195 function assignment_user_outline($course, $user, $mod, $assignment) {
2196     global $CFG;
2198     require_once("$CFG->libdir/gradelib.php");
2199     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2200     $assignmentclass = "assignment_$assignment->assignmenttype";
2201     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2202     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2203     if (!empty($grades->items[0]->grades)) {
2204         return $ass->user_outline(reset($grades->items[0]->grades));
2205     } else {
2206         return null;
2207     }
2210 /**
2211  * Prints the complete info about a user's interaction with an assignment
2212  *
2213  * This is done by calling the user_complete() method of the assignment type class
2214  */
2215 function assignment_user_complete($course, $user, $mod, $assignment) {
2216     global $CFG;
2218     require_once("$CFG->libdir/gradelib.php");
2219     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2220     $assignmentclass = "assignment_$assignment->assignmenttype";
2221     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2222     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2223     if (empty($grades->items[0]->grades)) {
2224         $grade = false;
2225     } else {
2226         $grade = reset($grades->items[0]->grades);
2227     }
2228     return $ass->user_complete($user, $grade);
2231 /**
2232  * Function to be run periodically according to the moodle cron
2233  *
2234  * Finds all assignment notifications that have yet to be mailed out, and mails them
2235  */
2236 function assignment_cron () {
2237     global $CFG, $USER, $DB;
2239     /// first execute all crons in plugins
2240     if ($plugins = get_plugin_list('assignment')) {
2241         foreach ($plugins as $plugin=>$dir) {
2242             require_once("$dir/assignment.class.php");
2243             $assignmentclass = "assignment_$plugin";
2244             $ass = new $assignmentclass();
2245             $ass->cron();
2246         }
2247     }
2249     /// Notices older than 1 day will not be mailed.  This is to avoid the problem where
2250     /// cron has not been running for a long time, and then suddenly people are flooded
2251     /// with mail from the past few weeks or months
2253     $timenow   = time();
2254     $endtime   = $timenow - $CFG->maxeditingtime;
2255     $starttime = $endtime - 24 * 3600;   /// One day earlier
2257     if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2259         $realuser = clone($USER);
2261         foreach ($submissions as $key => $submission) {
2262             if (! $DB->set_field("assignment_submissions", "mailed", "1", array("id"=>$submission->id))) {
2263                 echo "Could not update the mailed field for id $submission->id.  Not mailed.\n";
2264                 unset($submissions[$key]);
2265             }
2266         }
2268         $timenow = time();
2270         foreach ($submissions as $submission) {
2272             echo "Processing assignment submission $submission->id\n";
2274             if (! $user = $DB->get_record("user", array("id"=>$submission->userid))) {
2275                 echo "Could not find user $post->userid\n";
2276                 continue;
2277             }
2279             if (! $course = $DB->get_record("course", array("id"=>$submission->course))) {
2280                 echo "Could not find course $submission->course\n";
2281                 continue;
2282             }
2284             /// Override the language and timezone of the "current" user, so that
2285             /// mail is customised for the receiver.
2286             cron_setup_user($user, $course);
2288             if (!is_enrolled(get_context_instance(CONTEXT_COURSE, $submission->course), $user->id)) {
2289                 echo fullname($user)." not an active participant in " . format_string($course->shortname) . "\n";
2290                 continue;
2291             }
2293             if (! $teacher = $DB->get_record("user", array("id"=>$submission->teacher))) {
2294                 echo "Could not find teacher $submission->teacher\n";
2295                 continue;
2296             }
2298             if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2299                 echo "Could not find course module for assignment id $submission->assignment\n";
2300                 continue;
2301             }
2303             if (! $mod->visible) {    /// Hold mail notification for hidden assignments until later
2304                 continue;
2305             }
2307             $strassignments = get_string("modulenameplural", "assignment");
2308             $strassignment  = get_string("modulename", "assignment");
2310             $assignmentinfo = new object();
2311             $assignmentinfo->teacher = fullname($teacher);
2312             $assignmentinfo->assignment = format_string($submission->name,true);
2313             $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2315             $postsubject = "$course->shortname: $strassignments: ".format_string($submission->name,true);
2316             $posttext  = "$course->shortname -> $strassignments -> ".format_string($submission->name,true)."\n";
2317             $posttext .= "---------------------------------------------------------------------\n";
2318             $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2319             $posttext .= "---------------------------------------------------------------------\n";
2321             if ($user->mailformat == 1) {  // HTML
2322                 $posthtml = "<p><font face=\"sans-serif\">".
2323                 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> ->".
2324                 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2325                 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2326                 $posthtml .= "<hr /><font face=\"sans-serif\">";
2327                 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2328                 $posthtml .= "</font><hr />";
2329             } else {
2330                 $posthtml = "";
2331             }
2333             $eventdata = new object();
2334             $eventdata->modulename       = 'assignment';
2335             $eventdata->userfrom         = $teacher;
2336             $eventdata->userto           = $user;
2337             $eventdata->subject          = $postsubject;
2338             $eventdata->fullmessage      = $posttext;
2339             $eventdata->fullmessageformat = FORMAT_PLAIN;
2340             $eventdata->fullmessagehtml  = $posthtml;
2341             $eventdata->smallmessage     = '';
2342             message_send($eventdata);
2343         }
2345         cron_setup_user();
2346     }
2348     return true;
2351 /**
2352  * Return grade for given user or all users.
2353  *
2354  * @param int $assignmentid id of assignment
2355  * @param int $userid optional user id, 0 means all users
2356  * @return array array of grades, false if none
2357  */
2358 function assignment_get_user_grades($assignment, $userid=0) {
2359     global $CFG, $DB;
2361     if ($userid) {
2362         $user = "AND u.id = :userid";
2363         $params = array('userid'=>$userid);
2364     } else {
2365         $user = "";
2366     }
2367     $params['aid'] = $assignment->id;
2369     $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2370                    s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2371               FROM {user} u, {assignment_submissions} s
2372              WHERE u.id = s.userid AND s.assignment = :aid
2373                    $user";
2375     return $DB->get_records_sql($sql, $params);
2378 /**
2379  * Update activity grades
2380  *
2381  * @param object $assignment
2382  * @param int $userid specific user only, 0 means all
2383  */
2384 function assignment_update_grades($assignment, $userid=0, $nullifnone=true) {
2385     global $CFG, $DB;
2386     require_once($CFG->libdir.'/gradelib.php');
2388     if ($assignment->grade == 0) {
2389         assignment_grade_item_update($assignment);
2391     } else if ($grades = assignment_get_user_grades($assignment, $userid)) {
2392         foreach($grades as $k=>$v) {
2393             if ($v->rawgrade == -1) {
2394                 $grades[$k]->rawgrade = null;
2395             }
2396         }
2397         assignment_grade_item_update($assignment, $grades);
2399     } else {
2400         assignment_grade_item_update($assignment);
2401     }
2404 /**
2405  * Update all grades in gradebook.
2406  */
2407 function assignment_upgrade_grades() {
2408     global $DB;
2410     $sql = "SELECT COUNT('x')
2411               FROM {assignment} a, {course_modules} cm, {modules} m
2412              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2413     $count = $DB->count_records_sql($sql);
2415     $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
2416               FROM {assignment} a, {course_modules} cm, {modules} m
2417              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2418     if ($rs = $DB->get_recordset_sql($sql)) {
2419         // too much debug output
2420         $pbar = new progress_bar('assignmentupgradegrades', 500, true);
2421         $i=0;
2422         foreach ($rs as $assignment) {
2423             $i++;
2424             upgrade_set_timeout(60*5); // set up timeout, may also abort execution
2425             assignment_update_grades($assignment);
2426             $pbar->update($i, $count, "Updating Assignment grades ($i/$count).");
2427         }
2428         $rs->close();
2429         upgrade_set_timeout(); // reset to default timeout
2430     }
2433 /**
2434  * Create grade item for given assignment
2435  *
2436  * @param object $assignment object with extra cmidnumber
2437  * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
2438  * @return int 0 if ok, error code otherwise
2439  */
2440 function assignment_grade_item_update($assignment, $grades=NULL) {
2441     global $CFG;
2442     require_once($CFG->libdir.'/gradelib.php');
2444     if (!isset($assignment->courseid)) {
2445         $assignment->courseid = $assignment->course;
2446     }
2448     $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
2450     if ($assignment->grade > 0) {
2451         $params['gradetype'] = GRADE_TYPE_VALUE;
2452         $params['grademax']  = $assignment->grade;
2453         $params['grademin']  = 0;
2455     } else if ($assignment->grade < 0) {
2456         $params['gradetype'] = GRADE_TYPE_SCALE;
2457         $params['scaleid']   = -$assignment->grade;
2459     } else {
2460         $params['gradetype'] = GRADE_TYPE_TEXT; // allow text comments only
2461     }
2463     if ($grades  === 'reset') {
2464         $params['reset'] = true;
2465         $grades = NULL;
2466     }
2468     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades, $params);
2471 /**
2472  * Delete grade item for given assignment
2473  *
2474  * @param object $assignment object
2475  * @return object assignment
2476  */
2477 function assignment_grade_item_delete($assignment) {
2478     global $CFG;
2479     require_once($CFG->libdir.'/gradelib.php');
2481     if (!isset($assignment->courseid)) {
2482         $assignment->courseid = $assignment->course;
2483     }
2485     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
2488 /**
2489  * Returns the users with data in one assignment (students and teachers)
2490  *
2491  * @param $assignmentid int
2492  * @return array of user objects
2493  */
2494 function assignment_get_participants($assignmentid) {
2495     global $CFG, $DB;
2497     //Get students
2498     $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2499                                         FROM {user} u,
2500                                              {assignment_submissions} a
2501                                        WHERE a.assignment = ? and
2502                                              u.id = a.userid", array($assignmentid));
2503     //Get teachers
2504     $teachers = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2505                                         FROM {user} u,
2506                                              {assignment_submissions} a
2507                                        WHERE a.assignment = ? and
2508                                              u.id = a.teacher", array($assignmentid));
2510     //Add teachers to students
2511     if ($teachers) {
2512         foreach ($teachers as $teacher) {
2513             $students[$teacher->id] = $teacher;
2514         }
2515     }
2516     //Return students array (it contains an array of unique users)
2517     return ($students);
2520 /**
2521  * Serves assingment submissions and otehr files.
2522  *
2523  * @param object $course
2524  * @param object $cminfo
2525  * @param object $context
2526  * @param string $filearea
2527  * @param array $args
2528  * @param bool $forcedownload
2529  * @return bool false if file not found, does not return if found - justsend the file
2530  */
2531 function assignment_pluginfile($course, $cminfo, $context, $filearea, $args, $forcedownload) {
2532     global $CFG, $DB;
2534     if (!$assignment = $DB->get_record('assignment', array('id'=>$cminfo->instance))) {
2535         return false;
2536     }
2537     if (!$cm = get_coursemodule_from_instance('assignment', $assignment->id, $course->id)) {
2538         return false;
2539     }
2541     require_login($course, false, $cm);
2543     require_once($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
2544     $assignmentclass = 'assignment_'.$assignment->assignmenttype;
2545     $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm, $course);
2547     return $assignmentinstance->send_file($filearea, $args);
2549 /**
2550  * Checks if a scale is being used by an assignment
2551  *
2552  * This is used by the backup code to decide whether to back up a scale
2553  * @param $assignmentid int
2554  * @param $scaleid int
2555  * @return boolean True if the scale is used by the assignment
2556  */
2557 function assignment_scale_used($assignmentid, $scaleid) {
2558     global $DB;
2560     $return = false;
2562     $rec = $DB->get_record('assignment', array('id'=>$assignmentid,'grade'=>-$scaleid));
2564     if (!empty($rec) && !empty($scaleid)) {
2565         $return = true;
2566     }
2568     return $return;
2571 /**
2572  * Checks if scale is being used by any instance of assignment
2573  *
2574  * This is used to find out if scale used anywhere
2575  * @param $scaleid int
2576  * @return boolean True if the scale is used by any assignment
2577  */
2578 function assignment_scale_used_anywhere($scaleid) {
2579     global $DB;
2581     if ($scaleid and $DB->record_exists('assignment', array('grade'=>-$scaleid))) {
2582         return true;
2583     } else {
2584         return false;
2585     }
2588 /**
2589  * Make sure up-to-date events are created for all assignment instances
2590  *
2591  * This standard function will check all instances of this module
2592  * and make sure there are up-to-date events created for each of them.
2593  * If courseid = 0, then every assignment event in the site is checked, else
2594  * only assignment events belonging to the course specified are checked.
2595  * This function is used, in its new format, by restore_refresh_events()
2596  *
2597  * @param $courseid int optional If zero then all assignments for all courses are covered
2598  * @return boolean Always returns true
2599  */
2600 function assignment_refresh_events($courseid = 0) {
2601     global $DB;
2603     if ($courseid == 0) {
2604         if (! $assignments = $DB->get_records("assignment")) {
2605             return true;
2606         }
2607     } else {
2608         if (! $assignments = $DB->get_records("assignment", array("course"=>$courseid))) {
2609             return true;
2610         }
2611     }
2612     $moduleid = $DB->get_field('modules', 'id', array('name'=>'assignment'));
2614     foreach ($assignments as $assignment) {
2615         $cm = get_coursemodule_from_id('assignment', $assignment->id);
2616         $event = new object();
2617         $event->name        = $assignment->name;
2618         $event->description = format_module_intro('assignment', $assignment, $cm->id);
2619         $event->timestart   = $assignment->timedue;
2621         if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
2622             update_event($event);
2624         } else {
2625             $event->courseid    = $assignment->course;
2626             $event->groupid     = 0;
2627             $event->userid      = 0;
2628             $event->modulename  = 'assignment';
2629             $event->instance    = $assignment->id;
2630             $event->eventtype   = 'due';
2631             $event->timeduration = 0;
2632             $event->visible     = $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$assignment->id));
2633             add_event($event);
2634         }
2636     }
2637     return true;
2640 /**
2641  * Print recent activity from all assignments in a given course
2642  *
2643  * This is used by the recent activity block
2644  */
2645 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
2646     global $CFG, $USER, $DB, $OUTPUT;
2648     // do not use log table if possible, it may be huge
2650     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
2651                                                      u.firstname, u.lastname, u.email, u.picture
2652                                                 FROM {assignment_submissions} asb
2653                                                      JOIN {assignment} a      ON a.id = asb.assignment
2654                                                      JOIN {course_modules} cm ON cm.instance = a.id
2655                                                      JOIN {modules} md        ON md.id = cm.module
2656                                                      JOIN {user} u            ON u.id = asb.userid
2657                                                WHERE asb.timemodified > ? AND
2658                                                      a.course = ? AND
2659                                                      md.name = 'assignment'
2660                                             ORDER BY asb.timemodified ASC", array($timestart, $course->id))) {
2661          return false;
2662     }
2664     $modinfo =& get_fast_modinfo($course); // reference needed because we might load the groups
2665     $show    = array();
2666     $grader  = array();
2668     foreach($submissions as $submission) {
2669         if (!array_key_exists($submission->cmid, $modinfo->cms)) {
2670             continue;
2671         }
2672         $cm = $modinfo->cms[$submission->cmid];
2673         if (!$cm->uservisible) {
2674             continue;
2675         }
2676         if ($submission->userid == $USER->id) {
2677             $show[] = $submission;
2678             continue;
2679         }
2681         // the act of sumbitting of assignment may be considered private - only graders will see it if specified
2682         if (empty($CFG->assignment_showrecentsubmissions)) {
2683             if (!array_key_exists($cm->id, $grader)) {
2684                 $grader[$cm->id] = has_capability('moodle/grade:viewall', get_context_instance(CONTEXT_MODULE, $cm->id));
2685             }
2686             if (!$grader[$cm->id]) {
2687                 continue;
2688             }
2689         }
2691         $groupmode = groups_get_activity_groupmode($cm, $course);
2693         if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2694             if (isguestuser()) {
2695                 // shortcut - guest user does not belong into any group
2696                 continue;
2697             }
2699             if (is_null($modinfo->groups)) {
2700                 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2701             }
2703             // this will be slow - show only users that share group with me in this cm
2704             if (empty($modinfo->groups[$cm->id])) {
2705                 continue;
2706             }
2707             $usersgroups =  groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
2708             if (is_array($usersgroups)) {
2709                 $usersgroups = array_keys($usersgroups);
2710                 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2711                 if (empty($intersect)) {
2712                     continue;
2713                 }
2714             }
2715         }
2716         $show[] = $submission;
2717     }
2719     if (empty($show)) {
2720         return false;
2721     }
2723     echo $OUTPUT->heading(get_string('newsubmissions', 'assignment').':');
2725     foreach ($show as $submission) {
2726         $cm = $modinfo->cms[$submission->cmid];
2727         $link = $CFG->wwwroot.'/mod/assignment/view.php?id='.$cm->id;
2728         print_recent_activity_note($submission->timemodified, $submission, $cm->name, $link, false, $viewfullnames);
2729     }
2731     return true;
2735 /**
2736  * Returns all assignments since a given time in specified forum.
2737  */
2738 function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0)  {
2739     global $CFG, $COURSE, $USER, $DB;
2741     if ($COURSE->id == $courseid) {
2742         $course = $COURSE;
2743     } else {
2744         $course = $DB->get_record('course', array('id'=>$courseid));
2745     }
2747     $modinfo =& get_fast_modinfo($course);
2749     $cm = $modinfo->cms[$cmid];
2751     $params = array();
2752     if ($userid) {
2753         $userselect = "AND u.id = :userid";
2754         $params['userid'] = $userid;
2755     } else {
2756         $userselect = "";
2757     }
2759     if ($groupid) {
2760         $groupselect = "AND gm.groupid = :groupid";
2761         $groupjoin   = "JOIN {groups_members} gm ON  gm.userid=u.id";
2762         $params['groupid'] = $groupid;
2763     } else {
2764         $groupselect = "";
2765         $groupjoin   = "";
2766     }
2768     $params['cminstance'] = $cm->instance;
2769     $params['timestart'] = $timestart;
2771     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, asb.userid,
2772                                                      u.firstname, u.lastname, u.email, u.picture
2773                                                 FROM {assignment_submissions} asb
2774                                                 JOIN {assignment} a      ON a.id = asb.assignment
2775                                                 JOIN {user} u            ON u.id = asb.userid
2776                                           $groupjoin
2777                                                WHERE asb.timemodified > :timestart AND a.id = :cminstance
2778                                                      $userselect $groupselect
2779                                             ORDER BY asb.timemodified ASC", $params)) {
2780          return;
2781     }
2783     $groupmode       = groups_get_activity_groupmode($cm, $course);
2784     $cm_context      = get_context_instance(CONTEXT_MODULE, $cm->id);
2785     $grader          = has_capability('moodle/grade:viewall', $cm_context);
2786     $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
2787     $viewfullnames   = has_capability('moodle/site:viewfullnames', $cm_context);
2789     if (is_null($modinfo->groups)) {
2790         $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2791     }
2793     $show = array();
2795     foreach($submissions as $submission) {
2796         if ($submission->userid == $USER->id) {
2797             $show[] = $submission;
2798             continue;
2799         }
2800         // the act of submitting of assignment may be considered private - only graders will see it if specified
2801         if (empty($CFG->assignment_showrecentsubmissions)) {
2802             if (!$grader) {
2803                 continue;
2804             }
2805         }
2807         if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
2808             if (isguestuser()) {
2809                 // shortcut - guest user does not belong into any group
2810                 continue;
2811             }
2813             // this will be slow - show only users that share group with me in this cm
2814             if (empty($modinfo->groups[$cm->id])) {
2815                 continue;
2816             }
2817             $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
2818             if (is_array($usersgroups)) {
2819                 $usersgroups = array_keys($usersgroups);
2820                 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2821                 if (empty($intersect)) {
2822                     continue;
2823                 }
2824             }
2825         }
2826         $show[] = $submission;
2827     }
2829     if (empty($show)) {
2830         return;
2831     }
2833     if ($grader) {
2834         require_once($CFG->libdir.'/gradelib.php');
2835         $userids = array();
2836         foreach ($show as $id=>$submission) {
2837             $userids[] = $submission->userid;
2839         }
2840         $grades = grade_get_grades($courseid, 'mod', 'assignment', $cm->instance, $userids);
2841     }
2843     $aname = format_string($cm->name,true);
2844     foreach ($show as $submission) {
2845         $tmpactivity = new object();
2847         $tmpactivity->type         = 'assignment';
2848         $tmpactivity->cmid         = $cm->id;
2849         $tmpactivity->name         = $aname;
2850         $tmpactivity->sectionnum   = $cm->sectionnum;
2851         $tmpactivity->timestamp    = $submission->timemodified;
2853         if ($grader) {
2854             $tmpactivity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
2855         }
2857         $tmpactivity->user->userid   = $submission->userid;
2858         $tmpactivity->user->fullname = fullname($submission, $viewfullnames);
2859         $tmpactivity->user->picture  = $submission->picture;
2861         $activities[$index++] = $tmpactivity;
2862     }
2864     return;
2867 /**
2868  * Print recent activity from all assignments in a given course
2869  *
2870  * This is used by course/recent.php
2871  */
2872 function assignment_print_recent_mod_activity($activity, $courseid, $detail, $modnames)  {
2873     global $CFG, $OUTPUT;
2875     echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
2877     echo "<tr><td class=\"userpicture\" valign=\"top\">";
2878     echo $OUTPUT->user_picture($activity->user);
2879     echo "</td><td>";
2881     if ($detail) {
2882         $modname = $modnames[$activity->type];
2883         echo '<div class="title">';
2884         echo "<img src=\"" . $OUTPUT->pix_url('icon', 'assignment') . "\" ".
2885              "class=\"icon\" alt=\"$modname\">";
2886         echo "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id={$activity->cmid}\">{$activity->name}</a>";
2887         echo '</div>';
2888     }
2890     if (isset($activity->grade)) {
2891         echo '<div class="grade">';
2892         echo get_string('grade').': ';
2893         echo $activity->grade;
2894         echo '</div>';
2895     }
2897     echo '<div class="user">';
2898     echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->userid}&amp;course=$courseid\">"
2899          ."{$activity->user->fullname}</a>  - ".userdate($activity->timestamp);
2900     echo '</div>';
2902     echo "</td></tr></table>";
2905 /// GENERIC SQL FUNCTIONS
2907 /**
2908  * Fetch info from logs
2909  *
2910  * @param $log object with properties ->info (the assignment id) and ->userid
2911  * @return array with assignment name and user firstname and lastname
2912  */
2913 function assignment_log_info($log) {
2914     global $CFG, $DB;
2916     return $DB->get_record_sql("SELECT a.name, u.firstname, u.lastname
2917                                   FROM {assignment} a, {user} u
2918                                  WHERE a.id = ? AND u.id = ?", array($log->info, $log->userid));
2921 /**
2922  * Return list of marked submissions that have not been mailed out for currently enrolled students
2923  *
2924  * @return array
2925  */
2926 function assignment_get_unmailed_submissions($starttime, $endtime) {
2927     global $CFG, $DB;
2929     return $DB->get_records_sql("SELECT s.*, a.course, a.name
2930                                    FROM {assignment_submissions} s,
2931                                         {assignment} a
2932                                   WHERE s.mailed = 0
2933                                         AND s.timemarked <= ?
2934                                         AND s.timemarked >= ?
2935                                         AND s.assignment = a.id", array($endtime, $starttime));
2938 /**
2939  * Counts all real assignment submissions by ENROLLED students (not empty ones)
2940  *
2941  * There are also assignment type methods count_real_submissions() wich in the default
2942  * implementation simply call this function.
2943  * @param $groupid int optional If nonzero then count is restricted to this group
2944  * @return int The number of submissions
2945  */
2946 function assignment_count_real_submissions($cm, $groupid=0) {
2947     global $CFG, $DB;
2949     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2951     // this is all the users with this capability set, in this context or higher
2952     if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $groupid, '', false)) {
2953         $users = array_keys($users);
2954     }
2956     // if groupmembersonly used, remove users who are not in any group
2957     if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
2958         if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
2959             $users = array_intersect($users, array_keys($groupingusers));
2960         }
2961     }
2963     if (empty($users)) {
2964         return 0;
2965     }
2967     $userlists = implode(',', $users);
2969     return $DB->count_records_sql("SELECT COUNT('x')
2970                                      FROM {assignment_submissions}
2971                                     WHERE assignment = ? AND
2972                                           timemodified > 0 AND
2973                                           userid IN ($userlists)", array($cm->instance));
2977 /**
2978  * Return all assignment submissions by ENROLLED students (even empty)
2979  *
2980  * There are also assignment type methods get_submissions() wich in the default
2981  * implementation simply call this function.
2982  * @param $sort string optional field names for the ORDER BY in the sql query
2983  * @param $dir string optional specifying the sort direction, defaults to DESC
2984  * @return array The submission objects indexed by id
2985  */
2986 function assignment_get_all_submissions($assignment, $sort="", $dir="DESC") {
2987 /// Return all assignment submissions by ENROLLED students (even empty)
2988     global $CFG, $DB;
2990     if ($sort == "lastname" or $sort == "firstname") {
2991         $sort = "u.$sort $dir";
2992     } else if (empty($sort)) {
2993         $sort = "a.timemodified DESC";
2994     } else {
2995         $sort = "a.$sort $dir";
2996     }
2998     /* not sure this is needed at all since assignmenet already has a course define, so this join?
2999     $select = "s.course = '$assignment->course' AND";
3000     if ($assignment->course == SITEID) {
3001         $select = '';
3002     }*/
3004     return $DB->get_records_sql("SELECT a.*
3005                                    FROM {assignment_submissions} a, {user} u
3006                                   WHERE u.id = a.userid
3007                                         AND a.assignment = ?
3008                                ORDER BY $sort", array($assignment->id));
3012 /**
3013  * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
3014  * for the course (see resource).
3015  *
3016  * Given a course_module object, this function returns any "extra" information that may be needed
3017  * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
3018  *
3019  * @param $coursemodule object The coursemodule object (record).
3020  * @return object An object on information that the coures will know about (most noticeably, an icon).
3021  *
3022  */
3023 function assignment_get_coursemodule_info($coursemodule) {
3024     global $CFG, $DB;
3026     if (! $assignment = $DB->get_record('assignment', array('id'=>$coursemodule->instance), 'id, assignmenttype, name')) {
3027         return false;
3028     }
3030     $libfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
3032     if (file_exists($libfile)) {
3033         require_once($libfile);
3034         $assignmentclass = "assignment_$assignment->assignmenttype";
3035         $ass = new $assignmentclass('staticonly');
3036         if ($result = $ass->get_coursemodule_info($coursemodule)) {
3037             return $result;
3038         } else {
3039             $info = new object();
3040             $info->name = $assignment->name;
3041             return $info;
3042         }
3044     } else {
3045         debugging('Incorrect assignment type: '.$assignment->assignmenttype);
3046         return false;
3047     }
3052 /// OTHER GENERAL FUNCTIONS FOR ASSIGNMENTS  ///////////////////////////////////////
3054 /**
3055  * Returns an array of installed assignment types indexed and sorted by name
3056  *
3057  * @return array The index is the name of the assignment type, the value its full name from the language strings
3058  */
3059 function assignment_types() {
3060     $types = array();
3061     $names = get_plugin_list('assignment');
3062     foreach ($names as $name=>$dir) {
3063         $types[$name] = get_string('type'.$name, 'assignment');
3065         // ugly hack to support pluggable assignment type titles..
3066         if ($types[$name] == '[[type'.$name.']]') {
3067             $types[$name] = get_string('type'.$name, 'assignment_'.$name);
3068         }
3069     }
3070     asort($types);
3071     return $types;
3074 function assignment_print_overview($courses, &$htmlarray) {
3075     global $USER, $CFG, $DB;
3077     if (empty($courses) || !is_array($courses) || count($courses) == 0) {
3078         return array();
3079     }
3081     if (!$assignments = get_all_instances_in_courses('assignment',$courses)) {
3082         return;
3083     }
3085     $assignmentids = array();
3087     // Do assignment_base::isopen() here without loading the whole thing for speed
3088     foreach ($assignments as $key => $assignment) {
3089         $time = time();
3090         if ($assignment->timedue) {
3091             if ($assignment->preventlate) {
3092                 $isopen = ($assignment->timeavailable <= $time && $time <= $assignment->timedue);
3093             } else {
3094                 $isopen = ($assignment->timeavailable <= $time);
3095             }
3096         }
3097         if (empty($isopen) || empty($assignment->timedue)) {
3098             unset($assignments[$key]);
3099         }else{
3100             $assignmentids[] = $assignment->id;
3101         }
3102     }
3104     if(empty($assignmentids)){
3105         // no assigments to look at - we're done
3106         return true;
3107     }
3109     $strduedate = get_string('duedate', 'assignment');
3110     $strduedateno = get_string('duedateno', 'assignment');
3111     $strgraded = get_string('graded', 'assignment');
3112     $strnotgradedyet = get_string('notgradedyet', 'assignment');
3113     $strnotsubmittedyet = get_string('notsubmittedyet', 'assignment');
3114     $strsubmitted = get_string('submitted', 'assignment');
3115     $strassignment = get_string('modulename', 'assignment');
3116     $strreviewed = get_string('reviewed','assignment');
3119     // NOTE: we do all possible database work here *outside* of the loop to ensure this scales
3120     //
3121     list($sqlassignmentids, $assignmentidparams) = $DB->get_in_or_equal($assignmentids);
3123     // build up and array of unmarked submissions indexed by assigment id/ userid
3124     // for use where the user has grading rights on assigment
3125     $rs = $DB->get_recordset_sql("SELECT id, assignment, userid
3126                             FROM {assignment_submissions}
3127                             WHERE teacher = 0 AND timemarked = 0
3128                             AND assignment $sqlassignmentids", $assignmentidparams);
3130     $unmarkedsubmissions = array();
3131     foreach ($rs as $rd) {
3132         $unmarkedsubmissions[$rd->assignment][$rd->userid] = $rd->id;
3133     }
3134     $rs->close();
3137     // get all user submissions, indexed by assigment id
3138     $mysubmissions = $DB->get_records_sql("SELECT assignment, timemarked, teacher, grade
3139                                       FROM {assignment_submissions}
3140                                       WHERE userid = ? AND
3141                                       assignment $sqlassignmentids", array_merge(array($USER->id), $assignmentidparams));
3143     foreach ($assignments as $assignment) {
3144         $str = '<div class="assignment overview"><div class="name">'.$strassignment. ': '.
3145                '<a '.($assignment->visible ? '':' class="dimmed"').
3146                'title="'.$strassignment.'" href="'.$CFG->wwwroot.
3147                '/mod/assignment/view.php?id='.$assignment->coursemodule.'">'.
3148                $assignment->name.'</a></div>';
3149         if ($assignment->timedue) {
3150             $str .= '<div class="info">'.$strduedate.': '.userdate($assignment->timedue).'</div>';
3151         } else {
3152             $str .= '<div class="info">'.$strduedateno.'</div>';
3153         }
3154         $context = get_context_instance(CONTEXT_MODULE, $assignment->coursemodule);
3155         if (has_capability('mod/assignment:grade', $context)) {
3157             // count how many people can submit
3158             $submissions = 0; // init
3159             if ($students = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', 0, '', false)) {
3160                 foreach($students as $student){
3161                     if(isset($unmarkedsubmissions[$assignment->id][$student->id])){
3162                         $submissions++;
3163                     }
3164                 }
3165             }
3167             if ($submissions) {
3168                 $str .= get_string('submissionsnotgraded', 'assignment', $submissions);
3169             }
3170         } else {
3171             if(isset($mysubmissions[$assignment->id])){
3173                 $submission = $mysubmissions[$assignment->id];
3175                 if ($submission->teacher == 0 && $submission->timemarked == 0) {
3176                     $str .= $strsubmitted . ', ' . $strnotgradedyet;
3177                 } else if ($submission->grade <= 0) {
3178                     $str .= $strsubmitted . ', ' . $strreviewed;
3179                 } else {
3180                     $str .= $strsubmitted . ', ' . $strgraded;
3181                 }
3182             } else {
3183                 $str .= $strnotsubmittedyet . ' ' . assignment_display_lateness(time(), $assignment->timedue);
3184             }
3185         }
3186         $str .= '</div>';
3187         if (empty($htmlarray[$assignment->course]['assignment'])) {
3188             $htmlarray[$assignment->course]['assignment'] = $str;
3189         } else {
3190             $htmlarray[$assignment->course]['assignment'] .= $str;
3191         }
3192     }
3195 function assignment_display_lateness($timesubmitted, $timedue) {
3196     if (!$timedue) {
3197         return '';
3198     }
3199     $time = $timedue - $timesubmitted;
3200     if ($time < 0) {
3201         $timetext = get_string('late', 'assignment', format_time($time));
3202         return ' (<span class="late">'.$timetext.'</span>)';
3203     } else {
3204         $timetext = get_string('early', 'assignment', format_time($time));
3205         return ' (<span class="early">'.$timetext.'</span>)';
3206     }
3209 function assignment_get_view_actions() {
3210     return array('view');
3213 function assignment_get_post_actions() {
3214     return array('upload');
3217 function assignment_get_types() {
3218     global $CFG;
3219     $types = array();
3221     $type = new object();
3222     $type->modclass = MOD_CLASS_ACTIVITY;
3223     $type->type = "assignment_group_start";
3224     $type->typestr = '--'.get_string('modulenameplural', 'assignment');
3225     $types[] = $type;
3227     $standardassignments = array('upload','online','uploadsingle','offline');
3228     foreach ($standardassignments as $assignmenttype) {
3229         $type = new object();
3230         $type->modclass = MOD_CLASS_ACTIVITY;
3231         $type->type = "assignment&amp;type=$assignmenttype";
3232         $type->typestr = get_string("type$assignmenttype", 'assignment');
3233         $types[] = $type;
3234     }
3236     /// Drop-in extra assignment types
3237     $assignmenttypes = get_list_of_plugins('mod/assignment/type');
3238     foreach ($assignmenttypes as $assignmenttype) {
3239         if (!empty($CFG->{'assignment_hide_'.$assignmenttype})) {  // Not wanted
3240             continue;
3241         }
3242         if (!in_array($assignmenttype, $standardassignments)) {
3243             $type = new object();
3244             $type->modclass = MOD_CLASS_ACTIVITY;
3245             $type->type = "assignment&amp;type=$assignmenttype";
3246             $type->typestr = get_string("type$assignmenttype", 'assignment_'.$assignmenttype);
3247             $types[] = $type;
3248         }
3249     }
3251     $type = new object();
3252     $type->modclass = MOD_CLASS_ACTIVITY;
3253     $type->type = "assignment_group_end";
3254     $type->typestr = '--';
3255     $types[] = $type;
3257     return $types;
3260 /**
3261  * Removes all grades from gradebook
3262  * @param int $courseid
3263  * @param string optional type
3264  */
3265 function assignment_reset_gradebook($courseid, $type='') {
3266     global $CFG, $DB;
3268     $params = array('courseid'=>$courseid);
3269     if ($type) {
3270         $type = "AND a.assignmenttype= :type";
3271         $params['type'] = $type;
3272     }
3274     $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
3275               FROM {assignment} a, {course_modules} cm, {modules} m
3276              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id AND a.course=:courseid $type";
3278     if ($assignments = $DB->get_records_sql($sql, $params)) {
3279         foreach ($assignments as $assignment) {
3280             assignment_grade_item_update($assignment, 'reset');
3281         }
3282     }
3285 /**
3286  * This function is used by the reset_course_userdata function in moodlelib.
3287  * This function will remove all posts from the specified assignment
3288  * and clean up any related data.
3289  * @param $data the data submitted from the reset course.
3290  * @return array status array
3291  */
3292 function assignment_reset_userdata($data) {
3293     global $CFG;
3295     $status = array();
3297     foreach (get_plugin_list('mod/assignment/type') as $type=>$dir) {
3298         require_once("$dir/assignment.class.php");
3299         $assignmentclass = "assignment_$type";
3300         $ass = new $assignmentclass();
3301         $status = array_merge($status, $ass->reset_userdata($data));
3302     }
3304     return $status;
3307 /**
3308  * Implementation of the function for printing the form elements that control
3309  * whether the course reset functionality affects the assignment.
3310  * @param $mform form passed by reference
3311  */
3312 function assignment_reset_course_form_definition(&$mform) {
3313     $mform->addElement('header', 'assignmentheader', get_string('modulenameplural', 'assignment'));
3314     $mform->addElement('advcheckbox', 'reset_assignment_submissions', get_string('deleteallsubmissions','assignment'));
3317 /**
3318  * Course reset form defaults.
3319  */
3320 function assignment_reset_course_form_defaults($course) {
3321     return array('reset_assignment_submissions'=>1);
3324 /**
3325  * Returns all other caps used in module
3326  */
3327 function assignment_get_extra_capabilities() {
3328     return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames');
3331 /**
3332  * @param string $feature FEATURE_xx constant for requested feature
3333  * @return mixed True if module supports feature, null if doesn't know
3334  */
3335 function assignment_supports($feature) {
3336     switch($feature) {
3337         case FEATURE_GROUPS:                  return true;
3338         case FEATURE_GROUPINGS:               return true;
3339         case FEATURE_GROUPMEMBERSONLY:        return true;
3340         case FEATURE_MOD_INTRO:               return true;
3341         case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
3342         case FEATURE_GRADE_HAS_GRADE:         return true;
3343         case FEATURE_GRADE_OUTCOMES:          return true;
3344         case FEATURE_GRADE_HAS_GRADE:         return true;
3346         default: return null;
3347     }
3350 /**
3351  * Adds module specific settings to the settings block
3352  * 
3353  * @param settings_navigation $settings The settings navigation object
3354  * @param navigation_node $assignmentnode The node to add module settings to
3355  */
3356 function assignment_extend_settings_navigation(settings_navigation $settings, navigation_node $assignmentnode) {
3357     global $PAGE, $DB, $USER, $CFG;
3359     $assignmentrow = $DB->get_record("assignment", array("id" => $PAGE->cm->instance));
3360     require_once "$CFG->dirroot/mod/assignment/type/$assignmentrow->assignmenttype/assignment.class.php";
3361     
3362     $assignmentclass = 'assignment_'.$assignmentrow->assignmenttype;
3363     $assignmentinstance = new $assignmentclass($PAGE->cm->id, $assignmentrow, $PAGE->cm, $PAGE->course);
3365     $allgroups = false;
3367     // Add assignment submission information
3368     if (has_capability('mod/assignment:grade', $PAGE->cm->context)) {
3369         if ($allgroups && has_capability('moodle/site:accessallgroups', $PAGE->cm->context)) {
3370             $group = 0;
3371         } else {
3372             $group = groups_get_activity_group($PAGE->cm);
3373         }
3374         $link = new moodle_url('/mod/assignment/submissions.php', array('id'=>$PAGE->cm->id));
3375         if ($count = $assignmentinstance->count_real_submissions($group)) {
3376             $string = get_string('viewsubmissions', 'assignment', $count);
3377         } else {
3378             $string = get_string('noattempts', 'assignment');
3379         }
3380         $assignmentnode->add($string, $link, navigation_node::TYPE_SETTING);
3381     }
3383     if (is_object($assignmentinstance) && method_exists($assignmentinstance, 'extend_settings_navigation')) {
3384         $assignmentinstance->extend_settings_navigation($assignmentnode);
3385     }
3388 /**
3389  * generate zip file from array of given files
3390  * @param array $filesforzipping - array of files to pass into archive_to_pathname
3391  * @return path of temp file - note this returned file does not have a .zip extension - it is a temp file.
3392  */
3393 function assignment_pack_files($filesforzipping) {
3394         global $CFG;
3395         //create path for new zip file.
3396         $tempzip = tempnam($CFG->dataroot.'/temp/', 'assignment_');
3397         //zip files
3398         $zipper = new zip_packer();
3399         if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
3400       &nbs