MDL-22893, assignment module should use filepicker and filemanager
[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->idnumber; // 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 (!is_enrolled($this->context, $USER, 'mod/assignment:submit')) {
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         }
473         $mod = $DB->get_field('modules','id',array('name'=>'assignment'));
475         assignment_grade_item_delete($assignment);
477         return $result;
478     }
480     /**
481      * Updates a new assignment activity
482      *
483      * Given an object containing all the necessary data,
484      * (defined by the form in mod_form.php) this function
485      * will update the assignment instance and return the id number
486      * The due date is updated in the calendar
487      * This is common to all assignment types.
488      *
489      * @global object
490      * @global object
491      * @param object $assignment The data from the form on mod_form.php
492      * @return int The assignment id
493      */
494     function update_instance($assignment) {
495         global $COURSE, $DB;
497         $assignment->timemodified = time();
499         $assignment->id = $assignment->instance;
500         $assignment->courseid = $assignment->course;
502         $DB->update_record('assignment', $assignment);
504         if ($assignment->timedue) {
505             $event = new object();
507             if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
509                 $event->name        = $assignment->name;
510                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
511                 $event->timestart   = $assignment->timedue;
513                 $calendarevent = calendar_event::load($event->id);
514                 $calendarevent->update($event);
515             } else {
516                 $event = new object();
517                 $event->name        = $assignment->name;
518                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
519                 $event->courseid    = $assignment->course;
520                 $event->groupid     = 0;
521                 $event->userid      = 0;
522                 $event->modulename  = 'assignment';
523                 $event->instance    = $assignment->id;
524                 $event->eventtype   = 'due';
525                 $event->timestart   = $assignment->timedue;
526                 $event->timeduration = 0;
528                 calendar_event::create($event);
529             }
530         } else {
531             $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id));
532         }
534         // get existing grade item
535         assignment_grade_item_update($assignment);
537         return true;
538     }
540     /**
541      * Update grade item for this submission.
542      */
543     function update_grade($submission) {
544         assignment_update_grades($this->assignment, $submission->userid);
545     }
547     /**
548      * Top-level function for handling of submissions called by submissions.php
549      *
550      * This is for handling the teacher interaction with the grading interface
551      * This should be suitable for most assignment types.
552      *
553      * @global object
554      * @param string $mode Specifies the kind of teacher interaction taking place
555      */
556     function submissions($mode) {
557         ///The main switch is changed to facilitate
558         ///1) Batch fast grading
559         ///2) Skip to the next one on the popup
560         ///3) Save and Skip to the next one on the popup
562         //make user global so we can use the id
563         global $USER, $OUTPUT, $DB, $PAGE;
565         $mailinfo = optional_param('mailinfo', null, PARAM_BOOL);
566         $saved = optional_param('saved', null, PARAM_BOOL);
568         if (optional_param('next', null, PARAM_BOOL)) {
569             $mode='next';
570         }
571         if (optional_param('saveandnext', null, PARAM_BOOL)) {
572             $mode='saveandnext';
573         }
575         if (is_null($mailinfo)) {
576             $mailinfo = get_user_preferences('assignment_mailinfo', 0);
577         } else {
578             set_user_preference('assignment_mailinfo', $mailinfo);
579         }
581         if ($saved) {
582             $OUTPUT->heading(get_string('changessaved'));
583         }
585         switch ($mode) {
586             case 'grade':                         // We are in a main window grading
587                 if ($submission = $this->process_feedback()) {
588                     $this->display_submissions(get_string('changessaved'));
589                 } else {
590                     $this->display_submissions();
591                 }
592                 break;
594             case 'single':                        // We are in a main window displaying one submission
595                 if ($submission = $this->process_feedback()) {
596                     $this->display_submissions(get_string('changessaved'));
597                 } else {
598                     $this->display_submission();
599                 }
600                 break;
602             case 'all':                          // Main window, display everything
603                 $this->display_submissions();
604                 break;
606             case 'fastgrade':
607                 ///do the fast grading stuff  - this process should work for all 3 subclasses
608                 $grading    = false;
609                 $commenting = false;
610                 $col        = false;
611                 if (isset($_POST['submissioncomment'])) {
612                     $col = 'submissioncomment';
613                     $commenting = true;
614                 }
615                 if (isset($_POST['menu'])) {
616                     $col = 'menu';
617                     $grading = true;
618                 }
619                 if (!$col) {
620                     //both submissioncomment and grade columns collapsed..
621                     $this->display_submissions();
622                     break;
623                 }
625                 foreach ($_POST[$col] as $id => $unusedvalue){
627                     $id = (int)$id; //clean parameter name
629                     $this->process_outcomes($id);
631                     if (!$submission = $this->get_submission($id)) {
632                         $submission = $this->prepare_new_submission($id);
633                         $newsubmission = true;
634                     } else {
635                         $newsubmission = false;
636                     }
637                     unset($submission->data1);  // Don't need to update this.
638                     unset($submission->data2);  // Don't need to update this.
640                     //for fast grade, we need to check if any changes take place
641                     $updatedb = false;
643                     if ($grading) {
644                         $grade = $_POST['menu'][$id];
645                         $updatedb = $updatedb || ($submission->grade != $grade);
646                         $submission->grade = $grade;
647                     } else {
648                         if (!$newsubmission) {
649                             unset($submission->grade);  // Don't need to update this.
650                         }
651                     }
652                     if ($commenting) {
653                         $commentvalue = trim($_POST['submissioncomment'][$id]);
654                         $updatedb = $updatedb || ($submission->submissioncomment != $commentvalue);
655                         $submission->submissioncomment = $commentvalue;
656                     } else {
657                         unset($submission->submissioncomment);  // Don't need to update this.
658                     }
660                     $submission->teacher    = $USER->id;
661                     if ($updatedb) {
662                         $submission->mailed = (int)(!$mailinfo);
663                     }
665                     $submission->timemarked = time();
667                     //if it is not an update, we don't change the last modified time etc.
668                     //this will also not write into database if no submissioncomment and grade is entered.
670                     if ($updatedb){
671                         if ($newsubmission) {
672                             if (!isset($submission->submissioncomment)) {
673                                 $submission->submissioncomment = '';
674                             }
675                             $sid = $DB->insert_record('assignment_submissions', $submission);
676                             $submission->id = $sid;
677                         } else {
678                             $DB->update_record('assignment_submissions', $submission);
679                         }
681                         // triger grade event
682                         $this->update_grade($submission);
684                         //add to log only if updating
685                         add_to_log($this->course->id, 'assignment', 'update grades',
686                                    'submissions.php?id='.$this->assignment->id.'&user='.$submission->userid,
687                                    $submission->userid, $this->cm->id);
688                     }
690                 }
692                 $message = $OUTPUT->notification(get_string('changessaved'), 'notifysuccess');
694                 $this->display_submissions($message);
695                 break;
698             case 'saveandnext':
699                 ///We are in pop up. save the current one and go to the next one.
700                 //first we save the current changes
701                 if ($submission = $this->process_feedback()) {
702                     //print_heading(get_string('changessaved'));
703                     //$extra_javascript = $this->update_main_listing($submission);
704                 }
706             case 'next':
707                 /// We are currently in pop up, but we want to skip to next one without saving.
708                 ///    This turns out to be similar to a single case
709                 /// The URL used is for the next submission.
710                 $offset = required_param('offset', PARAM_INT);
711                 $nextid = required_param('nextid', PARAM_INT);
712                 $id = required_param('id', PARAM_INT);
713                 $offset = (int)$offset+1;
714                 //$this->display_submission($offset+1 , $nextid);
715                 redirect('submissions.php?id='.$id.'&userid='. $nextid . '&mode=single&offset='.$offset);
716                 break;
718             default:
719                 echo "something seriously is wrong!!";
720                 break;
721         }
722     }
724     /**
725      * Helper method updating the listing on the main script from popup using javascript
726      *
727      * @global object
728      * @global object
729      * @param $submission object The submission whose data is to be updated on the main page
730      */
731     function update_main_listing($submission) {
732         global $SESSION, $CFG, $OUTPUT;
734         $output = '';
736         $perpage = get_user_preferences('assignment_perpage', 10);
738         $quickgrade = get_user_preferences('assignment_quickgrade', 0);
740         /// Run some Javascript to try and update the parent page
741         $output .= '<script type="text/javascript">'."\n<!--\n";
742         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['submissioncomment'])) {
743             if ($quickgrade){
744                 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid.'").value="'
745                 .trim($submission->submissioncomment).'";'."\n";
746              } else {
747                 $output.= 'opener.document.getElementById("com'.$submission->userid.
748                 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment)), 15)."\";\n";
749             }
750         }
752         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['grade'])) {
753             //echo optional_param('menuindex');
754             if ($quickgrade){
755                 $output.= 'opener.document.getElementById("menumenu'.$submission->userid.
756                 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT).'";'."\n";
757             } else {
758                 $output.= 'opener.document.getElementById("g'.$submission->userid.'").innerHTML="'.
759                 $this->display_grade($submission->grade)."\";\n";
760             }
761         }
762         //need to add student's assignments in there too.
763         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemodified']) &&
764             $submission->timemodified) {
765             $output.= 'opener.document.getElementById("ts'.$submission->userid.
766                  '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid)).userdate($submission->timemodified)."\";\n";
767         }
769         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemarked']) &&
770             $submission->timemarked) {
771             $output.= 'opener.document.getElementById("tt'.$submission->userid.
772                  '").innerHTML="'.userdate($submission->timemarked)."\";\n";
773         }
775         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['status'])) {
776             $output.= 'opener.document.getElementById("up'.$submission->userid.'").className="s1";';
777             $buttontext = get_string('update');
778             $url = new moodle_url('/mod/assignment/submissions.php', array(
779                     'id' => $this->cm->id,
780                     'userid' => $submission->userid,
781                     'mode' => 'single',
782                     'offset' => (optional_param('offset', '', PARAM_INT)-1)));
783             $button = $OUTPUT->action_link($url, $buttontext, new popup_action('click', $url, 'grade'.$submission->userid, array('height' => 450, 'width' => 700)), array('ttile'=>$buttontext));
785             $output .= 'opener.document.getElementById("up'.$submission->userid.'").innerHTML="'.addslashes_js($button).'";';
786         }
788         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $submission->userid);
790         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['finalgrade'])) {
791             $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid.
792             '").innerHTML="'.$grading_info->items[0]->grades[$submission->userid]->str_grade.'";'."\n";
793         }
795         if (!empty($CFG->enableoutcomes) and empty($SESSION->flextable['mod-assignment-submissions']->collapse['outcome'])) {
797             if (!empty($grading_info->outcomes)) {
798                 foreach($grading_info->outcomes as $n=>$outcome) {
799                     if ($outcome->grades[$submission->userid]->locked) {
800                         continue;
801                     }
803                     if ($quickgrade){
804                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.
805                         '").selectedIndex="'.$outcome->grades[$submission->userid]->grade.'";'."\n";
807                     } else {
808                         $options = make_grades_menu(-$outcome->scaleid);
809                         $options[0] = get_string('nooutcome', 'grades');
810                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.'").innerHTML="'.$options[$outcome->grades[$submission->userid]->grade]."\";\n";
811                     }
813                 }
814             }
815         }
817         $output .= "\n-->\n</script>";
818         return $output;
819     }
821     /**
822      *  Return a grade in user-friendly form, whether it's a scale or not
823      *
824      * @global object
825      * @param mixed $grade
826      * @return string User-friendly representation of grade
827      */
828     function display_grade($grade) {
829         global $DB;
831         static $scalegrades = array();   // Cache scales for each assignment - they might have different scales!!
833         if ($this->assignment->grade >= 0) {    // Normal number
834             if ($grade == -1) {
835                 return '-';
836             } else {
837                 return $grade.' / '.$this->assignment->grade;
838             }
840         } else {                                // Scale
841             if (empty($scalegrades[$this->assignment->id])) {
842                 if ($scale = $DB->get_record('scale', array('id'=>-($this->assignment->grade)))) {
843                     $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
844                 } else {
845                     return '-';
846                 }
847             }
848             if (isset($scalegrades[$this->assignment->id][$grade])) {
849                 return $scalegrades[$this->assignment->id][$grade];
850             }
851             return '-';
852         }
853     }
855     /**
856      *  Display a single submission, ready for grading on a popup window
857      *
858      * This default method prints the teacher info and submissioncomment box at the top and
859      * the student info and submission at the bottom.
860      * This method also fetches the necessary data in order to be able to
861      * provide a "Next submission" button.
862      * Calls preprocess_submission() to give assignment type plug-ins a chance
863      * to process submissions before they are graded
864      * This method gets its arguments from the page parameters userid and offset
865      *
866      * @global object
867      * @global object
868      * @param string $extra_javascript
869      */
870     function display_submission($offset=-1,$userid =-1) {
871         global $CFG, $DB, $PAGE, $OUTPUT;
872         require_once($CFG->libdir.'/gradelib.php');
873         require_once($CFG->libdir.'/tablelib.php');
874         if ($userid==-1) {
875             $userid = required_param('userid', PARAM_INT);
876         }
877         if ($offset==-1) {
878             $offset = required_param('offset', PARAM_INT);//offset for where to start looking for student.
879         }
881         if (!$user = $DB->get_record('user', array('id'=>$userid))) {
882             print_error('nousers');
883         }
885         if (!$submission = $this->get_submission($user->id)) {
886             $submission = $this->prepare_new_submission($userid);
887         }
888         if ($submission->timemodified > $submission->timemarked) {
889             $subtype = 'assignmentnew';
890         } else {
891             $subtype = 'assignmentold';
892         }
894         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
895         $gradingdisabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
897     /// construct SQL, using current offset to find the data of the next student
898         $course     = $this->course;
899         $assignment = $this->assignment;
900         $cm         = $this->cm;
901         $context    = get_context_instance(CONTEXT_MODULE, $cm->id);
903         /// Get all ppl that can submit assignments
905         $currentgroup = groups_get_activity_group($cm);
906         if ($users = get_enrolled_users($context, 'mod/assignment:submit', $currentgroup, 'u.id')) {
907             $users = array_keys($users);
908         }
910         // if groupmembersonly used, remove users who are not in any group
911         if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
912             if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
913                 $users = array_intersect($users, array_keys($groupingusers));
914             }
915         }
917         $nextid = 0;
919         if ($users) {
920             $userfields = user_picture::fields('u', array('lastaccess'));
921             $select = "SELECT $userfields,
922                               s.id AS submissionid, s.grade, s.submissioncomment,
923                               s.timemodified, s.timemarked,
924                               COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ";
925             $sql = 'FROM {user} u '.
926                    'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
927                                                                       AND s.assignment = '.$this->assignment->id.' '.
928                    'WHERE u.id IN ('.implode(',', $users).') ';
930             if ($sort = flexible_table::get_sort_for_table('mod-assignment-submissions')) {
931                 $sort = 'ORDER BY '.$sort.' ';
932             }
933             $auser = $DB->get_records_sql($select.$sql.$sort, null, $offset, 2);
935             if (is_array($auser) && count($auser)>1) {
936                 $nextuser = next($auser);
937             /// Calculate user status
938                 $nextuser->status = ($nextuser->timemarked > 0) && ($nextuser->timemarked >= $nextuser->timemodified);
939                 $nextid = $nextuser->id;
940             }
941         }
943         if ($submission->teacher) {
944             $teacher = $DB->get_record('user', array('id'=>$submission->teacher));
945         } else {
946             global $USER;
947             $teacher = $USER;
948         }
950         $this->preprocess_submission($submission);
952         $mformdata = new stdclass;
953         $mformdata->context = $this->context;
954         $mformdata->maxbytes = $this->course->maxbytes;
955         $mformdata->courseid = $this->course->id;
956         $mformdata->teacher = $teacher;
957         $mformdata->assignment = $assignment;
958         $mformdata->submission = $submission;
959         $mformdata->lateness = $this->display_lateness($submission->timemodified);
960         $mformdata->auser = $auser;
961         $mformdata->user = $user;
962         $mformdata->offset = $offset;
963         $mformdata->userid = $userid;
964         $mformdata->cm = $this->cm;
965         $mformdata->grading_info = $grading_info;
966         $mformdata->enableoutcomes = $CFG->enableoutcomes;
967         $mformdata->grade = $this->assignment->grade;
968         $mformdata->gradingdisabled = $gradingdisabled;
969         $mformdata->usehtmleditor = $this->usehtmleditor;
970         $mformdata->nextid = $nextid;
971         $mformdata->submissioncomment= $submission->submissioncomment;
972         $mformdata->submissioncommentformat= FORMAT_HTML;
973         $mformdata->submission_content= $this->print_user_files($user->id, true);
975         $submitform = new mod_assignment_online_grading_form( null, $mformdata );
977         if ($submitform->is_cancelled()) {
978             redirect('submissions.php?id='.$this->cm->id);
979         }
981         $submitform->set_data($mformdata);
983         $PAGE->set_title($this->course->fullname . ': ' .get_string('feedback', 'assignment').' - '.fullname($user, true));
984         $PAGE->set_heading($this->course->fullname);
985         $PAGE->navbar->add( get_string('submissions', 'assignment') );
987         echo $OUTPUT->header();
988         echo $OUTPUT->heading(get_string('feedback', 'assignment').': '.fullname($user, true));
990         // display mform here...
991         $submitform->display();
993         $customfeedback = $this->custom_feedbackform($submission, true);
994         if (!empty($customfeedback)) {
995             echo $customfeedback;
996         }
998         echo $OUTPUT->footer();
999     }
1001     /**
1002      *  Preprocess submission before grading
1003      *
1004      * Called by display_submission()
1005      * The default type does nothing here.
1006      *
1007      * @param object $submission The submission object
1008      */
1009     function preprocess_submission(&$submission) {
1010     }
1012     /**
1013      *  Display all the submissions ready for grading
1014      *
1015      * @global object
1016      * @global object
1017      * @global object
1018      * @global object
1019      * @param string $message
1020      * @return bool|void
1021      */
1022     function display_submissions($message='') {
1023         global $CFG, $DB, $USER, $DB, $OUTPUT, $PAGE;
1024         require_once($CFG->libdir.'/gradelib.php');
1026         /* first we check to see if the form has just been submitted
1027          * to request user_preference updates
1028          */
1029         if (isset($_POST['updatepref'])){
1030             $perpage = optional_param('perpage', 10, PARAM_INT);
1031             $perpage = ($perpage <= 0) ? 10 : $perpage ;
1032             set_user_preference('assignment_perpage', $perpage);
1033             set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
1034         }
1036         /* next we get perpage and quickgrade (allow quick grade) params
1037          * from database
1038          */
1039         $perpage    = get_user_preferences('assignment_perpage', 10);
1041         $quickgrade = get_user_preferences('assignment_quickgrade', 0);
1043         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);
1045         if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
1046             $uses_outcomes = true;
1047         } else {
1048             $uses_outcomes = false;
1049         }
1051         $page    = optional_param('page', 0, PARAM_INT);
1052         $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
1054     /// Some shortcuts to make the code read better
1056         $course     = $this->course;
1057         $assignment = $this->assignment;
1058         $cm         = $this->cm;
1060         $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
1061         add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->cm->id, $this->assignment->id, $this->cm->id);
1063         $PAGE->set_title(format_string($this->assignment->name,true));
1064         $PAGE->set_heading($this->course->fullname);
1065         echo $OUTPUT->header();
1067         /// Print quickgrade form around the table
1068         if ($quickgrade) {
1069             echo '<form action="submissions.php" id="fastg" method="post">';
1070             echo '<div>';
1071             echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
1072             echo '<input type="hidden" name="mode" value="fastgrade" />';
1073             echo '<input type="hidden" name="page" value="'.$page.'" />';
1074             echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1075             echo '</div>';
1076         }
1078         $course_context = get_context_instance(CONTEXT_COURSE, $course->id);
1079         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
1080             echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">'
1081                 . get_string('seeallcoursegrades', 'grades') . '</a></div>';
1082         }
1084         if (!empty($message)) {
1085             echo $message;   // display messages here if any
1086         }
1088         $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1090     /// Check to see if groups are being used in this assignment
1092         /// find out current groups mode
1093         $groupmode = groups_get_activity_groupmode($cm);
1094         $currentgroup = groups_get_activity_group($cm, true);
1095         groups_print_activity_menu($cm, $CFG->wwwroot . '/mod/assignment/submissions.php?id=' . $this->cm->id);
1097         /// Get all ppl that are allowed to submit assignments
1098         if ($users = get_enrolled_users($context, 'mod/assignment:submit', $currentgroup, 'u.id')) {
1099             $users = array_keys($users);
1100         }
1102         // if groupmembersonly used, remove users who are not in any group
1103         if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
1104             if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1105                 $users = array_intersect($users, array_keys($groupingusers));
1106             }
1107         }
1109         $tablecolumns = array('picture', 'fullname', 'grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade');
1110         if ($uses_outcomes) {
1111             $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
1112         }
1114         $tableheaders = array('',
1115                               get_string('fullname'),
1116                               get_string('grade'),
1117                               get_string('comment', 'assignment'),
1118                               get_string('lastmodified').' ('.get_string('submission', 'assignment').')',
1119                               get_string('lastmodified').' ('.get_string('grade').')',
1120                               get_string('status'),
1121                               get_string('finalgrade', 'grades'));
1122         if ($uses_outcomes) {
1123             $tableheaders[] = get_string('outcome', 'grades');
1124         }
1126         require_once($CFG->libdir.'/tablelib.php');
1127         $table = new flexible_table('mod-assignment-submissions');
1129         $table->define_columns($tablecolumns);
1130         $table->define_headers($tableheaders);
1131         $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;currentgroup='.$currentgroup);
1133         $table->sortable(true, 'lastname');//sorted by lastname by default
1134         $table->collapsible(true);
1135         $table->initialbars(true);
1137         $table->column_suppress('picture');
1138         $table->column_suppress('fullname');
1140         $table->column_class('picture', 'picture');
1141         $table->column_class('fullname', 'fullname');
1142         $table->column_class('grade', 'grade');
1143         $table->column_class('submissioncomment', 'comment');
1144         $table->column_class('timemodified', 'timemodified');
1145         $table->column_class('timemarked', 'timemarked');
1146         $table->column_class('status', 'status');
1147         $table->column_class('finalgrade', 'finalgrade');
1148         if ($uses_outcomes) {
1149             $table->column_class('outcome', 'outcome');
1150         }
1152         $table->set_attribute('cellspacing', '0');
1153         $table->set_attribute('id', 'attempts');
1154         $table->set_attribute('class', 'submissions');
1155         $table->set_attribute('width', '100%');
1156         //$table->set_attribute('align', 'center');
1158         $table->no_sorting('finalgrade');
1159         $table->no_sorting('outcome');
1161         // Start working -- this is necessary as soon as the niceties are over
1162         $table->setup();
1164         if (empty($users)) {
1165             echo $OUTPUT->heading(get_string('nosubmitusers','assignment'));
1166             echo '</div>';
1167             return true;
1168         }
1169         if ($this->assignment->assignmenttype=='upload' || $this->assignment->assignmenttype=='online' || $this->assignment->assignmenttype=='uploadsingle') { //TODO: this is an ugly hack, where is the plugin spirit? (skodak)
1170             echo '<div style="text-align:right"><a href="submissions.php?id='.$this->cm->id.'&amp;download=zip">'.get_string('downloadall', 'assignment').'</a></div>';
1171         }
1172     /// Construct the SQL
1174         if ($where = $table->get_sql_where()) {
1175             $where .= ' AND ';
1176         }
1178         if ($sort = $table->get_sql_sort()) {
1179             $sort = ' ORDER BY '.$sort;
1180         }
1182         $ufields = user_picture::fields('u');
1183         $select = "SELECT $ufields,
1184                           s.id AS submissionid, s.grade, s.submissioncomment,
1185                           s.timemodified, s.timemarked,
1186                           COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ";
1187         $sql = 'FROM {user} u '.
1188                'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1189                                                                   AND s.assignment = '.$this->assignment->id.' '.
1190                'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1192         $table->pagesize($perpage, count($users));
1194         ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1195         $offset = $page * $perpage;
1197         $strupdate = get_string('update');
1198         $strgrade  = get_string('grade');
1199         $grademenu = make_grades_menu($this->assignment->grade);
1201         if (($ausers = $DB->get_records_sql($select.$sql.$sort, null, $table->get_page_start(), $table->get_page_size())) !== false) {
1202             $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
1203             foreach ($ausers as $auser) {
1204                 $final_grade = $grading_info->items[0]->grades[$auser->id];
1205                 $grademax = $grading_info->items[0]->grademax;
1206                 $final_grade->formatted_grade = round($final_grade->grade,2) .' / ' . round($grademax,2);
1207                 $locked_overridden = 'locked';
1208                 if ($final_grade->overridden) {
1209                     $locked_overridden = 'overridden';
1210                 }
1212             /// Calculate user status
1213                 $auser->status = ($auser->timemarked > 0) && ($auser->timemarked >= $auser->timemodified);
1214                 $picture = $OUTPUT->user_picture($auser);
1216                 if (empty($auser->submissionid)) {
1217                     $auser->grade = -1; //no submission yet
1218                 }
1220                 if (!empty($auser->submissionid)) {
1221                 ///Prints student answer and student modified date
1222                 ///attach file or print link to student answer, depending on the type of the assignment.
1223                 ///Refer to print_student_answer in inherited classes.
1224                     if ($auser->timemodified > 0) {
1225                         $studentmodified = '<div id="ts'.$auser->id.'">'.$this->print_student_answer($auser->id)
1226                                          . userdate($auser->timemodified).'</div>';
1227                     } else {
1228                         $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1229                     }
1230                 ///Print grade, dropdown or text
1231                     if ($auser->timemarked > 0) {
1232                         $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
1234                         if ($final_grade->locked or $final_grade->overridden) {
1235                             $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1236                         } else if ($quickgrade) {
1237                             $attributes = array();
1238                             $attributes['tabindex'] = $tabindex++;
1239                             $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1240                             $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
1241                         } else {
1242                             $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1243                         }
1245                     } else {
1246                         $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1247                         if ($final_grade->locked or $final_grade->overridden) {
1248                             $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1249                         } else if ($quickgrade) {
1250                             $attributes = array();
1251                             $attributes['tabindex'] = $tabindex++;
1252                             $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1253                             $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1254                         } else {
1255                             $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1256                         }
1257                     }
1258                 ///Print Comment
1259                     if ($final_grade->locked or $final_grade->overridden) {
1260                         $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';
1262                     } else if ($quickgrade) {
1263                         $comment = '<div id="com'.$auser->id.'">'
1264                                  . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1265                                  . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1266                     } else {
1267                         $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
1268                     }
1269                 } else {
1270                     $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1271                     $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1272                     $status          = '<div id="st'.$auser->id.'">&nbsp;</div>';
1274                     if ($final_grade->locked or $final_grade->overridden) {
1275                         $grade = '<div id="g'.$auser->id.'">'.$final_grade->formatted_grade . '</div>';
1276                     } else if ($quickgrade) {   // allow editing
1277                         $attributes = array();
1278                         $attributes['tabindex'] = $tabindex++;
1279                         $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1280                         $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1281                     } else {
1282                         $grade = '<div id="g'.$auser->id.'">-</div>';
1283                     }
1285                     if ($final_grade->locked or $final_grade->overridden) {
1286                         $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
1287                     } else if ($quickgrade) {
1288                         $comment = '<div id="com'.$auser->id.'">'
1289                                  . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1290                                  . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1291                     } else {
1292                         $comment = '<div id="com'.$auser->id.'">&nbsp;</div>';
1293                     }
1294                 }
1296                 if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
1297                     $auser->status = 0;
1298                 } else {
1299                     $auser->status = 1;
1300                 }
1302                 $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
1304                 ///No more buttons, we use popups ;-).
1305                 $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1306                            . '&userid='.$auser->id.'&mode=single'.'&offset='.$offset++;
1308                 $button = $OUTPUT->action_link($popup_url, $buttontext);
1310                 $status  = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
1312                 $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';
1314                 $outcomes = '';
1316                 if ($uses_outcomes) {
1318                     foreach($grading_info->outcomes as $n=>$outcome) {
1319                         $outcomes .= '<div class="outcome"><label>'.$outcome->name.'</label>';
1320                         $options = make_grades_menu(-$outcome->scaleid);
1322                         if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
1323                             $options[0] = get_string('nooutcome', 'grades');
1324                             $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
1325                         } else {
1326                             $attributes = array();
1327                             $attributes['tabindex'] = $tabindex++;
1328                             $attributes['id'] = 'outcome_'.$n.'_'.$auser->id;
1329                             $outcomes .= ' '.html_writer::select($options, 'outcome_'.$n.'['.$auser->id.']', $outcome->grades[$auser->id]->grade, array(0=>get_string('nooutcome', 'grades')), $attributes);
1330                         }
1331                         $outcomes .= '</div>';
1332                     }
1333                 }
1335                 $userlink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $auser->id . '&amp;course=' . $course->id . '">' . fullname($auser) . '</a>';
1336                 $row = array($picture, $userlink, $grade, $comment, $studentmodified, $teachermodified, $status, $finalgrade);
1337                 if ($uses_outcomes) {
1338                     $row[] = $outcomes;
1339                 }
1341                 $table->add_data($row);
1342             }
1343         }
1345         $table->print_html();  /// Print the whole table
1347         if ($quickgrade){
1348             $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? 'checked="checked"' : '';
1349             echo '<div class="fgcontrols">';
1350             echo '<div class="emailnotification">';
1351             echo '<label for="mailinfo">'.get_string('enableemailnotification','assignment').'</label>';
1352             echo '<input type="hidden" name="mailinfo" value="0" />';
1353             echo '<input type="checkbox" id="mailinfo" name="mailinfo" value="1" '.$lastmailinfo.' />';
1354             echo $OUTPUT->help_icon('enableemailnotification', 'assignment');
1355             echo '</div>';
1356             echo '</div>';
1357             echo '<div class="fastgbutton"><input type="submit" name="fastg" value="'.get_string('saveallfeedback', 'assignment').'" /></div>';
1358             echo '</form>';
1359         }
1360         /// End of fast grading form
1362         /// Mini form for setting user preference
1363         echo '<div class="qgprefs">';
1364         echo '<form id="options" action="submissions.php?id='.$this->cm->id.'" method="post"><div>';
1365         echo '<input type="hidden" name="updatepref" value="1" />';
1366         echo '<table id="optiontable">';
1367         echo '<tr><td>';
1368         echo '<label for="perpage">'.get_string('pagesize','assignment').'</label>';
1369         echo '</td>';
1370         echo '<td>';
1371         echo '<input type="text" id="perpage" name="perpage" size="1" value="'.$perpage.'" />';
1372         echo '</td></tr>';
1373         echo '<tr><td>';
1374         echo '<label for="quickgrade">'.get_string('quickgrade','assignment').'</label>';
1375         echo '</td>';
1376         echo '<td>';
1377         $checked = $quickgrade ? 'checked="checked"' : '';
1378         echo '<input type="checkbox" id="quickgrade" name="quickgrade" value="1" '.$checked.' />';
1379         echo '<p>'.$OUTPUT->help_icon('quickgrade', 'assignment').'</p>';
1380         echo '</td>';
1381         echo '</tr>';
1382         echo '<tr><td colspan="2">';
1383         echo '<input type="submit" value="'.get_string('savepreferences').'" />';
1384         echo '</td></tr></table>';
1385         echo '</div></form></div>';
1386         ///End of mini form
1387         echo $OUTPUT->footer();
1388     }
1390     /**
1391      *  Process teacher feedback submission
1392      *
1393      * This is called by submissions() when a grading even has taken place.
1394      * It gets its data from the submitted form.
1395      *
1396      * @global object
1397      * @global object
1398      * @global object
1399      * @return object|bool The updated submission object or false
1400      */
1401     function process_feedback() {
1402         global $CFG, $USER, $DB;
1403         require_once($CFG->libdir.'/gradelib.php');
1405         if (!$feedback = data_submitted() or !confirm_sesskey()) {      // No incoming data?
1406             return false;
1407         }
1409         ///For save and next, we need to know the userid to save, and the userid to go
1410         ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1411         ///as the userid to store
1412         if ((int)$feedback->saveuserid !== -1){
1413             $feedback->userid = $feedback->saveuserid;
1414         }
1416         if (!empty($feedback->cancel)) {          // User hit cancel button
1417             return false;
1418         }
1420         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);
1422         // store outcomes if needed
1423         $this->process_outcomes($feedback->userid);
1425         $submission = $this->get_submission($feedback->userid, true);  // Get or make one
1427         if (!($grading_info->items[0]->grades[$feedback->userid]->locked ||
1428             $grading_info->items[0]->grades[$feedback->userid]->overridden) ) {
1430             $submission->grade      = $feedback->xgrade;
1431             $submission->submissioncomment    = $feedback->submissioncomment_editor['text'];
1432             $submission->format     = $feedback->format;
1433             $submission->teacher    = $USER->id;
1434             $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1435             if (!$mailinfo) {
1436                 $submission->mailed = 1;       // treat as already mailed
1437             } else {
1438                 $submission->mailed = 0;       // Make sure mail goes out (again, even)
1439             }
1440             $submission->timemarked = time();
1442             unset($submission->data1);  // Don't need to update this.
1443             unset($submission->data2);  // Don't need to update this.
1445             if (empty($submission->timemodified)) {   // eg for offline assignments
1446                 // $submission->timemodified = time();
1447             }
1449             $DB->update_record('assignment_submissions', $submission);
1451             // triger grade event
1452             $this->update_grade($submission);
1454             add_to_log($this->course->id, 'assignment', 'update grades',
1455                        'submissions.php?id='.$this->assignment->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
1456         }
1458         return $submission;
1460     }
1462     function process_outcomes($userid) {
1463         global $CFG, $USER;
1465         if (empty($CFG->enableoutcomes)) {
1466             return;
1467         }
1469         require_once($CFG->libdir.'/gradelib.php');
1471         if (!$formdata = data_submitted() or !confirm_sesskey()) {
1472             return;
1473         }
1475         $data = array();
1476         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
1478         if (!empty($grading_info->outcomes)) {
1479             foreach($grading_info->outcomes as $n=>$old) {
1480                 $name = 'outcome_'.$n;
1481                 if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
1482                     $data[$n] = $formdata->{$name}[$userid];
1483                 }
1484             }
1485         }
1486         if (count($data) > 0) {
1487             grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1488         }
1490     }
1492     /**
1493      * Load the submission object for a particular user
1494      *
1495      * @global object
1496      * @global object
1497      * @param $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1498      * @param $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1499      * @param bool $teachermodified student submission set if false
1500      * @return object The submission
1501      */
1502     function get_submission($userid=0, $createnew=false, $teachermodified=false) {
1503         global $USER, $DB;
1505         if (empty($userid)) {
1506             $userid = $USER->id;
1507         }
1509         $submission = $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1511         if ($submission || !$createnew) {
1512             return $submission;
1513         }
1514         $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
1515         $DB->insert_record("assignment_submissions", $newsubmission);
1517         return $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1518     }
1520     /**
1521      * Instantiates a new submission object for a given user
1522      *
1523      * Sets the assignment, userid and times, everything else is set to default values.
1524      *
1525      * @param int $userid The userid for which we want a submission object
1526      * @param bool $teachermodified student submission set if false
1527      * @return object The submission
1528      */
1529     function prepare_new_submission($userid, $teachermodified=false) {
1530         $submission = new Object;
1531         $submission->assignment   = $this->assignment->id;
1532         $submission->userid       = $userid;
1533         $submission->timecreated = time();
1534         // teachers should not be modifying modified date, except offline assignments
1535         if ($teachermodified) {
1536             $submission->timemodified = 0;
1537         } else {
1538             $submission->timemodified = $submission->timecreated;
1539         }
1540         $submission->numfiles     = 0;
1541         $submission->data1        = '';
1542         $submission->data2        = '';
1543         $submission->grade        = -1;
1544         $submission->submissioncomment      = '';
1545         $submission->format       = 0;
1546         $submission->teacher      = 0;
1547         $submission->timemarked   = 0;
1548         $submission->mailed       = 0;
1549         return $submission;
1550     }
1552     /**
1553      * Return all assignment submissions by ENROLLED students (even empty)
1554      *
1555      * @param string $sort optional field names for the ORDER BY in the sql query
1556      * @param string $dir optional specifying the sort direction, defaults to DESC
1557      * @return array The submission objects indexed by id
1558      */
1559     function get_submissions($sort='', $dir='DESC') {
1560         return assignment_get_all_submissions($this->assignment, $sort, $dir);
1561     }
1563     /**
1564      * Counts all real assignment submissions by ENROLLED students (not empty ones)
1565      *
1566      * @param int $groupid optional If nonzero then count is restricted to this group
1567      * @return int The number of submissions
1568      */
1569     function count_real_submissions($groupid=0) {
1570         return assignment_count_real_submissions($this->cm, $groupid);
1571     }
1573     /**
1574      * Alerts teachers by email of new or changed assignments that need grading
1575      *
1576      * First checks whether the option to email teachers is set for this assignment.
1577      * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1578      * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1579      *
1580      * @global object
1581      * @global object
1582      * @param $submission object The submission that has changed
1583      * @return void
1584      */
1585     function email_teachers($submission) {
1586         global $CFG, $DB;
1588         if (empty($this->assignment->emailteachers)) {          // No need to do anything
1589             return;
1590         }
1592         $user = $DB->get_record('user', array('id'=>$submission->userid));
1594         if ($teachers = $this->get_graders($user)) {
1596             $strassignments = get_string('modulenameplural', 'assignment');
1597             $strassignment  = get_string('modulename', 'assignment');
1598             $strsubmitted  = get_string('submitted', 'assignment');
1600             foreach ($teachers as $teacher) {
1601                 $info = new object();
1602                 $info->username = fullname($user, true);
1603                 $info->assignment = format_string($this->assignment->name,true);
1604                 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
1606                 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1607                 $posttext = $this->email_teachers_text($info);
1608                 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
1610                 $eventdata = new object();
1611                 $eventdata->modulename       = 'assignment';
1612                 $eventdata->userfrom         = $user;
1613                 $eventdata->userto           = $teacher;
1614                 $eventdata->subject          = $postsubject;
1615                 $eventdata->fullmessage      = $posttext;
1616                 $eventdata->fullmessageformat = FORMAT_PLAIN;
1617                 $eventdata->fullmessagehtml  = $posthtml;
1618                 $eventdata->smallmessage     = '';
1619                 message_send($eventdata);
1620             }
1621         }
1622     }
1624     /**
1625      * @param string $filearea
1626      * @param array $args
1627      * @return bool
1628      */
1629     function send_file($filearea, $args) {
1630         debugging('plugin does not implement file sending', DEBUG_DEVELOPER);
1631         return false;
1632     }
1634     /**
1635      * Returns a list of teachers that should be grading given submission
1636      *
1637      * @param object $user
1638      * @return array
1639      */
1640     function get_graders($user) {
1641         //potential graders
1642         $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false);
1644         $graders = array();
1645         if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) {   // Separate groups are being used
1646             if ($groups = groups_get_all_groups($this->course->id, $user->id)) {  // Try to find all groups
1647                 foreach ($groups as $group) {
1648                     foreach ($potgraders as $t) {
1649                         if ($t->id == $user->id) {
1650                             continue; // do not send self
1651                         }
1652                         if (groups_is_member($group->id, $t->id)) {
1653                             $graders[$t->id] = $t;
1654                         }
1655                     }
1656                 }
1657             } else {
1658                 // user not in group, try to find graders without group
1659                 foreach ($potgraders as $t) {
1660                     if ($t->id == $user->id) {
1661                         continue; // do not send self
1662                     }
1663                     if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
1664                         $graders[$t->id] = $t;
1665                     }
1666                 }
1667             }
1668         } else {
1669             foreach ($potgraders as $t) {
1670                 if ($t->id == $user->id) {
1671                     continue; // do not send self
1672                 }
1673                 $graders[$t->id] = $t;
1674             }
1675         }
1676         return $graders;
1677     }
1679     /**
1680      * Creates the text content for emails to teachers
1681      *
1682      * @param $info object The info used by the 'emailteachermail' language string
1683      * @return string
1684      */
1685     function email_teachers_text($info) {
1686         $posttext  = format_string($this->course->shortname).' -> '.$this->strassignments.' -> '.
1687                      format_string($this->assignment->name)."\n";
1688         $posttext .= '---------------------------------------------------------------------'."\n";
1689         $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
1690         $posttext .= "\n---------------------------------------------------------------------\n";
1691         return $posttext;
1692     }
1694      /**
1695      * Creates the html content for emails to teachers
1696      *
1697      * @param $info object The info used by the 'emailteachermailhtml' language string
1698      * @return string
1699      */
1700     function email_teachers_html($info) {
1701         global $CFG;
1702         $posthtml  = '<p><font face="sans-serif">'.
1703                      '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname).'</a> ->'.
1704                      '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
1705                      '<a href="'.$CFG->wwwroot.'/mod/assignment/view.php?id='.$this->cm->id.'">'.format_string($this->assignment->name).'</a></font></p>';
1706         $posthtml .= '<hr /><font face="sans-serif">';
1707         $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
1708         $posthtml .= '</font><hr />';
1709         return $posthtml;
1710     }
1712     /**
1713      * Produces a list of links to the files uploaded by a user
1714      *
1715      * @param $userid int optional id of the user. If 0 then $USER->id is used.
1716      * @param $return boolean optional defaults to false. If true the list is returned rather than printed
1717      * @return string optional
1718      */
1719     function print_user_files($userid=0, $return=false) {
1720         global $CFG, $USER, $OUTPUT;
1722         if (!$userid) {
1723             if (!isloggedin()) {
1724                 return '';
1725             }
1726             $userid = $USER->id;
1727         }
1729         $output = '';
1731         $fs = get_file_storage();
1733         $found = false;
1735         if ($files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $userid, "timemodified", false)) {
1736             require_once($CFG->libdir.'/portfoliolib.php');
1737             require_once($CFG->dirroot . '/mod/assignment/locallib.php');
1738             $button = new portfolio_add_button();
1739             foreach ($files as $file) {
1740                 $filename = $file->get_filename();
1741                 $found = true;
1742                 $mimetype = $file->get_mimetype();
1743                 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/mod_assignment/submission/'.$userid.'/'.$filename);
1744                 $output .= '<a href="'.$path.'" ><img src="'.$OUTPUT->pix_url(file_mimetype_icon($mimetype)).'" class="icon" alt="'.$mimetype.'" />'.s($filename).'</a>';
1745                 if ($this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1746                     $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id, 'fileid' => $file->get_id()), '/mod/assignment/locallib.php');
1747                     $button->set_format_by_file($file);
1748                     $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
1749                 }
1750             }
1751             if (count($files) > 1  && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1752                 $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id), '/mod/assignment/locallib.php');
1753                 $output .= '<br />'  . $button->to_html();
1754             }
1755         }
1757         $output = '<div class="files">'.$output.'</div>';
1759         if ($return) {
1760             return $output;
1761         }
1762         echo $output;
1763     }
1765     /**
1766      * Count the files uploaded by a given user
1767      *
1768      * @param $userid int The user id
1769      * @return int
1770      */
1771     function count_user_files($userid) {
1772         $fs = get_file_storage();
1773         $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $userid, "id", false);
1774         return count($files);
1775     }
1777     /**
1778      * Returns true if the student is allowed to submit
1779      *
1780      * Checks that the assignment has started and, if the option to prevent late
1781      * submissions is set, also checks that the assignment has not yet closed.
1782      * @return boolean
1783      */
1784     function isopen() {
1785         $time = time();
1786         if ($this->assignment->preventlate && $this->assignment->timedue) {
1787             return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
1788         } else {
1789             return ($this->assignment->timeavailable <= $time);
1790         }
1791     }
1794     /**
1795      * Return true if is set description is hidden till available date
1796      *
1797      * This is needed by calendar so that hidden descriptions do not
1798      * come up in upcoming events.
1799      *
1800      * Check that description is hidden till available date
1801      * By default return false
1802      * Assignments types should implement this method if needed
1803      * @return boolen
1804      */
1805     function description_is_hidden() {
1806         return false;
1807     }
1809     /**
1810      * Return an outline of the user's interaction with the assignment
1811      *
1812      * The default method prints the grade and timemodified
1813      * @param $grade object
1814      * @return object with properties ->info and ->time
1815      */
1816     function user_outline($grade) {
1818         $result = new object();
1819         $result->info = get_string('grade').': '.$grade->str_long_grade;
1820         $result->time = $grade->dategraded;
1821         return $result;
1822     }
1824     /**
1825      * Print complete information about the user's interaction with the assignment
1826      *
1827      * @param $user object
1828      */
1829     function user_complete($user, $grade=null) {
1830         global $OUTPUT;
1831         if ($grade) {
1832             echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
1833             if ($grade->str_feedback) {
1834                 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
1835             }
1836         }
1838         if ($submission = $this->get_submission($user->id)) {
1840             $fs = get_file_storage();
1842             if ($files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $user->id, "timemodified", false)) {
1843                 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
1844                 foreach ($files as $file) {
1845                     $countfiles .= "; ".$file->get_filename();
1846                 }
1847             }
1849             echo $OUTPUT->box_start();
1850             echo get_string("lastmodified").": ";
1851             echo userdate($submission->timemodified);
1852             echo $this->display_lateness($submission->timemodified);
1854             $this->print_user_files($user->id);
1856             echo '<br />';
1858             $this->view_feedback($submission);
1860             echo $OUTPUT->box_end();
1862         } else {
1863             print_string("notsubmittedyet", "assignment");
1864         }
1865     }
1867     /**
1868      * Return a string indicating how late a submission is
1869      *
1870      * @param $timesubmitted int
1871      * @return string
1872      */
1873     function display_lateness($timesubmitted) {
1874         return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
1875     }
1877     /**
1878      * Empty method stub for all delete actions.
1879      */
1880     function delete() {
1881         //nothing by default
1882         redirect('view.php?id='.$this->cm->id);
1883     }
1885     /**
1886      * Empty custom feedback grading form.
1887      */
1888     function custom_feedbackform($submission, $return=false) {
1889         //nothing by default
1890         return '';
1891     }
1893     /**
1894      * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
1895      * for the course (see resource).
1896      *
1897      * Given a course_module object, this function returns any "extra" information that may be needed
1898      * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
1899      *
1900      * @param $coursemodule object The coursemodule object (record).
1901      * @return object An object on information that the coures will know about (most noticeably, an icon).
1902      *
1903      */
1904     function get_coursemodule_info($coursemodule) {
1905         return false;
1906     }
1908     /**
1909      * Plugin cron method - do not use $this here, create new assignment instances if needed.
1910      * @return void
1911      */
1912     function cron() {
1913         //no plugin cron by default - override if needed
1914     }
1916     /**
1917      * Reset all submissions
1918      */
1919     function reset_userdata($data) {
1920         global $CFG, $DB;
1922         if (!$DB->count_records('assignment', array('course'=>$data->courseid, 'assignmenttype'=>$this->type))) {
1923             return array(); // no assignments of this type present
1924         }
1926         $componentstr = get_string('modulenameplural', 'assignment');
1927         $status = array();
1929         $typestr = get_string('type'.$this->type, 'assignment');
1930         // ugly hack to support pluggable assignment type titles...
1931         if($typestr === '[[type'.$this->type.']]'){
1932             $typestr = get_string('type'.$this->type, 'assignment_'.$this->type);
1933         }
1935         if (!empty($data->reset_assignment_submissions)) {
1936             $assignmentssql = "SELECT a.id
1937                                  FROM {assignment} a
1938                                 WHERE a.course=? AND a.assignmenttype=?";
1939             $params = array($data->courseid, $this->type);
1941             // now get rid of all submissions and responses
1942             $fs = get_file_storage();
1943             if ($assignments = $DB->get_records_sql($assignmentssql, $params)) {
1944                 foreach ($assignments as $assignmentid=>$unused) {
1945                     if (!$cm = get_coursemodule_from_instance('assignment', $assignmentid)) {
1946                         continue;
1947                     }
1948                     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1949                     $fs->delete_area_files($context->id, 'mod_assignment', 'submission');
1950                     $fs->delete_area_files($context->id, 'mod_assignment', 'response');
1951                 }
1952             }
1954             $DB->delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)", $params);
1956             $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
1958             if (empty($data->reset_gradebook_grades)) {
1959                 // remove all grades from gradebook
1960                 assignment_reset_gradebook($data->courseid, $this->type);
1961             }
1962         }
1964         /// updating dates - shift may be negative too
1965         if ($data->timeshift) {
1966             shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
1967             $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
1968         }
1970         return $status;
1971     }
1974     function portfolio_exportable() {
1975         return false;
1976     }
1978     /**
1979      * base implementation for backing up subtype specific information
1980      * for one single module
1981      *
1982      * @param filehandle $bf file handle for xml file to write to
1983      * @param mixed $preferences the complete backup preference object
1984      *
1985      * @return boolean
1986      *
1987      * @static
1988      */
1989     static function backup_one_mod($bf, $preferences, $assignment) {
1990         return true;
1991     }
1993     /**
1994      * base implementation for backing up subtype specific information
1995      * for one single submission
1996      *
1997      * @param filehandle $bf file handle for xml file to write to
1998      * @param mixed $preferences the complete backup preference object
1999      * @param object $submission the assignment submission db record
2000      *
2001      * @return boolean
2002      *
2003      * @static
2004      */
2005     static function backup_one_submission($bf, $preferences, $assignment, $submission) {
2006         return true;
2007     }
2009     /**
2010      * base implementation for restoring subtype specific information
2011      * for one single module
2012      *
2013      * @param array  $info the array representing the xml
2014      * @param object $restore the restore preferences
2015      *
2016      * @return boolean
2017      *
2018      * @static
2019      */
2020     static function restore_one_mod($info, $restore, $assignment) {
2021         return true;
2022     }
2024     /**
2025      * base implementation for restoring subtype specific information
2026      * for one single submission
2027      *
2028      * @param object $submission the newly created submission
2029      * @param array  $info the array representing the xml
2030      * @param object $restore the restore preferences
2031      *
2032      * @return boolean
2033      *
2034      * @static
2035      */
2036     static function restore_one_submission($info, $restore, $assignment, $submission) {
2037         return true;
2038     }
2040 } ////// End of the assignment_base class
2043 class mod_assignment_online_grading_form extends moodleform { // TODO: why "online" in the name of this class? (skodak)
2045     function definition() {
2046         global $OUTPUT;
2047         $mform =& $this->_form;
2049         $formattr = $mform->getAttributes();
2050         $formattr['id'] = 'submitform';
2051         $mform->setAttributes($formattr);
2052         // hidden params
2053         $mform->addElement('hidden', 'offset', ($this->_customdata->offset+1));
2054         $mform->setType('offset', PARAM_INT);
2055         $mform->addElement('hidden', 'userid', $this->_customdata->userid);
2056         $mform->setType('userid', PARAM_INT);
2057         $mform->addElement('hidden', 'nextid', $this->_customdata->nextid);
2058         $mform->setType('nextid', PARAM_INT);
2059         $mform->addElement('hidden', 'id', $this->_customdata->cm->id);
2060         $mform->setType('id', PARAM_INT);
2061         $mform->addElement('hidden', 'sesskey', sesskey());
2062         $mform->setType('sesskey', PARAM_ALPHANUM);
2063         $mform->addElement('hidden', 'mode', 'grade');
2064         $mform->setType('mode', PARAM_INT);
2065         $mform->addElement('hidden', 'menuindex', "0");
2066         $mform->setType('menuindex', PARAM_INT);
2067         $mform->addElement('hidden', 'saveuserid', "-1");
2068         $mform->setType('saveuserid', PARAM_INT);
2070         $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->user),
2071                                                 fullname($this->_customdata->user, true) . '<br/>' .
2072                                                 userdate($this->_customdata->submission->timemodified) .
2073                                                 $this->_customdata->lateness );
2075         $this->add_grades_section();
2077         $this->add_feedback_section();
2079         if ($this->_customdata->submission->timemarked) {
2080             $mform->addElement('header', 'Last Grade', get_string('lastgrade', 'assignment'));
2081             $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->teacher) ,
2082                                                     fullname($this->_customdata->teacher,true).
2083                                                     '<br/>'.
2084                                                     userdate($this->_customdata->submission->timemarked));
2085         }
2086         // buttons
2087         $this->add_action_buttons();
2089         $this->add_submission_content();
2090     }
2092     function add_grades_section() {
2093         global $CFG;
2094         $mform =& $this->_form;
2095         $attributes = array();
2096         if ($this->_customdata->gradingdisabled) {
2097             $attributes['disabled'] ='disabled';
2098         }
2100         $grademenu = make_grades_menu($this->_customdata->assignment->grade);
2101         $grademenu['-1'] = get_string('nograde');
2103         $mform->addElement('header', 'Grades', get_string('grades', 'grades'));
2104         $mform->addElement('select', 'xgrade', get_string('grade').':', $grademenu, $attributes);
2105         $mform->setDefault('xgrade', $this->_customdata->submission->grade ); //@fixme some bug when element called 'grade' makes it break
2106         $mform->setType('xgrade', PARAM_INT);
2108         if (!empty($this->_customdata->enableoutcomes)) {
2109             foreach($this->_customdata->grading_info->outcomes as $n=>$outcome) {
2110                 $options = make_grades_menu(-$outcome->scaleid);
2111                 if ($outcome->grades[$this->_customdata->submission->userid]->locked) {
2112                     $options[0] = get_string('nooutcome', 'grades');
2113                     echo $options[$outcome->grades[$this->_customdata->submission->userid]->grade];
2114                 } else {
2115                     $options[''] = get_string('nooutcome', 'grades');
2116                     $attributes = array('id' => 'menuoutcome_'.$n );
2117                     $mform->addElement('select', 'outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->name.':', $options, $attributes );
2118                     $mform->setType('outcome_'.$n.'['.$this->_customdata->userid.']', PARAM_INT);
2119                     $mform->setDefault('outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->grades[$this->_customdata->submission->userid]->grade );
2120                 }
2121             }
2122         }
2123         $course_context = get_context_instance(CONTEXT_MODULE , $this->_customdata->cm->id);
2124         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
2125             $grade = '<a href="'.$CFG->wwwroot.'/grade/report/grader/index.php?id='. $this->_customdata->courseid .'" >'.
2126                         $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade . '</a>';
2127         }else{
2128             $grade = $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade;
2129         }
2130         $mform->addElement('static', 'finalgrade', get_string('currentgrade', 'assignment').':' ,$grade);
2131         $mform->setType('finalgrade', PARAM_INT);
2132     }
2134     /**
2135      *
2136      * @global core_renderer $OUTPUT
2137      */
2138     function add_feedback_section() {
2139         global $OUTPUT;
2140         $mform =& $this->_form;
2141         $mform->addElement('header', 'Feed Back', get_string('feedback', 'grades'));
2143         if ($this->_customdata->gradingdisabled) {
2144             $mform->addElement('static', 'disabledfeedback', $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_feedback );
2145         } else {
2146             // visible elements
2148             $mform->addElement('editor', 'submissioncomment_editor', get_string('feedback', 'assignment').':', null, $this->get_editor_options() );
2149             $mform->setType('submissioncomment_editor', PARAM_RAW); // to be cleaned before display
2150             $mform->setDefault('submissioncomment_editor', $this->_customdata->submission->submissioncomment);
2151             //$mform->addRule('submissioncomment', get_string('required'), 'required', null, 'client');
2153             if ($this->_customdata->usehtmleditor) {
2154                 $mform->addElement('hidden', 'format', FORMAT_HTML);
2155                 $mform->setType('format', PARAM_INT);
2156             } else {
2157                 //format menu
2158                 $format_menu = format_text_menu();
2159                 $mform->addElement('select', 'format', get_string('format'), $format_menu, array('selected' => $this->_customdata->submission->format ) );
2160                 $mform->setType('format', PARAM_INT);
2161             }
2162             $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? array('checked'=>'checked') : array();
2163             $mform->addElement('hidden', 'mailinfo_h', "0");
2164             $mform->setType('mailinfo_h', PARAM_INT);
2165             $mform->addElement('checkbox', 'mailinfo',get_string('enableemailnotification','assignment').
2166                     $OUTPUT->help_icon('enableemailnotification', 'assignment') .':' );
2167             $mform->updateElementAttr('mailinfo', $lastmailinfo);
2168             $mform->setType('mailinfo', PARAM_INT);
2169         }
2170     }
2172     function add_action_buttons() {
2173         $mform =& $this->_form;
2174         $mform->addElement('header', 'Operation', get_string('operation', 'assignment'));
2175         //if there are more to be graded.
2176         if ($this->_customdata->nextid>0) {
2177             $buttonarray=array();
2178             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2179             //@todo: fix accessibility: javascript dependency not necessary
2180             $buttonarray[] = &$mform->createElement('submit', 'saveandnext', get_string('saveandnext'));
2181             $buttonarray[] = &$mform->createElement('submit', 'next', get_string('next'));
2182             $buttonarray[] = &$mform->createElement('cancel');
2183         } else {
2184             $buttonarray=array();
2185             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2186             $buttonarray[] = &$mform->createElement('cancel');
2187         }
2188         $mform->addGroup($buttonarray, 'grading_buttonar', '', array(' '), false);
2189         $mform->setType('grading_buttonar', PARAM_RAW);
2190     }
2192     function add_submission_content() {
2193         $mform =& $this->_form;
2194         $mform->addElement('header', 'Submission', get_string('submission', 'assignment'));
2195         $mform->addElement('static', '', '' , $this->_customdata->submission_content );
2196     }
2198     protected function get_editor_options() {
2199         $editoroptions = array();
2200         $editoroptions['component'] = 'mod_assignment';
2201         $editoroptions['filearea'] = 'feedback';
2202         $editoroptions['noclean'] = false;
2203         $editoroptions['maxfiles'] = 0; //TODO: no files for now, we need to first implement assignment_feedback area, integration with gradebook, files support in quickgrading, etc. (skodak)
2204         $editoroptions['maxbytes'] = $this->_customdata->maxbytes;
2205         return $editoroptions;
2206     }
2208     public function set_data($data) {
2209         $editoroptions = $this->get_editor_options();
2210         if (!isset($data->text)) {
2211             $data->text = '';
2212         }
2213         if (!isset($data->format)) {
2214             $data->textformat = FORMAT_HTML;
2215         } else {
2216             $data->textformat = $data->format;
2217         }
2219         if (!empty($this->_customdata->submission->id)) {
2220             $itemid = $this->_customdata->submission->id;
2221         } else {
2222             $itemid = null;
2223         }
2225         $data = file_prepare_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2226         return parent::set_data($data);
2227     }
2229     public function get_data() {
2230         $data = parent::get_data();
2232         if (!empty($this->_customdata->submission->id)) {
2233             $itemid = $this->_customdata->submission->id;
2234         } else {
2235             $itemid = null; //TODO: this is wrong, itemid MUST be known when saving files!! (skodak)
2236         }
2238         if ($data) {
2239             $editoroptions = $this->get_editor_options();
2240             $data = file_postupdate_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2241             $data->format = $data->textformat;
2242         }
2243         return $data;
2244     }
2247 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
2249 /**
2250  * Deletes an assignment instance
2251  *
2252  * This is done by calling the delete_instance() method of the assignment type class
2253  */
2254 function assignment_delete_instance($id){
2255     global $CFG, $DB;
2257     if (! $assignment = $DB->get_record('assignment', array('id'=>$id))) {
2258         return false;
2259     }
2261     // fall back to base class if plugin missing
2262     $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2263     if (file_exists($classfile)) {
2264         require_once($classfile);
2265         $assignmentclass = "assignment_$assignment->assignmenttype";
2267     } else {
2268         debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
2269         $assignmentclass = "assignment_base";
2270     }
2272     $ass = new $assignmentclass();
2273     return $ass->delete_instance($assignment);
2277 /**
2278  * Updates an assignment instance
2279  *
2280  * This is done by calling the update_instance() method of the assignment type class
2281  */
2282 function assignment_update_instance($assignment){
2283     global $CFG;
2285     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2287     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2288     $assignmentclass = "assignment_$assignment->assignmenttype";
2289     $ass = new $assignmentclass();
2290     return $ass->update_instance($assignment);
2294 /**
2295  * Adds an assignment instance
2296  *
2297  * This is done by calling the add_instance() method of the assignment type class
2298  */
2299 function assignment_add_instance($assignment) {
2300     global $CFG;
2302     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2304     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2305     $assignmentclass = "assignment_$assignment->assignmenttype";
2306     $ass = new $assignmentclass();
2307     return $ass->add_instance($assignment);
2311 /**
2312  * Returns an outline of a user interaction with an assignment
2313  *
2314  * This is done by calling the user_outline() method of the assignment type class
2315  */
2316 function assignment_user_outline($course, $user, $mod, $assignment) {
2317     global $CFG;
2319     require_once("$CFG->libdir/gradelib.php");
2320     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2321     $assignmentclass = "assignment_$assignment->assignmenttype";
2322     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2323     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2324     if (!empty($grades->items[0]->grades)) {
2325         return $ass->user_outline(reset($grades->items[0]->grades));
2326     } else {
2327         return null;
2328     }
2331 /**
2332  * Prints the complete info about a user's interaction with an assignment
2333  *
2334  * This is done by calling the user_complete() method of the assignment type class
2335  */
2336 function assignment_user_complete($course, $user, $mod, $assignment) {
2337     global $CFG;
2339     require_once("$CFG->libdir/gradelib.php");
2340     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2341     $assignmentclass = "assignment_$assignment->assignmenttype";
2342     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2343     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2344     if (empty($grades->items[0]->grades)) {
2345         $grade = false;
2346     } else {
2347         $grade = reset($grades->items[0]->grades);
2348     }
2349     return $ass->user_complete($user, $grade);
2352 /**
2353  * Function to be run periodically according to the moodle cron
2354  *
2355  * Finds all assignment notifications that have yet to be mailed out, and mails them
2356  */
2357 function assignment_cron () {
2358     global $CFG, $USER, $DB;
2360     /// first execute all crons in plugins
2361     if ($plugins = get_plugin_list('assignment')) {
2362         foreach ($plugins as $plugin=>$dir) {
2363             require_once("$dir/assignment.class.php");
2364             $assignmentclass = "assignment_$plugin";
2365             $ass = new $assignmentclass();
2366             $ass->cron();
2367         }
2368     }
2370     /// Notices older than 1 day will not be mailed.  This is to avoid the problem where
2371     /// cron has not been running for a long time, and then suddenly people are flooded
2372     /// with mail from the past few weeks or months
2374     $timenow   = time();
2375     $endtime   = $timenow - $CFG->maxeditingtime;
2376     $starttime = $endtime - 24 * 3600;   /// One day earlier
2378     if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2380         $realuser = clone($USER);
2382         foreach ($submissions as $key => $submission) {
2383             if (! $DB->set_field("assignment_submissions", "mailed", "1", array("id"=>$submission->id))) {
2384                 echo "Could not update the mailed field for id $submission->id.  Not mailed.\n";
2385                 unset($submissions[$key]);
2386             }
2387         }
2389         $timenow = time();
2391         foreach ($submissions as $submission) {
2393             echo "Processing assignment submission $submission->id\n";
2395             if (! $user = $DB->get_record("user", array("id"=>$submission->userid))) {
2396                 echo "Could not find user $post->userid\n";
2397                 continue;
2398             }
2400             if (! $course = $DB->get_record("course", array("id"=>$submission->course))) {
2401                 echo "Could not find course $submission->course\n";
2402                 continue;
2403             }
2405             /// Override the language and timezone of the "current" user, so that
2406             /// mail is customised for the receiver.
2407             cron_setup_user($user, $course);
2409             if (!is_enrolled(get_context_instance(CONTEXT_COURSE, $submission->course), $user->id)) {
2410                 echo fullname($user)." not an active participant in " . format_string($course->shortname) . "\n";
2411                 continue;
2412             }
2414             if (! $teacher = $DB->get_record("user", array("id"=>$submission->teacher))) {
2415                 echo "Could not find teacher $submission->teacher\n";
2416                 continue;
2417             }
2419             if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2420                 echo "Could not find course module for assignment id $submission->assignment\n";
2421                 continue;
2422             }
2424             if (! $mod->visible) {    /// Hold mail notification for hidden assignments until later
2425                 continue;
2426             }
2428             $strassignments = get_string("modulenameplural", "assignment");
2429             $strassignment  = get_string("modulename", "assignment");
2431             $assignmentinfo = new object();
2432             $assignmentinfo->teacher = fullname($teacher);
2433             $assignmentinfo->assignment = format_string($submission->name,true);
2434             $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2436             $postsubject = "$course->shortname: $strassignments: ".format_string($submission->name,true);
2437             $posttext  = "$course->shortname -> $strassignments -> ".format_string($submission->name,true)."\n";
2438             $posttext .= "---------------------------------------------------------------------\n";
2439             $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2440             $posttext .= "---------------------------------------------------------------------\n";
2442             if ($user->mailformat == 1) {  // HTML
2443                 $posthtml = "<p><font face=\"sans-serif\">".
2444                 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> ->".
2445                 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2446                 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2447                 $posthtml .= "<hr /><font face=\"sans-serif\">";
2448                 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2449                 $posthtml .= "</font><hr />";
2450             } else {
2451                 $posthtml = "";
2452             }
2454             $eventdata = new object();
2455             $eventdata->modulename       = 'assignment';
2456             $eventdata->userfrom         = $teacher;
2457             $eventdata->userto           = $user;
2458             $eventdata->subject          = $postsubject;
2459             $eventdata->fullmessage      = $posttext;
2460             $eventdata->fullmessageformat = FORMAT_PLAIN;
2461             $eventdata->fullmessagehtml  = $posthtml;
2462             $eventdata->smallmessage     = '';
2463             message_send($eventdata);
2464         }
2466         cron_setup_user();
2467     }
2469     return true;
2472 /**
2473  * Return grade for given user or all users.
2474  *
2475  * @param int $assignmentid id of assignment
2476  * @param int $userid optional user id, 0 means all users
2477  * @return array array of grades, false if none
2478  */
2479 function assignment_get_user_grades($assignment, $userid=0) {
2480     global $CFG, $DB;
2482     if ($userid) {
2483         $user = "AND u.id = :userid";
2484         $params = array('userid'=>$userid);
2485     } else {
2486         $user = "";
2487     }
2488     $params['aid'] = $assignment->id;
2490     $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2491                    s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2492               FROM {user} u, {assignment_submissions} s
2493              WHERE u.id = s.userid AND s.assignment = :aid
2494                    $user";
2496     return $DB->get_records_sql($sql, $params);
2499 /**
2500  * Update activity grades
2501  *
2502  * @param object $assignment
2503  * @param int $userid specific user only, 0 means all
2504  */
2505 function assignment_update_grades($assignment, $userid=0, $nullifnone=true) {
2506     global $CFG, $DB;
2507     require_once($CFG->libdir.'/gradelib.php');
2509     if ($assignment->grade == 0) {
2510         assignment_grade_item_update($assignment);
2512     } else if ($grades = assignment_get_user_grades($assignment, $userid)) {
2513         foreach($grades as $k=>$v) {
2514             if ($v->rawgrade == -1) {
2515                 $grades[$k]->rawgrade = null;
2516             }
2517         }
2518         assignment_grade_item_update($assignment, $grades);
2520     } else {
2521         assignment_grade_item_update($assignment);
2522     }
2525 /**
2526  * Update all grades in gradebook.
2527  */
2528 function assignment_upgrade_grades() {
2529     global $DB;
2531     $sql = "SELECT COUNT('x')
2532               FROM {assignment} a, {course_modules} cm, {modules} m
2533              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2534     $count = $DB->count_records_sql($sql);
2536     $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
2537               FROM {assignment} a, {course_modules} cm, {modules} m
2538              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2539     if ($rs = $DB->get_recordset_sql($sql)) {
2540         // too much debug output
2541         $pbar = new progress_bar('assignmentupgradegrades', 500, true);
2542         $i=0;
2543         foreach ($rs as $assignment) {
2544             $i++;
2545             upgrade_set_timeout(60*5); // set up timeout, may also abort execution
2546             assignment_update_grades($assignment);
2547             $pbar->update($i, $count, "Updating Assignment grades ($i/$count).");
2548         }
2549         $rs->close();
2550         upgrade_set_timeout(); // reset to default timeout
2551     }
2554 /**
2555  * Create grade item for given assignment
2556  *
2557  * @param object $assignment object with extra cmidnumber
2558  * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
2559  * @return int 0 if ok, error code otherwise
2560  */
2561 function assignment_grade_item_update($assignment, $grades=NULL) {
2562     global $CFG;
2563     require_once($CFG->libdir.'/gradelib.php');
2565     if (!isset($assignment->courseid)) {
2566         $assignment->courseid = $assignment->course;
2567     }
2569     $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
2571     if ($assignment->grade > 0) {
2572         $params['gradetype'] = GRADE_TYPE_VALUE;
2573         $params['grademax']  = $assignment->grade;
2574         $params['grademin']  = 0;
2576     } else if ($assignment->grade < 0) {
2577         $params['gradetype'] = GRADE_TYPE_SCALE;
2578         $params['scaleid']   = -$assignment->grade;
2580     } else {
2581         $params['gradetype'] = GRADE_TYPE_TEXT; // allow text comments only
2582     }
2584     if ($grades  === 'reset') {
2585         $params['reset'] = true;
2586         $grades = NULL;
2587     }
2589     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades, $params);
2592 /**
2593  * Delete grade item for given assignment
2594  *
2595  * @param object $assignment object
2596  * @return object assignment
2597  */
2598 function assignment_grade_item_delete($assignment) {
2599     global $CFG;
2600     require_once($CFG->libdir.'/gradelib.php');
2602     if (!isset($assignment->courseid)) {
2603         $assignment->courseid = $assignment->course;
2604     }
2606     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
2609 /**
2610  * Returns the users with data in one assignment (students and teachers)
2611  *
2612  * @param $assignmentid int
2613  * @return array of user objects
2614  */
2615 function assignment_get_participants($assignmentid) {
2616     global $CFG, $DB;
2618     //Get students
2619     $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2620                                         FROM {user} u,
2621                                              {assignment_submissions} a
2622                                        WHERE a.assignment = ? and
2623                                              u.id = a.userid", array($assignmentid));
2624     //Get teachers
2625     $teachers = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2626                                         FROM {user} u,
2627                                              {assignment_submissions} a
2628                                        WHERE a.assignment = ? and
2629                                              u.id = a.teacher", array($assignmentid));
2631     //Add teachers to students
2632     if ($teachers) {
2633         foreach ($teachers as $teacher) {
2634             $students[$teacher->id] = $teacher;
2635         }
2636     }
2637     //Return students array (it contains an array of unique users)
2638     return ($students);
2641 /**
2642  * Serves assignment submissions and other files.
2643  *
2644  * @param object $course
2645  * @param object $cm
2646  * @param object $context
2647  * @param string $filearea
2648  * @param array $args
2649  * @param bool $forcedownload
2650  * @return bool false if file not found, does not return if found - just send the file
2651  */
2652 function assignment_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) {
2653     global $CFG, $DB;
2655     if ($context->contextlevel != CONTEXT_MODULE) {
2656         return false;
2657     }
2659     require_login($course, false, $cm);
2661     if (!$assignment = $DB->get_record('assignment', array('id'=>$cm->instance))) {
2662         return false;
2663     }
2665     require_once($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
2666     $assignmentclass = 'assignment_'.$assignment->assignmenttype;
2667     $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm, $course);
2669     return $assignmentinstance->send_file($filearea, $args);
2671 /**
2672  * Checks if a scale is being used by an assignment
2673  *
2674  * This is used by the backup code to decide whether to back up a scale
2675  * @param $assignmentid int
2676  * @param $scaleid int
2677  * @return boolean True if the scale is used by the assignment
2678  */
2679 function assignment_scale_used($assignmentid, $scaleid) {
2680     global $DB;
2682     $return = false;
2684     $rec = $DB->get_record('assignment', array('id'=>$assignmentid,'grade'=>-$scaleid));
2686     if (!empty($rec) && !empty($scaleid)) {
2687         $return = true;
2688     }
2690     return $return;
2693 /**
2694  * Checks if scale is being used by any instance of assignment
2695  *
2696  * This is used to find out if scale used anywhere
2697  * @param $scaleid int
2698  * @return boolean True if the scale is used by any assignment
2699  */
2700 function assignment_scale_used_anywhere($scaleid) {
2701     global $DB;
2703     if ($scaleid and $DB->record_exists('assignment', array('grade'=>-$scaleid))) {
2704         return true;
2705     } else {
2706         return false;
2707     }
2710 /**
2711  * Make sure up-to-date events are created for all assignment instances
2712  *
2713  * This standard function will check all instances of this module
2714  * and make sure there are up-to-date events created for each of them.
2715  * If courseid = 0, then every assignment event in the site is checked, else
2716  * only assignment events belonging to the course specified are checked.
2717  * This function is used, in its new format, by restore_refresh_events()
2718  *
2719  * @param $courseid int optional If zero then all assignments for all courses are covered
2720  * @return boolean Always returns true
2721  */
2722 function assignment_refresh_events($courseid = 0) {
2723     global $DB;
2725     if ($courseid == 0) {
2726         if (! $assignments = $DB->get_records("assignment")) {
2727             return true;
2728         }
2729     } else {
2730         if (! $assignments = $DB->get_records("assignment", array("course"=>$courseid))) {
2731             return true;
2732         }
2733     }
2734     $moduleid = $DB->get_field('modules', 'id', array('name'=>'assignment'));
2736     foreach ($assignments as $assignment) {
2737         $cm = get_coursemodule_from_id('assignment', $assignment->id);
2738         $event = new object();
2739         $event->name        = $assignment->name;
2740         $event->description = format_module_intro('assignment', $assignment, $cm->id);
2741         $event->timestart   = $assignment->timedue;
2743         if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
2744             update_event($event);
2746         } else {
2747             $event->courseid    = $assignment->course;
2748             $event->groupid     = 0;
2749             $event->userid      = 0;
2750             $event->modulename  = 'assignment';
2751             $event->instance    = $assignment->id;
2752             $event->eventtype   = 'due';
2753             $event->timeduration = 0;
2754             $event->visible     = $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$assignment->id));
2755             add_event($event);
2756         }
2758     }
2759     return true;
2762 /**
2763  * Print recent activity from all assignments in a given course
2764  *
2765  * This is used by the recent activity block
2766  */
2767 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
2768     global $CFG, $USER, $DB, $OUTPUT;
2770     // do not use log table if possible, it may be huge
2772     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
2773                                                      u.firstname, u.lastname, u.email, u.picture
2774                                                 FROM {assignment_submissions} asb
2775                                                      JOIN {assignment} a      ON a.id = asb.assignment
2776                                                      JOIN {course_modules} cm ON cm.instance = a.id
2777                                                      JOIN {modules} md        ON md.id = cm.module
2778                                                      JOIN {user} u            ON u.id = asb.userid
2779                                                WHERE asb.timemodified > ? AND
2780                                                      a.course = ? AND
2781                                                      md.name = 'assignment'
2782                                             ORDER BY asb.timemodified ASC", array($timestart, $course->id))) {
2783          return false;
2784     }
2786     $modinfo =& get_fast_modinfo($course); // reference needed because we might load the groups
2787     $show    = array();
2788     $grader  = array();
2790     foreach($submissions as $submission) {
2791         if (!array_key_exists($submission->cmid, $modinfo->cms)) {
2792             continue;
2793         }
2794         $cm = $modinfo->cms[$submission->cmid];
2795         if (!$cm->uservisible) {
2796             continue;
2797         }
2798         if ($submission->userid == $USER->id) {
2799             $show[] = $submission;
2800             continue;
2801         }
2803         // the act of sumbitting of assignment may be considered private - only graders will see it if specified
2804         if (empty($CFG->assignment_showrecentsubmissions)) {
2805             if (!array_key_exists($cm->id, $grader)) {
2806                 $grader[$cm->id] = has_capability('moodle/grade:viewall', get_context_instance(CONTEXT_MODULE, $cm->id));
2807             }
2808             if (!$grader[$cm->id]) {
2809                 continue;
2810             }
2811         }
2813         $groupmode = groups_get_activity_groupmode($cm, $course);
2815         if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2816             if (isguestuser()) {
2817                 // shortcut - guest user does not belong into any group
2818                 continue;
2819             }
2821             if (is_null($modinfo->groups)) {
2822                 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2823             }
2825             // this will be slow - show only users that share group with me in this cm
2826             if (empty($modinfo->groups[$cm->id])) {
2827                 continue;
2828             }
2829             $usersgroups =  groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
2830             if (is_array($usersgroups)) {
2831                 $usersgroups = array_keys($usersgroups);
2832                 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2833                 if (empty($intersect)) {
2834                     continue;
2835                 }
2836             }
2837         }
2838         $show[] = $submission;
2839     }
2841     if (empty($show)) {
2842         return false;
2843     }
2845     echo $OUTPUT->heading(get_string('newsubmissions', 'assignment').':');
2847     foreach ($show as $submission) {
2848         $cm = $modinfo->cms[$submission->cmid];
2849         $link = $CFG->wwwroot.'/mod/assignment/view.php?id='.$cm->id;
2850         print_recent_activity_note($submission->timemodified, $submission, $cm->name, $link, false, $viewfullnames);
2851     }
2853     return true;
2857 /**
2858  * Returns all assignments since a given time in specified forum.
2859  */
2860 function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0)  {
2861     global $CFG, $COURSE, $USER, $DB;
2863     if ($COURSE->id == $courseid) {
2864         $course = $COURSE;
2865     } else {
2866         $course = $DB->get_record('course', array('id'=>$courseid));
2867     }
2869     $modinfo =& get_fast_modinfo($course);
2871     $cm = $modinfo->cms[$cmid];
2873     $params = array();
2874     if ($userid) {
2875         $userselect = "AND u.id = :userid";
2876         $params['userid'] = $userid;
2877     } else {
2878         $userselect = "";
2879     }
2881     if ($groupid) {
2882         $groupselect = "AND gm.groupid = :groupid";
2883         $groupjoin   = "JOIN {groups_members} gm ON  gm.userid=u.id";
2884         $params['groupid'] = $groupid;
2885     } else {
2886         $groupselect = "";
2887         $groupjoin   = "";
2888     }
2890     $params['cminstance'] = $cm->instance;
2891     $params['timestart'] = $timestart;
2893     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, asb.userid,
2894                                                      u.firstname, u.lastname, u.email, u.picture
2895                                                 FROM {assignment_submissions} asb
2896                                                 JOIN {assignment} a      ON a.id = asb.assignment
2897                                                 JOIN {user} u            ON u.id = asb.userid
2898                                           $groupjoin
2899                                                WHERE asb.timemodified > :timestart AND a.id = :cminstance
2900                                                      $userselect $groupselect
2901                                             ORDER BY asb.timemodified ASC", $params)) {
2902          return;
2903     }
2905     $groupmode       = groups_get_activity_groupmode($cm, $course);
2906     $cm_context      = get_context_instance(CONTEXT_MODULE, $cm->id);
2907     $grader          = has_capability('moodle/grade:viewall', $cm_context);
2908     $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
2909     $viewfullnames   = has_capability('moodle/site:viewfullnames', $cm_context);
2911     if (is_null($modinfo->groups)) {
2912         $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2913     }
2915     $show = array();
2917     foreach($submissions as $submission) {
2918         if ($submission->userid == $USER->id) {
2919             $show[] = $submission;
2920             continue;
2921         }
2922         // the act of submitting of assignment may be considered private - only graders will see it if specified
2923         if (empty($CFG->assignment_showrecentsubmissions)) {
2924             if (!$grader) {
2925                 continue;
2926             }
2927         }
2929         if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
2930             if (isguestuser()) {
2931                 // shortcut - guest user does not belong into any group
2932                 continue;
2933             }
2935             // this will be slow - show only users that share group with me in this cm
2936             if (empty($modinfo->groups[$cm->id])) {
2937                 continue;
2938             }
2939             $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
2940             if (is_array($usersgroups)) {
2941                 $usersgroups = array_keys($usersgroups);
2942                 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2943                 if (empty($intersect)) {
2944                     continue;
2945                 }
2946             }
2947         }
2948         $show[] = $submission;
2949     }
2951     if (empty($show)) {
2952         return;
2953     }
2955     if ($grader) {
2956         require_once($CFG->libdir.'/gradelib.php');
2957         $userids = array();
2958         foreach ($show as $id=>$submission) {
2959             $userids[] = $submission->userid;
2961         }
2962         $grades = grade_get_grades($courseid, 'mod', 'assignment', $cm->instance, $userids);
2963     }
2965     $aname = format_string($cm->name,true);
2966     foreach ($show as $submission) {
2967         $tmpactivity = new object();
2969         $tmpactivity->type         = 'assignment';
2970         $tmpactivity->cmid         = $cm->id;
2971         $tmpactivity->name         = $aname;
2972         $tmpactivity->sectionnum   = $cm->sectionnum;
2973         $tmpactivity->timestamp    = $submission->timemodified;
2975         if ($grader) {
2976             $tmpactivity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
2977         }
2979         $tmpactivity->user->userid   = $submission->userid;
2980         $tmpactivity->user->fullname = fullname($submission, $viewfullnames);
2981         $tmpactivity->user->picture  = $submission->picture;
2983         $activities[$index++] = $tmpactivity;
2984     }
2986     return;
2989 /**
2990  * Print recent activity from all assignments in a given course
2991  *
2992  * This is used by course/recent.php
2993  */
2994 function assignment_print_recent_mod_activity($activity, $courseid, $detail, $modnames)  {
2995     global $CFG, $OUTPUT;
2997     echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
2999     echo "<tr><td class=\"userpicture\" valign=\"top\">";
3000     echo $OUTPUT->user_picture($activity->user);
3001     echo "</td><td>";
3003     if ($detail) {
3004         $modname = $modnames[$activity->type];
3005         echo '<div class="title">';
3006         echo "<img src=\"" . $OUTPUT->pix_url('icon', 'assignment') . "\" ".
3007              "class=\"icon\" alt=\"$modname\">";
3008         echo "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id={$activity->cmid}\">{$activity->name}</a>";
3009         echo '</div>';
3010     }
3012     if (isset($activity->grade)) {
3013         echo '<div class="grade">';
3014         echo get_string('grade').': ';
3015         echo $activity->grade;
3016         echo '</div>';
3017     }
3019     echo '<div class="user">';
3020     echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->userid}&amp;course=$courseid\">"
3021          ."{$activity->user->fullname}</a>  - ".userdate($activity->timestamp);
3022     echo '</div>';
3024     echo "</td></tr></table>";
3027 /// GENERIC SQL FUNCTIONS
3029 /**
3030  * Fetch info from logs
3031  *
3032  * @param $log object with properties ->info (the assignment id) and ->userid
3033  * @return array with assignment name and user firstname and lastname
3034  */
3035 function assignment_log_info($log) {
3036     global $CFG, $DB;
3038     return $DB->get_record_sql("SELECT a.name, u.firstname, u.lastname
3039                                   FROM {assignment} a, {user} u
3040                                  WHERE a.id = ? AND u.id = ?", array($log->info, $log->userid));
3043 /**
3044  * Return list of marked submissions that have not been mailed out for currently enrolled students
3045  *
3046  * @return array
3047  */
3048 function assignment_get_unmailed_submissions($starttime, $endtime) {
3049     global $CFG, $DB;
3051     return $DB->get_records_sql("SELECT s.*, a.course, a.name
3052                                    FROM {assignment_submissions} s,
3053                                         {assignment} a
3054                                   WHERE s.mailed = 0
3055                                         AND s.timemarked <= ?
3056                                         AND s.timemarked >= ?
3057                                         AND s.assignment = a.id", array($endtime, $starttime));
3060 /**
3061  * Counts all real assignment submissions by ENROLLED students (not empty ones)
3062  *
3063  * There are also assignment type methods count_real_submissions() wich in the default
3064  * implementation simply call this function.
3065  * @param $groupid int optional If nonzero then count is restricted to this group
3066  * @return int The number of submissions
3067  */
3068 function assignment_count_real_submissions($cm, $groupid=0) {
3069     global $CFG, $DB;
3071     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
3073     // this is all the users with this capability set, in this context or higher
3074     if ($users = get_enrolled_users($context, 'mod/assignment:submit', $groupid, 'u.id')) {
3075         $users = array_keys($users);
3076     }
3078     // if groupmembersonly used, remove users who are not in any group
3079     if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
3080         if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
3081             $users = array_intersect($users, array_keys($groupingusers));
3082         }
3083     }
3085     if (empty($users)) {
3086         return 0;
3087     }
3089     $userlists = implode(',', $users);
3091     return $DB->count_records_sql("SELECT COUNT('x')
3092                                      FROM {assignment_submissions}
3093                                     WHERE assignment = ? AND
3094                                           timemodified > 0 AND
3095                                           userid IN ($userlists)", array($cm->instance));
3099 /**
3100  * Return all assignment submissions by ENROLLED students (even empty)
3101  *
3102  * There are also assignment type methods get_submissions() wich in the default
3103  * implementation simply call this function.
3104  * @param $sort string optional field names for the ORDER BY in the sql query
3105  * @param $dir string optional specifying the sort direction, defaults to DESC
3106  * @return array The submission objects indexed by id
3107  */
3108 function assignment_get_all_submissions($assignment, $sort="", $dir="DESC") {
3109 /// Return all assignment submissions by ENROLLED students (even empty)
3110     global $CFG, $DB;
3112     if ($sort == "lastname" or $sort == "firstname") {
3113         $sort = "u.$sort $dir";
3114     } else if (empty($sort)) {
3115         $sort = "a.timemodified DESC";
3116     } else {
3117         $sort = "a.$sort $dir";
3118     }
3120     /* not sure this is needed at all since assignmenet already has a course define, so this join?
3121     $select = "s.course = '$assignment->course' AND";
3122     if ($assignment->course == SITEID) {
3123         $select = '';
3124     }*/
3126     return $DB->get_records_sql("SELECT a.*
3127                                    FROM {assignment_submissions} a, {user} u
3128                                   WHERE u.id = a.userid
3129                                         AND a.assignment = ?
3130                                ORDER BY $sort", array($assignment->id));
3134 /**
3135  * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
3136  * for the course (see resource).
3137  *
3138  * Given a course_module object, this function returns any "extra" information that may be needed
3139  * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
3140  *
3141  * @param $coursemodule object The coursemodule object (record).
3142  * @return object An object on information that the coures will know about (most noticeably, an icon).
3143  *
3144  */
3145 function assignment_get_coursemodule_info($coursemodule) {
3146     global $CFG, $DB;
3148     if (! $assignment = $DB->get_record('assignment', array('id'=>$coursemodule->instance), 'id, assignmenttype, name')) {
3149         return false;
3150     }
3152     $libfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
3154     if (file_exists($libfile)) {
3155         require_once($libfile);
3156         $assignmentclass = "assignment_$assignment->assignmenttype";
3157         $ass = new $assignmentclass('staticonly');
3158         if ($result = $ass->get_coursemodule_info($coursemodule)) {
3159             return $result;
3160         } else {
3161             $info = new object();
3162             $info->name = $assignment->name;
3163             return $info;
3164         }
3166     } else {
3167         debugging('Incorrect assignment type: '.$assignment->assignmenttype);
3168         return false;
3169     }
3174 /// OTHER GENERAL FUNCTIONS FOR ASSIGNMENTS  ///////////////////////////////////////
3176 /**
3177  * Returns an array of installed assignment types indexed and sorted by name
3178  *
3179  * @return array The index is the name of the assignment type, the value its full name from the language strings
3180  */
3181 function assignment_types() {
3182     $types = array();
3183     $names = get_plugin_list('assignment');
3184     foreach ($names as $name=>$dir) {
3185         $types[$name] = get_string('type'.$name, 'assignment');
3187         // ugly hack to support pluggable assignment type titles..
3188         if ($types[$name] == '[[type'.$name.']]') {
3189             $types[$name] = get_string('type'.$name, 'assignment_'.$name);
3190         }
3191     }
3192     asort($types);
3193     return $types;
3196 function assignment_print_overview($courses, &$htmlarray) {
3197     global $USER, $CFG, $DB;
3199     if (empty($courses) || !is_array($courses) || count($courses) == 0) {
3200         return array();
3201     }
3203     if (!$assignments = get_all_instances_in_courses('assignment',$courses)) {
3204         return;
3205     }
3207     $assignmentids = array();
3209     // Do assignment_base::isopen() here without loading the whole thing for speed
3210     foreach ($assignments as $key => $assignment) {
3211         $time = time();
3212         if ($assignment->timedue) {
3213             if ($assignment->preventlate) {
3214                 $isopen = ($assignment->timeavailable <= $time && $time <= $assignment->timedue);
3215             } else {
3216                 $isopen = ($assignment->timeavailable <= $time);
3217             }
3218         }
3219         if (empty($isopen) || empty($assignment->timedue)) {
3220             unset($assignments[$key]);
3221         } else {
3222             $assignmentids[] = $assignment->id;
3223         }
3224     }
3226     if (empty($assignmentids)){
3227         // no assigments to look at - we're done
3228         return true;
3229     }
3231     $strduedate = get_string('duedate', 'assignment');
3232     $strduedateno = get_string('duedateno', 'assignment');
3233     $strgraded = get_string('graded', 'assignment');
3234     $strnotgradedyet = get_string('notgradedyet', 'assignment');
3235     $strnotsubmittedyet = get_string('notsubmittedyet', 'assignment');
3236     $strsubmitted = get_string('submitted', 'assignment');
3237     $strassignment = get_string('modulename', 'assignment');
3238     $strreviewed = get_string('reviewed','assignment');
3241     // NOTE: we do all possible database work here *outside* of the loop to ensure this scales
3242     //
3243     list($sqlassignmentids, $assignmentidparams) = $DB->get_in_or_equal($assignmentids);
3245     // build up and array of unmarked submissions indexed by assigment id/ userid
3246     // for use where the user has grading rights on assigment
3247     $rs = $DB->get_recordset_sql("SELECT id, assignment, userid
3248                             FROM {assignment_submissions}
3249                             WHERE teacher = 0 AND timemarked = 0
3250                             AND assignment $sqlassignmentids", $assignmentidparams);
3252     $unmarkedsubmissions = array();
3253     foreach ($rs as $rd) {
3254         $unmarkedsubmissions[$rd->assignment][$rd->userid] = $rd->id;
3255     }
3256     $rs->close();
3259     // get all user submissions, indexed by assigment id
3260     $mysubmissions = $DB->get_records_sql("SELECT assignment, timemarked, teacher, grade
3261                                       FROM {assignment_submissions}
3262                                       WHERE userid = ? AND
3263                                       assignment $sqlassignmentids", array_merge(array($USER->id), $assignmentidparams));
3265     foreach ($assignments as $assignment) {
3266         $str = '<div class="assignment overview"><div class="name">'.$strassignment. ': '.
3267                '<a '.($assignment->visible ? '':' class="dimmed"').
3268                'title="'.$strassignment.'" href="'.$CFG->wwwroot.
3269                '/mod/assignment/view.php?id='.$assignment->coursemodule.'">'.
3270                $assignment->name.'</a></div>';
3271         if ($assignment->timedue) {
3272             $str .= '<div class="info">'.$strduedate.': '.userdate($assignment->timedue).'</div>';
3273         } else {
3274             $str .= '<div class="info">'.$strduedateno.'</div>';
3275         }
3276         $context = get_context_instance(CONTEXT_MODULE, $assignment->coursemodule);
3277         if (has_capability('mod/assignment:grade', $context)) {
3279             // count how many people can submit
3280             $submissions = 0; // init
3281             if ($students = get_enrolled_users($context, 'mod/assignment:submit', 0, 'u.id')) {
3282                 foreach ($students as $student) {
3283                     if (isset($unmarkedsubmissions[$assignment->id][$student->id])) {
3284                         $submissions++;
3285                     }
3286                 }
3287             }
3289             if ($submissions) {
3290                 $link = new moodle_url('/mod/assignment/submissions.php', array('id'=>$assignment->coursemodule));
3291                 $str .= '<div class="details"><a href="'.$link.'">'.get_string('submissionsnotgraded', 'assignment', $submissions).'</a></div>';
3292             }
3293         } else {
3294             $str .= '<div class="details">';
3295             if (isset($mysubmissions[$assignment->id])) {
3297                 $submission = $mysubmissions[$assignment->id];
3299                 if ($submission->teacher == 0 && $submission->timemarked == 0) {
3300                     $str .= $strsubmitted . ', ' . $strnotgradedyet;
3301                 } else if ($submission->grade <= 0) {
3302                     $str .= $strsubmitted . ', ' . $strreviewed;
3303                 } else {
3304                     $str .= $strsubmitted . ', ' . $strgraded;
3305                 }
3306             } else {
3307                 $str .= $strnotsubmittedyet . ' ' . assignment_display_lateness(time(), $assignment->timedue);
3308             }
3309             $str .= '</div>';
3310         }
3311         $str .= '</div>';
3312         if (empty($htmlarray[$assignment->course]['assignment'])) {
3313             $htmlarray[$assignment->course]['assignment'] = $str;
3314         } else {
3315             $htmlarray[$assignment->course]['assignment'] .= $str;
3316         }
3317     }
3320 function assignment_display_lateness($timesubmitted, $timedue) {
3321     if (!$timedue) {
3322         return '';
3323     }
3324     $time = $timedue - $timesubmitted;
3325     if ($time < 0) {
3326         $timetext = get_string('late', 'assignment', format_time($time));
3327         return ' (<span class="late">'.$timetext.'</span>)';
3328     } else {
3329         $timetext = get_string('early', 'assignment', format_time($time));
3330         return ' (<span class="early">'.$timetext.'</span>)';
3331     }
3334 function assignment_get_view_actions() {
3335     return array('view');
3338 function assignment_get_post_actions() {
3339     return array('upload');
3342 function assignment_get_types() {
3343     global $CFG;
3344     $types = array();
3346     $type = new object();
3347     $type->modclass = MOD_CLASS_ACTIVITY;
3348     $type->type = "assignment_group_start";
3349     $type->typestr = '--'.get_string('modulenameplural', 'assignment');
3350     $types[] = $type;
3352     $standardassignments = array('upload','online','uploadsingle','offline');
3353     foreach ($standardassignments as $assignmenttype) {
3354         $type = new object();
3355         $type->modclass = MOD_CLASS_ACTIVITY;
3356         $type->type = "assignment&amp;type=$assignmenttype";
3357         $type->typestr = get_string("type$assignmenttype", 'assignment');
3358         $types[] = $type;
3359     }
3361     /// Drop-in extra assignment types
3362     $assignmenttypes = get_list_of_plugins('mod/assignment/type');
3363     foreach ($assignmenttypes as $assignmenttype) {
3364         if (!empty($CFG->{'assignment_hide_'.$assignmenttype})) {  // Not wanted
3365             continue;
3366         }
3367         if (!in_array($assignmenttype, $standardassignments)) {
3368             $type = new object();
3369             $type->modclass = MOD_CLASS_ACTIVITY;
3370             $type->type = "assignment&amp;type=$assignmenttype";
3371             $type->typestr = get_string("type$assignmenttype", 'assignment_'.$assignmenttype);
3372             $types[] = $type;
3373         }
3374     }
3376     $type = new object();
3377     $type->modclass = MOD_CLASS_ACTIVITY;
3378     $type->type = "assignment_group_end";
3379     $type->typestr = '--';
3380     $types[] = $type;
3382     return $types;
3385 /**