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