3af7cfe7e1002c22f108f8f5fe32c9213b3433a4
[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 portfoliolib.php */
33 require_once($CFG->libdir.'/portfoliolib.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='') {
182         global $CFG;
185         if ($subpage) {
186             $navigation = build_navigation($subpage, $this->cm);
187         } else {
188             $navigation = build_navigation('', $this->cm);
189         }
191         print_header($this->pagetitle, $this->course->fullname, $navigation, '', '',
192                      true, update_module_button($this->cm->id, $this->course->id, $this->strassignment),
193                      navmenu($this->course, $this->cm));
195         groups_print_activity_menu($this->cm, 'view.php?id=' . $this->cm->id);
197         echo '<div class="reportlink">'.$this->submittedlink().'</div>';
198         echo '<div class="clearer"></div>';
199     }
202     /**
203      * Display the assignment intro
204      *
205      * This will most likely be extended by assignment type plug-ins
206      * The default implementation prints the assignment description in a box
207      */
208     function view_intro() {
209         print_simple_box_start('center', '', '', 0, 'generalbox', 'intro');
210         echo format_module_intro('assignment', $this->assignment, $this->cm->id);
211         print_simple_box_end();
212     }
214     /**
215      * Display the assignment dates
216      *
217      * Prints the assignment start and end dates in a box.
218      * This will be suitable for most assignment types
219      */
220     function view_dates() {
221         if (!$this->assignment->timeavailable && !$this->assignment->timedue) {
222             return;
223         }
225         print_simple_box_start('center', '', '', 0, 'generalbox', 'dates');
226         echo '<table>';
227         if ($this->assignment->timeavailable) {
228             echo '<tr><td class="c0">'.get_string('availabledate','assignment').':</td>';
229             echo '    <td class="c1">'.userdate($this->assignment->timeavailable).'</td></tr>';
230         }
231         if ($this->assignment->timedue) {
232             echo '<tr><td class="c0">'.get_string('duedate','assignment').':</td>';
233             echo '    <td class="c1">'.userdate($this->assignment->timedue).'</td></tr>';
234         }
235         echo '</table>';
236         print_simple_box_end();
237     }
240     /**
241      * Display the bottom and footer of a page
242      *
243      * This default method just prints the footer.
244      * This will be suitable for most assignment types
245      */
246     function view_footer() {
247         print_footer($this->course);
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;
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         print_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             print_user_picture($teacher, $this->course->id, $teacher->picture);
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 (!empty($USER->id)) {
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                 add_event($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                 update_event($event);
513             } else {
514                 $event = new object();
515                 $event->name        = $assignment->name;
516                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
517                 $event->courseid    = $assignment->course;
518                 $event->groupid     = 0;
519                 $event->userid      = 0;
520                 $event->modulename  = 'assignment';
521                 $event->instance    = $assignment->id;
522                 $event->eventtype   = 'due';
523                 $event->timestart   = $assignment->timedue;
524                 $event->timeduration = 0;
526                 add_event($event);
527             }
528         } else {
529             $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id));
530         }
532         // get existing grade item
533         assignment_grade_item_update($assignment);
535         return true;
536     }
538     /**
539      * Update grade item for this submission.
540      */
541     function update_grade($submission) {
542         assignment_update_grades($this->assignment, $submission->userid);
543     }
545     /**
546      * Top-level function for handling of submissions called by submissions.php
547      *
548      * This is for handling the teacher interaction with the grading interface
549      * This should be suitable for most assignment types.
550      *
551      * @global object
552      * @param string $mode Specifies the kind of teacher interaction taking place
553      */
554     function submissions($mode) {
555         ///The main switch is changed to facilitate
556         ///1) Batch fast grading
557         ///2) Skip to the next one on the popup
558         ///3) Save and Skip to the next one on the popup
560         //make user global so we can use the id
561         global $USER;
563         $mailinfo = optional_param('mailinfo', null, PARAM_BOOL);
564         if (is_null($mailinfo)) {
565             $mailinfo = get_user_preferences('assignment_mailinfo', 0);
566         } else {
567             set_user_preference('assignment_mailinfo', $mailinfo);
568         }
570         switch ($mode) {
571             case 'grade':                         // We are in a popup window grading
572                 if ($submission = $this->process_feedback()) {
573                     //IE needs proper header with encoding
574                     print_header(get_string('feedback', 'assignment').':'.format_string($this->assignment->name));
575                     print_heading(get_string('changessaved'));
576                     print $this->update_main_listing($submission);
577                 }
578                 close_window();
579                 break;
581             case 'single':                        // We are in a popup window displaying submission
582                 $this->display_submission();
583                 break;
585             case 'all':                          // Main window, display everything
586                 $this->display_submissions();
587                 break;
589             case 'fastgrade':
590                 ///do the fast grading stuff  - this process should work for all 3 subclasses
592                 $grading    = false;
593                 $commenting = false;
594                 $col        = false;
595                 if (isset($_POST['submissioncomment'])) {
596                     $col = 'submissioncomment';
597                     $commenting = true;
598                 }
599                 if (isset($_POST['menu'])) {
600                     $col = 'menu';
601                     $grading = true;
602                 }
603                 if (!$col) {
604                     //both submissioncomment and grade columns collapsed..
605                     $this->display_submissions();
606                     break;
607                 }
609                 foreach ($_POST[$col] as $id => $unusedvalue){
611                     $id = (int)$id; //clean parameter name
613                     $this->process_outcomes($id);
615                     if (!$submission = $this->get_submission($id)) {
616                         $submission = $this->prepare_new_submission($id);
617                         $newsubmission = true;
618                     } else {
619                         $newsubmission = false;
620                     }
621                     unset($submission->data1);  // Don't need to update this.
622                     unset($submission->data2);  // Don't need to update this.
624                     //for fast grade, we need to check if any changes take place
625                     $updatedb = false;
627                     if ($grading) {
628                         $grade = $_POST['menu'][$id];
629                         $updatedb = $updatedb || ($submission->grade != $grade);
630                         $submission->grade = $grade;
631                     } else {
632                         if (!$newsubmission) {
633                             unset($submission->grade);  // Don't need to update this.
634                         }
635                     }
636                     if ($commenting) {
637                         $commentvalue = trim($_POST['submissioncomment'][$id]);
638                         $updatedb = $updatedb || ($submission->submissioncomment != $commentvalue);
639                         $submission->submissioncomment = $commentvalue;
640                     } else {
641                         unset($submission->submissioncomment);  // Don't need to update this.
642                     }
644                     $submission->teacher    = $USER->id;
645                     if ($updatedb) {
646                         $submission->mailed = (int)(!$mailinfo);
647                     }
649                     $submission->timemarked = time();
651                     //if it is not an update, we don't change the last modified time etc.
652                     //this will also not write into database if no submissioncomment and grade is entered.
654                     if ($updatedb){
655                         if ($newsubmission) {
656                             if (!isset($submission->submissioncomment)) {
657                                 $submission->submissioncomment = '';
658                             }
659                             $sid = $DB->insert_record('assignment_submissions', $submission);
660                             $submission->id = $sid;
661                         } else {
662                             $DB->update_record('assignment_submissions', $submission);
663                         }
665                         // triger grade event
666                         $this->update_grade($submission);
668                         //add to log only if updating
669                         add_to_log($this->course->id, 'assignment', 'update grades',
670                                    'submissions.php?id='.$this->assignment->id.'&user='.$submission->userid,
671                                    $submission->userid, $this->cm->id);
672                     }
674                 }
676                 $message = notify(get_string('changessaved'), 'notifysuccess', 'center', true);
678                 $this->display_submissions($message);
679                 break;
682             case 'next':
683                 /// We are currently in pop up, but we want to skip to next one without saving.
684                 ///    This turns out to be similar to a single case
685                 /// The URL used is for the next submission.
687                 $this->display_submission();
688                 break;
690             case 'saveandnext':
691                 ///We are in pop up. save the current one and go to the next one.
692                 //first we save the current changes
693                 if ($submission = $this->process_feedback()) {
694                     //print_heading(get_string('changessaved'));
695                     $extra_javascript = $this->update_main_listing($submission);
696                 }
698                 //then we display the next submission
699                 $this->display_submission($extra_javascript);
700                 break;
702             default:
703                 echo "something seriously is wrong!!";
704                 break;
705         }
706     }
708     /**
709      * Helper method updating the listing on the main script from popup using javascript
710      *
711      * @global object
712      * @global object
713      * @param $submission object The submission whose data is to be updated on the main page
714      */
715     function update_main_listing($submission) {
716         global $SESSION, $CFG;
718         $output = '';
720         $perpage = get_user_preferences('assignment_perpage', 10);
722         $quickgrade = get_user_preferences('assignment_quickgrade', 0);
724         /// Run some Javascript to try and update the parent page
725         $output .= '<script type="text/javascript">'."\n<!--\n";
726         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['submissioncomment'])) {
727             if ($quickgrade){
728                 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid.'").value="'
729                 .trim($submission->submissioncomment).'";'."\n";
730              } else {
731                 $output.= 'opener.document.getElementById("com'.$submission->userid.
732                 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment)), 15)."\";\n";
733             }
734         }
736         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['grade'])) {
737             //echo optional_param('menuindex');
738             if ($quickgrade){
739                 $output.= 'opener.document.getElementById("menumenu'.$submission->userid.
740                 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT).'";'."\n";
741             } else {
742                 $output.= 'opener.document.getElementById("g'.$submission->userid.'").innerHTML="'.
743                 $this->display_grade($submission->grade)."\";\n";
744             }
745         }
746         //need to add student's assignments in there too.
747         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemodified']) &&
748             $submission->timemodified) {
749             $output.= 'opener.document.getElementById("ts'.$submission->userid.
750                  '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid)).userdate($submission->timemodified)."\";\n";
751         }
753         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemarked']) &&
754             $submission->timemarked) {
755             $output.= 'opener.document.getElementById("tt'.$submission->userid.
756                  '").innerHTML="'.userdate($submission->timemarked)."\";\n";
757         }
759         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['status'])) {
760             $output.= 'opener.document.getElementById("up'.$submission->userid.'").className="s1";';
761             $buttontext = get_string('update');
762             $button = link_to_popup_window ('/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;userid='.$submission->userid.'&amp;mode=single'.'&amp;offset='.(optional_param('offset', '', PARAM_INT)-1),
763                       'grade'.$submission->userid, $buttontext, 450, 700, $buttontext, 'none', true, 'button'.$submission->userid);
764             $output.= 'opener.document.getElementById("up'.$submission->userid.'").innerHTML="'.addslashes_js($button).'";';
765         }
767         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $submission->userid);
769         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['finalgrade'])) {
770             $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid.
771             '").innerHTML="'.$grading_info->items[0]->grades[$submission->userid]->str_grade.'";'."\n";
772         }
774         if (!empty($CFG->enableoutcomes) and empty($SESSION->flextable['mod-assignment-submissions']->collapse['outcome'])) {
776             if (!empty($grading_info->outcomes)) {
777                 foreach($grading_info->outcomes as $n=>$outcome) {
778                     if ($outcome->grades[$submission->userid]->locked) {
779                         continue;
780                     }
782                     if ($quickgrade){
783                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.
784                         '").selectedIndex="'.$outcome->grades[$submission->userid]->grade.'";'."\n";
786                     } else {
787                         $options = make_grades_menu(-$outcome->scaleid);
788                         $options[0] = get_string('nooutcome', 'grades');
789                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.'").innerHTML="'.$options[$outcome->grades[$submission->userid]->grade]."\";\n";
790                     }
792                 }
793             }
794         }
796         $output .= "\n-->\n</script>";
797         return $output;
798     }
800     /**
801      *  Return a grade in user-friendly form, whether it's a scale or not
802      *
803      * @global object
804      * @param mixed $grade
805      * @return string User-friendly representation of grade
806      */
807     function display_grade($grade) {
808         global $DB;
810         static $scalegrades = array();   // Cache scales for each assignment - they might have different scales!!
812         if ($this->assignment->grade >= 0) {    // Normal number
813             if ($grade == -1) {
814                 return '-';
815             } else {
816                 return $grade.' / '.$this->assignment->grade;
817             }
819         } else {                                // Scale
820             if (empty($scalegrades[$this->assignment->id])) {
821                 if ($scale = $DB->get_record('scale', array('id'=>-($this->assignment->grade)))) {
822                     $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
823                 } else {
824                     return '-';
825                 }
826             }
827             if (isset($scalegrades[$this->assignment->id][$grade])) {
828                 return $scalegrades[$this->assignment->id][$grade];
829             }
830             return '-';
831         }
832     }
834     /**
835      *  Display a single submission, ready for grading on a popup window
836      *
837      * This default method prints the teacher info and submissioncomment box at the top and
838      * the student info and submission at the bottom.
839      * This method also fetches the necessary data in order to be able to
840      * provide a "Next submission" button.
841      * Calls preprocess_submission() to give assignment type plug-ins a chance
842      * to process submissions before they are graded
843      * This method gets its arguments from the page parameters userid and offset
844      *
845      * @global object
846      * @global object
847      * @param string $extra_javascript
848      */
849     function display_submission($extra_javascript = '') {
850         global $CFG, $DB, $PAGE;
851         require_once($CFG->libdir.'/gradelib.php');
852         require_once($CFG->libdir.'/tablelib.php');
854         $userid = required_param('userid', PARAM_INT);
855         $offset = required_param('offset', PARAM_INT);//offset for where to start looking for student.
857         if (!$user = $DB->get_record('user', array('id'=>$userid))) {
858             print_error('nousers');
859         }
861         if (!$submission = $this->get_submission($user->id)) {
862             $submission = $this->prepare_new_submission($userid);
863         }
864         if ($submission->timemodified > $submission->timemarked) {
865             $subtype = 'assignmentnew';
866         } else {
867             $subtype = 'assignmentold';
868         }
870         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
871         $disabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
873     /// construct SQL, using current offset to find the data of the next student
874         $course     = $this->course;
875         $assignment = $this->assignment;
876         $cm         = $this->cm;
877         $context    = get_context_instance(CONTEXT_MODULE, $cm->id);
879         /// Get all ppl that can submit assignments
881         $currentgroup = groups_get_activity_group($cm);
882         if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $currentgroup, '', false)) {
883             $users = array_keys($users);
884         }
886         // if groupmembersonly used, remove users who are not in any group
887         if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
888             if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
889                 $users = array_intersect($users, array_keys($groupingusers));
890             }
891         }
893         $nextid = 0;
895         if ($users) {
896             $select = 'SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt,
897                               s.id AS submissionid, s.grade, s.submissioncomment,
898                               s.timemodified, s.timemarked,
899                               COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ';
900             $sql = 'FROM {user} u '.
901                    'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
902                                                                       AND s.assignment = '.$this->assignment->id.' '.
903                    'WHERE u.id IN ('.implode(',', $users).') ';
905             if ($sort = flexible_table::get_sql_sort('mod-assignment-submissions')) {
906                 $sort = 'ORDER BY '.$sort.' ';
907             }
909             if (($auser = $DB->get_records_sql($select.$sql.$sort, null, $offset+1, 1)) !== false) {
910                 $nextuser = array_shift($auser);
911             /// Calculate user status
912                 $nextuser->status = ($nextuser->timemarked > 0) && ($nextuser->timemarked >= $nextuser->timemodified);
913                 $nextid = $nextuser->id;
914             }
915         }
917         print_header(get_string('feedback', 'assignment').':'.fullname($user, true).':'.format_string($this->assignment->name));
919         /// Print any extra javascript needed for saveandnext
920         echo $extra_javascript;
922         echo $PAGE->requires->data_for_js('assignment', Array('nextid'=>$nextid, 'userid'=>$userid))->asap();
923         echo $PAGE->requires->js('mod/assignment/assignment.js')->asap();
925         echo '<table cellspacing="0" class="feedback '.$subtype.'" >';
927         ///Start of teacher info row
929         echo '<tr>';
930         echo '<td class="picture teacher">';
931         if ($submission->teacher) {
932             $teacher = $DB->get_record('user', array('id'=>$submission->teacher));
933         } else {
934             global $USER;
935             $teacher = $USER;
936         }
937         print_user_picture($teacher, $this->course->id, $teacher->picture);
938         echo '</td>';
939         echo '<td class="content">';
940         echo '<form id="submitform" action="submissions.php" method="post">';
941         echo '<div>'; // xhtml compatibility - invisiblefieldset was breaking layout here
942         echo '<input type="hidden" name="offset" value="'.($offset+1).'" />';
943         echo '<input type="hidden" name="userid" value="'.$userid.'" />';
944         echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
945         echo '<input type="hidden" name="mode" value="grade" />';
946         echo '<input type="hidden" name="menuindex" value="0" />';//selected menu index
948         //new hidden field, initialized to -1.
949         echo '<input type="hidden" name="saveuserid" value="-1" />';
951         if ($submission->timemarked) {
952             echo '<div class="from">';
953             echo '<div class="fullname">'.fullname($teacher, true).'</div>';
954             echo '<div class="time">'.userdate($submission->timemarked).'</div>';
955             echo '</div>';
956         }
957         echo '<div class="grade"><label for="menugrade">'.get_string('grade').'</label> ';
958         choose_from_menu(make_grades_menu($this->assignment->grade), 'grade', $submission->grade, get_string('nograde'), '', -1, false, $disabled);
959         echo '</div>';
961         echo '<div class="clearer"></div>';
962         echo '<div class="finalgrade">'.get_string('finalgrade', 'grades').': '.$grading_info->items[0]->grades[$userid]->str_grade.'</div>';
963         echo '<div class="clearer"></div>';
965         if (!empty($CFG->enableoutcomes)) {
966             foreach($grading_info->outcomes as $n=>$outcome) {
967                 echo '<div class="outcome"><label for="menuoutcome_'.$n.'">'.$outcome->name.'</label> ';
968                 $options = make_grades_menu(-$outcome->scaleid);
969                 if ($outcome->grades[$submission->userid]->locked) {
970                     $options[0] = get_string('nooutcome', 'grades');
971                     echo $options[$outcome->grades[$submission->userid]->grade];
972                 } else {
973                     choose_from_menu($options, 'outcome_'.$n.'['.$userid.']', $outcome->grades[$submission->userid]->grade, get_string('nooutcome', 'grades'), '', 0, false, false, 0, 'menuoutcome_'.$n);
974                 }
975                 echo '</div>';
976                 echo '<div class="clearer"></div>';
977             }
978         }
981         $this->preprocess_submission($submission);
983         if ($disabled) {
984             echo '<div class="disabledfeedback">'.$grading_info->items[0]->grades[$userid]->str_feedback.'</div>';
986         } else {
987             print_textarea($this->usehtmleditor, 14, 58, 0, 0, 'submissioncomment', $submission->submissioncomment, $this->course->id);
988             if ($this->usehtmleditor) {
989                 echo '<input type="hidden" name="format" value="'.FORMAT_HTML.'" />';
990             } else {
991                 echo '<div class="format">';
992                 choose_from_menu(format_text_menu(), "format", $submission->format, "");
993                 helpbutton("textformat", get_string("helpformatting"));
994                 echo '</div>';
995             }
996         }
998         $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? 'checked="checked"' : '';
1000         ///Print Buttons in Single View
1001         echo '<input type="hidden" name="mailinfo" value="0" />';
1002         echo '<input type="checkbox" id="mailinfo" name="mailinfo" value="1" '.$lastmailinfo.' /><label for="mailinfo">'.get_string('enableemailnotification','assignment').'</label>';
1003         echo '<div class="buttons">';
1004         echo '<input type="submit" name="submit" value="'.get_string('savechanges').'" onclick = "document.getElementById(\'submitform\').menuindex.value = document.getElementById(\'submitform\').grade.selectedIndex" />';
1005         echo '<input type="submit" name="cancel" value="'.get_string('cancel').'" />';
1006         //if there are more to be graded.
1007         if ($nextid) {
1008             echo '<input type="submit" name="saveandnext" value="'.get_string('saveandnext').'" onclick="saveNext()" />';
1009             echo '<input type="submit" name="next" value="'.get_string('next').'" onclick="setNext();" />';
1010         }
1011         echo '</div>';
1012         echo '</div></form>';
1014         $customfeedback = $this->custom_feedbackform($submission, true);
1015         if (!empty($customfeedback)) {
1016             echo $customfeedback;
1017         }
1019         echo '</td></tr>';
1021         ///End of teacher info row, Start of student info row
1022         echo '<tr>';
1023         echo '<td class="picture user">';
1024         print_user_picture($user, $this->course->id, $user->picture);
1025         echo '</td>';
1026         echo '<td class="topic">';
1027         echo '<div class="from">';
1028         echo '<div class="fullname">'.fullname($user, true).'</div>';
1029         if ($submission->timemodified) {
1030             echo '<div class="time">'.userdate($submission->timemodified).
1031                                      $this->display_lateness($submission->timemodified).'</div>';
1032         }
1033         echo '</div>';
1034         $this->print_user_files($user->id);
1035         echo '</td>';
1036         echo '</tr>';
1038         ///End of student info row
1040         echo '</table>';
1042         print_footer('none');
1043     }
1045     /**
1046      *  Preprocess submission before grading
1047      *
1048      * Called by display_submission()
1049      * The default type does nothing here.
1050      *
1051      * @param object $submission The submission object
1052      */
1053     function preprocess_submission(&$submission) {
1054     }
1056     /**
1057      *  Display all the submissions ready for grading
1058      *
1059      * @global object
1060      * @global object
1061      * @global object
1062      * @global object
1063      * @param string $message
1064      * @return bool|void
1065      */
1066     function display_submissions($message='') {
1067         global $CFG, $DB, $USER, $DB;
1068         require_once($CFG->libdir.'/gradelib.php');
1070         /* first we check to see if the form has just been submitted
1071          * to request user_preference updates
1072          */
1074         if (isset($_POST['updatepref'])){
1075             $perpage = optional_param('perpage', 10, PARAM_INT);
1076             $perpage = ($perpage <= 0) ? 10 : $perpage ;
1077             set_user_preference('assignment_perpage', $perpage);
1078             set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
1079         }
1081         /* next we get perpage and quickgrade (allow quick grade) params
1082          * from database
1083          */
1084         $perpage    = get_user_preferences('assignment_perpage', 10);
1086         $quickgrade = get_user_preferences('assignment_quickgrade', 0);
1088         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);
1090         if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
1091             $uses_outcomes = true;
1092         } else {
1093             $uses_outcomes = false;
1094         }
1096         $page    = optional_param('page', 0, PARAM_INT);
1097         $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
1099     /// Some shortcuts to make the code read better
1101         $course     = $this->course;
1102         $assignment = $this->assignment;
1103         $cm         = $this->cm;
1105         $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
1106         add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->cm->id, $this->assignment->id, $this->cm->id);
1107         $navigation = build_navigation($this->strsubmissions, $this->cm);
1108         print_header_simple(format_string($this->assignment->name,true), "", $navigation,
1109                 '', '', true, update_module_button($cm->id, $course->id, $this->strassignment), navmenu($course, $cm));
1111         $course_context = get_context_instance(CONTEXT_COURSE, $course->id);
1112         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
1113             echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">'
1114                 . get_string('seeallcoursegrades', 'grades') . '</a></div>';
1115         }
1117         if (!empty($message)) {
1118             echo $message;   // display messages here if any
1119         }
1121         $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1123     /// Check to see if groups are being used in this assignment
1125         /// find out current groups mode
1126         $groupmode = groups_get_activity_groupmode($cm);
1127         $currentgroup = groups_get_activity_group($cm, true);
1128         groups_print_activity_menu($cm, 'submissions.php?id=' . $this->cm->id);
1130         /// Get all ppl that are allowed to submit assignments
1131         if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $currentgroup, '', false)) {
1132             $users = array_keys($users);
1133         }
1135         // if groupmembersonly used, remove users who are not in any group
1136         if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
1137             if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1138                 $users = array_intersect($users, array_keys($groupingusers));
1139             }
1140         }
1142         $tablecolumns = array('picture', 'fullname', 'grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade');
1143         if ($uses_outcomes) {
1144             $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
1145         }
1147         $tableheaders = array('',
1148                               get_string('fullname'),
1149                               get_string('grade'),
1150                               get_string('comment', 'assignment'),
1151                               get_string('lastmodified').' ('.get_string('submission', 'assignment').')',
1152                               get_string('lastmodified').' ('.get_string('grade').')',
1153                               get_string('status'),
1154                               get_string('finalgrade', 'grades'));
1155         if ($uses_outcomes) {
1156             $tableheaders[] = get_string('outcome', 'grades');
1157         }
1159         require_once($CFG->libdir.'/tablelib.php');
1160         $table = new flexible_table('mod-assignment-submissions');
1162         $table->define_columns($tablecolumns);
1163         $table->define_headers($tableheaders);
1164         $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;currentgroup='.$currentgroup);
1166         $table->sortable(true, 'lastname');//sorted by lastname by default
1167         $table->collapsible(true);
1168         $table->initialbars(true);
1170         $table->column_suppress('picture');
1171         $table->column_suppress('fullname');
1173         $table->column_class('picture', 'picture');
1174         $table->column_class('fullname', 'fullname');
1175         $table->column_class('grade', 'grade');
1176         $table->column_class('submissioncomment', 'comment');
1177         $table->column_class('timemodified', 'timemodified');
1178         $table->column_class('timemarked', 'timemarked');
1179         $table->column_class('status', 'status');
1180         $table->column_class('finalgrade', 'finalgrade');
1181         if ($uses_outcomes) {
1182             $table->column_class('outcome', 'outcome');
1183         }
1185         $table->set_attribute('cellspacing', '0');
1186         $table->set_attribute('id', 'attempts');
1187         $table->set_attribute('class', 'submissions');
1188         $table->set_attribute('width', '100%');
1189         //$table->set_attribute('align', 'center');
1191         $table->no_sorting('finalgrade');
1192         $table->no_sorting('outcome');
1194         // Start working -- this is necessary as soon as the niceties are over
1195         $table->setup();
1197         if (empty($users)) {
1198             print_heading(get_string('nosubmitusers','assignment'));
1199             return true;
1200         }
1202     /// Construct the SQL
1204         if ($where = $table->get_sql_where()) {
1205             $where .= ' AND ';
1206         }
1208         if ($sort = $table->get_sql_sort()) {
1209             $sort = ' ORDER BY '.$sort;
1210         }
1212         $select = 'SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt,
1213                           s.id AS submissionid, s.grade, s.submissioncomment,
1214                           s.timemodified, s.timemarked,
1215                           COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ';
1216         $sql = 'FROM {user} u '.
1217                'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1218                                                                   AND s.assignment = '.$this->assignment->id.' '.
1219                'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1221         $table->pagesize($perpage, count($users));
1223         ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1224         $offset = $page * $perpage;
1226         $strupdate = get_string('update');
1227         $strgrade  = get_string('grade');
1228         $grademenu = make_grades_menu($this->assignment->grade);
1230         if (($ausers = $DB->get_records_sql($select.$sql.$sort, null, $table->get_page_start(), $table->get_page_size())) !== false) {
1231             $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
1232             foreach ($ausers as $auser) {
1233                 $final_grade = $grading_info->items[0]->grades[$auser->id];
1234                 $grademax = $grading_info->items[0]->grademax;
1235                 $final_grade->formatted_grade = round($final_grade->grade,2) .' / ' . round($grademax,2);
1236                 $locked_overridden = 'locked';
1237                 if ($final_grade->overridden) {
1238                     $locked_overridden = 'overridden';
1239                 }
1241             /// Calculate user status
1242                 $auser->status = ($auser->timemarked > 0) && ($auser->timemarked >= $auser->timemodified);
1243                 $picture = print_user_picture($auser, $course->id, $auser->picture, false, true);
1245                 if (empty($auser->submissionid)) {
1246                     $auser->grade = -1; //no submission yet
1247                 }
1249                 if (!empty($auser->submissionid)) {
1250                 ///Prints student answer and student modified date
1251                 ///attach file or print link to student answer, depending on the type of the assignment.
1252                 ///Refer to print_student_answer in inherited classes.
1253                     if ($auser->timemodified > 0) {
1254                         $studentmodified = '<div id="ts'.$auser->id.'">'.$this->print_student_answer($auser->id)
1255                                          . userdate($auser->timemodified).'</div>';
1256                     } else {
1257                         $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1258                     }
1259                 ///Print grade, dropdown or text
1260                     if ($auser->timemarked > 0) {
1261                         $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
1263                         if ($final_grade->locked or $final_grade->overridden) {
1264                             $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1265                         } else if ($quickgrade) {
1266                             $menu = choose_from_menu(make_grades_menu($this->assignment->grade),
1267                                                      'menu['.$auser->id.']', $auser->grade,
1268                                                      get_string('nograde'),'',-1,true,false,$tabindex++);
1269                             $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
1270                         } else {
1271                             $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1272                         }
1274                     } else {
1275                         $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1276                         if ($final_grade->locked or $final_grade->overridden) {
1277                             $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1278                         } else if ($quickgrade) {
1279                             $menu = choose_from_menu(make_grades_menu($this->assignment->grade),
1280                                                      'menu['.$auser->id.']', $auser->grade,
1281                                                      get_string('nograde'),'',-1,true,false,$tabindex++);
1282                             $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1283                         } else {
1284                             $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1285                         }
1286                     }
1287                 ///Print Comment
1288                     if ($final_grade->locked or $final_grade->overridden) {
1289                         $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';
1291                     } else if ($quickgrade) {
1292                         $comment = '<div id="com'.$auser->id.'">'
1293                                  . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1294                                  . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1295                     } else {
1296                         $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
1297                     }
1298                 } else {
1299                     $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1300                     $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1301                     $status          = '<div id="st'.$auser->id.'">&nbsp;</div>';
1303                     if ($final_grade->locked or $final_grade->overridden) {
1304                         $grade = '<div id="g'.$auser->id.'">'.$final_grade->formatted_grade . '</div>';
1305                     } else if ($quickgrade) {   // allow editing
1306                         $menu = choose_from_menu(make_grades_menu($this->assignment->grade),
1307                                                  'menu['.$auser->id.']', $auser->grade,
1308                                                  get_string('nograde'),'',-1,true,false,$tabindex++);
1309                         $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1310                     } else {
1311                         $grade = '<div id="g'.$auser->id.'">-</div>';
1312                     }
1314                     if ($final_grade->locked or $final_grade->overridden) {
1315                         $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
1316                     } else if ($quickgrade) {
1317                         $comment = '<div id="com'.$auser->id.'">'
1318                                  . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1319                                  . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1320                     } else {
1321                         $comment = '<div id="com'.$auser->id.'">&nbsp;</div>';
1322                     }
1323                 }
1325                 if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
1326                     $auser->status = 0;
1327                 } else {
1328                     $auser->status = 1;
1329                 }
1331                 $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
1333                 ///No more buttons, we use popups ;-).
1334                 $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1335                            . '&amp;userid='.$auser->id.'&amp;mode=single'.'&amp;offset='.$offset++;
1336                 $button = link_to_popup_window ($popup_url, 'grade'.$auser->id, $buttontext, 600, 780,
1337                                                 $buttontext, 'none', true, 'button'.$auser->id);
1339                 $status  = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
1341                 $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';
1343                 $outcomes = '';
1345                 if ($uses_outcomes) {
1347                     foreach($grading_info->outcomes as $n=>$outcome) {
1348                         $outcomes .= '<div class="outcome"><label>'.$outcome->name.'</label>';
1349                         $options = make_grades_menu(-$outcome->scaleid);
1351                         if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
1352                             $options[0] = get_string('nooutcome', 'grades');
1353                             $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
1354                         } else {
1355                             $outcomes .= ' ';
1356                             $outcomes .= choose_from_menu($options, 'outcome_'.$n.'['.$auser->id.']',
1357                                         $outcome->grades[$auser->id]->grade, get_string('nooutcome', 'grades'), '', 0, true, false, 0, 'outcome_'.$n.'_'.$auser->id);
1358                         }
1359                         $outcomes .= '</div>';
1360                     }
1361                 }
1363                                 $userlink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $auser->id . '&amp;course=' . $course->id . '">' . fullname($auser) . '</a>';
1364                 $row = array($picture, $userlink, $grade, $comment, $studentmodified, $teachermodified, $status, $finalgrade);
1365                 if ($uses_outcomes) {
1366                     $row[] = $outcomes;
1367                 }
1369                 $table->add_data($row);
1370             }
1371         }
1373         /// Print quickgrade form around the table
1374         if ($quickgrade){
1375             echo '<form action="submissions.php" id="fastg" method="post">';
1376             echo '<div>';
1377             echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
1378             echo '<input type="hidden" name="mode" value="fastgrade" />';
1379             echo '<input type="hidden" name="page" value="'.$page.'" />';
1380             echo '</div>';
1381         }
1383         $table->print_html();  /// Print the whole table
1385         if ($quickgrade){
1386             $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? 'checked="checked"' : '';
1387             echo '<div class="fgcontrols">';
1388             echo '<div class="emailnotification">';
1389             echo '<label for="mailinfo">'.get_string('enableemailnotification','assignment').'</label>';
1390             echo '<input type="hidden" name="mailinfo" value="0" />';
1391             echo '<input type="checkbox" id="mailinfo" name="mailinfo" value="1" '.$lastmailinfo.' />';
1392             helpbutton('emailnotification', get_string('enableemailnotification', 'assignment'), 'assignment').'</p></div>';
1393             echo '</div>';
1394             echo '<div class="fastgbutton"><input type="submit" name="fastg" value="'.get_string('saveallfeedback', 'assignment').'" /></div>';
1395             echo '</div>';
1396             echo '</form>';
1397         }
1398         /// End of fast grading form
1400         /// Mini form for setting user preference
1401         echo '<div class="qgprefs">';
1402         echo '<form id="options" action="submissions.php?id='.$this->cm->id.'" method="post"><div>';
1403         echo '<input type="hidden" name="updatepref" value="1" />';
1404         echo '<table id="optiontable">';
1405         echo '<tr><td>';
1406         echo '<label for="perpage">'.get_string('pagesize','assignment').'</label>';
1407         echo '</td>';
1408         echo '<td>';
1409         echo '<input type="text" id="perpage" name="perpage" size="1" value="'.$perpage.'" />';
1410         helpbutton('pagesize', get_string('pagesize','assignment'), 'assignment');
1411         echo '</td></tr>';
1412         echo '<tr><td>';
1413         echo '<label for="quickgrade">'.get_string('quickgrade','assignment').'</label>';
1414         echo '</td>';
1415         echo '<td>';
1416         $checked = $quickgrade ? 'checked="checked"' : '';
1417         echo '<input type="checkbox" id="quickgrade" name="quickgrade" value="1" '.$checked.' />';
1418         helpbutton('quickgrade', get_string('quickgrade', 'assignment'), 'assignment').'</p></div>';
1419         echo '</td></tr>';
1420         echo '<tr><td colspan="2">';
1421         echo '<input type="submit" value="'.get_string('savepreferences').'" />';
1422         echo '</td></tr></table>';
1423         echo '</div></form></div>';
1424         ///End of mini form
1425         print_footer($this->course);
1426     }
1428     /**
1429      *  Process teacher feedback submission
1430      *
1431      * This is called by submissions() when a grading even has taken place.
1432      * It gets its data from the submitted form.
1433      *
1434      * @global object
1435      * @global object
1436      * @global object
1437      * @return object|bool The updated submission object or false
1438      */
1439     function process_feedback() {
1440         global $CFG, $USER, $DB;
1441         require_once($CFG->libdir.'/gradelib.php');
1443         if (!$feedback = data_submitted()) {      // No incoming data?
1444             return false;
1445         }
1447         ///For save and next, we need to know the userid to save, and the userid to go
1448         ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1449         ///as the userid to store
1450         if ((int)$feedback->saveuserid !== -1){
1451             $feedback->userid = $feedback->saveuserid;
1452         }
1454         if (!empty($feedback->cancel)) {          // User hit cancel button
1455             return false;
1456         }
1458         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);
1460         // store outcomes if needed
1461         $this->process_outcomes($feedback->userid);
1463         $submission = $this->get_submission($feedback->userid, true);  // Get or make one
1465         if (!$grading_info->items[0]->grades[$feedback->userid]->locked and
1466             !$grading_info->items[0]->grades[$feedback->userid]->overridden) {
1468             $submission->grade      = $feedback->grade;
1469             $submission->submissioncomment    = $feedback->submissioncomment;
1470             $submission->format     = $feedback->format;
1471             $submission->teacher    = $USER->id;
1472             $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1473             if (!$mailinfo) {
1474                 $submission->mailed = 1;       // treat as already mailed
1475             } else {
1476                 $submission->mailed = 0;       // Make sure mail goes out (again, even)
1477             }
1478             $submission->timemarked = time();
1480             unset($submission->data1);  // Don't need to update this.
1481             unset($submission->data2);  // Don't need to update this.
1483             if (empty($submission->timemodified)) {   // eg for offline assignments
1484                 // $submission->timemodified = time();
1485             }
1487             $DB->update_record('assignment_submissions', $submission);
1489             // triger grade event
1490             $this->update_grade($submission);
1492             add_to_log($this->course->id, 'assignment', 'update grades',
1493                        'submissions.php?id='.$this->assignment->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
1494         }
1496         return $submission;
1498     }
1500     function process_outcomes($userid) {
1501         global $CFG, $USER;
1503         if (empty($CFG->enableoutcomes)) {
1504             return;
1505         }
1507         require_once($CFG->libdir.'/gradelib.php');
1509         if (!$formdata = data_submitted()) {
1510             return;
1511         }
1513         $data = array();
1514         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
1516         if (!empty($grading_info->outcomes)) {
1517             foreach($grading_info->outcomes as $n=>$old) {
1518                 $name = 'outcome_'.$n;
1519                 if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
1520                     $data[$n] = $formdata->{$name}[$userid];
1521                 }
1522             }
1523         }
1524         if (count($data) > 0) {
1525             grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1526         }
1528     }
1530     /**
1531      * Load the submission object for a particular user
1532      *
1533      * @global object
1534      * @global object
1535      * @param $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1536      * @param $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1537      * @param bool $teachermodified student submission set if false
1538      * @return object The submission
1539      */
1540     function get_submission($userid=0, $createnew=false, $teachermodified=false) {
1541         global $USER, $DB;
1543         if (empty($userid)) {
1544             $userid = $USER->id;
1545         }
1547         $submission = $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1549         if ($submission || !$createnew) {
1550             return $submission;
1551         }
1552         $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
1553         $DB->insert_record("assignment_submissions", $newsubmission);
1555         return $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1556     }
1558     /**
1559      * Instantiates a new submission object for a given user
1560      *
1561      * Sets the assignment, userid and times, everything else is set to default values.
1562      *
1563      * @param int $userid The userid for which we want a submission object
1564      * @param bool $teachermodified student submission set if false
1565      * @return object The submission
1566      */
1567     function prepare_new_submission($userid, $teachermodified=false) {
1568         $submission = new Object;
1569         $submission->assignment   = $this->assignment->id;
1570         $submission->userid       = $userid;
1571         //$submission->timecreated  = time();
1572         $submission->timecreated = '';
1573         // teachers should not be modifying modified date, except offline assignments
1574         if ($teachermodified) {
1575             $submission->timemodified = 0;
1576         } else {
1577             $submission->timemodified = $submission->timecreated;
1578         }
1579         $submission->numfiles     = 0;
1580         $submission->data1        = '';
1581         $submission->data2        = '';
1582         $submission->grade        = -1;
1583         $submission->submissioncomment      = '';
1584         $submission->format       = 0;
1585         $submission->teacher      = 0;
1586         $submission->timemarked   = 0;
1587         $submission->mailed       = 0;
1588         return $submission;
1589     }
1591     /**
1592      * Return all assignment submissions by ENROLLED students (even empty)
1593      *
1594      * @param string $sort optional field names for the ORDER BY in the sql query
1595      * @param string $dir optional specifying the sort direction, defaults to DESC
1596      * @return array The submission objects indexed by id
1597      */
1598     function get_submissions($sort='', $dir='DESC') {
1599         return assignment_get_all_submissions($this->assignment, $sort, $dir);
1600     }
1602     /**
1603      * Counts all real assignment submissions by ENROLLED students (not empty ones)
1604      *
1605      * @param int $groupid optional If nonzero then count is restricted to this group
1606      * @return int The number of submissions
1607      */
1608     function count_real_submissions($groupid=0) {
1609         return assignment_count_real_submissions($this->cm, $groupid);
1610     }
1612     /**
1613      * Alerts teachers by email of new or changed assignments that need grading
1614      *
1615      * First checks whether the option to email teachers is set for this assignment.
1616      * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1617      * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1618      *
1619      * @global object
1620      * @global object
1621      * @param $submission object The submission that has changed
1622      * @return void
1623      */
1624     function email_teachers($submission) {
1625         global $CFG, $DB;
1627         if (empty($this->assignment->emailteachers)) {          // No need to do anything
1628             return;
1629         }
1631         $user = $DB->get_record('user', array('id'=>$submission->userid));
1633         if ($teachers = $this->get_graders($user)) {
1635             $strassignments = get_string('modulenameplural', 'assignment');
1636             $strassignment  = get_string('modulename', 'assignment');
1637             $strsubmitted  = get_string('submitted', 'assignment');
1639             foreach ($teachers as $teacher) {
1640                 $info = new object();
1641                 $info->username = fullname($user, true);
1642                 $info->assignment = format_string($this->assignment->name,true);
1643                 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
1645                 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1646                 $posttext = $this->email_teachers_text($info);
1647                 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
1649                 $eventdata = new object();
1650                 $eventdata->modulename       = 'assignment';
1651                 $eventdata->userfrom         = $user;
1652                 $eventdata->userto           = $teacher;
1653                 $eventdata->subject          = $postsubject;
1654                 $eventdata->fullmessage      = $posttext;
1655                 $eventdata->fullmessageformat = FORMAT_PLAIN;
1656                 $eventdata->fullmessagehtml  = $posthtml;
1657                 $eventdata->smallmessage     = '';
1658                 if ( events_trigger('message_send', $eventdata) > 0 ){
1659                 }
1660             }
1661         }
1662     }
1664     /**
1665      * @param string $filearea
1666      * @param array $args
1667      * @return bool
1668      */
1669     function send_file($filearea, $args) {
1670         debugging('plugin does not implement file sending', DEBUG_DEVELOPER);
1671         return false;
1672     }
1674     /**
1675      * Returns a list of teachers that should be grading given submission
1676      *
1677      * @param object $user
1678      * @return array
1679      */
1680     function get_graders($user) {
1681         //potential graders
1682         $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false);
1684         $graders = array();
1685         if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) {   // Separate groups are being used
1686             if ($groups = groups_get_all_groups($this->course->id, $user->id)) {  // Try to find all groups
1687                 foreach ($groups as $group) {
1688                     foreach ($potgraders as $t) {
1689                         if ($t->id == $user->id) {
1690                             continue; // do not send self
1691                         }
1692                         if (groups_is_member($group->id, $t->id)) {
1693                             $graders[$t->id] = $t;
1694                         }
1695                     }
1696                 }
1697             } else {
1698                 // user not in group, try to find graders without group
1699                 foreach ($potgraders as $t) {
1700                     if ($t->id == $user->id) {
1701                         continue; // do not send self
1702                     }
1703                     if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
1704                         $graders[$t->id] = $t;
1705                     }
1706                 }
1707             }
1708         } else {
1709             foreach ($potgraders as $t) {
1710                 if ($t->id == $user->id) {
1711                     continue; // do not send self
1712                 }
1713                 $graders[$t->id] = $t;
1714             }
1715         }
1716         return $graders;
1717     }
1719     /**
1720      * Creates the text content for emails to teachers
1721      *
1722      * @param $info object The info used by the 'emailteachermail' language string
1723      * @return string
1724      */
1725     function email_teachers_text($info) {
1726         $posttext  = format_string($this->course->shortname).' -> '.$this->strassignments.' -> '.
1727                      format_string($this->assignment->name)."\n";
1728         $posttext .= '---------------------------------------------------------------------'."\n";
1729         $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
1730         $posttext .= "\n---------------------------------------------------------------------\n";
1731         return $posttext;
1732     }
1734      /**
1735      * Creates the html content for emails to teachers
1736      *
1737      * @param $info object The info used by the 'emailteachermailhtml' language string
1738      * @return string
1739      */
1740     function email_teachers_html($info) {
1741         global $CFG;
1742         $posthtml  = '<p><font face="sans-serif">'.
1743                      '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname).'</a> ->'.
1744                      '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
1745                      '<a href="'.$CFG->wwwroot.'/mod/assignment/view.php?id='.$this->cm->id.'">'.format_string($this->assignment->name).'</a></font></p>';
1746         $posthtml .= '<hr /><font face="sans-serif">';
1747         $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
1748         $posthtml .= '</font><hr />';
1749         return $posthtml;
1750     }
1752     /**
1753      * Produces a list of links to the files uploaded by a user
1754      *
1755      * @param $userid int optional id of the user. If 0 then $USER->id is used.
1756      * @param $return boolean optional defaults to false. If true the list is returned rather than printed
1757      * @return string optional
1758      */
1759     function print_user_files($userid=0, $return=false) {
1760         global $CFG, $USER, $OUTPUT;
1762         if (!$userid) {
1763             if (!isloggedin()) {
1764                 return '';
1765             }
1766             $userid = $USER->id;
1767         }
1769         $output = '';
1771         $fs = get_file_storage();
1772         $browser = get_file_browser();
1774         $found = false;
1776         if ($files = $fs->get_area_files($this->context->id, 'assignment_submission', $userid, "timemodified", false)) {
1777             $button = new portfolio_add_button();
1778             foreach ($files as $file) {
1779                 $filename = $file->get_filename();
1780                 $found = true;
1781                 $mimetype = $file->get_mimetype();
1782                 $icon = str_replace(array('.gif', '.png'), '', mimeinfo_from_type('icon', $mimetype));
1783                 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/assignment_submission/'.$userid.'/'.$filename);
1784                 $output .= '<a href="'.$path.'" ><img src="'.$OUTPUT->old_icon_url('f/'.$icon).'" class="icon" alt="'.$icon.'" />'.s($filename).'</a>';
1785                 if ($this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1786                     $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id, 'fileid' => $file->get_id()));
1787                     $button->set_formats(portfolio_format_from_file($file));
1788                     $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
1789                 }
1790                 $output .= '<br />';
1791             }
1792             if (count($files) > 1  && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1793                 $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id));
1794                 $button->set_formats(PORTFOLIO_PORMAT_FILE);
1795                 $output .= '<br />'  . $button->to_html();
1796             }
1797         }
1799         $output = '<div class="files">'.$output.'</div>';
1801         if ($return) {
1802             return $output;
1803         }
1804         echo $output;
1805     }
1807     /**
1808      * Count the files uploaded by a given user
1809      *
1810      * @param $userid int The user id
1811      * @return int
1812      */
1813     function count_user_files($userid) {
1814         $fs = get_file_storage();
1815         $files = $fs->get_area_files($this->context->id, 'assignment_submission', $userid, "id", false);
1816         return count($files);
1817     }
1819     /**
1820      * Returns true if the student is allowed to submit
1821      *
1822      * Checks that the assignment has started and, if the option to prevent late
1823      * submissions is set, also checks that the assignment has not yet closed.
1824      * @return boolean
1825      */
1826     function isopen() {
1827         $time = time();
1828         if ($this->assignment->preventlate && $this->assignment->timedue) {
1829             return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
1830         } else {
1831             return ($this->assignment->timeavailable <= $time);
1832         }
1833     }
1836     /**
1837      * Return true if is set description is hidden till available date
1838      *
1839      * This is needed by calendar so that hidden descriptions do not
1840      * come up in upcoming events.
1841      *
1842      * Check that description is hidden till available date
1843      * By default return false
1844      * Assignments types should implement this method if needed
1845      * @return boolen
1846      */
1847     function description_is_hidden() {
1848         return false;
1849     }
1851     /**
1852      * Return an outline of the user's interaction with the assignment
1853      *
1854      * The default method prints the grade and timemodified
1855      * @param $user object
1856      * @return object with properties ->info and ->time
1857      */
1858     function user_outline($user) {
1859         if ($submission = $this->get_submission($user->id)) {
1861             $result = new object();
1862             $result->info = get_string('grade').': '.$this->display_grade($submission->grade);
1863             $result->time = $submission->timemodified;
1864             return $result;
1865         }
1866         return NULL;
1867     }
1869     /**
1870      * Print complete information about the user's interaction with the assignment
1871      *
1872      * @param $user object
1873      */
1874     function user_complete($user) {
1875         if ($submission = $this->get_submission($user->id)) {
1877             $fs = get_file_storage();
1878             $browser = get_file_browser();
1880             if ($files = $fs->get_area_files($this->context->id, 'assignment_submission', $user->id, "timemodified", false)) {
1881                 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
1882                 foreach ($files as $file) {
1883                     $countfiles .= "; ".$file->get_filename();
1884                 }
1885             }
1887             print_simple_box_start();
1888             echo get_string("lastmodified").": ";
1889             echo userdate($submission->timemodified);
1890             echo $this->display_lateness($submission->timemodified);
1892             $this->print_user_files($user->id);
1894             echo '<br />';
1896             if (empty($submission->timemarked)) {
1897                 print_string("notgradedyet", "assignment");
1898             } else {
1899                 $this->view_feedback($submission);
1900             }
1902             print_simple_box_end();
1904         } else {
1905             print_string("notsubmittedyet", "assignment");
1906         }
1907     }
1909     /**
1910      * Return a string indicating how late a submission is
1911      *
1912      * @param $timesubmitted int
1913      * @return string
1914      */
1915     function display_lateness($timesubmitted) {
1916         return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
1917     }
1919     /**
1920      * Empty method stub for all delete actions.
1921      */
1922     function delete() {
1923         //nothing by default
1924         redirect('view.php?id='.$this->cm->id);
1925     }
1927     /**
1928      * Empty custom feedback grading form.
1929      */
1930     function custom_feedbackform($submission, $return=false) {
1931         //nothing by default
1932         return '';
1933     }
1935     /**
1936      * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
1937      * for the course (see resource).
1938      *
1939      * Given a course_module object, this function returns any "extra" information that may be needed
1940      * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
1941      *
1942      * @param $coursemodule object The coursemodule object (record).
1943      * @return object An object on information that the coures will know about (most noticeably, an icon).
1944      *
1945      */
1946     function get_coursemodule_info($coursemodule) {
1947         return false;
1948     }
1950     /**
1951      * Plugin cron method - do not use $this here, create new assignment instances if needed.
1952      * @return void
1953      */
1954     function cron() {
1955         //no plugin cron by default - override if needed
1956     }
1958     /**
1959      * Reset all submissions
1960      */
1961     function reset_userdata($data) {
1962         global $CFG, $DB;
1964         if (!$DB->count_records('assignment', array('course'=>$data->courseid, 'assignmenttype'=>$this->type))) {
1965             return array(); // no assignments of this type present
1966         }
1968         $componentstr = get_string('modulenameplural', 'assignment');
1969         $status = array();
1971         $typestr = get_string('type'.$this->type, 'assignment');
1973         if (!empty($data->reset_assignment_submissions)) {
1974             $assignmentssql = "SELECT a.id
1975                                  FROM {assignment} a
1976                                 WHERE a.course=? AND a.assignmenttype=?";
1977             $params = array($data->courseid, $this->type);
1979             // now get rid of all submissions and responses
1980             $fs = get_file_storage();
1981             if ($assignments = $DB->get_records_sql($assignmentssql, $params)) {
1982                 foreach ($assignments as $assignmentid=>$unused) {
1983                     if (!$cm = get_coursemodule_from_instance('assignment', $assignmentid)) {
1984                         continue;
1985                     }
1986                     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1987                     $fs->delete_area_files($context->id, 'assignment_submission');
1988                     $fs->delete_area_files($context->id, 'assignment_response');
1989                 }
1990             }
1992             $DB->delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)", $params);
1994             $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
1996             if (empty($data->reset_gradebook_grades)) {
1997                 // remove all grades from gradebook
1998                 assignment_reset_gradebook($data->courseid, $this->type);
1999             }
2000         }
2002         /// updating dates - shift may be negative too
2003         if ($data->timeshift) {
2004             shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
2005             $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
2006         }
2008         return $status;
2009     }
2012     function portfolio_exportable() {
2013         return false;
2014     }
2015 } ////// End of the assignment_base class
2017 /**
2018  * @package   mod-assignment
2019  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
2020  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2021  */
2022 class mod_assignment_upload_file_form extends moodleform {
2023     function definition() {
2024         $mform = $this->_form;
2025         $instance = $this->_customdata;
2027         //TODO: improve upload size checking
2028         $mform->setMaxFileSize($instance->assignment->maxbytes);
2030         // visible elements
2031         $mform->addElement('file', 'newfile', get_string('uploadafile'));
2033         // hidden params
2034         $mform->addElement('hidden', 'id', $instance->cm->id);
2035         $mform->setType('id', PARAM_INT);
2036         $mform->addElement('hidden', 'action', 'uploadfile');
2037         $mform->setType('action', PARAM_ALPHA);
2039         // buttons
2040         $this->add_action_buttons(false, get_string('uploadthisfile'));
2041     }
2045 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
2047 /**
2048  * Deletes an assignment instance
2049  *
2050  * This is done by calling the delete_instance() method of the assignment type class
2051  */
2052 function assignment_delete_instance($id){
2053     global $CFG, $DB;
2055     if (! $assignment = $DB->get_record('assignment', array('id'=>$id))) {
2056         return false;
2057     }
2059     // fall back to base class if plugin missing
2060     $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2061     if (file_exists($classfile)) {
2062         require_once($classfile);
2063         $assignmentclass = "assignment_$assignment->assignmenttype";
2065     } else {
2066         debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
2067         $assignmentclass = "assignment_base";
2068     }
2070     $ass = new $assignmentclass();
2071     return $ass->delete_instance($assignment);
2075 /**
2076  * Updates an assignment instance
2077  *
2078  * This is done by calling the update_instance() method of the assignment type class
2079  */
2080 function assignment_update_instance($assignment){
2081     global $CFG;
2083     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2085     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2086     $assignmentclass = "assignment_$assignment->assignmenttype";
2087     $ass = new $assignmentclass();
2088     return $ass->update_instance($assignment);
2092 /**
2093  * Adds an assignment instance
2094  *
2095  * This is done by calling the add_instance() method of the assignment type class
2096  */
2097 function assignment_add_instance($assignment) {
2098     global $CFG;
2100     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2102     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2103     $assignmentclass = "assignment_$assignment->assignmenttype";
2104     $ass = new $assignmentclass();
2105     return $ass->add_instance($assignment);
2109 /**
2110  * Returns an outline of a user interaction with an assignment
2111  *
2112  * This is done by calling the user_outline() method of the assignment type class
2113  */
2114 function assignment_user_outline($course, $user, $mod, $assignment) {
2115     global $CFG;
2117     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2118     $assignmentclass = "assignment_$assignment->assignmenttype";
2119     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2120     return $ass->user_outline($user);
2123 /**
2124  * Prints the complete info about a user's interaction with an assignment
2125  *
2126  * This is done by calling the user_complete() method of the assignment type class
2127  */
2128 function assignment_user_complete($course, $user, $mod, $assignment) {
2129     global $CFG;
2131     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2132     $assignmentclass = "assignment_$assignment->assignmenttype";
2133     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2134     return $ass->user_complete($user);
2137 /**
2138  * Function to be run periodically according to the moodle cron
2139  *
2140  * Finds all assignment notifications that have yet to be mailed out, and mails them
2141  */
2142 function assignment_cron () {
2143     global $CFG, $USER, $DB;
2145     /// first execute all crons in plugins
2146     if ($plugins = get_plugin_list('assignment')) {
2147         foreach ($plugins as $plugin=>$dir) {
2148             require_once("$dir/assignment.class.php");
2149             $assignmentclass = "assignment_$plugin";
2150             $ass = new $assignmentclass();
2151             $ass->cron();
2152         }
2153     }
2155     /// Notices older than 1 day will not be mailed.  This is to avoid the problem where
2156     /// cron has not been running for a long time, and then suddenly people are flooded
2157     /// with mail from the past few weeks or months
2159     $timenow   = time();
2160     $endtime   = $timenow - $CFG->maxeditingtime;
2161     $starttime = $endtime - 24 * 3600;   /// One day earlier
2163     if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2165         $realuser = clone($USER);
2167         foreach ($submissions as $key => $submission) {
2168             if (! $DB->set_field("assignment_submissions", "mailed", "1", array("id"=>$submission->id))) {
2169                 echo "Could not update the mailed field for id $submission->id.  Not mailed.\n";
2170                 unset($submissions[$key]);
2171             }
2172         }
2174         $timenow = time();
2176         foreach ($submissions as $submission) {
2178             echo "Processing assignment submission $submission->id\n";
2180             if (! $user = $DB->get_record("user", array("id"=>$submission->userid))) {
2181                 echo "Could not find user $post->userid\n";
2182                 continue;
2183             }
2185             if (! $course = $DB->get_record("course", array("id"=>$submission->course))) {
2186                 echo "Could not find course $submission->course\n";
2187                 continue;
2188             }
2190             /// Override the language and timezone of the "current" user, so that
2191             /// mail is customised for the receiver.
2192             cron_setup_user($user, $course);
2194             if (!has_capability('moodle/course:view', get_context_instance(CONTEXT_COURSE, $submission->course), $user->id)) {
2195                 echo fullname($user)." not an active participant in " . format_string($course->shortname) . "\n";
2196                 continue;
2197             }
2199             if (! $teacher = $DB->get_record("user", array("id"=>$submission->teacher))) {
2200                 echo "Could not find teacher $submission->teacher\n";
2201                 continue;
2202             }
2204             if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2205                 echo "Could not find course module for assignment id $submission->assignment\n";
2206                 continue;
2207             }
2209             if (! $mod->visible) {    /// Hold mail notification for hidden assignments until later
2210                 continue;
2211             }
2213             $strassignments = get_string("modulenameplural", "assignment");
2214             $strassignment  = get_string("modulename", "assignment");
2216             $assignmentinfo = new object();
2217             $assignmentinfo->teacher = fullname($teacher);
2218             $assignmentinfo->assignment = format_string($submission->name,true);
2219             $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2221             $postsubject = "$course->shortname: $strassignments: ".format_string($submission->name,true);
2222             $posttext  = "$course->shortname -> $strassignments -> ".format_string($submission->name,true)."\n";
2223             $posttext .= "---------------------------------------------------------------------\n";
2224             $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2225             $posttext .= "---------------------------------------------------------------------\n";
2227             if ($user->mailformat == 1) {  // HTML
2228                 $posthtml = "<p><font face=\"sans-serif\">".
2229                 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> ->".
2230                 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2231                 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2232                 $posthtml .= "<hr /><font face=\"sans-serif\">";
2233                 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2234                 $posthtml .= "</font><hr />";
2235             } else {
2236                 $posthtml = "";
2237             }
2239             $eventdata = new object();
2240             $eventdata->modulename       = 'assignment';
2241             $eventdata->userfrom         = $teacher;
2242             $eventdata->userto           = $user;
2243             $eventdata->subject          = $postsubject;
2244             $eventdata->fullmessage      = $posttext;
2245             $eventdata->fullmessageformat = FORMAT_PLAIN;
2246             $eventdata->fullmessagehtml  = $posthtml;
2247             $eventdata->smallmessage     = '';
2248             if ( events_trigger('message_send', $eventdata) > 0 ){
2249                 echo "Error: assignment cron: Could not send out mail for id $submission->id to user $user->id ($user->email)\n";
2250             }
2251         }
2253         cron_setup_user();
2254     }
2256     return true;
2259 /**
2260  * Return grade for given user or all users.
2261  *
2262  * @param int $assignmentid id of assignment
2263  * @param int $userid optional user id, 0 means all users
2264  * @return array array of grades, false if none
2265  */
2266 function assignment_get_user_grades($assignment, $userid=0) {
2267     global $CFG, $DB;
2269     if ($userid) {
2270         $user = "AND u.id = :userid";
2271         $params = array('userid'=>$userid);
2272     } else {
2273         $user = "";
2274     }
2275     $params['aid'] = $assignment->id;
2277     $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2278                    s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2279               FROM {user} u, {assignment_submissions} s
2280              WHERE u.id = s.userid AND s.assignment = :aid
2281                    $user";
2283     return $DB->get_records_sql($sql, $params);
2286 /**
2287  * Update activity grades
2288  *
2289  * @param object $assignment
2290  * @param int $userid specific user only, 0 means all
2291  */
2292 function assignment_update_grades($assignment, $userid=0, $nullifnone=true) {
2293     global $CFG, $DB;
2294     require_once($CFG->libdir.'/gradelib.php');
2296     if ($assignment->grade == 0) {
2297         assignment_grade_item_update($assignment);
2299     } else if ($grades = assignment_get_user_grades($assignment, $userid)) {
2300         foreach($grades as $k=>$v) {
2301             if ($v->rawgrade == -1) {
2302                 $grades[$k]->rawgrade = null;
2303             }
2304         }
2305         assignment_grade_item_update($assignment, $grades);
2307     } else {
2308         assignment_grade_item_update($assignment);
2309     }
2312 /**
2313  * Update all grades in gradebook.
2314  */
2315 function assignment_upgrade_grades() {
2316     global $DB;
2318     $sql = "SELECT COUNT('x')
2319               FROM {assignment} a, {course_modules} cm, {modules} m
2320              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2321     $count = $DB->count_records_sql($sql);
2323     $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
2324               FROM {assignment} a, {course_modules} cm, {modules} m
2325              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2326     if ($rs = $DB->get_recordset_sql($sql)) {
2327         // too much debug output
2328         $pbar = new progress_bar('assignmentupgradegrades', 500, true);
2329         $i=0;
2330         foreach ($rs as $assignment) {
2331             $i++;
2332             upgrade_set_timeout(60*5); // set up timeout, may also abort execution
2333             assignment_update_grades($assignment);
2334             $pbar->update($i, $count, "Updating Assignment grades ($i/$count).");
2335         }
2336         $rs->close();
2337         upgrade_set_timeout(); // reset to default timeout
2338     }
2341 /**
2342  * Create grade item for given assignment
2343  *
2344  * @param object $assignment object with extra cmidnumber
2345  * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
2346  * @return int 0 if ok, error code otherwise
2347  */
2348 function assignment_grade_item_update($assignment, $grades=NULL) {
2349     global $CFG;
2350     require_once($CFG->libdir.'/gradelib.php');
2352     if (!isset($assignment->courseid)) {
2353         $assignment->courseid = $assignment->course;
2354     }
2356     $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
2358     if ($assignment->grade > 0) {
2359         $params['gradetype'] = GRADE_TYPE_VALUE;
2360         $params['grademax']  = $assignment->grade;
2361         $params['grademin']  = 0;
2363     } else if ($assignment->grade < 0) {
2364         $params['gradetype'] = GRADE_TYPE_SCALE;
2365         $params['scaleid']   = -$assignment->grade;
2367     } else {
2368         $params['gradetype'] = GRADE_TYPE_TEXT; // allow text comments only
2369     }
2371     if ($grades  === 'reset') {
2372         $params['reset'] = true;
2373         $grades = NULL;
2374     }
2376     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades, $params);
2379 /**
2380  * Delete grade item for given assignment
2381  *
2382  * @param object $assignment object
2383  * @return object assignment
2384  */
2385 function assignment_grade_item_delete($assignment) {
2386     global $CFG;
2387     require_once($CFG->libdir.'/gradelib.php');
2389     if (!isset($assignment->courseid)) {
2390         $assignment->courseid = $assignment->course;
2391     }
2393     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
2396 /**
2397  * Returns the users with data in one assignment (students and teachers)
2398  *
2399  * @param $assignmentid int
2400  * @return array of user objects
2401  */
2402 function assignment_get_participants($assignmentid) {
2403     global $CFG, $DB;
2405     //Get students
2406     $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2407                                         FROM {user} u,
2408                                              {assignment_submissions} a
2409                                        WHERE a.assignment = ? and
2410                                              u.id = a.userid", array($assignmentid));
2411     //Get teachers
2412     $teachers = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2413                                         FROM {user} u,
2414                                              {assignment_submissions} a
2415                                        WHERE a.assignment = ? and
2416                                              u.id = a.teacher", array($assignmentid));
2418     //Add teachers to students
2419     if ($teachers) {
2420         foreach ($teachers as $teacher) {
2421             $students[$teacher->id] = $teacher;
2422         }
2423     }
2424     //Return students array (it contains an array of unique users)
2425     return ($students);
2428 function assignment_pluginfile($course, $cminfo, $context, $filearea, $args) {
2429     global $CFG, $DB;
2431     if (!$assignment = $DB->get_record('assignment', array('id'=>$cminfo->instance))) {
2432         return false;
2433     }
2434     if (!$cm = get_coursemodule_from_instance('assignment', $assignment->id, $course->id)) {
2435         return false;
2436     }
2438     require_once($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
2439     $assignmentclass = 'assignment_'.$assignment->assignmenttype;
2440     $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm, $course);
2442     return $assignmentinstance->send_file($filearea, $args);
2444 /**
2445  * Checks if a scale is being used by an assignment
2446  *
2447  * This is used by the backup code to decide whether to back up a scale
2448  * @param $assignmentid int
2449  * @param $scaleid int
2450  * @return boolean True if the scale is used by the assignment
2451  */
2452 function assignment_scale_used($assignmentid, $scaleid) {
2453     global $DB;
2455     $return = false;
2457     $rec = $DB->get_record('assignment', array('id'=>$assignmentid,'grade'=>-$scaleid));
2459     if (!empty($rec) && !empty($scaleid)) {
2460         $return = true;
2461     }
2463     return $return;
2466 /**
2467  * Checks if scale is being used by any instance of assignment
2468  *
2469  * This is used to find out if scale used anywhere
2470  * @param $scaleid int
2471  * @return boolean True if the scale is used by any assignment
2472  */
2473 function assignment_scale_used_anywhere($scaleid) {
2474     global $DB;
2476     if ($scaleid and $DB->record_exists('assignment', array('grade'=>-$scaleid))) {
2477         return true;
2478     } else {
2479         return false;
2480     }
2483 /**
2484  * Make sure up-to-date events are created for all assignment instances
2485  *
2486  * This standard function will check all instances of this module
2487  * and make sure there are up-to-date events created for each of them.
2488  * If courseid = 0, then every assignment event in the site is checked, else
2489  * only assignment events belonging to the course specified are checked.
2490  * This function is used, in its new format, by restore_refresh_events()
2491  *
2492  * @param $courseid int optional If zero then all assignments for all courses are covered
2493  * @return boolean Always returns true
2494  */
2495 function assignment_refresh_events($courseid = 0) {
2496     global $DB;
2498     if ($courseid == 0) {
2499         if (! $assignments = $DB->get_records("assignment")) {
2500             return true;
2501         }
2502     } else {
2503         if (! $assignments = $DB->get_records("assignment", array("course"=>$courseid))) {
2504             return true;
2505         }
2506     }
2507     $moduleid = $DB->get_field('modules', 'id', array('name'=>'assignment'));
2509     foreach ($assignments as $assignment) {
2510         $cm = get_coursemodule_from_id('assignment', $assignment->id);
2511         $event = new object();
2512         $event->name        = $assignment->name;
2513         $event->description = format_module_intro('assignment', $assignment, $cm->id);
2514         $event->timestart   = $assignment->timedue;
2516         if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
2517             update_event($event);
2519         } else {
2520             $event->courseid    = $assignment->course;
2521             $event->groupid     = 0;
2522             $event->userid      = 0;
2523             $event->modulename  = 'assignment';
2524             $event->instance    = $assignment->id;
2525             $event->eventtype   = 'due';
2526             $event->timeduration = 0;
2527             $event->visible     = $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$assignment->id));
2528             add_event($event);
2529         }
2531     }
2532     return true;
2535 /**
2536  * Print recent activity from all assignments in a given course
2537  *
2538  * This is used by the recent activity block
2539  */
2540 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
2541     global $CFG, $USER, $DB;
2543     // do not use log table if possible, it may be huge
2545     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
2546                                                      u.firstname, u.lastname, u.email, u.picture
2547                                                 FROM {assignment_submissions} asb
2548                                                      JOIN {assignment} a      ON a.id = asb.assignment
2549                                                      JOIN {course_modules} cm ON cm.instance = a.id
2550                                                      JOIN {modules} md        ON md.id = cm.module
2551                                                      JOIN {user} u            ON u.id = asb.userid
2552                                                WHERE asb.timemodified > ? AND
2553                                                      a.course = ? AND
2554                                                      md.name = 'assignment'
2555                                             ORDER BY asb.timemodified ASC", array($timestart, $course->id))) {
2556          return false;
2557     }
2559     $modinfo =& get_fast_modinfo($course); // reference needed because we might load the groups
2560     $show    = array();
2561     $grader  = array();
2563     foreach($submissions as $submission) {
2564         if (!array_key_exists($submission->cmid, $modinfo->cms)) {
2565             continue;
2566         }
2567         $cm = $modinfo->cms[$submission->cmid];
2568         if (!$cm->uservisible) {
2569             continue;
2570         }
2571         if ($submission->userid == $USER->id) {
2572             $show[] = $submission;
2573             continue;
2574         }
2576         // the act of sumbitting of assignment may be considered private - only graders will see it if specified
2577         if (empty($CFG->assignment_showrecentsubmissions)) {
2578             if (!array_key_exists($cm->id, $grader)) {
2579                 $grader[$cm->id] = has_capability('moodle/grade:viewall', get_context_instance(CONTEXT_MODULE, $cm->id));
2580             }
2581             if (!$grader[$cm->id]) {
2582                 continue;
2583             }
2584         }
2586         $groupmode = groups_get_activity_groupmode($cm, $course);
2588         if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2589             if (isguestuser()) {
2590                 // shortcut - guest user does not belong into any group
2591                 continue;
2592             }
2594             if (is_null($modinfo->groups)) {
2595                 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2596             }
2598             // this will be slow - show only users that share group with me in this cm
2599             if (empty($modinfo->groups[$cm->id])) {
2600                 continue;
2601             }
2602             $usersgroups =  groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
2603             if (is_array($usersgroups)) {
2604                 $usersgroups = array_keys($usersgroups);
2605                 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2606                 if (empty($intersect)) {
2607                     continue;
2608                 }
2609             }
2610         }
2611         $show[] = $submission;
2612     }
2614     if (empty($show)) {
2615         return false;
2616     }
2618     print_headline(get_string('newsubmissions', 'assignment').':');
2620     foreach ($show as $submission) {
2621         $cm = $modinfo->cms[$submission->cmid];
2622         $link = $CFG->wwwroot.'/mod/assignment/view.php?id='.$cm->id;
2623         print_recent_activity_note($submission->timemodified, $submission, $cm->name, $link, false, $viewfullnames);
2624     }
2626     return true;
2630 /**
2631  * Returns all assignments since a given time in specified forum.
2632  */
2633 function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0)  {
2634     global $CFG, $COURSE, $USER, $DB;
2636     if ($COURSE->id == $courseid) {
2637         $course = $COURSE;
2638     } else {
2639         $course = $DB->get_record('course', array('id'=>$courseid));
2640     }
2642     $modinfo =& get_fast_modinfo($course);
2644     $cm = $modinfo->cms[$cmid];
2646     $params = array();
2647     if ($userid) {
2648         $userselect = "AND u.id = :userid";
2649         $params['userid'] = $userid;
2650     } else {
2651         $userselect = "";
2652     }
2654     if ($groupid) {
2655         $groupselect = "AND gm.groupid = :groupid";
2656         $groupjoin   = "JOIN {groups_members} gm ON  gm.userid=u.id";
2657         $params['groupid'] = $groupid;
2658     } else {
2659         $groupselect = "";
2660         $groupjoin   = "";
2661     }
2663     $params['cminstance'] = $cm->instance;
2664     $params['timestart'] = $timestart;
2666     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, asb.userid,
2667                                                      u.firstname, u.lastname, u.email, u.picture
2668                                                 FROM {assignment_submissions} asb
2669                                                 JOIN {assignment} a      ON a.id = asb.assignment
2670                                                 JOIN {user} u            ON u.id = asb.userid
2671                                           $groupjoin
2672                                                WHERE asb.timemodified > :timestart AND a.id = :cminstance
2673                                                      $userselect $groupselect
2674                                             ORDER BY asb.timemodified ASC", $params)) {
2675          return;
2676     }
2678     $groupmode       = groups_get_activity_groupmode($cm, $course);
2679     $cm_context      = get_context_instance(CONTEXT_MODULE, $cm->id);
2680     $grader          = has_capability('moodle/grade:viewall', $cm_context);
2681     $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
2682     $viewfullnames   = has_capability('moodle/site:viewfullnames', $cm_context);
2684     if (is_null($modinfo->groups)) {
2685         $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2686     }
2688     $show = array();
2690     foreach($submissions as $submission) {
2691         if ($submission->userid == $USER->id) {
2692             $show[] = $submission;
2693             continue;
2694         }
2695         // the act of submitting of assignment may be considered private - only graders will see it if specified
2696         if (empty($CFG->assignment_showrecentsubmissions)) {
2697             if (!$grader) {
2698                 continue;
2699             }
2700         }
2702         if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
2703             if (isguestuser()) {
2704                 // shortcut - guest user does not belong into any group
2705                 continue;
2706             }
2708             // this will be slow - show only users that share group with me in this cm
2709             if (empty($modinfo->groups[$cm->id])) {
2710                 continue;
2711             }
2712             $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
2713             if (is_array($usersgroups)) {
2714                 $usersgroups = array_keys($usersgroups);
2715                 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2716                 if (empty($intersect)) {
2717                     continue;
2718                 }
2719             }
2720         }
2721         $show[] = $submission;
2722     }
2724     if (empty($show)) {
2725         return;
2726     }
2728     if ($grader) {
2729         require_once($CFG->libdir.'/gradelib.php');
2730         $userids = array();
2731         foreach ($show as $id=>$submission) {
2732             $userids[] = $submission->userid;
2734         }
2735         $grades = grade_get_grades($courseid, 'mod', 'assignment', $cm->instance, $userids);
2736     }
2738     $aname = format_string($cm->name,true);
2739     foreach ($show as $submission) {
2740         $tmpactivity = new object();
2742         $tmpactivity->type         = 'assignment';
2743         $tmpactivity->cmid         = $cm->id;
2744         $tmpactivity->name         = $aname;
2745         $tmpactivity->sectionnum   = $cm->sectionnum;
2746         $tmpactivity->timestamp    = $submission->timemodified;
2748         if ($grader) {
2749             $tmpactivity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
2750         }
2752         $tmpactivity->user->userid   = $submission->userid;
2753         $tmpactivity->user->fullname = fullname($submission, $viewfullnames);
2754         $tmpactivity->user->picture  = $submission->picture;
2756         $activities[$index++] = $tmpactivity;
2757     }
2759     return;
2762 /**
2763  * Print recent activity from all assignments in a given course
2764  *
2765  * This is used by course/recent.php
2766  */
2767 function assignment_print_recent_mod_activity($activity, $courseid, $detail, $modnames)  {
2768     global $CFG, $OUTPUT;
2770     echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
2772     echo "<tr><td class=\"userpicture\" valign=\"top\">";
2773     print_user_picture($activity->user->userid, $courseid, $activity->user->picture);
2774     echo "</td><td>";
2776     if ($detail) {
2777         $modname = $modnames[$activity->type];
2778         echo '<div class="title">';
2779         echo "<img src=\"" . $OUTPUT->mod_icon_url('icon', 'assignment') . "\" ".
2780              "class=\"icon\" alt=\"$modname\">";
2781         echo "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id={$activity->cmid}\">{$activity->name}</a>";
2782         echo '</div>';
2783     }
2785     if (isset($activity->grade)) {
2786         echo '<div class="grade">';
2787         echo get_string('grade').': ';
2788         echo $activity->grade;
2789         echo '</div>';
2790     }
2792     echo '<div class="user">';
2793     echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->userid}&amp;course=$courseid\">"
2794          ."{$activity->user->fullname}</a>  - ".userdate($activity->timestamp);
2795     echo '</div>';
2797     echo "</td></tr></table>";
2800 /// GENERIC SQL FUNCTIONS
2802 /**
2803  * Fetch info from logs
2804  *
2805  * @param $log object with properties ->info (the assignment id) and ->userid
2806  * @return array with assignment name and user firstname and lastname
2807  */
2808 function assignment_log_info($log) {
2809     global $CFG, $DB;
2811     return $DB->get_record_sql("SELECT a.name, u.firstname, u.lastname
2812                                   FROM {assignment} a, {user} u
2813                                  WHERE a.id = ? AND u.id = ?", array($log->info, $log->userid));
2816 /**
2817  * Return list of marked submissions that have not been mailed out for currently enrolled students
2818  *
2819  * @return array
2820  */
2821 function assignment_get_unmailed_submissions($starttime, $endtime) {
2822     global $CFG, $DB;
2824     return $DB->get_records_sql("SELECT s.*, a.course, a.name
2825                                    FROM {assignment_submissions} s,
2826                                         {assignment} a
2827                                   WHERE s.mailed = 0
2828                                         AND s.timemarked <= ?
2829                                         AND s.timemarked >= ?
2830                                         AND s.assignment = a.id", array($endtime, $starttime));
2833 /**
2834  * Counts all real assignment submissions by ENROLLED students (not empty ones)
2835  *
2836  * There are also assignment type methods count_real_submissions() wich in the default
2837  * implementation simply call this function.
2838  * @param $groupid int optional If nonzero then count is restricted to this group
2839  * @return int The number of submissions
2840  */
2841 function assignment_count_real_submissions($cm, $groupid=0) {
2842     global $CFG, $DB;
2844     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2846     // this is all the users with this capability set, in this context or higher
2847     if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $groupid, '', false)) {
2848         $users = array_keys($users);
2849     }
2851     // if groupmembersonly used, remove users who are not in any group
2852     if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
2853         if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
2854             $users = array_intersect($users, array_keys($groupingusers));
2855         }
2856     }
2858     if (empty($users)) {
2859         return 0;
2860     }
2862     $userlists = implode(',', $users);
2864     return $DB->count_records_sql("SELECT COUNT('x')
2865                                      FROM {assignment_submissions}
2866                                     WHERE assignment = ? AND
2867                                           timemodified > 0 AND
2868                                           userid IN ($userlists)", array($cm->instance));
2872 /**
2873  * Return all assignment submissions by ENROLLED students (even empty)
2874  *
2875  * There are also assignment type methods get_submissions() wich in the default
2876  * implementation simply call this function.
2877  * @param $sort string optional field names for the ORDER BY in the sql query
2878  * @param $dir string optional specifying the sort direction, defaults to DESC
2879  * @return array The submission objects indexed by id
2880  */
2881 function assignment_get_all_submissions($assignment, $sort="", $dir="DESC") {
2882 /// Return all assignment submissions by ENROLLED students (even empty)
2883     global $CFG, $DB;
2885     if ($sort == "lastname" or $sort == "firstname") {
2886         $sort = "u.$sort $dir";
2887     } else if (empty($sort)) {
2888         $sort = "a.timemodified DESC";
2889     } else {
2890         $sort = "a.$sort $dir";
2891     }
2893     /* not sure this is needed at all since assignmenet already has a course define, so this join?
2894     $select = "s.course = '$assignment->course' AND";
2895     if ($assignment->course == SITEID) {
2896         $select = '';
2897     }*/
2899     return $DB->get_records_sql("SELECT a.*
2900                                    FROM {assignment_submissions} a, {user} u
2901                                   WHERE u.id = a.userid
2902                                         AND a.assignment = ?
2903                                ORDER BY $sort", array($assignment->id));
2907 /**
2908  * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
2909  * for the course (see resource).
2910  *
2911  * Given a course_module object, this function returns any "extra" information that may be needed
2912  * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
2913  *
2914  * @param $coursemodule object The coursemodule object (record).
2915  * @return object An object on information that the coures will know about (most noticeably, an icon).
2916  *
2917  */
2918 function assignment_get_coursemodule_info($coursemodule) {
2919     global $CFG, $DB;
2921     if (! $assignment = $DB->get_record('assignment', array('id'=>$coursemodule->instance), 'id, assignmenttype, name')) {
2922         return false;
2923     }
2925     $libfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2927     if (file_exists($libfile)) {
2928         require_once($libfile);
2929         $assignmentclass = "assignment_$assignment->assignmenttype";
2930         $ass = new $assignmentclass('staticonly');
2931         if ($result = $ass->get_coursemodule_info($coursemodule)) {
2932             return $result;
2933         } else {
2934             $info = new object();
2935             $info->name = $assignment->name;
2936             return $info;
2937         }
2939     } else {
2940         debugging('Incorrect assignment type: '.$assignment->assignmenttype);
2941         return false;
2942     }
2947 /// OTHER GENERAL FUNCTIONS FOR ASSIGNMENTS  ///////////////////////////////////////
2949 /**
2950  * Returns an array of installed assignment types indexed and sorted by name
2951  *
2952  * @return array The index is the name of the assignment type, the value its full name from the language strings
2953  */
2954 function assignment_types() {
2955     $types = array();
2956     $names = get_plugin_list('assignment');
2957     foreach ($names as $name=>$dir) {
2958         $types[$name] = get_string('type'.$name, 'assignment');
2959     }
2960     asort($types);
2961     return $types;
2964 function assignment_print_overview($courses, &$htmlarray) {
2965     global $USER, $CFG, $DB;
2967     if (empty($courses) || !is_array($courses) || count($courses) == 0) {
2968         return array();
2969     }
2971     if (!$assignments = get_all_instances_in_courses('assignment',$courses)) {
2972         return;
2973     }
2975     $assignmentids = array();
2977     // Do assignment_base::isopen() here without loading the whole thing for speed
2978     foreach ($assignments as $key => $assignment) {
2979         $time = time();
2980         if ($assignment->timedue) {
2981             if ($assignment->preventlate) {
2982                 $isopen = ($assignment->timeavailable <= $time && $time <= $assignment->timedue);
2983             } else {
2984                 $isopen = ($assignment->timeavailable <= $time);
2985             }
2986         }
2987         if (empty($isopen) || empty($assignment->timedue)) {
2988             unset($assignments[$key]);
2989         }else{
2990             $assignmentids[] = $assignment->id;
2991         }
2992     }
2994     if(empty($assignmentids)){
2995         // no assigments to look at - we're done
2996         return true;
2997     }
2999     $strduedate = get_string('duedate', 'assignment');
3000     $strduedateno = get_string('duedateno', 'assignment');
3001     $strgraded = get_string('graded', 'assignment');
3002     $strnotgradedyet = get_string('notgradedyet', 'assignment');
3003     $strnotsubmittedyet = get_string('notsubmittedyet', 'assignment');
3004     $strsubmitted = get_string('submitted', 'assignment');
3005     $strassignment = get_string('modulename', 'assignment');
3006     $strreviewed = get_string('reviewed','assignment');
3009     // NOTE: we do all possible database work here *outside* of the loop to ensure this scales 
3010     //
3011     list($sqlassignmentids, $assignmentidparams) = $DB->get_in_or_equal($assignmentids);
3012     
3013     // build up and array of unmarked submissions indexed by assigment id/ userid
3014     // for use where the user has grading rights on assigment
3015     $rs = $DB->get_recordset_sql("SELECT id, assignment, userid 
3016                             FROM {assignment_submissions}
3017                             WHERE teacher = 0 AND timemarked = 0
3018                             AND assignment $sqlassignmentids", $assignmentidparams);
3020     $unmarkedsubmissions = array();
3021     foreach ($rs as $rd) {
3022         $unmarkedsubmissions[$rd->assignment][$rd->userid] = $rd->id;
3023     }
3024     $rs->close();
3027     // get all user submissions, indexed by assigment id
3028     $mysubmissions = $DB->get_records_sql("SELECT assignment, timemarked, teacher, grade
3029                                       FROM {assignment_submissions}
3030                                       WHERE userid = ? AND 
3031                                       assignment $sqlassignmentids", array_merge(array($USER->id), $assignmentidparams));
3033     foreach ($assignments as $assignment) {
3034         $str = '<div class="assignment overview"><div class="name">'.$strassignment. ': '.
3035                '<a '.($assignment->visible ? '':' class="dimmed"').
3036                'title="'.$strassignment.'" href="'.$CFG->wwwroot.
3037                '/mod/assignment/view.php?id='.$assignment->coursemodule.'">'.
3038                $assignment->name.'</a></div>';
3039         if ($assignment->timedue) {
3040             $str .= '<div class="info">'.$strduedate.': '.userdate($assignment->timedue).'</div>';
3041         } else {
3042             $str .= '<div class="info">'.$strduedateno.'</div>';
3043         }
3044         $context = get_context_instance(CONTEXT_MODULE, $assignment->coursemodule);
3045         if (has_capability('mod/assignment:grade', $context)) {
3047             // count how many people can submit
3048             $submissions = 0; // init
3049             if ($students = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', 0, '', false)) {
3050                 foreach($students as $student){
3051                     if(isset($unmarkedsubmissions[$assignment->id][$student->id])){
3052                         $submissions++;
3053                     }
3054                 }
3055             }
3057             if ($submissions) {
3058                 $str .= get_string('submissionsnotgraded', 'assignment', $submissions);
3059             }
3060         } else {
3061             if(isset($mysubmissions[$assignment->id])){
3063                 $submission = $mysubmissions[$assignment->id];
3065                 if ($submission->teacher == 0 && $submission->timemarked == 0) {
3066                     $str .= $strsubmitted . ', ' . $strnotgradedyet;
3067                 } else if ($submission->grade <= 0) {
3068                     $str .= $strsubmitted . ', ' . $strreviewed;
3069                 } else {
3070                     $str .= $strsubmitted . ', ' . $strgraded;
3071                 }
3072             } else {
3073                 $str .= $strnotsubmittedyet . ' ' . assignment_display_lateness(time(), $assignment->timedue);
3074             }
3075         }
3076         $str .= '</div>';
3077         if (empty($htmlarray[$assignment->course]['assignment'])) {
3078             $htmlarray[$assignment->course]['assignment'] = $str;
3079         } else {
3080             $htmlarray[$assignment->course]['assignment'] .= $str;
3081         }
3082     }
3085 function assignment_display_lateness($timesubmitted, $timedue) {
3086     if (!$timedue) {
3087         return '';
3088     }
3089     $time = $timedue - $timesubmitted;
3090     if ($time < 0) {
3091         $timetext = get_string('late', 'assignment', format_time($time));
3092         return ' (<span class="late">'.$timetext.'</span>)';
3093     } else {
3094         $timetext = get_string('early', 'assignment', format_time($time));
3095         return ' (<span class="early">'.$timetext.'</span>)';
3096     }
3099 function assignment_get_view_actions() {
3100     return array('view');
3103 function assignment_get_post_actions() {
3104     return array('upload');
3107 function assignment_get_types() {
3108     global $CFG;
3109     $types = array();
3111     $type = new object();
3112     $type->modclass = MOD_CLASS_ACTIVITY;
3113     $type->type = "assignment_group_start";
3114     $type->typestr = '--'.get_string('modulenameplural', 'assignment');
3115     $types[] = $type;
3117     $standardassignments = array('upload','online','uploadsingle','offline');
3118     foreach ($standardassignments as $assignmenttype) {
3119         $type = new object();
3120         $type->modclass = MOD_CLASS_ACTIVITY;
3121         $type->type = "assignment&amp;type=$assignmenttype";
3122         $type->typestr = get_string("type$assignmenttype", 'assignment');
3123         $types[] = $type;
3124     }
3126     /// Drop-in extra assignment types
3127     $assignmenttypes = get_list_of_plugins('mod/assignment/type');
3128     foreach ($assignmenttypes as $assignmenttype) {
3129         if (!empty($CFG->{'assignment_hide_'.$assignmenttype})) {  // Not wanted
3130             continue;
3131         }
3132         if (!in_array($assignmenttype, $standardassignments)) {
3133             $type = new object();
3134             $type->modclass = MOD_CLASS_ACTIVITY;
3135             $type->type = "assignment&amp;type=$assignmenttype";
3136             $type->typestr = get_string("type$assignmenttype", 'assignment');
3137             $types[] = $type;
3138         }
3139     }
3141     $type = new object();
3142     $type->modclass = MOD_CLASS_ACTIVITY;
3143     $type->type = "assignment_group_end";
3144     $type->typestr = '--';
3145     $types[] = $type;
3147     return $types;
3150 /**
3151  * Removes all grades from gradebook
3152  * @param int $courseid
3153  * @param string optional type
3154  */
3155 function assignment_reset_gradebook($courseid, $type='') {
3156     global $CFG, $DB;
3158     $params = array('courseid'=>$courseid);
3159     if ($type) {
3160         $type = "AND a.assignmenttype= :type";
3161         $params['type'] = $type;
3162     }
3164     $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
3165               FROM {assignment} a, {course_modules} cm, {modules} m
3166              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id AND a.course=:courseid $type";
3168     if ($assignments = $DB->get_records_sql($sql, $params)) {
3169         foreach ($assignments as $assignment) {
3170             assignment_grade_item_update($assignment, 'reset');
3171         }
3172     }
3175 /**
3176  * This function is used by the reset_course_userdata function in moodlelib.
3177  * This function will remove all posts from the specified assignment
3178  * and clean up any related data.
3179  * @param $data the data submitted from the reset course.
3180  * @return array status array
3181  */
3182 function assignment_reset_userdata($data) {
3183     global $CFG;
3185     $status = array();
3187     foreach (get_plugin_list('mod/assignment/type') as $type=>$dir) {
3188         require_once("$dir/assignment.class.php");
3189         $assignmentclass = "assignment_$type";
3190         $ass = new $assignmentclass();
3191         $status = array_merge($status, $ass->reset_userdata($data));
3192     }
3194     return $status;
3197 /**
3198  * Implementation of the function for printing the form elements that control
3199  * whether the course reset functionality affects the assignment.
3200  * @param $mform form passed by reference
3201  */
3202 function assignment_reset_course_form_definition(&$mform) {
3203     $mform->addElement('header', 'assignmentheader', get_string('modulenameplural', 'assignment'));
3204     $mform->addElement('advcheckbox', 'reset_assignment_submissions', get_string('deleteallsubmissions','assignment'));
3207 /**
3208  * Course reset form defaults.
3209  */
3210 function assignment_reset_course_form_defaults($course) {
3211     return array('reset_assignment_submissions'=>1);
3214 /**
3215  * Returns all other caps used in module
3216  */
3217 function assignment_get_extra_capabilities() {
3218     return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames');
3221 /**
3222  * @package   mod-assignment
3223  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
3224  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3225  */
3226 class assignment_portfolio_caller extends portfolio_module_caller_base {
3228     /**
3229     * the assignment subclass
3230     */
3231     private $assignment;
3233     /**
3234     * the file to include when waking up to load the assignment subclass def
3235     */
3236     private $assignmentfile;
3238     /**
3239     * callback arg for a single file export
3240     */
3241     protected $fileid;
3243     public static function expected_callbackargs() {
3244         return array(
3245             'id'     => true,
3246             'fileid' => false,
3247         );
3248     }
3250     public function load_data() {
3251         global $DB, $CFG;
3253         if (! $this->cm = get_coursemodule_from_id('assignment', $this->id)) {
3254             throw new portfolio_caller_exception('invalidcoursemodule');
3255         }
3257         if (! $assignment = $DB->get_record("assignment", array("id"=>$this->cm->instance))) {
3258             throw new portfolio_caller_exception('invalidid', 'assignment');
3259         }
3261         $this->assignmentfile = $CFG->dirroot . '/mod/assignment/type/' . $assignment->assignmenttype . '/assignment.class.php';
3262         require_once($this->assignmentfile);
3263         $assignmentclass = "assignment_$assignment->assignmenttype";
3265         $this->assignment = new $assignmentclass($this->cm->id, $assignment, $this->cm);
3267         if (!$this->assignment->portfolio_exportable()) {
3268             throw new portfolio_caller_exception('notexportable', 'portfolio', $this->get_return_url());
3269         }
3271         $this->set_file_and_format_data($this->fileid, $this->assignment->context->id, 'assignment_submission', $this->user->id);
3272         if (empty($this->supportedformats) && is_callable(array($this->assignment, 'portfolio_supported_formats'))) {
3273             $this->supportedformats = $this->assignment->portfolio_supported_formats();
3274         }
3275     }
3277     public function prepare_package() {
3278         global $CFG;
3279         if (is_callable(array($this->assignment, 'portfolio_prepare_package'))) {
3280             return $this->assignment->portfolio_prepare_package($this->exporter, $this->user->id);
3281         }
3282         return $this->prepare_package_file();
3283     }
3285     public function get_sha1() {
3286         global $CFG;
3287         if (is_callable(array($this->assignment, 'portfolio_get_sha1'))) {
3288             return $this->assignment->portfolio_get_sha1($this->user->id);
3289         }
3290         return $this->get_sha1_file();
3291     }
3293     public function expected_time() {
3294         if (is_callable(array($this->assignment, 'portfolio_get_expected_time'))) {
3295             return $this->assignment->portfolio_get_expected_time();
3296         }
3297         return $this->expected_time_file();
3298     }
3300     public function check_permissions() {
3301         $context = get_context_instance(CONTEXT_MODULE, $this->assignment->cm->id);
3302         return has_capability('mod/assignment:exportownsubmission', $context);
3303     }
3305     public function __wakeup() {
3306         global $CFG;
3307         if (empty($CFG)) {
3308             return true; // too early yet
3309         }
3310         require_once($this->assignmentfile);
3311         $this->assignment = unserialize(serialize($this->assignment));
3312     }
3314     public static function display_name() {
3315         return get_string('modulename', 'assignment');
3316     }
3319 /**
3320  * @param string $feature FEATURE_xx constant for requested feature
3321  * @return mixed True if module supports feature, null if doesn't know
3322  */
3323 function assignment_supports($feature) {
3324     switch($feature) {
3325         case FEATURE_GROUPS:                  return true;
3326         case FEATURE_GROUPINGS:               return true;
3327         case FEATURE_GROUPMEMBERSONLY:        return true;
3328         case FEATURE_MOD_INTRO:               return true;
3329         case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
3330         case FEATURE_GRADE_HAS_GRADE:         return true;
3331         case FEATURE_GRADE_OUTCOMES:          return true;
3332         case FEATURE_MOD_SUBPLUGINS:          return array('assignment'=>'mod/assignment/type'); // to be hopefully removed in 2.0
3334         default: return null;
3335     }