assignment MDL-23820 improved grading pages for file type assignments.
[moodle.git] / mod / assignment / lib.php
1 <?PHP
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
18 /**
19  * assignment_base is the base class for assignment types
20  *
21  * This class provides all the functionality for an assignment
22  *
23  * @package   mod-assignment
24  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
25  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26  */
28 /** Include eventslib.php */
29 require_once($CFG->libdir.'/eventslib.php');
30 /** Include formslib.php */
31 require_once($CFG->libdir.'/formslib.php');
32 /** Include calendar/lib.php */
33 require_once($CFG->dirroot.'/calendar/lib.php');
35 /** ASSIGNMENT_COUNT_WORDS = 1 */
36 DEFINE ('ASSIGNMENT_COUNT_WORDS', 1);
37 /** ASSIGNMENT_COUNT_LETTERS = 2 */
38 DEFINE ('ASSIGNMENT_COUNT_LETTERS', 2);
40 /**
41  * Standard base class for all assignment submodules (assignment types).
42  *
43  * @package   mod-assignment
44  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
45  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
46  */
47 class assignment_base {
49     const FILTER_ALL             = 0;
50     const FILTER_SUBMITTED       = 1;
51     const FILTER_REQUIRE_GRADING = 2;
53     /** @var object */
54     var $cm;
55     /** @var object */
56     var $course;
57     /** @var object */
58     var $assignment;
59     /** @var string */
60     var $strassignment;
61     /** @var string */
62     var $strassignments;
63     /** @var string */
64     var $strsubmissions;
65     /** @var string */
66     var $strlastmodified;
67     /** @var string */
68     var $pagetitle;
69     /** @var bool */
70     var $usehtmleditor;
71     /**
72      * @todo document this var
73      */
74     var $defaultformat;
75     /**
76      * @todo document this var
77      */
78     var $context;
79     /** @var string */
80     var $type;
82     /**
83      * Constructor for the base assignment class
84      *
85      * Constructor for the base assignment class.
86      * If cmid is set create the cm, course, assignment objects.
87      * If the assignment is hidden and the user is not a teacher then
88      * this prints a page header and notice.
89      *
90      * @global object
91      * @global object
92      * @param int $cmid the current course module id - not set for new assignments
93      * @param object $assignment usually null, but if we have it we pass it to save db access
94      * @param object $cm usually null, but if we have it we pass it to save db access
95      * @param object $course usually null, but if we have it we pass it to save db access
96      */
97     function assignment_base($cmid='staticonly', $assignment=NULL, $cm=NULL, $course=NULL) {
98         global $COURSE, $DB;
100         if ($cmid == 'staticonly') {
101             //use static functions only!
102             return;
103         }
105         global $CFG;
107         if ($cm) {
108             $this->cm = $cm;
109         } else if (! $this->cm = get_coursemodule_from_id('assignment', $cmid)) {
110             print_error('invalidcoursemodule');
111         }
113         $this->context = get_context_instance(CONTEXT_MODULE, $this->cm->id);
115         if ($course) {
116             $this->course = $course;
117         } else if ($this->cm->course == $COURSE->id) {
118             $this->course = $COURSE;
119         } else if (! $this->course = $DB->get_record('course', array('id'=>$this->cm->course))) {
120             print_error('invalidid', 'assignment');
121         }
123         if ($assignment) {
124             $this->assignment = $assignment;
125         } else if (! $this->assignment = $DB->get_record('assignment', array('id'=>$this->cm->instance))) {
126             print_error('invalidid', 'assignment');
127         }
129         $this->assignment->cmidnumber = $this->cm->idnumber; // compatibility with modedit assignment obj
130         $this->assignment->courseid   = $this->course->id; // compatibility with modedit assignment obj
132         $this->strassignment = get_string('modulename', 'assignment');
133         $this->strassignments = get_string('modulenameplural', 'assignment');
134         $this->strsubmissions = get_string('submissions', 'assignment');
135         $this->strlastmodified = get_string('lastmodified');
136         $this->pagetitle = strip_tags($this->course->shortname.': '.$this->strassignment.': '.format_string($this->assignment->name,true));
138         // visibility handled by require_login() with $cm parameter
139         // get current group only when really needed
141     /// Set up things for a HTML editor if it's needed
142         $this->defaultformat = editors_get_preferred_format();
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          if ($this->type == 'uploadsingle') { //@TODO: move to overload view_feedback method in the class or is uploadsingle merging into upload?
329             $responsefiles = $this->print_responsefiles($submission->userid, true);
330             if (!empty($responsefiles)) {
331                 echo '<tr>';
332                 echo '<td class="left side">&nbsp;</td>';
333                 echo '<td class="content">';
334                 echo $responsefiles;
335                 echo '</tr>';
336             }
337          }
339         echo '</table>';
340     }
342     /**
343      * Returns a link with info about the state of the assignment submissions
344      *
345      * This is used by view_header to put this link at the top right of the page.
346      * For teachers it gives the number of submitted assignments with a link
347      * For students it gives the time of their submission.
348      * This will be suitable for most assignment types.
349      *
350      * @global object
351      * @global object
352      * @param bool $allgroup print all groups info if user can access all groups, suitable for index.php
353      * @return string
354      */
355     function submittedlink($allgroups=false) {
356         global $USER;
357         global $CFG;
359         $submitted = '';
360         $urlbase = "{$CFG->wwwroot}/mod/assignment/";
362         $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
363         if (has_capability('mod/assignment:grade', $context)) {
364             if ($allgroups and has_capability('moodle/site:accessallgroups', $context)) {
365                 $group = 0;
366             } else {
367                 $group = groups_get_activity_group($this->cm);
368             }
369             if ($count = $this->count_real_submissions($group)) {
370                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
371                              get_string('viewsubmissions', 'assignment', $count).'</a>';
372             } else {
373                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
374                              get_string('noattempts', 'assignment').'</a>';
375             }
376         } else {
377             if (isloggedin()) {
378                 if ($submission = $this->get_submission($USER->id)) {
379                     if ($submission->timemodified) {
380                         if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
381                             $submitted = '<span class="early">'.userdate($submission->timemodified).'</span>';
382                         } else {
383                             $submitted = '<span class="late">'.userdate($submission->timemodified).'</span>';
384                         }
385                     }
386                 }
387             }
388         }
390         return $submitted;
391     }
394     /**
395      * @todo Document this function
396      */
397     function setup_elements(&$mform) {
399     }
401     /**
402      * Any preprocessing needed for the settings form for
403      * this assignment type
404      *
405      * @param array $default_values - array to fill in with the default values
406      *      in the form 'formelement' => 'value'
407      * @param object $form - the form that is to be displayed
408      * @return none
409      */
410     function form_data_preprocessing(&$default_values, $form) {
411     }
413     /**
414      * Any extra validation checks needed for the settings
415      * form for this assignment type
416      *
417      * See lib/formslib.php, 'validation' function for details
418      */
419     function form_validation($data, $files) {
420         return array();
421     }
423     /**
424      * Create a new assignment activity
425      *
426      * Given an object containing all the necessary data,
427      * (defined by the form in mod_form.php) this function
428      * will create a new instance and return the id number
429      * of the new instance.
430      * The due data is added to the calendar
431      * This is common to all assignment types.
432      *
433      * @global object
434      * @global object
435      * @param object $assignment The data from the form on mod_form.php
436      * @return int The id of the assignment
437      */
438     function add_instance($assignment) {
439         global $COURSE, $DB;
441         $assignment->timemodified = time();
442         $assignment->courseid = $assignment->course;
444         if ($returnid = $DB->insert_record("assignment", $assignment)) {
445             $assignment->id = $returnid;
447             if ($assignment->timedue) {
448                 $event = new object();
449                 $event->name        = $assignment->name;
450                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
451                 $event->courseid    = $assignment->course;
452                 $event->groupid     = 0;
453                 $event->userid      = 0;
454                 $event->modulename  = 'assignment';
455                 $event->instance    = $returnid;
456                 $event->eventtype   = 'due';
457                 $event->timestart   = $assignment->timedue;
458                 $event->timeduration = 0;
460                 calendar_event::create($event);
461             }
463             assignment_grade_item_update($assignment);
465         }
468         return $returnid;
469     }
471     /**
472      * Deletes an assignment activity
473      *
474      * Deletes all database records, files and calendar events for this assignment.
475      *
476      * @global object
477      * @global object
478      * @param object $assignment The assignment to be deleted
479      * @return boolean False indicates error
480      */
481     function delete_instance($assignment) {
482         global $CFG, $DB;
484         $assignment->courseid = $assignment->course;
486         $result = true;
488         // now get rid of all files
489         $fs = get_file_storage();
490         if ($cm = get_coursemodule_from_instance('assignment', $assignment->id)) {
491             $context = get_context_instance(CONTEXT_MODULE, $cm->id);
492             $fs->delete_area_files($context->id);
493         }
495         if (! $DB->delete_records('assignment_submissions', array('assignment'=>$assignment->id))) {
496             $result = false;
497         }
499         if (! $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
500             $result = false;
501         }
503         if (! $DB->delete_records('assignment', array('id'=>$assignment->id))) {
504             $result = false;
505         }
506         $mod = $DB->get_field('modules','id',array('name'=>'assignment'));
508         assignment_grade_item_delete($assignment);
510         return $result;
511     }
513     /**
514      * Updates a new assignment activity
515      *
516      * Given an object containing all the necessary data,
517      * (defined by the form in mod_form.php) this function
518      * will update the assignment instance and return the id number
519      * The due date is updated in the calendar
520      * This is common to all assignment types.
521      *
522      * @global object
523      * @global object
524      * @param object $assignment The data from the form on mod_form.php
525      * @return bool success
526      */
527     function update_instance($assignment) {
528         global $COURSE, $DB;
530         $assignment->timemodified = time();
532         $assignment->id = $assignment->instance;
533         $assignment->courseid = $assignment->course;
535         $DB->update_record('assignment', $assignment);
537         if ($assignment->timedue) {
538             $event = new object();
540             if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
542                 $event->name        = $assignment->name;
543                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
544                 $event->timestart   = $assignment->timedue;
546                 $calendarevent = calendar_event::load($event->id);
547                 $calendarevent->update($event);
548             } else {
549                 $event = new object();
550                 $event->name        = $assignment->name;
551                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
552                 $event->courseid    = $assignment->course;
553                 $event->groupid     = 0;
554                 $event->userid      = 0;
555                 $event->modulename  = 'assignment';
556                 $event->instance    = $assignment->id;
557                 $event->eventtype   = 'due';
558                 $event->timestart   = $assignment->timedue;
559                 $event->timeduration = 0;
561                 calendar_event::create($event);
562             }
563         } else {
564             $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id));
565         }
567         // get existing grade item
568         assignment_grade_item_update($assignment);
570         return true;
571     }
573     /**
574      * Update grade item for this submission.
575      */
576     function update_grade($submission) {
577         assignment_update_grades($this->assignment, $submission->userid);
578     }
580     /**
581      * Top-level function for handling of submissions called by submissions.php
582      *
583      * This is for handling the teacher interaction with the grading interface
584      * This should be suitable for most assignment types.
585      *
586      * @global object
587      * @param string $mode Specifies the kind of teacher interaction taking place
588      */
589     function submissions($mode) {
590         ///The main switch is changed to facilitate
591         ///1) Batch fast grading
592         ///2) Skip to the next one on the popup
593         ///3) Save and Skip to the next one on the popup
595         //make user global so we can use the id
596         global $USER, $OUTPUT, $DB, $PAGE;
598         $mailinfo = optional_param('mailinfo', null, PARAM_BOOL);
600         if (optional_param('next', null, PARAM_BOOL)) {
601             $mode='next';
602         }
603         if (optional_param('saveandnext', null, PARAM_BOOL)) {
604             $mode='saveandnext';
605         }
607         if (is_null($mailinfo)) {
608             if (optional_param('sesskey', null, PARAM_BOOL)) {
609                 set_user_preference('assignment_mailinfo', $mailinfo);
610             } else {
611                 $mailinfo = get_user_preferences('assignment_mailinfo', 0);
612             }
613         } else {
614             set_user_preference('assignment_mailinfo', $mailinfo);
615         }
617         switch ($mode) {
618             case 'grade':                         // We are in a main window grading
619                 if ($submission = $this->process_feedback()) {
620                     $this->display_submissions(get_string('changessaved'));
621                 } else {
622                     $this->display_submissions();
623                 }
624                 break;
626             case 'single':                        // We are in a main window displaying one submission
627                 if ($submission = $this->process_feedback()) {
628                     $this->display_submissions(get_string('changessaved'));
629                 } else {
630                     $this->display_submission();
631                 }
632                 break;
634             case 'all':                          // Main window, display everything
635                 $this->display_submissions();
636                 break;
638             case 'fastgrade':
639                 ///do the fast grading stuff  - this process should work for all 3 subclasses
640                 $grading    = false;
641                 $commenting = false;
642                 $col        = false;
643                 if (isset($_POST['submissioncomment'])) {
644                     $col = 'submissioncomment';
645                     $commenting = true;
646                 }
647                 if (isset($_POST['menu'])) {
648                     $col = 'menu';
649                     $grading = true;
650                 }
651                 if (!$col) {
652                     //both submissioncomment and grade columns collapsed..
653                     $this->display_submissions();
654                     break;
655                 }
657                 foreach ($_POST[$col] as $id => $unusedvalue){
659                     $id = (int)$id; //clean parameter name
661                     $this->process_outcomes($id);
663                     if (!$submission = $this->get_submission($id)) {
664                         $submission = $this->prepare_new_submission($id);
665                         $newsubmission = true;
666                     } else {
667                         $newsubmission = false;
668                     }
669                     unset($submission->data1);  // Don't need to update this.
670                     unset($submission->data2);  // Don't need to update this.
672                     //for fast grade, we need to check if any changes take place
673                     $updatedb = false;
675                     if ($grading) {
676                         $grade = $_POST['menu'][$id];
677                         $updatedb = $updatedb || ($submission->grade != $grade);
678                         $submission->grade = $grade;
679                     } else {
680                         if (!$newsubmission) {
681                             unset($submission->grade);  // Don't need to update this.
682                         }
683                     }
684                     if ($commenting) {
685                         $commentvalue = trim($_POST['submissioncomment'][$id]);
686                         $updatedb = $updatedb || ($submission->submissioncomment != $commentvalue);
687                         $submission->submissioncomment = $commentvalue;
688                     } else {
689                         unset($submission->submissioncomment);  // Don't need to update this.
690                     }
692                     $submission->teacher    = $USER->id;
693                     if ($updatedb) {
694                         $submission->mailed = (int)(!$mailinfo);
695                     }
697                     $submission->timemarked = time();
699                     //if it is not an update, we don't change the last modified time etc.
700                     //this will also not write into database if no submissioncomment and grade is entered.
702                     if ($updatedb){
703                         if ($newsubmission) {
704                             if (!isset($submission->submissioncomment)) {
705                                 $submission->submissioncomment = '';
706                             }
707                             $sid = $DB->insert_record('assignment_submissions', $submission);
708                             $submission->id = $sid;
709                         } else {
710                             $DB->update_record('assignment_submissions', $submission);
711                         }
713                         // triger grade event
714                         $this->update_grade($submission);
716                         //add to log only if updating
717                         add_to_log($this->course->id, 'assignment', 'update grades',
718                                    'submissions.php?id='.$this->assignment->id.'&user='.$submission->userid,
719                                    $submission->userid, $this->cm->id);
720                     }
722                 }
724                 $message = $OUTPUT->notification(get_string('changessaved'), 'notifysuccess');
726                 $this->display_submissions($message);
727                 break;
730             case 'saveandnext':
731                 ///We are in pop up. save the current one and go to the next one.
732                 //first we save the current changes
733                 if ($submission = $this->process_feedback()) {
734                     //print_heading(get_string('changessaved'));
735                     //$extra_javascript = $this->update_main_listing($submission);
736                 }
738             case 'next':
739                 /// We are currently in pop up, but we want to skip to next one without saving.
740                 ///    This turns out to be similar to a single case
741                 /// The URL used is for the next submission.
742                 $offset = required_param('offset', PARAM_INT);
743                 $nextid = required_param('nextid', PARAM_INT);
744                 $id = required_param('id', PARAM_INT);
745                 $offset = (int)$offset+1;
746                 //$this->display_submission($offset+1 , $nextid);
747                 redirect('submissions.php?id='.$id.'&userid='. $nextid . '&mode=single&offset='.$offset);
748                 break;
750             default:
751                 echo "something seriously is wrong!!";
752                 break;
753         }
754     }
756     /**
757      * Helper method updating the listing on the main script from popup using javascript
758      *
759      * @global object
760      * @global object
761      * @param $submission object The submission whose data is to be updated on the main page
762      */
763     function update_main_listing($submission) {
764         global $SESSION, $CFG, $OUTPUT;
766         $output = '';
768         $perpage = get_user_preferences('assignment_perpage', 10);
770         $quickgrade = get_user_preferences('assignment_quickgrade', 0);
772         /// Run some Javascript to try and update the parent page
773         $output .= '<script type="text/javascript">'."\n<!--\n";
774         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['submissioncomment'])) {
775             if ($quickgrade){
776                 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid.'").value="'
777                 .trim($submission->submissioncomment).'";'."\n";
778              } else {
779                 $output.= 'opener.document.getElementById("com'.$submission->userid.
780                 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment)), 15)."\";\n";
781             }
782         }
784         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['grade'])) {
785             //echo optional_param('menuindex');
786             if ($quickgrade){
787                 $output.= 'opener.document.getElementById("menumenu'.$submission->userid.
788                 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT).'";'."\n";
789             } else {
790                 $output.= 'opener.document.getElementById("g'.$submission->userid.'").innerHTML="'.
791                 $this->display_grade($submission->grade)."\";\n";
792             }
793         }
794         //need to add student's assignments in there too.
795         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemodified']) &&
796             $submission->timemodified) {
797             $output.= 'opener.document.getElementById("ts'.$submission->userid.
798                  '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid)).userdate($submission->timemodified)."\";\n";
799         }
801         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemarked']) &&
802             $submission->timemarked) {
803             $output.= 'opener.document.getElementById("tt'.$submission->userid.
804                  '").innerHTML="'.userdate($submission->timemarked)."\";\n";
805         }
807         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['status'])) {
808             $output.= 'opener.document.getElementById("up'.$submission->userid.'").className="s1";';
809             $buttontext = get_string('update');
810             $url = new moodle_url('/mod/assignment/submissions.php', array(
811                     'id' => $this->cm->id,
812                     'userid' => $submission->userid,
813                     'mode' => 'single',
814                     'offset' => (optional_param('offset', '', PARAM_INT)-1)));
815             $button = $OUTPUT->action_link($url, $buttontext, new popup_action('click', $url, 'grade'.$submission->userid, array('height' => 450, 'width' => 700)), array('ttile'=>$buttontext));
817             $output .= 'opener.document.getElementById("up'.$submission->userid.'").innerHTML="'.addslashes_js($button).'";';
818         }
820         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $submission->userid);
822         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['finalgrade'])) {
823             $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid.
824             '").innerHTML="'.$grading_info->items[0]->grades[$submission->userid]->str_grade.'";'."\n";
825         }
827         if (!empty($CFG->enableoutcomes) and empty($SESSION->flextable['mod-assignment-submissions']->collapse['outcome'])) {
829             if (!empty($grading_info->outcomes)) {
830                 foreach($grading_info->outcomes as $n=>$outcome) {
831                     if ($outcome->grades[$submission->userid]->locked) {
832                         continue;
833                     }
835                     if ($quickgrade){
836                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.
837                         '").selectedIndex="'.$outcome->grades[$submission->userid]->grade.'";'."\n";
839                     } else {
840                         $options = make_grades_menu(-$outcome->scaleid);
841                         $options[0] = get_string('nooutcome', 'grades');
842                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.'").innerHTML="'.$options[$outcome->grades[$submission->userid]->grade]."\";\n";
843                     }
845                 }
846             }
847         }
849         $output .= "\n-->\n</script>";
850         return $output;
851     }
853     /**
854      *  Return a grade in user-friendly form, whether it's a scale or not
855      *
856      * @global object
857      * @param mixed $grade
858      * @return string User-friendly representation of grade
859      */
860     function display_grade($grade) {
861         global $DB;
863         static $scalegrades = array();   // Cache scales for each assignment - they might have different scales!!
865         if ($this->assignment->grade >= 0) {    // Normal number
866             if ($grade == -1) {
867                 return '-';
868             } else {
869                 return $grade.' / '.$this->assignment->grade;
870             }
872         } else {                                // Scale
873             if (empty($scalegrades[$this->assignment->id])) {
874                 if ($scale = $DB->get_record('scale', array('id'=>-($this->assignment->grade)))) {
875                     $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
876                 } else {
877                     return '-';
878                 }
879             }
880             if (isset($scalegrades[$this->assignment->id][$grade])) {
881                 return $scalegrades[$this->assignment->id][$grade];
882             }
883             return '-';
884         }
885     }
887     /**
888      *  Display a single submission, ready for grading on a popup window
889      *
890      * This default method prints the teacher info and submissioncomment box at the top and
891      * the student info and submission at the bottom.
892      * This method also fetches the necessary data in order to be able to
893      * provide a "Next submission" button.
894      * Calls preprocess_submission() to give assignment type plug-ins a chance
895      * to process submissions before they are graded
896      * This method gets its arguments from the page parameters userid and offset
897      *
898      * @global object
899      * @global object
900      * @param string $extra_javascript
901      */
902     function display_submission($offset=-1,$userid =-1, $display=true) {
903         global $CFG, $DB, $PAGE, $OUTPUT;
904         require_once($CFG->libdir.'/gradelib.php');
905         require_once($CFG->libdir.'/tablelib.php');
906         require_once("$CFG->dirroot/repository/lib.php");
907         if ($userid==-1) {
908             $userid = required_param('userid', PARAM_INT);
909         }
910         if ($offset==-1) {
911             $offset = required_param('offset', PARAM_INT);//offset for where to start looking for student.
912         }
913         $filter = optional_param('filter', 0, PARAM_INT);
915         if (!$user = $DB->get_record('user', array('id'=>$userid))) {
916             print_error('nousers');
917         }
919         if (!$submission = $this->get_submission($user->id)) {
920             $submission = $this->prepare_new_submission($userid);
921         }
922         if ($submission->timemodified > $submission->timemarked) {
923             $subtype = 'assignmentnew';
924         } else {
925             $subtype = 'assignmentold';
926         }
928         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
929         $gradingdisabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
931     /// construct SQL, using current offset to find the data of the next student
932         $course     = $this->course;
933         $assignment = $this->assignment;
934         $cm         = $this->cm;
935         $context    = get_context_instance(CONTEXT_MODULE, $cm->id);
937         /// Get all ppl that can submit assignments
939         $currentgroup = groups_get_activity_group($cm);
940         if ($users = get_enrolled_users($context, 'mod/assignment:submit', $currentgroup, 'u.id')) {
941             $users = array_keys($users);
942         }
944         // if groupmembersonly used, remove users who are not in any group
945         if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
946             if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
947                 $users = array_intersect($users, array_keys($groupingusers));
948             }
949         }
951         $nextid = 0;
952         $where = '';
953         if($filter == 'submitted') {
954             $where .= 's.timemodified > 0 AND ';
955         } else if($filter == 'requiregrading') {
956             $where .= 's.timemarked < s.timemodified AND ';
957         }
959         if ($users) {
960             $userfields = user_picture::fields('u', array('lastaccess'));
961             $select = "SELECT $userfields,
962                               s.id AS submissionid, s.grade, s.submissioncomment,
963                               s.timemodified, s.timemarked,
964                               COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ";
965             $sql = 'FROM {user} u '.
966                    'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
967                    AND s.assignment = '.$this->assignment->id.' '.
968                    'WHERE '.$where.'u.id IN ('.implode(',', $users).') ';
970             if ($sort = flexible_table::get_sort_for_table('mod-assignment-submissions')) {
971                 $sort = 'ORDER BY '.$sort.' ';
972             }
973             $auser = $DB->get_records_sql($select.$sql.$sort, null, $offset, 2);
975             if (is_array($auser) && count($auser)>1) {
976                 $nextuser = next($auser);
977             /// Calculate user status
978                 $nextuser->status = ($nextuser->timemarked > 0) && ($nextuser->timemarked >= $nextuser->timemodified);
979                 $nextid = $nextuser->id;
980             }
981         }
983         if ($submission->teacher) {
984             $teacher = $DB->get_record('user', array('id'=>$submission->teacher));
985         } else {
986             global $USER;
987             $teacher = $USER;
988         }
990         $this->preprocess_submission($submission);
992         $mformdata = new stdclass;
993         $mformdata->context = $this->context;
994         $mformdata->maxbytes = $this->course->maxbytes;
995         $mformdata->courseid = $this->course->id;
996         $mformdata->teacher = $teacher;
997         $mformdata->assignment = $assignment;
998         $mformdata->submission = $submission;
999         $mformdata->lateness = $this->display_lateness($submission->timemodified);
1000         $mformdata->auser = $auser;
1001         $mformdata->user = $user;
1002         $mformdata->offset = $offset;
1003         $mformdata->userid = $userid;
1004         $mformdata->cm = $this->cm;
1005         $mformdata->grading_info = $grading_info;
1006         $mformdata->enableoutcomes = $CFG->enableoutcomes;
1007         $mformdata->grade = $this->assignment->grade;
1008         $mformdata->gradingdisabled = $gradingdisabled;
1009         $mformdata->nextid = $nextid;
1010         $mformdata->submissioncomment= $submission->submissioncomment;
1011         $mformdata->submissioncommentformat= FORMAT_HTML;
1012         $mformdata->submission_content= $this->print_user_files($user->id,true);
1013         $mformdata->filter = $filter;
1014          if ($assignment->assignmenttype == 'upload') {
1015             $mformdata->fileui_options = array('subdirs'=>1, 'maxbytes'=>$assignment->maxbytes, 'maxfiles'=>$assignment->var1, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL);
1016         } elseif ($assignment->assignmenttype == 'uploadsingle') {
1017             $mformdata->fileui_options = array('subdirs'=>0, 'maxbytes'=>$CFG->userquota, 'maxfiles'=>1, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL);
1018         }
1020         $submitform = new mod_assignment_grading_form( null, $mformdata );
1022          if (!$display) {
1023             $ret_data = new stdClass();
1024             $ret_data->mform = $submitform;
1025             $ret_data->fileui_options = $mformdata->fileui_options;
1026             return $ret_data;
1027         }
1029         if ($submitform->is_cancelled()) {
1030             redirect('submissions.php?id='.$this->cm->id);
1031         }
1033         $submitform->set_data($mformdata);
1035         $PAGE->set_title($this->course->fullname . ': ' .get_string('feedback', 'assignment').' - '.fullname($user, true));
1036         $PAGE->set_heading($this->course->fullname);
1037         $PAGE->navbar->add(get_string('submissions', 'assignment'), new moodle_url('/mod/assignment/submissions.php', array('id'=>$cm->id)));
1038         $PAGE->navbar->add(fullname($user, true));
1040         echo $OUTPUT->header();
1041         echo $OUTPUT->heading(get_string('feedback', 'assignment').': '.fullname($user, true));
1043         // display mform here...
1044         $submitform->display();
1046         $customfeedback = $this->custom_feedbackform($submission, true);
1047         if (!empty($customfeedback)) {
1048             echo $customfeedback;
1049         }
1051         echo $OUTPUT->footer();
1052     }
1054     /**
1055      *  Preprocess submission before grading
1056      *
1057      * Called by display_submission()
1058      * The default type does nothing here.
1059      *
1060      * @param object $submission The submission object
1061      */
1062     function preprocess_submission(&$submission) {
1063     }
1065     /**
1066      *  Display all the submissions ready for grading
1067      *
1068      * @global object
1069      * @global object
1070      * @global object
1071      * @global object
1072      * @param string $message
1073      * @return bool|void
1074      */
1075     function display_submissions($message='') {
1076         global $CFG, $DB, $USER, $DB, $OUTPUT, $PAGE;
1077         require_once($CFG->libdir.'/gradelib.php');
1079         /* first we check to see if the form has just been submitted
1080          * to request user_preference updates
1081          */
1083        $filters = array(self::FILTER_ALL             => get_string('all'),
1084                         self::FILTER_SUBMITTED       => get_string('submitted', 'assignment'),
1085                         self::FILTER_REQUIRE_GRADING => get_string('requiregrading', 'assignment'));
1087         $updatepref = optional_param('updatepref', 0, PARAM_INT);
1089         if (isset($_POST['updatepref'])){
1090             $perpage = optional_param('perpage', 10, PARAM_INT);
1091             $perpage = ($perpage <= 0) ? 10 : $perpage ;
1092             $filter = optional_param('filter', 0, PARAM_INT);
1093             set_user_preference('assignment_perpage', $perpage);
1094             set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
1095             set_user_preference('assignment_filter', $filter);
1096         }
1098         /* next we get perpage and quickgrade (allow quick grade) params
1099          * from database
1100          */
1101         $perpage    = get_user_preferences('assignment_perpage', 10);
1102         $quickgrade = get_user_preferences('assignment_quickgrade', 0);
1103         $filter = get_user_preferences('assignment_filter', 0);
1104         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);
1106         if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
1107             $uses_outcomes = true;
1108         } else {
1109             $uses_outcomes = false;
1110         }
1112         $page    = optional_param('page', 0, PARAM_INT);
1113         $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
1115     /// Some shortcuts to make the code read better
1117         $course     = $this->course;
1118         $assignment = $this->assignment;
1119         $cm         = $this->cm;
1121         $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
1122         add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->cm->id, $this->assignment->id, $this->cm->id);
1124         $PAGE->set_title(format_string($this->assignment->name,true));
1125         $PAGE->set_heading($this->course->fullname);
1126         echo $OUTPUT->header();
1128         echo '<div class="usersubmissions">';
1130         /// Print quickgrade form around the table
1131         if ($quickgrade) {
1132             $formattrs = array();
1133             $formattrs['action'] = new moodle_url('/mod/assignment/submissions.php');
1134             $formattrs['id'] = 'fastg';
1135             $formattrs['method'] = 'post';
1137             echo html_writer::start_tag('form', $formattrs);
1138             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'id',      'value'=> $this->cm->id));
1139             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'mode',    'value'=> 'fastgrade'));
1140             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'page',    'value'=> $page));
1141             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=> sesskey()));
1142         }
1144         $course_context = get_context_instance(CONTEXT_COURSE, $course->id);
1145         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
1146             echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">'
1147                 . get_string('seeallcoursegrades', 'grades') . '</a></div>';
1148         }
1150         if (!empty($message)) {
1151             echo $message;   // display messages here if any
1152         }
1154         $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1156     /// Check to see if groups are being used in this assignment
1158         /// find out current groups mode
1159         $groupmode = groups_get_activity_groupmode($cm);
1160         $currentgroup = groups_get_activity_group($cm, true);
1161         groups_print_activity_menu($cm, $CFG->wwwroot . '/mod/assignment/submissions.php?id=' . $this->cm->id);
1163         /// Get all ppl that are allowed to submit assignments
1164         list($esql, $params) = get_enrolled_sql($context, 'mod/assignment:submit', $currentgroup);
1166         if ($filter == self::FILTER_ALL) {
1167             $sql = "SELECT u.id FROM {user} u ".
1168                    "LEFT JOIN ($esql) eu ON eu.id=u.id ".
1169                    "WHERE u.deleted = 0 AND eu.id=u.id ";
1170         } else {
1171             $wherefilter = '';
1172             if($filter == self::FILTER_SUBMITTED) {
1173                $wherefilter = ' AND s.timemodified > 0';
1174             } else if($filter == self::FILTER_REQUIRE_GRADING) {
1175                 $wherefilter = ' AND s.timemarked < s.timemodified ';
1176             }
1178             $sql = "SELECT u.id FROM {user} u ".
1179                    "LEFT JOIN ($esql) eu ON eu.id=u.id ".
1180                    "LEFT JOIN {assignment_submissions} s ON (u.id = s.userid) " .
1181                    "WHERE u.deleted = 0 AND eu.id=u.id ".
1182                    'AND s.assignment = '. $this->assignment->id .
1183                     $wherefilter;
1184         }
1186         $users = $DB->get_records_sql($sql, $params);
1187         if (!empty($users)) {
1188             $users = array_keys($users);
1189         }
1191         // if groupmembersonly used, remove users who are not in any group
1192         if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
1193             if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1194                 $users = array_intersect($users, array_keys($groupingusers));
1195             }
1196         }
1198         $tablecolumns = array('picture', 'fullname', 'grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade');
1199         if ($uses_outcomes) {
1200             $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
1201         }
1203         $tableheaders = array('',
1204                               get_string('fullname'),
1205                               get_string('grade'),
1206                               get_string('comment', 'assignment'),
1207                               get_string('lastmodified').' ('.get_string('submission', 'assignment').')',
1208                               get_string('lastmodified').' ('.get_string('grade').')',
1209                               get_string('status'),
1210                               get_string('finalgrade', 'grades'));
1211         if ($uses_outcomes) {
1212             $tableheaders[] = get_string('outcome', 'grades');
1213         }
1215         require_once($CFG->libdir.'/tablelib.php');
1216         $table = new flexible_table('mod-assignment-submissions');
1218         $table->define_columns($tablecolumns);
1219         $table->define_headers($tableheaders);
1220         $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;currentgroup='.$currentgroup);
1222         $table->sortable(true, 'lastname');//sorted by lastname by default
1223         $table->collapsible(true);
1224         $table->initialbars(true);
1226         $table->column_suppress('picture');
1227         $table->column_suppress('fullname');
1229         $table->column_class('picture', 'picture');
1230         $table->column_class('fullname', 'fullname');
1231         $table->column_class('grade', 'grade');
1232         $table->column_class('submissioncomment', 'comment');
1233         $table->column_class('timemodified', 'timemodified');
1234         $table->column_class('timemarked', 'timemarked');
1235         $table->column_class('status', 'status');
1236         $table->column_class('finalgrade', 'finalgrade');
1237         if ($uses_outcomes) {
1238             $table->column_class('outcome', 'outcome');
1239         }
1241         $table->set_attribute('cellspacing', '0');
1242         $table->set_attribute('id', 'attempts');
1243         $table->set_attribute('class', 'submissions');
1244         $table->set_attribute('width', '100%');
1245         //$table->set_attribute('align', 'center');
1247         $table->no_sorting('finalgrade');
1248         $table->no_sorting('outcome');
1250         // Start working -- this is necessary as soon as the niceties are over
1251         $table->setup();
1253         if (empty($users)) {
1254             echo $OUTPUT->heading(get_string('nosubmitusers','assignment'));
1255             echo '</div>';
1256             return true;
1257         }
1258         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)
1259             echo '<div style="text-align:right"><a href="submissions.php?id='.$this->cm->id.'&amp;download=zip">'.get_string('downloadall', 'assignment').'</a></div>';
1260         }
1261     /// Construct the SQL
1263         if ($where = $table->get_sql_where()) {
1264             $where .= ' AND ';
1265         }
1267         if($filter == self::FILTER_SUBMITTED) {
1268            $where .= 's.timemodified > 0 AND ';
1269         } else if($filter == self::FILTER_REQUIRE_GRADING) {
1270            $where .= 's.timemarked < s.timemodified AND ';
1271         }
1273         if ($sort = $table->get_sql_sort()) {
1274             $sort = ' ORDER BY '.$sort;
1275         }
1277         $ufields = user_picture::fields('u');
1279         $select = "SELECT $ufields,
1280                           s.id AS submissionid, s.grade, s.submissioncomment,
1281                           s.timemodified, s.timemarked,
1282                           COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ";
1283         $sql = 'FROM {user} u '.
1284                'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1285                 AND s.assignment = '.$this->assignment->id.' '.
1286                'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1288         $ausers = $DB->get_records_sql($select.$sql.$sort, null, $table->get_page_start(), $table->get_page_size());
1290         $table->pagesize($perpage, count($users));
1292         ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1293         $offset = $page * $perpage;
1294         $strupdate = get_string('update');
1295         $strgrade  = get_string('grade');
1296         $grademenu = make_grades_menu($this->assignment->grade);
1298         if ($ausers !== false) {
1299             $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
1300             $endposition = $offset + $perpage;
1301             $currentposition = 0;
1302             foreach ($ausers as $auser) {
1303                 if ($currentposition == $offset && $offset < $endposition) {
1304                     $final_grade = $grading_info->items[0]->grades[$auser->id];
1305                     $grademax = $grading_info->items[0]->grademax;
1306                     $final_grade->formatted_grade = round($final_grade->grade,2) .' / ' . round($grademax,2);
1307                     $locked_overridden = 'locked';
1308                     if ($final_grade->overridden) {
1309                         $locked_overridden = 'overridden';
1310                     }
1312                 /// Calculate user status
1313                     $auser->status = ($auser->timemarked > 0) && ($auser->timemarked >= $auser->timemodified);
1314                     $picture = $OUTPUT->user_picture($auser);
1316                     if (empty($auser->submissionid)) {
1317                         $auser->grade = -1; //no submission yet
1318                     }
1320                     if (!empty($auser->submissionid)) {
1321                     ///Prints student answer and student modified date
1322                     ///attach file or print link to student answer, depending on the type of the assignment.
1323                     ///Refer to print_student_answer in inherited classes.
1324                         if ($auser->timemodified > 0) {
1325                             $studentmodified = '<div id="ts'.$auser->id.'">'.$this->print_student_answer($auser->id)
1326                                              . userdate($auser->timemodified).'</div>';
1327                         } else {
1328                             $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1329                         }
1330                     ///Print grade, dropdown or text
1331                         if ($auser->timemarked > 0) {
1332                             $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
1334                             if ($final_grade->locked or $final_grade->overridden) {
1335                                 $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1336                             } else if ($quickgrade) {
1337                                 $attributes = array();
1338                                 $attributes['tabindex'] = $tabindex++;
1339                                 $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1340                                 $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
1341                             } else {
1342                                 $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1343                             }
1345                         } else {
1346                             $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1347                             if ($final_grade->locked or $final_grade->overridden) {
1348                                 $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1349                             } else if ($quickgrade) {
1350                                 $attributes = array();
1351                                 $attributes['tabindex'] = $tabindex++;
1352                                 $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1353                                 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1354                             } else {
1355                                 $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1356                             }
1357                         }
1358                     ///Print Comment
1359                         if ($final_grade->locked or $final_grade->overridden) {
1360                             $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';
1362                         } else if ($quickgrade) {
1363                             $comment = '<div id="com'.$auser->id.'">'
1364                                      . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1365                                      . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1366                         } else {
1367                             $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
1368                         }
1369                     } else {
1370                         $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1371                         $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1372                         $status          = '<div id="st'.$auser->id.'">&nbsp;</div>';
1374                         if ($final_grade->locked or $final_grade->overridden) {
1375                             $grade = '<div id="g'.$auser->id.'">'.$final_grade->formatted_grade . '</div>';
1376                         } else if ($quickgrade) {   // allow editing
1377                             $attributes = array();
1378                             $attributes['tabindex'] = $tabindex++;
1379                             $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1380                             $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1381                         } else {
1382                             $grade = '<div id="g'.$auser->id.'">-</div>';
1383                         }
1385                         if ($final_grade->locked or $final_grade->overridden) {
1386                             $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
1387                         } else if ($quickgrade) {
1388                             $comment = '<div id="com'.$auser->id.'">'
1389                                      . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1390                                      . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1391                         } else {
1392                             $comment = '<div id="com'.$auser->id.'">&nbsp;</div>';
1393                         }
1394                     }
1396                     if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
1397                         $auser->status = 0;
1398                     } else {
1399                         $auser->status = 1;
1400                     }
1402                     $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
1404                     ///No more buttons, we use popups ;-).
1405                     $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1406                                . '&amp;userid='.$auser->id.'&amp;mode=single'.'&amp;filter='.$filter.'&amp;offset='.$offset++;
1408                     $button = $OUTPUT->action_link($popup_url, $buttontext);
1410                     $status  = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
1412                     $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';
1414                     $outcomes = '';
1416                     if ($uses_outcomes) {
1418                         foreach($grading_info->outcomes as $n=>$outcome) {
1419                             $outcomes .= '<div class="outcome"><label>'.$outcome->name.'</label>';
1420                             $options = make_grades_menu(-$outcome->scaleid);
1422                             if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
1423                                 $options[0] = get_string('nooutcome', 'grades');
1424                                 $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
1425                             } else {
1426                                 $attributes = array();
1427                                 $attributes['tabindex'] = $tabindex++;
1428                                 $attributes['id'] = 'outcome_'.$n.'_'.$auser->id;
1429                                 $outcomes .= ' '.html_writer::select($options, 'outcome_'.$n.'['.$auser->id.']', $outcome->grades[$auser->id]->grade, array(0=>get_string('nooutcome', 'grades')), $attributes);
1430                             }
1431                             $outcomes .= '</div>';
1432                         }
1433                     }
1435                     $userlink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $auser->id . '&amp;course=' . $course->id . '">' . fullname($auser, has_capability('moodle/site:viewfullnames', $this->context)) . '</a>';
1436                     $row = array($picture, $userlink, $grade, $comment, $studentmodified, $teachermodified, $status, $finalgrade);
1437                     if ($uses_outcomes) {
1438                         $row[] = $outcomes;
1439                     }
1441                     $table->add_data($row);
1442                 }
1443                 $currentposition++;
1444             }
1445         }
1447         $table->print_html();  /// Print the whole table
1449         /// Print quickgrade form around the table
1450         if ($quickgrade && $table->started_output){
1451             $mailinfopref = false;
1452             if (get_user_preferences('assignment_mailinfo', 1)) {
1453                 $mailinfopref = true;
1454             }
1455             $emailnotification =  html_writer::checkbox('mailinfo', 1, $mailinfopref, get_string('enableemailnotification','assignment'));
1457             $emailnotification .= $OUTPUT->help_icon('enableemailnotification', 'assignment');
1458             echo html_writer::tag('div', $emailnotification, array('class'=>'emailnotification'));
1460             $savefeedback = html_writer::empty_tag('input', array('type'=>'submit', 'name'=>'fastg', 'value'=>get_string('saveallfeedback', 'assignment')));
1461             echo html_writer::tag('div', $savefeedback, array('class'=>'fastgbutton'));
1463             echo html_writer::end_tag('form');
1464         } else if ($quickgrade) {
1465             echo html_writer::end_tag('form');
1466         }
1468         echo '</div>';
1469         /// End of fast grading form
1471         /// Mini form for setting user preference
1473         $formaction = new moodle_url('/mod/assignment/submissions.php', array('id'=>$this->cm->id));
1474         $mform = new MoodleQuickForm('optionspref', 'post', $formaction, '', array('class'=>'optionspref'));
1476         $mform->addElement('hidden', 'updatepref');
1477         $mform->setDefault('updatepref', 1);
1478         $mform->addElement('header', 'qgprefs', get_string('optionalsettings', 'assignment'));
1479         $mform->addElement('select', 'filter', get_string('show'),  $filters);
1481         $mform->setDefault('filter', $filter);
1483         $mform->addElement('text', 'perpage', get_string('pagesize', 'assignment'), array('size'=>1));
1484         $mform->setDefault('perpage', $perpage);
1486         $mform->addElement('checkbox', 'quickgrade', get_string('quickgrade','assignment'));
1487         $mform->setDefault('quickgrade', $quickgrade);
1488         $mform->addHelpButton('quickgrade', 'quickgrade', 'assignment');
1490         $mform->addElement('submit', 'savepreferences', get_string('savepreferences'));
1492         $mform->display();
1494         echo $OUTPUT->footer();
1495     }
1497     /**
1498      *  Process teacher feedback submission
1499      *
1500      * This is called by submissions() when a grading even has taken place.
1501      * It gets its data from the submitted form.
1502      *
1503      * @global object
1504      * @global object
1505      * @global object
1506      * @return object|bool The updated submission object or false
1507      */
1508     function process_feedback($formdata=null) {
1509         global $CFG, $USER, $DB;
1510         require_once($CFG->libdir.'/gradelib.php');
1512         if (!$feedback = data_submitted() or !confirm_sesskey()) {      // No incoming data?
1513             return false;
1514         }
1516         ///For save and next, we need to know the userid to save, and the userid to go
1517         ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1518         ///as the userid to store
1519         if ((int)$feedback->saveuserid !== -1){
1520             $feedback->userid = $feedback->saveuserid;
1521         }
1523         if (!empty($feedback->cancel)) {          // User hit cancel button
1524             return false;
1525         }
1527         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);
1529         // store outcomes if needed
1530         $this->process_outcomes($feedback->userid);
1532         $submission = $this->get_submission($feedback->userid, true);  // Get or make one
1534         if (!($grading_info->items[0]->grades[$feedback->userid]->locked ||
1535             $grading_info->items[0]->grades[$feedback->userid]->overridden) ) {
1537             $submission->grade      = $feedback->xgrade;
1538             $submission->submissioncomment    = $feedback->submissioncomment_editor['text'];
1539             $submission->teacher    = $USER->id;
1540             $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1541             if (!$mailinfo) {
1542                 $submission->mailed = 1;       // treat as already mailed
1543             } else {
1544                 $submission->mailed = 0;       // Make sure mail goes out (again, even)
1545             }
1546             $submission->timemarked = time();
1548             unset($submission->data1);  // Don't need to update this.
1549             unset($submission->data2);  // Don't need to update this.
1551             if (empty($submission->timemodified)) {   // eg for offline assignments
1552                 // $submission->timemodified = time();
1553             }
1555             $DB->update_record('assignment_submissions', $submission);
1557             // triger grade event
1558             $this->update_grade($submission);
1560             add_to_log($this->course->id, 'assignment', 'update grades',
1561                        'submissions.php?id='.$this->assignment->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
1562              if (!is_null($formdata)) {
1563                     if ($this->type == 'upload' || $this->type == 'uploadsingle') {
1564                         $mformdata = $formdata->mform->get_data();
1565                         $mformdata = file_postupdate_standard_filemanager($mformdata, 'files', $formdata->fileui_options, $this->context, 'mod_assignment', 'response', $submission->id);
1566                     }
1567              }
1568         }
1570         return $submission;
1572     }
1574     function process_outcomes($userid) {
1575         global $CFG, $USER;
1577         if (empty($CFG->enableoutcomes)) {
1578             return;
1579         }
1581         require_once($CFG->libdir.'/gradelib.php');
1583         if (!$formdata = data_submitted() or !confirm_sesskey()) {
1584             return;
1585         }
1587         $data = array();
1588         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
1590         if (!empty($grading_info->outcomes)) {
1591             foreach($grading_info->outcomes as $n=>$old) {
1592                 $name = 'outcome_'.$n;
1593                 if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
1594                     $data[$n] = $formdata->{$name}[$userid];
1595                 }
1596             }
1597         }
1598         if (count($data) > 0) {
1599             grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1600         }
1602     }
1604     /**
1605      * Load the submission object for a particular user
1606      *
1607      * @global object
1608      * @global object
1609      * @param $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1610      * @param $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1611      * @param bool $teachermodified student submission set if false
1612      * @return object The submission
1613      */
1614     function get_submission($userid=0, $createnew=false, $teachermodified=false) {
1615         global $USER, $DB;
1617         if (empty($userid)) {
1618             $userid = $USER->id;
1619         }
1621         $submission = $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1623         if ($submission || !$createnew) {
1624             return $submission;
1625         }
1626         $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
1627         $DB->insert_record("assignment_submissions", $newsubmission);
1629         return $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1630     }
1632     /**
1633      * Instantiates a new submission object for a given user
1634      *
1635      * Sets the assignment, userid and times, everything else is set to default values.
1636      *
1637      * @param int $userid The userid for which we want a submission object
1638      * @param bool $teachermodified student submission set if false
1639      * @return object The submission
1640      */
1641     function prepare_new_submission($userid, $teachermodified=false) {
1642         $submission = new Object;
1643         $submission->assignment   = $this->assignment->id;
1644         $submission->userid       = $userid;
1645         $submission->timecreated = time();
1646         // teachers should not be modifying modified date, except offline assignments
1647         if ($teachermodified) {
1648             $submission->timemodified = 0;
1649         } else {
1650             $submission->timemodified = $submission->timecreated;
1651         }
1652         $submission->numfiles     = 0;
1653         $submission->data1        = '';
1654         $submission->data2        = '';
1655         $submission->grade        = -1;
1656         $submission->submissioncomment      = '';
1657         $submission->format       = 0;
1658         $submission->teacher      = 0;
1659         $submission->timemarked   = 0;
1660         $submission->mailed       = 0;
1661         return $submission;
1662     }
1664     /**
1665      * Return all assignment submissions by ENROLLED students (even empty)
1666      *
1667      * @param string $sort optional field names for the ORDER BY in the sql query
1668      * @param string $dir optional specifying the sort direction, defaults to DESC
1669      * @return array The submission objects indexed by id
1670      */
1671     function get_submissions($sort='', $dir='DESC') {
1672         return assignment_get_all_submissions($this->assignment, $sort, $dir);
1673     }
1675     /**
1676      * Counts all real assignment submissions by ENROLLED students (not empty ones)
1677      *
1678      * @param int $groupid optional If nonzero then count is restricted to this group
1679      * @return int The number of submissions
1680      */
1681     function count_real_submissions($groupid=0) {
1682         return assignment_count_real_submissions($this->cm, $groupid);
1683     }
1685     /**
1686      * Alerts teachers by email of new or changed assignments that need grading
1687      *
1688      * First checks whether the option to email teachers is set for this assignment.
1689      * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1690      * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1691      *
1692      * @global object
1693      * @global object
1694      * @param $submission object The submission that has changed
1695      * @return void
1696      */
1697     function email_teachers($submission) {
1698         global $CFG, $DB;
1700         if (empty($this->assignment->emailteachers)) {          // No need to do anything
1701             return;
1702         }
1704         $user = $DB->get_record('user', array('id'=>$submission->userid));
1706         if ($teachers = $this->get_graders($user)) {
1708             $strassignments = get_string('modulenameplural', 'assignment');
1709             $strassignment  = get_string('modulename', 'assignment');
1710             $strsubmitted  = get_string('submitted', 'assignment');
1712             foreach ($teachers as $teacher) {
1713                 $info = new object();
1714                 $info->username = fullname($user, true);
1715                 $info->assignment = format_string($this->assignment->name,true);
1716                 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
1718                 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1719                 $posttext = $this->email_teachers_text($info);
1720                 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
1722                 $eventdata = new object();
1723                 $eventdata->modulename       = 'assignment';
1724                 $eventdata->userfrom         = $user;
1725                 $eventdata->userto           = $teacher;
1726                 $eventdata->subject          = $postsubject;
1727                 $eventdata->fullmessage      = $posttext;
1728                 $eventdata->fullmessageformat = FORMAT_PLAIN;
1729                 $eventdata->fullmessagehtml  = $posthtml;
1730                 $eventdata->smallmessage     = '';
1731                 message_send($eventdata);
1732             }
1733         }
1734     }
1736     /**
1737      * @param string $filearea
1738      * @param array $args
1739      * @return bool
1740      */
1741     function send_file($filearea, $args) {
1742         debugging('plugin does not implement file sending', DEBUG_DEVELOPER);
1743         return false;
1744     }
1746     /**
1747      * Returns a list of teachers that should be grading given submission
1748      *
1749      * @param object $user
1750      * @return array
1751      */
1752     function get_graders($user) {
1753         //potential graders
1754         $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false);
1756         $graders = array();
1757         if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) {   // Separate groups are being used
1758             if ($groups = groups_get_all_groups($this->course->id, $user->id)) {  // Try to find all groups
1759                 foreach ($groups as $group) {
1760                     foreach ($potgraders as $t) {
1761                         if ($t->id == $user->id) {
1762                             continue; // do not send self
1763                         }
1764                         if (groups_is_member($group->id, $t->id)) {
1765                             $graders[$t->id] = $t;
1766                         }
1767                     }
1768                 }
1769             } else {
1770                 // user not in group, try to find graders without group
1771                 foreach ($potgraders as $t) {
1772                     if ($t->id == $user->id) {
1773                         continue; // do not send self
1774                     }
1775                     if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
1776                         $graders[$t->id] = $t;
1777                     }
1778                 }
1779             }
1780         } else {
1781             foreach ($potgraders as $t) {
1782                 if ($t->id == $user->id) {
1783                     continue; // do not send self
1784                 }
1785                 $graders[$t->id] = $t;
1786             }
1787         }
1788         return $graders;
1789     }
1791     /**
1792      * Creates the text content for emails to teachers
1793      *
1794      * @param $info object The info used by the 'emailteachermail' language string
1795      * @return string
1796      */
1797     function email_teachers_text($info) {
1798         $posttext  = format_string($this->course->shortname).' -> '.$this->strassignments.' -> '.
1799                      format_string($this->assignment->name)."\n";
1800         $posttext .= '---------------------------------------------------------------------'."\n";
1801         $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
1802         $posttext .= "\n---------------------------------------------------------------------\n";
1803         return $posttext;
1804     }
1806      /**
1807      * Creates the html content for emails to teachers
1808      *
1809      * @param $info object The info used by the 'emailteachermailhtml' language string
1810      * @return string
1811      */
1812     function email_teachers_html($info) {
1813         global $CFG;
1814         $posthtml  = '<p><font face="sans-serif">'.
1815                      '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname).'</a> ->'.
1816                      '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
1817                      '<a href="'.$CFG->wwwroot.'/mod/assignment/view.php?id='.$this->cm->id.'">'.format_string($this->assignment->name).'</a></font></p>';
1818         $posthtml .= '<hr /><font face="sans-serif">';
1819         $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
1820         $posthtml .= '</font><hr />';
1821         return $posthtml;
1822     }
1824     /**
1825      * Produces a list of links to the files uploaded by a user
1826      *
1827      * @param $userid int optional id of the user. If 0 then $USER->id is used.
1828      * @param $return boolean optional defaults to false. If true the list is returned rather than printed
1829      * @return string optional
1830      */
1831     function print_user_files($userid=0, $return=false) {
1832         global $CFG, $USER, $OUTPUT;
1834         if (!$userid) {
1835             if (!isloggedin()) {
1836                 return '';
1837             }
1838             $userid = $USER->id;
1839         }
1841         $output = '';
1843         $fs = get_file_storage();
1845         $found = false;
1847         $submission = $this->get_submission($userid);
1849         if (($submission) && $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false)) {
1850             require_once($CFG->libdir.'/portfoliolib.php');
1851             require_once($CFG->dirroot . '/mod/assignment/locallib.php');
1852             $button = new portfolio_add_button();
1853             foreach ($files as $file) {
1854                 $filename = $file->get_filename();
1855                 $found = true;
1856                 $mimetype = $file->get_mimetype();
1857                 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/mod_assignment/submission/'.$submission->id.'/'.$filename);
1858                 $output .= '<a href="'.$path.'" ><img src="'.$OUTPUT->pix_url(file_mimetype_icon($mimetype)).'" class="icon" alt="'.$mimetype.'" />'.s($filename).'</a>';
1859                 if ($this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1860                     $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id, 'fileid' => $file->get_id()), '/mod/assignment/locallib.php');
1861                     $button->set_format_by_file($file);
1862                     $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
1863                 }
1864             }
1865             if (count($files) > 1  && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1866                 $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id), '/mod/assignment/locallib.php');
1867                 $output .= '<br />'  . $button->to_html();
1868             }
1869         }
1871         $output = '<div class="files">'.$output.'</div>';
1873         if ($return) {
1874             return $output;
1875         }
1876         echo $output;
1877     }
1879     /**
1880      * Count the files uploaded by a given user
1881      *
1882      * @param $itemid int The submission's id as the file's itemid.
1883      * @return int
1884      */
1885     function count_user_files($itemid) {
1886         $fs = get_file_storage();
1887         $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $itemid, "id", false);
1888         return count($files);
1889     }
1891     /**
1892      * Returns true if the student is allowed to submit
1893      *
1894      * Checks that the assignment has started and, if the option to prevent late
1895      * submissions is set, also checks that the assignment has not yet closed.
1896      * @return boolean
1897      */
1898     function isopen() {
1899         $time = time();
1900         if ($this->assignment->preventlate && $this->assignment->timedue) {
1901             return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
1902         } else {
1903             return ($this->assignment->timeavailable <= $time);
1904         }
1905     }
1908     /**
1909      * Return true if is set description is hidden till available date
1910      *
1911      * This is needed by calendar so that hidden descriptions do not
1912      * come up in upcoming events.
1913      *
1914      * Check that description is hidden till available date
1915      * By default return false
1916      * Assignments types should implement this method if needed
1917      * @return boolen
1918      */
1919     function description_is_hidden() {
1920         return false;
1921     }
1923     /**
1924      * Return an outline of the user's interaction with the assignment
1925      *
1926      * The default method prints the grade and timemodified
1927      * @param $grade object
1928      * @return object with properties ->info and ->time
1929      */
1930     function user_outline($grade) {
1932         $result = new object();
1933         $result->info = get_string('grade').': '.$grade->str_long_grade;
1934         $result->time = $grade->dategraded;
1935         return $result;
1936     }
1938     /**
1939      * Print complete information about the user's interaction with the assignment
1940      *
1941      * @param $user object
1942      */
1943     function user_complete($user, $grade=null) {
1944         global $OUTPUT;
1945         if ($grade) {
1946             echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
1947             if ($grade->str_feedback) {
1948                 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
1949             }
1950         }
1952         if ($submission = $this->get_submission($user->id)) {
1954             $fs = get_file_storage();
1956             if ($files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false)) {
1957                 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
1958                 foreach ($files as $file) {
1959                     $countfiles .= "; ".$file->get_filename();
1960                 }
1961             }
1963             echo $OUTPUT->box_start();
1964             echo get_string("lastmodified").": ";
1965             echo userdate($submission->timemodified);
1966             echo $this->display_lateness($submission->timemodified);
1968             $this->print_user_files($user->id);
1970             echo '<br />';
1972             $this->view_feedback($submission);
1974             echo $OUTPUT->box_end();
1976         } else {
1977             print_string("notsubmittedyet", "assignment");
1978         }
1979     }
1981     /**
1982      * Return a string indicating how late a submission is
1983      *
1984      * @param $timesubmitted int
1985      * @return string
1986      */
1987     function display_lateness($timesubmitted) {
1988         return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
1989     }
1991     /**
1992      * Empty method stub for all delete actions.
1993      */
1994     function delete() {
1995         //nothing by default
1996         redirect('view.php?id='.$this->cm->id);
1997     }
1999     /**
2000      * Empty custom feedback grading form.
2001      */
2002     function custom_feedbackform($submission, $return=false) {
2003         //nothing by default
2004         return '';
2005     }
2007     /**
2008      * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
2009      * for the course (see resource).
2010      *
2011      * Given a course_module object, this function returns any "extra" information that may be needed
2012      * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
2013      *
2014      * @param $coursemodule object The coursemodule object (record).
2015      * @return object An object on information that the coures will know about (most noticeably, an icon).
2016      *
2017      */
2018     function get_coursemodule_info($coursemodule) {
2019         return false;
2020     }
2022     /**
2023      * Plugin cron method - do not use $this here, create new assignment instances if needed.
2024      * @return void
2025      */
2026     function cron() {
2027         //no plugin cron by default - override if needed
2028     }
2030     /**
2031      * Reset all submissions
2032      */
2033     function reset_userdata($data) {
2034         global $CFG, $DB;
2036         if (!$DB->count_records('assignment', array('course'=>$data->courseid, 'assignmenttype'=>$this->type))) {
2037             return array(); // no assignments of this type present
2038         }
2040         $componentstr = get_string('modulenameplural', 'assignment');
2041         $status = array();
2043         $typestr = get_string('type'.$this->type, 'assignment');
2044         // ugly hack to support pluggable assignment type titles...
2045         if($typestr === '[[type'.$this->type.']]'){
2046             $typestr = get_string('type'.$this->type, 'assignment_'.$this->type);
2047         }
2049         if (!empty($data->reset_assignment_submissions)) {
2050             $assignmentssql = "SELECT a.id
2051                                  FROM {assignment} a
2052                                 WHERE a.course=? AND a.assignmenttype=?";
2053             $params = array($data->courseid, $this->type);
2055             // now get rid of all submissions and responses
2056             $fs = get_file_storage();
2057             if ($assignments = $DB->get_records_sql($assignmentssql, $params)) {
2058                 foreach ($assignments as $assignmentid=>$unused) {
2059                     if (!$cm = get_coursemodule_from_instance('assignment', $assignmentid)) {
2060                         continue;
2061                     }
2062                     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2063                     $fs->delete_area_files($context->id, 'mod_assignment', 'submission');
2064                     $fs->delete_area_files($context->id, 'mod_assignment', 'response');
2065                 }
2066             }
2068             $DB->delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)", $params);
2070             $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
2072             if (empty($data->reset_gradebook_grades)) {
2073                 // remove all grades from gradebook
2074                 assignment_reset_gradebook($data->courseid, $this->type);
2075             }
2076         }
2078         /// updating dates - shift may be negative too
2079         if ($data->timeshift) {
2080             shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
2081             $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
2082         }
2084         return $status;
2085     }
2088     function portfolio_exportable() {
2089         return false;
2090     }
2092     /**
2093      * base implementation for backing up subtype specific information
2094      * for one single module
2095      *
2096      * @param filehandle $bf file handle for xml file to write to
2097      * @param mixed $preferences the complete backup preference object
2098      *
2099      * @return boolean
2100      *
2101      * @static
2102      */
2103     static function backup_one_mod($bf, $preferences, $assignment) {
2104         return true;
2105     }
2107     /**
2108      * base implementation for backing up subtype specific information
2109      * for one single submission
2110      *
2111      * @param filehandle $bf file handle for xml file to write to
2112      * @param mixed $preferences the complete backup preference object
2113      * @param object $submission the assignment submission db record
2114      *
2115      * @return boolean
2116      *
2117      * @static
2118      */
2119     static function backup_one_submission($bf, $preferences, $assignment, $submission) {
2120         return true;
2121     }
2123     /**
2124      * base implementation for restoring subtype specific information
2125      * for one single module
2126      *
2127      * @param array  $info the array representing the xml
2128      * @param object $restore the restore preferences
2129      *
2130      * @return boolean
2131      *
2132      * @static
2133      */
2134     static function restore_one_mod($info, $restore, $assignment) {
2135         return true;
2136     }
2138     /**
2139      * base implementation for restoring subtype specific information
2140      * for one single submission
2141      *
2142      * @param object $submission the newly created submission
2143      * @param array  $info the array representing the xml
2144      * @param object $restore the restore preferences
2145      *
2146      * @return boolean
2147      *
2148      * @static
2149      */
2150     static function restore_one_submission($info, $restore, $assignment, $submission) {
2151         return true;
2152     }
2154 } ////// End of the assignment_base class
2157 class mod_assignment_grading_form extends moodleform {
2159     function definition() {
2160         global $OUTPUT;
2161         $mform =& $this->_form;
2163         $formattr = $mform->getAttributes();
2164         $formattr['id'] = 'submitform';
2165         $mform->setAttributes($formattr);
2166         // hidden params
2167         $mform->addElement('hidden', 'offset', ($this->_customdata->offset+1));
2168         $mform->setType('offset', PARAM_INT);
2169         $mform->addElement('hidden', 'userid', $this->_customdata->userid);
2170         $mform->setType('userid', PARAM_INT);
2171         $mform->addElement('hidden', 'nextid', $this->_customdata->nextid);
2172         $mform->setType('nextid', PARAM_INT);
2173         $mform->addElement('hidden', 'id', $this->_customdata->cm->id);
2174         $mform->setType('id', PARAM_INT);
2175         $mform->addElement('hidden', 'sesskey', sesskey());
2176         $mform->setType('sesskey', PARAM_ALPHANUM);
2177         $mform->addElement('hidden', 'mode', 'grade');
2178         $mform->setType('mode', PARAM_INT);
2179         $mform->addElement('hidden', 'menuindex', "0");
2180         $mform->setType('menuindex', PARAM_INT);
2181         $mform->addElement('hidden', 'saveuserid', "-1");
2182         $mform->setType('saveuserid', PARAM_INT);
2183         $mform->addElement('hidden', 'filter', "0");
2184         $mform->setType('filter', PARAM_INT);
2186         $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->user),
2187                                                 fullname($this->_customdata->user, true) . '<br/>' .
2188                                                 userdate($this->_customdata->submission->timemodified) .
2189                                                 $this->_customdata->lateness );
2191         $this->add_submission_content();
2192         $this->add_grades_section();
2194         $this->add_feedback_section();
2196         if ($this->_customdata->submission->timemarked) {
2197             $datestring = userdate($this->_customdata->submission->timemarked)."&nbsp; (".format_time(time() - $this->_customdata->submission->timemarked).")";
2198             $mform->addElement('header', 'Last Grade', get_string('lastgrade', 'assignment'));
2199             $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->teacher) ,
2200                                                     fullname($this->_customdata->teacher,true).
2201                                                     '<br/>'.$datestring);
2202         }
2203         // buttons
2204         $this->add_action_buttons();
2206     }
2208     function add_grades_section() {
2209         global $CFG;
2210         $mform =& $this->_form;
2211         $attributes = array();
2212         if ($this->_customdata->gradingdisabled) {
2213             $attributes['disabled'] ='disabled';
2214         }
2216         $grademenu = make_grades_menu($this->_customdata->assignment->grade);
2217         $grademenu['-1'] = get_string('nograde');
2219         $mform->addElement('header', 'Grades', get_string('grades', 'grades'));
2220         $mform->addElement('select', 'xgrade', get_string('grade').':', $grademenu, $attributes);
2221         $mform->setDefault('xgrade', $this->_customdata->submission->grade ); //@fixme some bug when element called 'grade' makes it break
2222         $mform->setType('xgrade', PARAM_INT);
2224         if (!empty($this->_customdata->enableoutcomes)) {
2225             foreach($this->_customdata->grading_info->outcomes as $n=>$outcome) {
2226                 $options = make_grades_menu(-$outcome->scaleid);
2227                 if ($outcome->grades[$this->_customdata->submission->userid]->locked) {
2228                     $options[0] = get_string('nooutcome', 'grades');
2229                     echo $options[$outcome->grades[$this->_customdata->submission->userid]->grade];
2230                 } else {
2231                     $options[''] = get_string('nooutcome', 'grades');
2232                     $attributes = array('id' => 'menuoutcome_'.$n );
2233                     $mform->addElement('select', 'outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->name.':', $options, $attributes );
2234                     $mform->setType('outcome_'.$n.'['.$this->_customdata->userid.']', PARAM_INT);
2235                     $mform->setDefault('outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->grades[$this->_customdata->submission->userid]->grade );
2236                 }
2237             }
2238         }
2239         $course_context = get_context_instance(CONTEXT_MODULE , $this->_customdata->cm->id);
2240         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
2241             $grade = '<a href="'.$CFG->wwwroot.'/grade/report/grader/index.php?id='. $this->_customdata->courseid .'" >'.
2242                         $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade . '</a>';
2243         }else{
2244             $grade = $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade;
2245         }
2246         $mform->addElement('static', 'finalgrade', get_string('currentgrade', 'assignment').':' ,$grade);
2247         $mform->setType('finalgrade', PARAM_INT);
2248     }
2250     /**
2251      *
2252      * @global core_renderer $OUTPUT
2253      */
2254     function add_feedback_section() {
2255         global $OUTPUT;
2256         $mform =& $this->_form;
2257         $mform->addElement('header', 'Feed Back', get_string('feedback', 'grades'));
2259         if ($this->_customdata->gradingdisabled) {
2260             $mform->addElement('static', 'disabledfeedback', $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_feedback );
2261         } else {
2262             // visible elements
2264             $mform->addElement('editor', 'submissioncomment_editor', get_string('feedback', 'assignment').':', null, $this->get_editor_options() );
2265             $mform->setType('submissioncomment_editor', PARAM_RAW); // to be cleaned before display
2266             $mform->setDefault('submissioncomment_editor', $this->_customdata->submission->submissioncomment);
2267             //$mform->addRule('submissioncomment', get_string('required'), 'required', null, 'client');
2268             switch ($this->_customdata->assignment->assignmenttype) {
2269                 case 'upload' :
2270                 case 'uploadsingle' :
2271                     $mform->addElement('filemanager', 'files_filemanager', get_string('responsefiles', 'assignment'). ':', null, $this->_customdata->fileui_options);
2272                     break;
2273                 default :
2274                     break;
2275             }
2276             $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? array('checked'=>'checked') : array();
2277             $mform->addElement('hidden', 'mailinfo_h', "0");
2278             $mform->setType('mailinfo_h', PARAM_INT);
2279             $mform->addElement('checkbox', 'mailinfo',get_string('enableemailnotification','assignment').
2280             $OUTPUT->help_icon('enableemailnotification', 'assignment') .':' );
2281             $mform->updateElementAttr('mailinfo', $lastmailinfo);
2282             $mform->setType('mailinfo', PARAM_INT);
2283         }
2284     }
2286     function add_action_buttons() {
2287         $mform =& $this->_form;
2288         //if there are more to be graded.
2289         if ($this->_customdata->nextid>0) {
2290             $buttonarray=array();
2291             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2292             //@todo: fix accessibility: javascript dependency not necessary
2293             $buttonarray[] = &$mform->createElement('submit', 'saveandnext', get_string('saveandnext'));
2294             $buttonarray[] = &$mform->createElement('submit', 'next', get_string('next'));
2295             $buttonarray[] = &$mform->createElement('cancel');
2296         } else {
2297             $buttonarray=array();
2298             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2299             $buttonarray[] = &$mform->createElement('cancel');
2300         }
2301         $mform->addGroup($buttonarray, 'grading_buttonar', '', array(' '), false);
2302         $mform->closeHeaderBefore('grading_buttonar');
2303         $mform->setType('grading_buttonar', PARAM_RAW);
2304     }
2306     function add_submission_content() {
2307         $mform =& $this->_form;
2308         $mform->addElement('header', 'Submission', get_string('submission', 'assignment'));
2309         $mform->addElement('static', '', '' , $this->_customdata->submission_content );
2310     }
2312     protected function get_editor_options() {
2313         $editoroptions = array();
2314         $editoroptions['component'] = 'mod_assignment';
2315         $editoroptions['filearea'] = 'feedback';
2316         $editoroptions['noclean'] = false;
2317         $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)
2318         $editoroptions['maxbytes'] = $this->_customdata->maxbytes;
2319         return $editoroptions;
2320     }
2322     public function set_data($data) {
2323         $editoroptions = $this->get_editor_options();
2324         if (!isset($data->text)) {
2325             $data->text = '';
2326         }
2327         if (!isset($data->format)) {
2328             $data->textformat = FORMAT_HTML;
2329         } else {
2330             $data->textformat = $data->format;
2331         }
2333         if (!empty($this->_customdata->submission->id)) {
2334             $itemid = $this->_customdata->submission->id;
2335         } else {
2336             $itemid = null;
2337         }
2339         switch ($this->_customdata->assignment->assignmenttype) {
2340                 case 'upload' :
2341                 case 'uploadsingle' :
2342                     $data = file_prepare_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2343                     break;
2344                 default :
2345                     break;
2346         }
2348         $data = file_prepare_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2349         return parent::set_data($data);
2350     }
2352     public function get_data() {
2353         $data = parent::get_data();
2355         if (!empty($this->_customdata->submission->id)) {
2356             $itemid = $this->_customdata->submission->id;
2357         } else {
2358             $itemid = null; //TODO: this is wrong, itemid MUST be known when saving files!! (skodak)
2359         }
2361         if ($data) {
2362             $editoroptions = $this->get_editor_options();
2363             switch ($this->_customdata->assignment->assignmenttype) {
2364                 case 'upload' :
2365                 case 'uploadsingle' :
2366                     $data = file_postupdate_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2367                     break;
2368                 default :
2369                     break;
2370             }
2371             $data = file_postupdate_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2372         }
2373         return $data;
2374     }
2377 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
2379 /**
2380  * Deletes an assignment instance
2381  *
2382  * This is done by calling the delete_instance() method of the assignment type class
2383  */
2384 function assignment_delete_instance($id){
2385     global $CFG, $DB;
2387     if (! $assignment = $DB->get_record('assignment', array('id'=>$id))) {
2388         return false;
2389     }
2391     // fall back to base class if plugin missing
2392     $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2393     if (file_exists($classfile)) {
2394         require_once($classfile);
2395         $assignmentclass = "assignment_$assignment->assignmenttype";
2397     } else {
2398         debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
2399         $assignmentclass = "assignment_base";
2400     }
2402     $ass = new $assignmentclass();
2403     return $ass->delete_instance($assignment);
2407 /**
2408  * Updates an assignment instance
2409  *
2410  * This is done by calling the update_instance() method of the assignment type class
2411  */
2412 function assignment_update_instance($assignment){
2413     global $CFG;
2415     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2417     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2418     $assignmentclass = "assignment_$assignment->assignmenttype";
2419     $ass = new $assignmentclass();
2420     return $ass->update_instance($assignment);
2424 /**
2425  * Adds an assignment instance
2426  *
2427  * This is done by calling the add_instance() method of the assignment type class
2428  */
2429 function assignment_add_instance($assignment) {
2430     global $CFG;
2432     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2434     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2435     $assignmentclass = "assignment_$assignment->assignmenttype";
2436     $ass = new $assignmentclass();
2437     return $ass->add_instance($assignment);
2441 /**
2442  * Returns an outline of a user interaction with an assignment
2443  *
2444  * This is done by calling the user_outline() method of the assignment type class
2445  */
2446 function assignment_user_outline($course, $user, $mod, $assignment) {
2447     global $CFG;
2449     require_once("$CFG->libdir/gradelib.php");
2450     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2451     $assignmentclass = "assignment_$assignment->assignmenttype";
2452     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2453     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2454     if (!empty($grades->items[0]->grades)) {
2455         return $ass->user_outline(reset($grades->items[0]->grades));
2456     } else {
2457         return null;
2458     }
2461 /**
2462  * Prints the complete info about a user's interaction with an assignment
2463  *
2464  * This is done by calling the user_complete() method of the assignment type class
2465  */
2466 function assignment_user_complete($course, $user, $mod, $assignment) {
2467     global $CFG;
2469     require_once("$CFG->libdir/gradelib.php");
2470     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2471     $assignmentclass = "assignment_$assignment->assignmenttype";
2472     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2473     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2474     if (empty($grades->items[0]->grades)) {
2475         $grade = false;
2476     } else {
2477         $grade = reset($grades->items[0]->grades);
2478     }
2479     return $ass->user_complete($user, $grade);
2482 /**
2483  * Function to be run periodically according to the moodle cron
2484  *
2485  * Finds all assignment notifications that have yet to be mailed out, and mails them
2486  */
2487 function assignment_cron () {
2488     global $CFG, $USER, $DB;
2490     /// first execute all crons in plugins
2491     if ($plugins = get_plugin_list('assignment')) {
2492         foreach ($plugins as $plugin=>$dir) {
2493             require_once("$dir/assignment.class.php");
2494             $assignmentclass = "assignment_$plugin";
2495             $ass = new $assignmentclass();
2496             $ass->cron();
2497         }
2498     }
2500     /// Notices older than 1 day will not be mailed.  This is to avoid the problem where
2501     /// cron has not been running for a long time, and then suddenly people are flooded
2502     /// with mail from the past few weeks or months
2504     $timenow   = time();
2505     $endtime   = $timenow - $CFG->maxeditingtime;
2506     $starttime = $endtime - 24 * 3600;   /// One day earlier
2508     if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2510         $realuser = clone($USER);
2512         foreach ($submissions as $key => $submission) {
2513             if (! $DB->set_field("assignment_submissions", "mailed", "1", array("id"=>$submission->id))) {
2514                 echo "Could not update the mailed field for id $submission->id.  Not mailed.\n";
2515                 unset($submissions[$key]);
2516             }
2517         }
2519         $timenow = time();
2521         foreach ($submissions as $submission) {
2523             echo "Processing assignment submission $submission->id\n";
2525             if (! $user = $DB->get_record("user", array("id"=>$submission->userid))) {
2526                 echo "Could not find user $post->userid\n";
2527                 continue;
2528             }
2530             if (! $course = $DB->get_record("course", array("id"=>$submission->course))) {
2531                 echo "Could not find course $submission->course\n";
2532                 continue;
2533             }
2535             /// Override the language and timezone of the "current" user, so that
2536             /// mail is customised for the receiver.
2537             cron_setup_user($user, $course);
2539             if (!is_enrolled(get_context_instance(CONTEXT_COURSE, $submission->course), $user->id)) {
2540                 echo fullname($user)." not an active participant in " . format_string($course->shortname) . "\n";
2541                 continue;
2542             }
2544             if (! $teacher = $DB->get_record("user", array("id"=>$submission->teacher))) {
2545                 echo "Could not find teacher $submission->teacher\n";
2546                 continue;
2547             }
2549             if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2550                 echo "Could not find course module for assignment id $submission->assignment\n";
2551                 continue;
2552             }
2554             if (! $mod->visible) {    /// Hold mail notification for hidden assignments until later
2555                 continue;
2556             }
2558             $strassignments = get_string("modulenameplural", "assignment");
2559             $strassignment  = get_string("modulename", "assignment");
2561             $assignmentinfo = new object();
2562             $assignmentinfo->teacher = fullname($teacher);
2563             $assignmentinfo->assignment = format_string($submission->name,true);
2564             $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2566             $postsubject = "$course->shortname: $strassignments: ".format_string($submission->name,true);
2567             $posttext  = "$course->shortname -> $strassignments -> ".format_string($submission->name,true)."\n";
2568             $posttext .= "---------------------------------------------------------------------\n";
2569             $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2570             $posttext .= "---------------------------------------------------------------------\n";
2572             if ($user->mailformat == 1) {  // HTML
2573                 $posthtml = "<p><font face=\"sans-serif\">".
2574                 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> ->".
2575                 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2576                 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2577                 $posthtml .= "<hr /><font face=\"sans-serif\">";
2578                 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2579                 $posthtml .= "</font><hr />";
2580             } else {
2581                 $posthtml = "";
2582             }
2584             $eventdata = new object();
2585             $eventdata->modulename       = 'assignment';
2586             $eventdata->userfrom         = $teacher;
2587             $eventdata->userto           = $user;
2588             $eventdata->subject          = $postsubject;
2589             $eventdata->fullmessage      = $posttext;
2590             $eventdata->fullmessageformat = FORMAT_PLAIN;
2591             $eventdata->fullmessagehtml  = $posthtml;
2592             $eventdata->smallmessage     = '';
2593             message_send($eventdata);
2594         }
2596         cron_setup_user();
2597     }
2599     return true;
2602 /**
2603  * Return grade for given user or all users.
2604  *
2605  * @param int $assignmentid id of assignment
2606  * @param int $userid optional user id, 0 means all users
2607  * @return array array of grades, false if none
2608  */
2609 function assignment_get_user_grades($assignment, $userid=0) {
2610     global $CFG, $DB;
2612     if ($userid) {
2613         $user = "AND u.id = :userid";
2614         $params = array('userid'=>$userid);
2615     } else {
2616         $user = "";
2617     }
2618     $params['aid'] = $assignment->id;
2620     $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2621                    s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2622               FROM {user} u, {assignment_submissions} s
2623              WHERE u.id = s.userid AND s.assignment = :aid
2624                    $user";
2626     return $DB->get_records_sql($sql, $params);
2629 /**
2630  * Update activity grades
2631  *
2632  * @param object $assignment
2633  * @param int $userid specific user only, 0 means all
2634  */
2635 function assignment_update_grades($assignment, $userid=0, $nullifnone=true) {
2636     global $CFG, $DB;
2637     require_once($CFG->libdir.'/gradelib.php');
2639     if ($assignment->grade == 0) {
2640         assignment_grade_item_update($assignment);
2642     } else if ($grades = assignment_get_user_grades($assignment, $userid)) {
2643         foreach($grades as $k=>$v) {
2644             if ($v->rawgrade == -1) {
2645                 $grades[$k]->rawgrade = null;
2646             }
2647         }
2648         assignment_grade_item_update($assignment, $grades);
2650     } else {
2651         assignment_grade_item_update($assignment);
2652     }
2655 /**
2656  * Update all grades in gradebook.
2657  */
2658 function assignment_upgrade_grades() {
2659     global $DB;
2661     $sql = "SELECT COUNT('x')
2662               FROM {assignment} a, {course_modules} cm, {modules} m
2663              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2664     $count = $DB->count_records_sql($sql);
2666     $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
2667               FROM {assignment} a, {course_modules} cm, {modules} m
2668              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2669     if ($rs = $DB->get_recordset_sql($sql)) {
2670         // too much debug output
2671         $pbar = new progress_bar('assignmentupgradegrades', 500, true);
2672         $i=0;
2673         foreach ($rs as $assignment) {
2674             $i++;
2675             upgrade_set_timeout(60*5); // set up timeout, may also abort execution
2676             assignment_update_grades($assignment);
2677             $pbar->update($i, $count, "Updating Assignment grades ($i/$count).");
2678         }
2679         $rs->close();
2680         upgrade_set_timeout(); // reset to default timeout
2681     }
2684 /**
2685  * Create grade item for given assignment
2686  *
2687  * @param object $assignment object with extra cmidnumber
2688  * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
2689  * @return int 0 if ok, error code otherwise
2690  */
2691 function assignment_grade_item_update($assignment, $grades=NULL) {
2692     global $CFG;
2693     require_once($CFG->libdir.'/gradelib.php');
2695     if (!isset($assignment->courseid)) {
2696         $assignment->courseid = $assignment->course;
2697     }
2699     $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
2701     if ($assignment->grade > 0) {
2702         $params['gradetype'] = GRADE_TYPE_VALUE;
2703         $params['grademax']  = $assignment->grade;
2704         $params['grademin']  = 0;
2706     } else if ($assignment->grade < 0) {
2707         $params['gradetype'] = GRADE_TYPE_SCALE;
2708         $params['scaleid']   = -$assignment->grade;
2710     } else {
2711         $params['gradetype'] = GRADE_TYPE_TEXT; // allow text comments only
2712     }
2714     if ($grades  === 'reset') {
2715         $params['reset'] = true;
2716         $grades = NULL;
2717     }
2719     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades, $params);
2722 /**
2723  * Delete grade item for given assignment
2724  *
2725  * @param object $assignment object
2726  * @return object assignment
2727  */
2728 function assignment_grade_item_delete($assignment) {
2729     global $CFG;
2730     require_once($CFG->libdir.'/gradelib.php');
2732     if (!isset($assignment->courseid)) {
2733         $assignment->courseid = $assignment->course;
2734     }
2736     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
2739 /**
2740  * Returns the users with data in one assignment (students and teachers)
2741  *
2742  * @param $assignmentid int
2743  * @return array of user objects
2744  */
2745 function assignment_get_participants($assignmentid) {
2746     global $CFG, $DB;
2748     //Get students
2749     $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2750                                         FROM {user} u,
2751                                              {assignment_submissions} a
2752                                        WHERE a.assignment = ? and
2753                                              u.id = a.userid", array($assignmentid));
2754     //Get teachers
2755     $teachers = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2756                                         FROM {user} u,
2757                                              {assignment_submissions} a
2758                                        WHERE a.assignment = ? and
2759                                              u.id = a.teacher", array($assignmentid));
2761     //Add teachers to students
2762     if ($teachers) {
2763         foreach ($teachers as $teacher) {
2764             $students[$teacher->id] = $teacher;
2765         }
2766     }
2767     //Return students array (it contains an array of unique users)
2768     return ($students);
2771 /**
2772  * Serves assignment submissions and other files.
2773  *
2774  * @param object $course
2775  * @param object $cm
2776  * @param object $context
2777  * @param string $filearea
2778  * @param array $args
2779  * @param bool $forcedownload
2780  * @return bool false if file not found, does not return if found - just send the file
2781  */
2782 function assignment_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) {
2783     global $CFG, $DB;
2785     if ($context->contextlevel != CONTEXT_MODULE) {
2786         return false;
2787     }
2789     require_login($course, false, $cm);
2791     if (!$assignment = $DB->get_record('assignment', array('id'=>$cm->instance))) {
2792         return false;
2793     }
2795     require_once($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
2796     $assignmentclass = 'assignment_'.$assignment->assignmenttype;
2797     $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm, $course);
2799     return $assignmentinstance->send_file($filearea, $args);
2801 /**
2802  * Checks if a scale is being used by an assignment
2803  *
2804  * This is used by the backup code to decide whether to back up a scale
2805  * @param $assignmentid int
2806  * @param $scaleid int
2807  * @return boolean True if the scale is used by the assignment
2808  */
2809 function assignment_scale_used($assignmentid, $scaleid) {
2810     global $DB;
2812     $return = false;
2814     $rec = $DB->get_record('assignment', array('id'=>$assignmentid,'grade'=>-$scaleid));
2816     if (!empty($rec) && !empty($scaleid)) {
2817         $return = true;
2818     }
2820     return $return;
2823 /**
2824  * Checks if scale is being used by any instance of assignment
2825  *
2826  * This is used to find out if scale used anywhere
2827  * @param $scaleid int
2828  * @return boolean True if the scale is used by any assignment
2829  */
2830 function assignment_scale_used_anywhere($scaleid) {
2831     global $DB;
2833     if ($scaleid and $DB->record_exists('assignment', array('grade'=>-$scaleid))) {
2834         return true;
2835     } else {
2836         return false;
2837     }
2840 /**
2841  * Make sure up-to-date events are created for all assignment instances
2842  *
2843  * This standard function will check all instances of this module
2844  * and make sure there are up-to-date events created for each of them.
2845  * If courseid = 0, then every assignment event in the site is checked, else
2846  * only assignment events belonging to the course specified are checked.
2847  * This function is used, in its new format, by restore_refresh_events()
2848  *
2849  * @param $courseid int optional If zero then all assignments for all courses are covered
2850  * @return boolean Always returns true
2851  */
2852 function assignment_refresh_events($courseid = 0) {
2853     global $DB;
2855     if ($courseid == 0) {
2856         if (! $assignments = $DB->get_records("assignment")) {
2857             return true;
2858         }
2859     } else {
2860         if (! $assignments = $DB->get_records("assignment", array("course"=>$courseid))) {
2861             return true;
2862         }
2863     }
2864     $moduleid = $DB->get_field('modules', 'id', array('name'=>'assignment'));
2866     foreach ($assignments as $assignment) {
2867         $cm = get_coursemodule_from_id('assignment', $assignment->id);
2868         $event = new object();
2869         $event->name        = $assignment->name;
2870         $event->description = format_module_intro('assignment', $assignment, $cm->id);
2871         $event->timestart   = $assignment->timedue;
2873         if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
2874             update_event($event);
2876         } else {
2877             $event->courseid    = $assignment->course;
2878             $event->groupid     = 0;
2879             $event->userid      = 0;
2880             $event->modulename  = 'assignment';
2881             $event->instance    = $assignment->id;
2882             $event->eventtype   = 'due';
2883             $event->timeduration = 0;
2884             $event->visible     = $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$assignment->id));
2885             add_event($event);
2886         }
2888     }
2889     return true;
2892 /**
2893  * Print recent activity from all assignments in a given course
2894  *
2895  * This is used by the recent activity block
2896  */
2897 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
2898     global $CFG, $USER, $DB, $OUTPUT;
2900     // do not use log table if possible, it may be huge
2902     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
2903                                                      u.firstname, u.lastname, u.email, u.picture
2904                                                 FROM {assignment_submissions} asb
2905                                                      JOIN {assignment} a      ON a.id = asb.assignment
2906                                                      JOIN {course_modules} cm ON cm.instance = a.id
2907                                                      JOIN {modules} md        ON md.id = cm.module
2908                                                      JOIN {user} u            ON u.id = asb.userid
2909                                                WHERE asb.timemodified > ? AND
2910                                                      a.course = ? AND
2911                                                      md.name = 'assignment'
2912                                             ORDER BY asb.timemodified ASC", array($timestart, $course->id))) {
2913          return false;
2914     }
2916     $modinfo =& get_fast_modinfo($course); // reference needed because we might load the groups
2917     $show    = array();
2918     $grader  = array();
2920     foreach($submissions as $submission) {
2921         if (!array_key_exists($submission->cmid, $modinfo->cms)) {
2922             continue;
2923         }
2924         $cm = $modinfo->cms[$submission->cmid];
2925         if (!$cm->uservisible) {
2926             continue;
2927         }
2928         if ($submission->userid == $USER->id) {
2929             $show[] = $submission;
2930             continue;
2931         }
2933         // the act of sumbitting of assignment may be considered private - only graders will see it if specified
2934         if (empty($CFG->assignment_showrecentsubmissions)) {
2935             if (!array_key_exists($cm->id, $grader)) {
2936                 $grader[$cm->id] = has_capability('moodle/grade:viewall', get_context_instance(CONTEXT_MODULE, $cm->id));
2937             }
2938             if (!$grader[$cm->id]) {
2939                 continue;
2940             }
2941         }
2943         $groupmode = groups_get_activity_groupmode($cm, $course);
2945         if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2946             if (isguestuser()) {
2947                 // shortcut - guest user does not belong into any group
2948                 continue;
2949             }
2951             if (is_null($modinfo->groups)) {
2952                 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2953             }
2955             // this will be slow - show only users that share group with me in this cm
2956             if (empty($modinfo->groups[$cm->id])) {
2957                 continue;
2958             }
2959             $usersgroups =  groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
2960             if (is_array($usersgroups)) {
2961                 $usersgroups = array_keys($usersgroups);
2962                 $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2963                 if (empty($intersect)) {
2964                     continue;
2965                 }
2966             }
2967         }
2968         $show[] = $submission;
2969     }
2971     if (empty($show)) {
2972         return false;
2973     }
2975     echo $OUTPUT->heading(get_string('newsubmissions', 'assignment').':', 3);
2977     foreach ($show as $submission) {
2978         $cm = $modinfo->cms[$submission->cmid];
2979         $link = $CFG->wwwroot.'/mod/assignment/view.php?id='.$cm->id;
2980         print_recent_activity_note($submission->timemodified, $submission, $cm->name, $link, false, $viewfullnames);
2981     }
2983     return true;
2987 /**
2988  * Returns all assignments since a given time in specified forum.
2989  */
2990 function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0)  {
2991     global $CFG, $COURSE, $USER, $DB;
2993     if ($COURSE->id == $courseid) {
2994         $course = $COURSE;
2995     } else {
2996         $course = $DB->get_record('course', array('id'=>$courseid));
2997     }
2999     $modinfo =& get_fast_modinfo($course);
3001     $cm = $modinfo->cms[$cmid];
3003     $params = array();
3004     if ($userid) {
3005         $userselect = "AND u.id = :userid";
3006         $params['userid'] = $userid;
3007     } else {
3008         $userselect = "";
3009     }
3011     if ($groupid) {
3012         $groupselect = "AND gm.groupid = :groupid";
3013         $groupjoin   = "JOIN {groups_members} gm ON  gm.userid=u.id";
3014         $params['groupid'] = $groupid;
3015     } else {
3016         $groupselect = "";
3017         $groupjoin   = "";
3018     }
3020     $params['cminstance'] = $cm->instance;
3021     $params['timestart'] = $timestart;
3023     $userfields = user_picture::fields('u', null, 'userid');
3025     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified,
3026                                                      $userfields
3027                                                 FROM {assignment_submissions} asb
3028                                                 JOIN {assignment} a      ON a.id = asb.assignment
3029                                                 JOIN {user} u            ON u.id = asb.userid
3030                                           $groupjoin
3031                                                WHERE asb.timemodified > :timestart AND a.id = :cminstance
3032                                                      $userselect $groupselect
3033                                             ORDER BY asb.timemodified ASC", $params)) {
3034          return;
3035     }
3037     $groupmode       = groups_get_activity_groupmode($cm, $course);
3038     $cm_context      = get_context_instance(CONTEXT_MODULE, $cm->id);
3039     $grader          = has_capability('moodle/grade:viewall', $cm_context);
3040     $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
3041     $viewfullnames   = has_capability('moodle/site:viewfullnames', $cm_context);
3043     if (is_null($modinfo->groups)) {
3044         $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
3045     }
3047     $show = array();
3049     foreach($submissions as $submission) {
3050         if ($submission->userid == $USER->id) {
3051             $show[] = $submission;
3052             continue;
3053         }
3054         // the act of submitting of assignment may be considered private - only graders will see it if specified
3055         if (empty($CFG->assignment_showrecentsubmissions)) {
3056             if (!$grader) {
3057                 continue;
3058             }
3059         }
3061         if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
3062             if (isguestuser()) {
3063                 // shortcut - guest user does not belong into any group
3064                 continue;
3065             }
3067             // this will be slow - show only users that share group with me in this cm
3068             if (empty($modinfo->groups[$cm->id])) {
3069                 continue;
3070             }
3071             $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
3072             if (is_array($usersgroups)) {
3073                 $usersgroups = array_keys($usersgroups);
3074                 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
3075                 if (empty($intersect)) {
3076                     continue;
3077                 }
3078             }
3079         }
3080         $show[] = $submission;
3081     }
3083     if (empty($show)) {
3084         return;
3085     }
3087     if ($grader) {
3088         require_once($CFG->libdir.'/gradelib.php');
3089         $userids = array();
3090         foreach ($show as $id=>$submission) {
3091             $userids[] = $submission->userid;
3093         }
3094         $grades = grade_get_grades($courseid, 'mod', 'assignment', $cm->instance, $userids);
3095     }
3097     $aname = format_string($cm->name,true);
3098     foreach ($show as $submission) {
3099         $tmpactivity = new object();
3101         $tmpactivity->type         = 'assignment';
3102         $tmpactivity->cmid         = $cm->id;
3103         $tmpactivity->name         = $aname;
3104         $tmpactivity->sectionnum   = $cm->sectionnum;
3105         $tmpactivity->timestamp    = $submission->timemodified;
3107         if ($grader) {
3108             $tmpactivity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
3109         }
3111         $userfields = explode(',', user_picture::fields());
3112         foreach ($userfields as $userfield) {
3113             if ($userfield == 'id') {
3114                 $tmpactivity->user->{$userfield} = $submission->userid; // aliased in SQL above
3115             } else {
3116                 $tmpactivity->user->{$userfield} = $submission->{$userfield};
3117             }
3118         }
3119         $tmpactivity->user->fullname = fullname($submission, $viewfullnames);
3121         $activities[$index++] = $tmpactivity;
3122     }
3124     return;
3127 /**
3128  * Print recent activity from all assignments in a given course
3129  *
3130  * This is used by course/recent.php
3131  */
3132 function assignment_print_recent_mod_activity($activity, $courseid, $detail, $modnames)  {
3133     global $CFG, $OUTPUT;
3135     echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
3137     echo "<tr><td class=\"userpicture\" valign=\"top\">";
3138     echo $OUTPUT->user_picture($activity->user);
3139     echo "</td><td>";
3141     if ($detail) {
3142         $modname = $modnames[$activity->type];
3143         echo '<div class="title">';
3144         echo "<img src=\"" . $OUTPUT->pix_url('icon', 'assignment') . "\" ".
3145              "class=\"icon\" alt=\"$modname\">";
3146         echo "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id={$activity->cmid}\">{$activity->name}</a>";
3147         echo '</div>';
3148     }
3150     if (isset($activity->grade)) {
3151         echo '<div class="grade">';
3152         echo get_string('grade').': ';
3153         echo $activity->grade;
3154         echo '</div>';
3155     }
3157     echo '<div class="user">';
3158     echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->id}&amp;course=$courseid\">"
3159          ."{$activity->user->fullname}</a>  - ".userdate($activity->timestamp);
3160     echo '</div>';
3162     echo "</td></tr></table>";
3165 /// GENERIC SQL FUNCTIONS
3167 /**
3168  * Fetch info from logs
3169  *
3170  * @param $log object with properties ->info (the assignment id) and ->userid
3171  * @return array with assignment name and user firstname and lastname
3172  */
3173 function assignment_log_info($log) {
3174     global $CFG, $DB;
3176     return $DB->get_record_sql("SELECT a.name, u.firstname, u.lastname
3177                                   FROM {assignment} a, {user} u
3178                                  WHERE a.id = ? AND u.id = ?", array($log->info, $log->userid));
3181 /**
3182  * Return list of marked submissions that have not been mailed out for currently enrolled students
3183  *
3184  * @return array
3185  */
3186 function assignment_get_unmailed_submissions($starttime, $endtime) {
3187     global $CFG, $DB;
3189     return $DB->get_records_sql("SELECT s.*, a.course, a.name
3190                                    FROM {assignment_submissions} s,
3191                                         {assignment} a
3192                                   WHERE s.mailed = 0
3193                                         AND s.timemarked <= ?
3194                                         AND s.timemarked >= ?
3195                                         AND s.assignment = a.id", array($endtime, $starttime));
3198 /**
3199  * Counts all real assignment submissions by ENROLLED students (not empty ones)
3200  *
3201  * There are also assignment type methods count_real_submissions() wich in the default
3202  * implementation simply call this function.
3203  * @param $groupid int optional If nonzero then count is restricted to this group
3204  * @return int The number of submissions
3205  */
3206 function assignment_count_real_submissions($cm, $groupid=0) {
3207     global $CFG, $DB;
3209     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
3211     // this is all the users with this capability set, in this context or higher
3212     if ($users = get_enrolled_users($context, 'mod/assignment:submit', $groupid, 'u.id')) {
3213         $users = array_keys($users);
3214     }
3216     // if groupmembersonly used, remove users who are not in any group
3217     if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
3218         if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
3219             $users = array_intersect($users, array_keys($groupingusers));
3220         }
3221     }
3223     if (empty($users)) {
3224         return 0;
3225     }
3227     $userlists = implode(',', $users);
3229     return $DB->count_records_sql("SELECT COUNT('x')
3230                                      FROM {assignment_submissions}
3231                                     WHERE assignment = ? AND
3232                                           timemodified > 0 AND
3233                                           userid IN ($userlists)", array($cm->instance));
3237 /**
3238  * Return all assignment submissions by ENROLLED students (even empty)
3239  *
3240  * There are also assignment type methods get_submissions() wich in the default
3241  * implementation simply call this function.
3242  * @param $sort string optional field names for the ORDER BY in the sql query
3243  * @param $dir string optional specifying the sort direction, defaults to DESC
3244  * @return array The submission objects indexed by id
3245  */
3246 function assignment_get_all_submissions($assignment, $sort="", $dir="DESC") {
3247 /// Return all assignment submissions by ENROLLED students (even empty)
3248     global $CFG, $DB;
3250     if ($sort == "lastname" or $sort == "firstname") {
3251         $sort = "u.$sort $dir";
3252     } else if (empty($sort)) {
3253         $sort = "a.timemodified DESC";
3254     } else {
3255         $sort = "a.$sort $dir";
3256     }
3258     /* not sure this is needed at all since assignmenet already has a course define, so this join?
3259     $select = "s.course = '$assignment->course' AND";
3260     if ($assignment->course == SITEID) {
3261         $select = '';
3262     }*/
3264     return $DB->get_records_sql("SELECT a.*
3265                                    FROM {assignment_submissions} a, {user} u
3266                                   WHERE u.id = a.userid
3267                                         AND a.assignment = ?
3268                                ORDER BY $sort", array($assignment->id));
3272 /**
3273  * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
3274  * for the course (see resource).
3275  *
3276  * Given a course_module object, this function returns any "extra" information that may be needed
3277  * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
3278  *
3279  * @param $coursemodule object The coursemodule object (record).
3280  * @return object An object on information that the coures will know about (most noticeably, an icon).
3281  *
3282  */
3283 function assignment_get_coursemodule_info($coursemodule) {
3284     global $CFG, $DB;
3286     if (! $assignment = $DB->get_record('assignment', array('id'=>$coursemodule->instance), 'id, assignmenttype, name')) {
3287         return false;
3288     }
3290     $libfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
3292     if (file_exists($libfile)) {
3293         require_once($libfile);
3294         $assignmentclass = "assignment_$assignment->assignmenttype";
3295         $ass = new $assignmentclass('staticonly');
3296         if ($result = $ass->get_coursemodule_info($coursemodule)) {
3297             return $result;
3298         } else {
3299             $info = new object();
3300             $info->name = $assignment->name;
3301             return $info;
3302         }
3304     } else {
3305         debugging('Incorrect assignment type: '.$assignment->assignmenttype);
3306         return false;
3307     }
3312 /// OTHER GENERAL FUNCTIONS FOR ASSIGNMENTS  ///////////////////////////////////////
3314 /**
3315  * Returns an array of installed assignment types indexed and sorted by name
3316  *
3317  * @return array The index is the name of the assignment type, the value its full name from the language strings
3318  */
3319 function assignment_types() {
3320     $types = array();
3321     $names = get_plugin_list('assignment');
3322     foreach ($names as $name=>$dir) {
3323         $types[$name] = get_string('type'.$name, 'assignment');
3325         // ugly hack to support pluggable assignment type titles..
3326         if ($types[$name] == '[[type'.$name.']]') {
3327             $types[$name] = get_string('type'.$name, 'assignment_'.$name);
3328         }
3329     }
3330     asort($types);
3331     return $types;
3334 function assignment_print_overview($courses, &$htmlarray) {
3335     global $USER, $CFG, $DB;
3337     if (empty($courses) || !is_array($courses) || count($courses) == 0) {
3338         return array();
3339     }
3341     if (!$assignments = get_all_instances_in_courses('assignment',$courses)) {
3342         return;
3343     }
3345     $assignmentids = array();
3347     // Do assignment_base::isopen() here without loading the whole thing for speed
3348     foreach ($assignments as $key => $assignment) {
3349         $time = time();
3350         if ($assignment->timedue) {
3351             if ($assignment->preventlate) {
3352                 $isopen = ($assignment->timeavailable <= $time && $time <= $assignment->timedue);
3353             } else {
3354                 $isopen = ($assignment->timeavailable <= $time);
3355             }
3356         }
3357         if (empty($isopen) || empty($assignment->timedue)) {
3358             unset($assignments[$key]);
3359         } else {
3360             $assignmentids[] = $assignment->id;
3361         }
3362     }
3364     if (empty($assignmentids)){
3365         // no assigments to look at - we're done
3366         return true;
3367     }
3369     $strduedate = get_string('duedate', 'assignment');
3370     $strduedateno = get_string('duedateno', 'assignment');
3371     $strgraded = get_string('graded', 'assignment');
3372     $strnotgradedyet = get_string('notgradedyet', 'assignment');
3373     $strnotsubmittedyet = get_string('notsubmittedyet', 'assignment&#