MDL-14679 fixed multiple old style insert_record calls, we throw exceptions now from DML
[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         $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         return $returnid;
466     }
468     /**
469      * Deletes an assignment activity
470      *
471      * Deletes all database records, files and calendar events for this assignment.
472      *
473      * @global object
474      * @global object
475      * @param object $assignment The assignment to be deleted
476      * @return boolean False indicates error
477      */
478     function delete_instance($assignment) {
479         global $CFG, $DB;
481         $assignment->courseid = $assignment->course;
483         $result = true;
485         // now get rid of all files
486         $fs = get_file_storage();
487         if ($cm = get_coursemodule_from_instance('assignment', $assignment->id)) {
488             $context = get_context_instance(CONTEXT_MODULE, $cm->id);
489             $fs->delete_area_files($context->id);
490         }
492         if (! $DB->delete_records('assignment_submissions', array('assignment'=>$assignment->id))) {
493             $result = false;
494         }
496         if (! $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
497             $result = false;
498         }
500         if (! $DB->delete_records('assignment', array('id'=>$assignment->id))) {
501             $result = false;
502         }
503         $mod = $DB->get_field('modules','id',array('name'=>'assignment'));
505         assignment_grade_item_delete($assignment);
507         return $result;
508     }
510     /**
511      * Updates a new assignment activity
512      *
513      * Given an object containing all the necessary data,
514      * (defined by the form in mod_form.php) this function
515      * will update the assignment instance and return the id number
516      * The due date is updated in the calendar
517      * This is common to all assignment types.
518      *
519      * @global object
520      * @global object
521      * @param object $assignment The data from the form on mod_form.php
522      * @return bool success
523      */
524     function update_instance($assignment) {
525         global $COURSE, $DB;
527         $assignment->timemodified = time();
529         $assignment->id = $assignment->instance;
530         $assignment->courseid = $assignment->course;
532         $DB->update_record('assignment', $assignment);
534         if ($assignment->timedue) {
535             $event = new object();
537             if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
539                 $event->name        = $assignment->name;
540                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
541                 $event->timestart   = $assignment->timedue;
543                 $calendarevent = calendar_event::load($event->id);
544                 $calendarevent->update($event);
545             } else {
546                 $event = new object();
547                 $event->name        = $assignment->name;
548                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
549                 $event->courseid    = $assignment->course;
550                 $event->groupid     = 0;
551                 $event->userid      = 0;
552                 $event->modulename  = 'assignment';
553                 $event->instance    = $assignment->id;
554                 $event->eventtype   = 'due';
555                 $event->timestart   = $assignment->timedue;
556                 $event->timeduration = 0;
558                 calendar_event::create($event);
559             }
560         } else {
561             $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id));
562         }
564         // get existing grade item
565         assignment_grade_item_update($assignment);
567         return true;
568     }
570     /**
571      * Update grade item for this submission.
572      */
573     function update_grade($submission) {
574         assignment_update_grades($this->assignment, $submission->userid);
575     }
577     /**
578      * Top-level function for handling of submissions called by submissions.php
579      *
580      * This is for handling the teacher interaction with the grading interface
581      * This should be suitable for most assignment types.
582      *
583      * @global object
584      * @param string $mode Specifies the kind of teacher interaction taking place
585      */
586     function submissions($mode) {
587         ///The main switch is changed to facilitate
588         ///1) Batch fast grading
589         ///2) Skip to the next one on the popup
590         ///3) Save and Skip to the next one on the popup
592         //make user global so we can use the id
593         global $USER, $OUTPUT, $DB, $PAGE;
595         $mailinfo = optional_param('mailinfo', null, PARAM_BOOL);
597         if (optional_param('next', null, PARAM_BOOL)) {
598             $mode='next';
599         }
600         if (optional_param('saveandnext', null, PARAM_BOOL)) {
601             $mode='saveandnext';
602         }
604         if (is_null($mailinfo)) {
605             if (optional_param('sesskey', null, PARAM_BOOL)) {
606                 set_user_preference('assignment_mailinfo', $mailinfo);
607             } else {
608                 $mailinfo = get_user_preferences('assignment_mailinfo', 0);
609             }
610         } else {
611             set_user_preference('assignment_mailinfo', $mailinfo);
612         }
614         switch ($mode) {
615             case 'grade':                         // We are in a main window grading
616                 if ($submission = $this->process_feedback()) {
617                     $this->display_submissions(get_string('changessaved'));
618                 } else {
619                     $this->display_submissions();
620                 }
621                 break;
623             case 'single':                        // We are in a main window displaying one submission
624                 if ($submission = $this->process_feedback()) {
625                     $this->display_submissions(get_string('changessaved'));
626                 } else {
627                     $this->display_submission();
628                 }
629                 break;
631             case 'all':                          // Main window, display everything
632                 $this->display_submissions();
633                 break;
635             case 'fastgrade':
636                 ///do the fast grading stuff  - this process should work for all 3 subclasses
637                 $grading    = false;
638                 $commenting = false;
639                 $col        = false;
640                 if (isset($_POST['submissioncomment'])) {
641                     $col = 'submissioncomment';
642                     $commenting = true;
643                 }
644                 if (isset($_POST['menu'])) {
645                     $col = 'menu';
646                     $grading = true;
647                 }
648                 if (!$col) {
649                     //both submissioncomment and grade columns collapsed..
650                     $this->display_submissions();
651                     break;
652                 }
654                 foreach ($_POST[$col] as $id => $unusedvalue){
656                     $id = (int)$id; //clean parameter name
658                     $this->process_outcomes($id);
660                     if (!$submission = $this->get_submission($id)) {
661                         $submission = $this->prepare_new_submission($id);
662                         $newsubmission = true;
663                     } else {
664                         $newsubmission = false;
665                     }
666                     unset($submission->data1);  // Don't need to update this.
667                     unset($submission->data2);  // Don't need to update this.
669                     //for fast grade, we need to check if any changes take place
670                     $updatedb = false;
672                     if ($grading) {
673                         $grade = $_POST['menu'][$id];
674                         $updatedb = $updatedb || ($submission->grade != $grade);
675                         $submission->grade = $grade;
676                     } else {
677                         if (!$newsubmission) {
678                             unset($submission->grade);  // Don't need to update this.
679                         }
680                     }
681                     if ($commenting) {
682                         $commentvalue = trim($_POST['submissioncomment'][$id]);
683                         $updatedb = $updatedb || ($submission->submissioncomment != $commentvalue);
684                         $submission->submissioncomment = $commentvalue;
685                     } else {
686                         unset($submission->submissioncomment);  // Don't need to update this.
687                     }
689                     $submission->teacher    = $USER->id;
690                     if ($updatedb) {
691                         $submission->mailed = (int)(!$mailinfo);
692                     }
694                     $submission->timemarked = time();
696                     //if it is not an update, we don't change the last modified time etc.
697                     //this will also not write into database if no submissioncomment and grade is entered.
699                     if ($updatedb){
700                         if ($newsubmission) {
701                             if (!isset($submission->submissioncomment)) {
702                                 $submission->submissioncomment = '';
703                             }
704                             $sid = $DB->insert_record('assignment_submissions', $submission);
705                             $submission->id = $sid;
706                         } else {
707                             $DB->update_record('assignment_submissions', $submission);
708                         }
710                         // triger grade event
711                         $this->update_grade($submission);
713                         //add to log only if updating
714                         add_to_log($this->course->id, 'assignment', 'update grades',
715                                    'submissions.php?id='.$this->assignment->id.'&user='.$submission->userid,
716                                    $submission->userid, $this->cm->id);
717                     }
719                 }
721                 $message = $OUTPUT->notification(get_string('changessaved'), 'notifysuccess');
723                 $this->display_submissions($message);
724                 break;
727             case 'saveandnext':
728                 ///We are in pop up. save the current one and go to the next one.
729                 //first we save the current changes
730                 if ($submission = $this->process_feedback()) {
731                     //print_heading(get_string('changessaved'));
732                     //$extra_javascript = $this->update_main_listing($submission);
733                 }
735             case 'next':
736                 /// We are currently in pop up, but we want to skip to next one without saving.
737                 ///    This turns out to be similar to a single case
738                 /// The URL used is for the next submission.
739                 $offset = required_param('offset', PARAM_INT);
740                 $nextid = required_param('nextid', PARAM_INT);
741                 $id = required_param('id', PARAM_INT);
742                 $offset = (int)$offset+1;
743                 //$this->display_submission($offset+1 , $nextid);
744                 redirect('submissions.php?id='.$id.'&userid='. $nextid . '&mode=single&offset='.$offset);
745                 break;
747             case 'singlenosave':
748                 $this->display_submission();
749                 break;
751             default:
752                 echo "something seriously is wrong!!";
753                 break;
754         }
755     }
757     /**
758      * Helper method updating the listing on the main script from popup using javascript
759      *
760      * @global object
761      * @global object
762      * @param $submission object The submission whose data is to be updated on the main page
763      */
764     function update_main_listing($submission) {
765         global $SESSION, $CFG, $OUTPUT;
767         $output = '';
769         $perpage = get_user_preferences('assignment_perpage', 10);
771         $quickgrade = get_user_preferences('assignment_quickgrade', 0);
773         /// Run some Javascript to try and update the parent page
774         $output .= '<script type="text/javascript">'."\n<!--\n";
775         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['submissioncomment'])) {
776             if ($quickgrade){
777                 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid.'").value="'
778                 .trim($submission->submissioncomment).'";'."\n";
779              } else {
780                 $output.= 'opener.document.getElementById("com'.$submission->userid.
781                 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment)), 15)."\";\n";
782             }
783         }
785         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['grade'])) {
786             //echo optional_param('menuindex');
787             if ($quickgrade){
788                 $output.= 'opener.document.getElementById("menumenu'.$submission->userid.
789                 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT).'";'."\n";
790             } else {
791                 $output.= 'opener.document.getElementById("g'.$submission->userid.'").innerHTML="'.
792                 $this->display_grade($submission->grade)."\";\n";
793             }
794         }
795         //need to add student's assignments in there too.
796         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemodified']) &&
797             $submission->timemodified) {
798             $output.= 'opener.document.getElementById("ts'.$submission->userid.
799                  '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid)).userdate($submission->timemodified)."\";\n";
800         }
802         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemarked']) &&
803             $submission->timemarked) {
804             $output.= 'opener.document.getElementById("tt'.$submission->userid.
805                  '").innerHTML="'.userdate($submission->timemarked)."\";\n";
806         }
808         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['status'])) {
809             $output.= 'opener.document.getElementById("up'.$submission->userid.'").className="s1";';
810             $buttontext = get_string('update');
811             $url = new moodle_url('/mod/assignment/submissions.php', array(
812                     'id' => $this->cm->id,
813                     'userid' => $submission->userid,
814                     'mode' => 'single',
815                     'offset' => (optional_param('offset', '', PARAM_INT)-1)));
816             $button = $OUTPUT->action_link($url, $buttontext, new popup_action('click', $url, 'grade'.$submission->userid, array('height' => 450, 'width' => 700)), array('ttile'=>$buttontext));
818             $output .= 'opener.document.getElementById("up'.$submission->userid.'").innerHTML="'.addslashes_js($button).'";';
819         }
821         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $submission->userid);
823         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['finalgrade'])) {
824             $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid.
825             '").innerHTML="'.$grading_info->items[0]->grades[$submission->userid]->str_grade.'";'."\n";
826         }
828         if (!empty($CFG->enableoutcomes) and empty($SESSION->flextable['mod-assignment-submissions']->collapse['outcome'])) {
830             if (!empty($grading_info->outcomes)) {
831                 foreach($grading_info->outcomes as $n=>$outcome) {
832                     if ($outcome->grades[$submission->userid]->locked) {
833                         continue;
834                     }
836                     if ($quickgrade){
837                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.
838                         '").selectedIndex="'.$outcome->grades[$submission->userid]->grade.'";'."\n";
840                     } else {
841                         $options = make_grades_menu(-$outcome->scaleid);
842                         $options[0] = get_string('nooutcome', 'grades');
843                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.'").innerHTML="'.$options[$outcome->grades[$submission->userid]->grade]."\";\n";
844                     }
846                 }
847             }
848         }
850         $output .= "\n-->\n</script>";
851         return $output;
852     }
854     /**
855      *  Return a grade in user-friendly form, whether it's a scale or not
856      *
857      * @global object
858      * @param mixed $grade
859      * @return string User-friendly representation of grade
860      */
861     function display_grade($grade) {
862         global $DB;
864         static $scalegrades = array();   // Cache scales for each assignment - they might have different scales!!
866         if ($this->assignment->grade >= 0) {    // Normal number
867             if ($grade == -1) {
868                 return '-';
869             } else {
870                 return $grade.' / '.$this->assignment->grade;
871             }
873         } else {                                // Scale
874             if (empty($scalegrades[$this->assignment->id])) {
875                 if ($scale = $DB->get_record('scale', array('id'=>-($this->assignment->grade)))) {
876                     $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
877                 } else {
878                     return '-';
879                 }
880             }
881             if (isset($scalegrades[$this->assignment->id][$grade])) {
882                 return $scalegrades[$this->assignment->id][$grade];
883             }
884             return '-';
885         }
886     }
888     /**
889      *  Display a single submission, ready for grading on a popup window
890      *
891      * This default method prints the teacher info and submissioncomment box at the top and
892      * the student info and submission at the bottom.
893      * This method also fetches the necessary data in order to be able to
894      * provide a "Next submission" button.
895      * Calls preprocess_submission() to give assignment type plug-ins a chance
896      * to process submissions before they are graded
897      * This method gets its arguments from the page parameters userid and offset
898      *
899      * @global object
900      * @global object
901      * @param string $extra_javascript
902      */
903     function display_submission($offset=-1,$userid =-1, $display=true) {
904         global $CFG, $DB, $PAGE, $OUTPUT;
905         require_once($CFG->libdir.'/gradelib.php');
906         require_once($CFG->libdir.'/tablelib.php');
907         require_once("$CFG->dirroot/repository/lib.php");
908         if ($userid==-1) {
909             $userid = required_param('userid', PARAM_INT);
910         }
911         if ($offset==-1) {
912             $offset = required_param('offset', PARAM_INT);//offset for where to start looking for student.
913         }
914         $filter = optional_param('filter', 0, PARAM_INT);
916         if (!$user = $DB->get_record('user', array('id'=>$userid))) {
917             print_error('nousers');
918         }
920         if (!$submission = $this->get_submission($user->id)) {
921             $submission = $this->prepare_new_submission($userid);
922         }
923         if ($submission->timemodified > $submission->timemarked) {
924             $subtype = 'assignmentnew';
925         } else {
926             $subtype = 'assignmentold';
927         }
929         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
930         $gradingdisabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
932     /// construct SQL, using current offset to find the data of the next student
933         $course     = $this->course;
934         $assignment = $this->assignment;
935         $cm         = $this->cm;
936         $context    = get_context_instance(CONTEXT_MODULE, $cm->id);
938         /// Get all ppl that can submit assignments
940         $currentgroup = groups_get_activity_group($cm);
941         if ($users = get_enrolled_users($context, 'mod/assignment:submit', $currentgroup, 'u.id')) {
942             $users = array_keys($users);
943         }
945         // if groupmembersonly used, remove users who are not in any group
946         if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
947             if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
948                 $users = array_intersect($users, array_keys($groupingusers));
949             }
950         }
952         $nextid = 0;
953         $where = '';
954         if($filter == 'submitted') {
955             $where .= 's.timemodified > 0 AND ';
956         } else if($filter == 'requiregrading') {
957             $where .= 's.timemarked < s.timemodified AND ';
958         }
960         if ($users) {
961             $userfields = user_picture::fields('u', array('lastaccess'));
962             $select = "SELECT $userfields,
963                               s.id AS submissionid, s.grade, s.submissioncomment,
964                               s.timemodified, s.timemarked,
965                               COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ";
966             $sql = 'FROM {user} u '.
967                    'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
968                    AND s.assignment = '.$this->assignment->id.' '.
969                    'WHERE '.$where.'u.id IN ('.implode(',', $users).') ';
971             if ($sort = flexible_table::get_sort_for_table('mod-assignment-submissions')) {
972                 $sort = 'ORDER BY '.$sort.' ';
973             }
974             $auser = $DB->get_records_sql($select.$sql.$sort, null, $offset, 2);
976             if (is_array($auser) && count($auser)>1) {
977                 $nextuser = next($auser);
978             /// Calculate user status
979                 $nextuser->status = ($nextuser->timemarked > 0) && ($nextuser->timemarked >= $nextuser->timemodified);
980                 $nextid = $nextuser->id;
981             }
982         }
984         if ($submission->teacher) {
985             $teacher = $DB->get_record('user', array('id'=>$submission->teacher));
986         } else {
987             global $USER;
988             $teacher = $USER;
989         }
991         $this->preprocess_submission($submission);
993         $mformdata = new stdclass;
994         $mformdata->context = $this->context;
995         $mformdata->maxbytes = $this->course->maxbytes;
996         $mformdata->courseid = $this->course->id;
997         $mformdata->teacher = $teacher;
998         $mformdata->assignment = $assignment;
999         $mformdata->submission = $submission;
1000         $mformdata->lateness = $this->display_lateness($submission->timemodified);
1001         $mformdata->auser = $auser;
1002         $mformdata->user = $user;
1003         $mformdata->offset = $offset;
1004         $mformdata->userid = $userid;
1005         $mformdata->cm = $this->cm;
1006         $mformdata->grading_info = $grading_info;
1007         $mformdata->enableoutcomes = $CFG->enableoutcomes;
1008         $mformdata->grade = $this->assignment->grade;
1009         $mformdata->gradingdisabled = $gradingdisabled;
1010         $mformdata->nextid = $nextid;
1011         $mformdata->submissioncomment= $submission->submissioncomment;
1012         $mformdata->submissioncommentformat= FORMAT_HTML;
1013         $mformdata->submission_content= $this->print_user_files($user->id,true);
1014         $mformdata->filter = $filter;
1015          if ($assignment->assignmenttype == 'upload') {
1016             $mformdata->fileui_options = array('subdirs'=>1, 'maxbytes'=>$assignment->maxbytes, 'maxfiles'=>$assignment->var1, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL);
1017         } elseif ($assignment->assignmenttype == 'uploadsingle') {
1018             $mformdata->fileui_options = array('subdirs'=>0, 'maxbytes'=>$CFG->userquota, 'maxfiles'=>1, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL);
1019         }
1021         $submitform = new mod_assignment_grading_form( null, $mformdata );
1023          if (!$display) {
1024             $ret_data = new stdClass();
1025             $ret_data->mform = $submitform;
1026             $ret_data->fileui_options = $mformdata->fileui_options;
1027             return $ret_data;
1028         }
1030         if ($submitform->is_cancelled()) {
1031             redirect('submissions.php?id='.$this->cm->id);
1032         }
1034         $submitform->set_data($mformdata);
1036         $PAGE->set_title($this->course->fullname . ': ' .get_string('feedback', 'assignment').' - '.fullname($user, true));
1037         $PAGE->set_heading($this->course->fullname);
1038         $PAGE->navbar->add(get_string('submissions', 'assignment'), new moodle_url('/mod/assignment/submissions.php', array('id'=>$cm->id)));
1039         $PAGE->navbar->add(fullname($user, true));
1041         echo $OUTPUT->header();
1042         echo $OUTPUT->heading(get_string('feedback', 'assignment').': '.fullname($user, true));
1044         // display mform here...
1045         $submitform->display();
1047         $customfeedback = $this->custom_feedbackform($submission, true);
1048         if (!empty($customfeedback)) {
1049             echo $customfeedback;
1050         }
1052         echo $OUTPUT->footer();
1053     }
1055     /**
1056      *  Preprocess submission before grading
1057      *
1058      * Called by display_submission()
1059      * The default type does nothing here.
1060      *
1061      * @param object $submission The submission object
1062      */
1063     function preprocess_submission(&$submission) {
1064     }
1066     /**
1067      *  Display all the submissions ready for grading
1068      *
1069      * @global object
1070      * @global object
1071      * @global object
1072      * @global object
1073      * @param string $message
1074      * @return bool|void
1075      */
1076     function display_submissions($message='') {
1077         global $CFG, $DB, $USER, $DB, $OUTPUT, $PAGE;
1078         require_once($CFG->libdir.'/gradelib.php');
1080         /* first we check to see if the form has just been submitted
1081          * to request user_preference updates
1082          */
1084        $filters = array(self::FILTER_ALL             => get_string('all'),
1085                         self::FILTER_SUBMITTED       => get_string('submitted', 'assignment'),
1086                         self::FILTER_REQUIRE_GRADING => get_string('requiregrading', 'assignment'));
1088         $updatepref = optional_param('updatepref', 0, PARAM_INT);
1090         if (isset($_POST['updatepref'])){
1091             $perpage = optional_param('perpage', 10, PARAM_INT);
1092             $perpage = ($perpage <= 0) ? 10 : $perpage ;
1093             $filter = optional_param('filter', 0, PARAM_INT);
1094             set_user_preference('assignment_perpage', $perpage);
1095             set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
1096             set_user_preference('assignment_filter', $filter);
1097         }
1099         /* next we get perpage and quickgrade (allow quick grade) params
1100          * from database
1101          */
1102         $perpage    = get_user_preferences('assignment_perpage', 10);
1103         $quickgrade = get_user_preferences('assignment_quickgrade', 0);
1104         $filter = get_user_preferences('assignment_filter', 0);
1105         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);
1107         if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
1108             $uses_outcomes = true;
1109         } else {
1110             $uses_outcomes = false;
1111         }
1113         $page    = optional_param('page', 0, PARAM_INT);
1114         $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
1116     /// Some shortcuts to make the code read better
1118         $course     = $this->course;
1119         $assignment = $this->assignment;
1120         $cm         = $this->cm;
1122         $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
1123         add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->cm->id, $this->assignment->id, $this->cm->id);
1125         $PAGE->set_title(format_string($this->assignment->name,true));
1126         $PAGE->set_heading($this->course->fullname);
1127         echo $OUTPUT->header();
1129         echo '<div class="usersubmissions">';
1131         /// Print quickgrade form around the table
1132         if ($quickgrade) {
1133             $formattrs = array();
1134             $formattrs['action'] = new moodle_url('/mod/assignment/submissions.php');
1135             $formattrs['id'] = 'fastg';
1136             $formattrs['method'] = 'post';
1138             echo html_writer::start_tag('form', $formattrs);
1139             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'id',      'value'=> $this->cm->id));
1140             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'mode',    'value'=> 'fastgrade'));
1141             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'page',    'value'=> $page));
1142             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=> sesskey()));
1143         }
1145         $course_context = get_context_instance(CONTEXT_COURSE, $course->id);
1146         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
1147             echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">'
1148                 . get_string('seeallcoursegrades', 'grades') . '</a></div>';
1149         }
1151         if (!empty($message)) {
1152             echo $message;   // display messages here if any
1153         }
1155         $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1157     /// Check to see if groups are being used in this assignment
1159         /// find out current groups mode
1160         $groupmode = groups_get_activity_groupmode($cm);
1161         $currentgroup = groups_get_activity_group($cm, true);
1162         groups_print_activity_menu($cm, $CFG->wwwroot . '/mod/assignment/submissions.php?id=' . $this->cm->id);
1164         /// Get all ppl that are allowed to submit assignments
1165         list($esql, $params) = get_enrolled_sql($context, 'mod/assignment:submit', $currentgroup);
1167         if ($filter == self::FILTER_ALL) {
1168             $sql = "SELECT u.id FROM {user} u ".
1169                    "LEFT JOIN ($esql) eu ON eu.id=u.id ".
1170                    "WHERE u.deleted = 0 AND eu.id=u.id ";
1171         } else {
1172             $wherefilter = '';
1173             if($filter == self::FILTER_SUBMITTED) {
1174                $wherefilter = ' AND s.timemodified > 0';
1175             } else if($filter == self::FILTER_REQUIRE_GRADING) {
1176                 $wherefilter = ' AND s.timemarked < s.timemodified ';
1177             }
1179             $sql = "SELECT u.id FROM {user} u ".
1180                    "LEFT JOIN ($esql) eu ON eu.id=u.id ".
1181                    "LEFT JOIN {assignment_submissions} s ON (u.id = s.userid) " .
1182                    "WHERE u.deleted = 0 AND eu.id=u.id ".
1183                    'AND s.assignment = '. $this->assignment->id .
1184                     $wherefilter;
1185         }
1187         $users = $DB->get_records_sql($sql, $params);
1188         if (!empty($users)) {
1189             $users = array_keys($users);
1190         }
1192         // if groupmembersonly used, remove users who are not in any group
1193         if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
1194             if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1195                 $users = array_intersect($users, array_keys($groupingusers));
1196             }
1197         }
1199         $tablecolumns = array('picture', 'fullname', 'grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade');
1200         if ($uses_outcomes) {
1201             $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
1202         }
1204         $tableheaders = array('',
1205                               get_string('fullname'),
1206                               get_string('grade'),
1207                               get_string('comment', 'assignment'),
1208                               get_string('lastmodified').' ('.get_string('submission', 'assignment').')',
1209                               get_string('lastmodified').' ('.get_string('grade').')',
1210                               get_string('status'),
1211                               get_string('finalgrade', 'grades'));
1212         if ($uses_outcomes) {
1213             $tableheaders[] = get_string('outcome', 'grades');
1214         }
1216         require_once($CFG->libdir.'/tablelib.php');
1217         $table = new flexible_table('mod-assignment-submissions');
1219         $table->define_columns($tablecolumns);
1220         $table->define_headers($tableheaders);
1221         $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;currentgroup='.$currentgroup);
1223         $table->sortable(true, 'lastname');//sorted by lastname by default
1224         $table->collapsible(true);
1225         $table->initialbars(true);
1227         $table->column_suppress('picture');
1228         $table->column_suppress('fullname');
1230         $table->column_class('picture', 'picture');
1231         $table->column_class('fullname', 'fullname');
1232         $table->column_class('grade', 'grade');
1233         $table->column_class('submissioncomment', 'comment');
1234         $table->column_class('timemodified', 'timemodified');
1235         $table->column_class('timemarked', 'timemarked');
1236         $table->column_class('status', 'status');
1237         $table->column_class('finalgrade', 'finalgrade');
1238         if ($uses_outcomes) {
1239             $table->column_class('outcome', 'outcome');
1240         }
1242         $table->set_attribute('cellspacing', '0');
1243         $table->set_attribute('id', 'attempts');
1244         $table->set_attribute('class', 'submissions');
1245         $table->set_attribute('width', '100%');
1246         //$table->set_attribute('align', 'center');
1248         $table->no_sorting('finalgrade');
1249         $table->no_sorting('outcome');
1251         // Start working -- this is necessary as soon as the niceties are over
1252         $table->setup();
1254         if (empty($users)) {
1255             echo $OUTPUT->heading(get_string('nosubmitusers','assignment'));
1256             echo '</div>';
1257             return true;
1258         }
1259         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)
1260             echo '<div style="text-align:right"><a href="submissions.php?id='.$this->cm->id.'&amp;download=zip">'.get_string('downloadall', 'assignment').'</a></div>';
1261         }
1262     /// Construct the SQL
1264         if ($where = $table->get_sql_where()) {
1265             $where .= ' AND ';
1266         }
1268         if($filter == self::FILTER_SUBMITTED) {
1269            $where .= 's.timemodified > 0 AND ';
1270         } else if($filter == self::FILTER_REQUIRE_GRADING) {
1271            $where .= 's.timemarked < s.timemodified AND ';
1272         }
1274         if ($sort = $table->get_sql_sort()) {
1275             $sort = ' ORDER BY '.$sort;
1276         }
1278         $ufields = user_picture::fields('u');
1280         $select = "SELECT $ufields,
1281                           s.id AS submissionid, s.grade, s.submissioncomment,
1282                           s.timemodified, s.timemarked,
1283                           COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ";
1284         $sql = 'FROM {user} u '.
1285                'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1286                 AND s.assignment = '.$this->assignment->id.' '.
1287                'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1289         $ausers = $DB->get_records_sql($select.$sql.$sort, null, $table->get_page_start(), $table->get_page_size());
1291         $table->pagesize($perpage, count($users));
1293         ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1294         $offset = $page * $perpage;
1295         $strupdate = get_string('update');
1296         $strgrade  = get_string('grade');
1297         $grademenu = make_grades_menu($this->assignment->grade);
1299         if ($ausers !== false) {
1300             $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
1301             $endposition = $offset + $perpage;
1302             $currentposition = 0;
1303             foreach ($ausers as $auser) {
1304                 if ($currentposition == $offset && $offset < $endposition) {
1305                     $final_grade = $grading_info->items[0]->grades[$auser->id];
1306                     $grademax = $grading_info->items[0]->grademax;
1307                     $final_grade->formatted_grade = round($final_grade->grade,2) .' / ' . round($grademax,2);
1308                     $locked_overridden = 'locked';
1309                     if ($final_grade->overridden) {
1310                         $locked_overridden = 'overridden';
1311                     }
1313                 /// Calculate user status
1314                     $auser->status = ($auser->timemarked > 0) && ($auser->timemarked >= $auser->timemodified);
1315                     $picture = $OUTPUT->user_picture($auser);
1317                     if (empty($auser->submissionid)) {
1318                         $auser->grade = -1; //no submission yet
1319                     }
1321                     if (!empty($auser->submissionid)) {
1322                     ///Prints student answer and student modified date
1323                     ///attach file or print link to student answer, depending on the type of the assignment.
1324                     ///Refer to print_student_answer in inherited classes.
1325                         if ($auser->timemodified > 0) {
1326                             $studentmodified = '<div id="ts'.$auser->id.'">'.$this->print_student_answer($auser->id)
1327                                              . userdate($auser->timemodified).'</div>';
1328                         } else {
1329                             $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1330                         }
1331                     ///Print grade, dropdown or text
1332                         if ($auser->timemarked > 0) {
1333                             $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
1335                             if ($final_grade->locked or $final_grade->overridden) {
1336                                 $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1337                             } else if ($quickgrade) {
1338                                 $attributes = array();
1339                                 $attributes['tabindex'] = $tabindex++;
1340                                 $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1341                                 $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
1342                             } else {
1343                                 $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1344                             }
1346                         } else {
1347                             $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1348                             if ($final_grade->locked or $final_grade->overridden) {
1349                                 $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1350                             } else if ($quickgrade) {
1351                                 $attributes = array();
1352                                 $attributes['tabindex'] = $tabindex++;
1353                                 $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1354                                 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1355                             } else {
1356                                 $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1357                             }
1358                         }
1359                     ///Print Comment
1360                         if ($final_grade->locked or $final_grade->overridden) {
1361                             $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';
1363                         } else if ($quickgrade) {
1364                             $comment = '<div id="com'.$auser->id.'">'
1365                                      . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1366                                      . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1367                         } else {
1368                             $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
1369                         }
1370                     } else {
1371                         $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1372                         $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1373                         $status          = '<div id="st'.$auser->id.'">&nbsp;</div>';
1375                         if ($final_grade->locked or $final_grade->overridden) {
1376                             $grade = '<div id="g'.$auser->id.'">'.$final_grade->formatted_grade . '</div>';
1377                         } else if ($quickgrade) {   // allow editing
1378                             $attributes = array();
1379                             $attributes['tabindex'] = $tabindex++;
1380                             $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1381                             $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1382                         } else {
1383                             $grade = '<div id="g'.$auser->id.'">-</div>';
1384                         }
1386                         if ($final_grade->locked or $final_grade->overridden) {
1387                             $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
1388                         } else if ($quickgrade) {
1389                             $comment = '<div id="com'.$auser->id.'">'
1390                                      . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1391                                      . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1392                         } else {
1393                             $comment = '<div id="com'.$auser->id.'">&nbsp;</div>';
1394                         }
1395                     }
1397                     if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
1398                         $auser->status = 0;
1399                     } else {
1400                         $auser->status = 1;
1401                     }
1403                     $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
1405                     ///No more buttons, we use popups ;-).
1406                     $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1407                                . '&amp;userid='.$auser->id.'&amp;mode=single'.'&amp;filter='.$filter.'&amp;offset='.$offset++;
1409                     $button = $OUTPUT->action_link($popup_url, $buttontext);
1411                     $status  = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
1413                     $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';
1415                     $outcomes = '';
1417                     if ($uses_outcomes) {
1419                         foreach($grading_info->outcomes as $n=>$outcome) {
1420                             $outcomes .= '<div class="outcome"><label>'.$outcome->name.'</label>';
1421                             $options = make_grades_menu(-$outcome->scaleid);
1423                             if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
1424                                 $options[0] = get_string('nooutcome', 'grades');
1425                                 $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
1426                             } else {
1427                                 $attributes = array();
1428                                 $attributes['tabindex'] = $tabindex++;
1429                                 $attributes['id'] = 'outcome_'.$n.'_'.$auser->id;
1430                                 $outcomes .= ' '.html_writer::select($options, 'outcome_'.$n.'['.$auser->id.']', $outcome->grades[$auser->id]->grade, array(0=>get_string('nooutcome', 'grades')), $attributes);
1431                             }
1432                             $outcomes .= '</div>';
1433                         }
1434                     }
1436                     $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>';
1437                     $row = array($picture, $userlink, $grade, $comment, $studentmodified, $teachermodified, $status, $finalgrade);
1438                     if ($uses_outcomes) {
1439                         $row[] = $outcomes;
1440                     }
1442                     $table->add_data($row);
1443                 }
1444                 $currentposition++;
1445             }
1446         }
1448         $table->print_html();  /// Print the whole table
1450         /// Print quickgrade form around the table
1451         if ($quickgrade && $table->started_output){
1452             $mailinfopref = false;
1453             if (get_user_preferences('assignment_mailinfo', 1)) {
1454                 $mailinfopref = true;
1455             }
1456             $emailnotification =  html_writer::checkbox('mailinfo', 1, $mailinfopref, get_string('enableemailnotification','assignment'));
1458             $emailnotification .= $OUTPUT->help_icon('enableemailnotification', 'assignment');
1459             echo html_writer::tag('div', $emailnotification, array('class'=>'emailnotification'));
1461             $savefeedback = html_writer::empty_tag('input', array('type'=>'submit', 'name'=>'fastg', 'value'=>get_string('saveallfeedback', 'assignment')));
1462             echo html_writer::tag('div', $savefeedback, array('class'=>'fastgbutton'));
1464             echo html_writer::end_tag('form');
1465         } else if ($quickgrade) {
1466             echo html_writer::end_tag('form');
1467         }
1469         echo '</div>';
1470         /// End of fast grading form
1472         /// Mini form for setting user preference
1474         $formaction = new moodle_url('/mod/assignment/submissions.php', array('id'=>$this->cm->id));
1475         $mform = new MoodleQuickForm('optionspref', 'post', $formaction, '', array('class'=>'optionspref'));
1477         $mform->addElement('hidden', 'updatepref');
1478         $mform->setDefault('updatepref', 1);
1479         $mform->addElement('header', 'qgprefs', get_string('optionalsettings', 'assignment'));
1480         $mform->addElement('select', 'filter', get_string('show'),  $filters);
1482         $mform->setDefault('filter', $filter);
1484         $mform->addElement('text', 'perpage', get_string('pagesize', 'assignment'), array('size'=>1));
1485         $mform->setDefault('perpage', $perpage);
1487         $mform->addElement('checkbox', 'quickgrade', get_string('quickgrade','assignment'));
1488         $mform->setDefault('quickgrade', $quickgrade);
1489         $mform->addHelpButton('quickgrade', 'quickgrade', 'assignment');
1491         $mform->addElement('submit', 'savepreferences', get_string('savepreferences'));
1493         $mform->display();
1495         echo $OUTPUT->footer();
1496     }
1498     /**
1499      *  Process teacher feedback submission
1500      *
1501      * This is called by submissions() when a grading even has taken place.
1502      * It gets its data from the submitted form.
1503      *
1504      * @global object
1505      * @global object
1506      * @global object
1507      * @return object|bool The updated submission object or false
1508      */
1509     function process_feedback($formdata=null) {
1510         global $CFG, $USER, $DB;
1511         require_once($CFG->libdir.'/gradelib.php');
1513         if (!$feedback = data_submitted() or !confirm_sesskey()) {      // No incoming data?
1514             return false;
1515         }
1517         ///For save and next, we need to know the userid to save, and the userid to go
1518         ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1519         ///as the userid to store
1520         if ((int)$feedback->saveuserid !== -1){
1521             $feedback->userid = $feedback->saveuserid;
1522         }
1524         if (!empty($feedback->cancel)) {          // User hit cancel button
1525             return false;
1526         }
1528         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);
1530         // store outcomes if needed
1531         $this->process_outcomes($feedback->userid);
1533         $submission = $this->get_submission($feedback->userid, true);  // Get or make one
1535         if (!($grading_info->items[0]->grades[$feedback->userid]->locked ||
1536             $grading_info->items[0]->grades[$feedback->userid]->overridden) ) {
1538             $submission->grade      = $feedback->xgrade;
1539             $submission->submissioncomment    = $feedback->submissioncomment_editor['text'];
1540             $submission->teacher    = $USER->id;
1541             $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1542             if (!$mailinfo) {
1543                 $submission->mailed = 1;       // treat as already mailed
1544             } else {
1545                 $submission->mailed = 0;       // Make sure mail goes out (again, even)
1546             }
1547             $submission->timemarked = time();
1549             unset($submission->data1);  // Don't need to update this.
1550             unset($submission->data2);  // Don't need to update this.
1552             if (empty($submission->timemodified)) {   // eg for offline assignments
1553                 // $submission->timemodified = time();
1554             }
1556             $DB->update_record('assignment_submissions', $submission);
1558             // triger grade event
1559             $this->update_grade($submission);
1561             add_to_log($this->course->id, 'assignment', 'update grades',
1562                        'submissions.php?id='.$this->assignment->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
1563              if (!is_null($formdata)) {
1564                     if ($this->type == 'upload' || $this->type == 'uploadsingle') {
1565                         $mformdata = $formdata->mform->get_data();
1566                         $mformdata = file_postupdate_standard_filemanager($mformdata, 'files', $formdata->fileui_options, $this->context, 'mod_assignment', 'response', $submission->id);
1567                     }
1568              }
1569         }
1571         return $submission;
1573     }
1575     function process_outcomes($userid) {
1576         global $CFG, $USER;
1578         if (empty($CFG->enableoutcomes)) {
1579             return;
1580         }
1582         require_once($CFG->libdir.'/gradelib.php');
1584         if (!$formdata = data_submitted() or !confirm_sesskey()) {
1585             return;
1586         }
1588         $data = array();
1589         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
1591         if (!empty($grading_info->outcomes)) {
1592             foreach($grading_info->outcomes as $n=>$old) {
1593                 $name = 'outcome_'.$n;
1594                 if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
1595                     $data[$n] = $formdata->{$name}[$userid];
1596                 }
1597             }
1598         }
1599         if (count($data) > 0) {
1600             grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1601         }
1603     }
1605     /**
1606      * Load the submission object for a particular user
1607      *
1608      * @global object
1609      * @global object
1610      * @param $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1611      * @param $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1612      * @param bool $teachermodified student submission set if false
1613      * @return object The submission
1614      */
1615     function get_submission($userid=0, $createnew=false, $teachermodified=false) {
1616         global $USER, $DB;
1618         if (empty($userid)) {
1619             $userid = $USER->id;
1620         }
1622         $submission = $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1624         if ($submission || !$createnew) {
1625             return $submission;
1626         }
1627         $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
1628         $DB->insert_record("assignment_submissions", $newsubmission);
1630         return $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1631     }
1633     /**
1634      * Instantiates a new submission object for a given user
1635      *
1636      * Sets the assignment, userid and times, everything else is set to default values.
1637      *
1638      * @param int $userid The userid for which we want a submission object
1639      * @param bool $teachermodified student submission set if false
1640      * @return object The submission
1641      */
1642     function prepare_new_submission($userid, $teachermodified=false) {
1643         $submission = new Object;
1644         $submission->assignment   = $this->assignment->id;
1645         $submission->userid       = $userid;
1646         $submission->timecreated = time();
1647         // teachers should not be modifying modified date, except offline assignments
1648         if ($teachermodified) {
1649             $submission->timemodified = 0;
1650         } else {
1651             $submission->timemodified = $submission->timecreated;
1652         }
1653         $submission->numfiles     = 0;
1654         $submission->data1        = '';
1655         $submission->data2        = '';
1656         $submission->grade        = -1;
1657         $submission->submissioncomment      = '';
1658         $submission->format       = 0;
1659         $submission->teacher      = 0;
1660         $submission->timemarked   = 0;
1661         $submission->mailed       = 0;
1662         return $submission;
1663     }
1665     /**
1666      * Return all assignment submissions by ENROLLED students (even empty)
1667      *
1668      * @param string $sort optional field names for the ORDER BY in the sql query
1669      * @param string $dir optional specifying the sort direction, defaults to DESC
1670      * @return array The submission objects indexed by id
1671      */
1672     function get_submissions($sort='', $dir='DESC') {
1673         return assignment_get_all_submissions($this->assignment, $sort, $dir);
1674     }
1676     /**
1677      * Counts all real assignment submissions by ENROLLED students (not empty ones)
1678      *
1679      * @param int $groupid optional If nonzero then count is restricted to this group
1680      * @return int The number of submissions
1681      */
1682     function count_real_submissions($groupid=0) {
1683         return assignment_count_real_submissions($this->cm, $groupid);
1684     }
1686     /**
1687      * Alerts teachers by email of new or changed assignments that need grading
1688      *
1689      * First checks whether the option to email teachers is set for this assignment.
1690      * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1691      * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1692      *
1693      * @global object
1694      * @global object
1695      * @param $submission object The submission that has changed
1696      * @return void
1697      */
1698     function email_teachers($submission) {
1699         global $CFG, $DB;
1701         if (empty($this->assignment->emailteachers)) {          // No need to do anything
1702             return;
1703         }
1705         $user = $DB->get_record('user', array('id'=>$submission->userid));
1707         if ($teachers = $this->get_graders($user)) {
1709             $strassignments = get_string('modulenameplural', 'assignment');
1710             $strassignment  = get_string('modulename', 'assignment');
1711             $strsubmitted  = get_string('submitted', 'assignment');
1713             foreach ($teachers as $teacher) {
1714                 $info = new object();
1715                 $info->username = fullname($user, true);
1716                 $info->assignment = format_string($this->assignment->name,true);
1717                 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
1719                 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1720                 $posttext = $this->email_teachers_text($info);
1721                 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
1723                 $eventdata = new object();
1724                 $eventdata->modulename       = 'assignment';
1725                 $eventdata->userfrom         = $user;
1726                 $eventdata->userto           = $teacher;
1727                 $eventdata->subject          = $postsubject;
1728                 $eventdata->fullmessage      = $posttext;
1729                 $eventdata->fullmessageformat = FORMAT_PLAIN;
1730                 $eventdata->fullmessagehtml  = $posthtml;
1731                 $eventdata->smallmessage     = '';
1732                 message_send($eventdata);
1733             }
1734         }
1735     }
1737     /**
1738      * @param string $filearea
1739      * @param array $args
1740      * @return bool
1741      */
1742     function send_file($filearea, $args) {
1743         debugging('plugin does not implement file sending', DEBUG_DEVELOPER);
1744         return false;
1745     }
1747     /**
1748      * Returns a list of teachers that should be grading given submission
1749      *
1750      * @param object $user
1751      * @return array
1752      */
1753     function get_graders($user) {
1754         //potential graders
1755         $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false);
1757         $graders = array();
1758         if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) {   // Separate groups are being used
1759             if ($groups = groups_get_all_groups($this->course->id, $user->id)) {  // Try to find all groups
1760                 foreach ($groups as $group) {
1761                     foreach ($potgraders as $t) {
1762                         if ($t->id == $user->id) {
1763                             continue; // do not send self
1764                         }
1765                         if (groups_is_member($group->id, $t->id)) {
1766                             $graders[$t->id] = $t;
1767                         }
1768                     }
1769                 }
1770             } else {
1771                 // user not in group, try to find graders without group
1772                 foreach ($potgraders as $t) {
1773                     if ($t->id == $user->id) {
1774                         continue; // do not send self
1775                     }
1776                     if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
1777                         $graders[$t->id] = $t;
1778                     }
1779                 }
1780             }
1781         } else {
1782             foreach ($potgraders as $t) {
1783                 if ($t->id == $user->id) {
1784                     continue; // do not send self
1785                 }
1786                 $graders[$t->id] = $t;
1787             }
1788         }
1789         return $graders;
1790     }
1792     /**
1793      * Creates the text content for emails to teachers
1794      *
1795      * @param $info object The info used by the 'emailteachermail' language string
1796      * @return string
1797      */
1798     function email_teachers_text($info) {
1799         $posttext  = format_string($this->course->shortname).' -> '.$this->strassignments.' -> '.
1800                      format_string($this->assignment->name)."\n";
1801         $posttext .= '---------------------------------------------------------------------'."\n";
1802         $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
1803         $posttext .= "\n---------------------------------------------------------------------\n";
1804         return $posttext;
1805     }
1807      /**
1808      * Creates the html content for emails to teachers
1809      *
1810      * @param $info object The info used by the 'emailteachermailhtml' language string
1811      * @return string
1812      */
1813     function email_teachers_html($info) {
1814         global $CFG;
1815         $posthtml  = '<p><font face="sans-serif">'.
1816                      '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname).'</a> ->'.
1817                      '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
1818                      '<a href="'.$CFG->wwwroot.'/mod/assignment/view.php?id='.$this->cm->id.'">'.format_string($this->assignment->name).'</a></font></p>';
1819         $posthtml .= '<hr /><font face="sans-serif">';
1820         $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
1821         $posthtml .= '</font><hr />';
1822         return $posthtml;
1823     }
1825     /**
1826      * Produces a list of links to the files uploaded by a user
1827      *
1828      * @param $userid int optional id of the user. If 0 then $USER->id is used.
1829      * @param $return boolean optional defaults to false. If true the list is returned rather than printed
1830      * @return string optional
1831      */
1832     function print_user_files($userid=0, $return=false) {
1833         global $CFG, $USER, $OUTPUT;
1835         if (!$userid) {
1836             if (!isloggedin()) {
1837                 return '';
1838             }
1839             $userid = $USER->id;
1840         }
1842         $output = '';
1844         $fs = get_file_storage();
1846         $found = false;
1848         $submission = $this->get_submission($userid);
1850         if (($submission) && $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false)) {
1851             require_once($CFG->libdir.'/portfoliolib.php');
1852             require_once($CFG->dirroot . '/mod/assignment/locallib.php');
1853             $button = new portfolio_add_button();
1854             foreach ($files as $file) {
1855                 $filename = $file->get_filename();
1856                 $found = true;
1857                 $mimetype = $file->get_mimetype();
1858                 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/mod_assignment/submission/'.$submission->id.'/'.$filename);
1859                 $output .= '<a href="'.$path.'" ><img src="'.$OUTPUT->pix_url(file_mimetype_icon($mimetype)).'" class="icon" alt="'.$mimetype.'" />'.s($filename).'</a>';
1860                 if ($this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1861                     $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id, 'fileid' => $file->get_id()), '/mod/assignment/locallib.php');
1862                     $button->set_format_by_file($file);
1863                     $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
1864                 }
1865             }
1866             if (count($files) > 1  && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1867                 $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id), '/mod/assignment/locallib.php');
1868                 $output .= '<br />'  . $button->to_html();
1869             }
1870         }
1872         $output = '<div class="files">'.$output.'</div>';
1874         if ($return) {
1875             return $output;
1876         }
1877         echo $output;
1878     }
1880     /**
1881      * Count the files uploaded by a given user
1882      *
1883      * @param $itemid int The submission's id as the file's itemid.
1884      * @return int
1885      */
1886     function count_user_files($itemid) {
1887         $fs = get_file_storage();
1888         $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $itemid, "id", false);
1889         return count($files);
1890     }
1892     /**
1893      * Returns true if the student is allowed to submit
1894      *
1895      * Checks that the assignment has started and, if the option to prevent late
1896      * submissions is set, also checks that the assignment has not yet closed.
1897      * @return boolean
1898      */
1899     function isopen() {
1900         $time = time();
1901         if ($this->assignment->preventlate && $this->assignment->timedue) {
1902             return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
1903         } else {
1904             return ($this->assignment->timeavailable <= $time);
1905         }
1906     }
1909     /**
1910      * Return true if is set description is hidden till available date
1911      *
1912      * This is needed by calendar so that hidden descriptions do not
1913      * come up in upcoming events.
1914      *
1915      * Check that description is hidden till available date
1916      * By default return false
1917      * Assignments types should implement this method if needed
1918      * @return boolen
1919      */
1920     function description_is_hidden() {
1921         return false;
1922     }
1924     /**
1925      * Return an outline of the user's interaction with the assignment
1926      *
1927      * The default method prints the grade and timemodified
1928      * @param $grade object
1929      * @return object with properties ->info and ->time
1930      */
1931     function user_outline($grade) {
1933         $result = new object();
1934         $result->info = get_string('grade').': '.$grade->str_long_grade;
1935         $result->time = $grade->dategraded;
1936         return $result;
1937     }
1939     /**
1940      * Print complete information about the user's interaction with the assignment
1941      *
1942      * @param $user object
1943      */
1944     function user_complete($user, $grade=null) {
1945         global $OUTPUT;
1946         if ($grade) {
1947             echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
1948             if ($grade->str_feedback) {
1949                 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
1950             }
1951         }
1953         if ($submission = $this->get_submission($user->id)) {
1955             $fs = get_file_storage();
1957             if ($files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false)) {
1958                 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
1959                 foreach ($files as $file) {
1960                     $countfiles .= "; ".$file->get_filename();
1961                 }
1962             }
1964             echo $OUTPUT->box_start();
1965             echo get_string("lastmodified").": ";
1966             echo userdate($submission->timemodified);
1967             echo $this->display_lateness($submission->timemodified);
1969             $this->print_user_files($user->id);
1971             echo '<br />';
1973             $this->view_feedback($submission);
1975             echo $OUTPUT->box_end();
1977         } else {
1978             print_string("notsubmittedyet", "assignment");
1979         }
1980     }
1982     /**
1983      * Return a string indicating how late a submission is
1984      *
1985      * @param $timesubmitted int
1986      * @return string
1987      */
1988     function display_lateness($timesubmitted) {
1989         return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
1990     }
1992     /**
1993      * Empty method stub for all delete actions.
1994      */
1995     function delete() {
1996         //nothing by default
1997         redirect('view.php?id='.$this->cm->id);
1998     }
2000     /**
2001      * Empty custom feedback grading form.
2002      */
2003     function custom_feedbackform($submission, $return=false) {
2004         //nothing by default
2005         return '';
2006     }
2008     /**
2009      * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
2010      * for the course (see resource).
2011      *
2012      * Given a course_module object, this function returns any "extra" information that may be needed
2013      * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
2014      *
2015      * @param $coursemodule object The coursemodule object (record).
2016      * @return object An object on information that the coures will know about (most noticeably, an icon).
2017      *
2018      */
2019     function get_coursemodule_info($coursemodule) {
2020         return false;
2021     }
2023     /**
2024      * Plugin cron method - do not use $this here, create new assignment instances if needed.
2025      * @return void
2026      */
2027     function cron() {
2028         //no plugin cron by default - override if needed
2029     }
2031     /**
2032      * Reset all submissions
2033      */
2034     function reset_userdata($data) {
2035         global $CFG, $DB;
2037         if (!$DB->count_records('assignment', array('course'=>$data->courseid, 'assignmenttype'=>$this->type))) {
2038             return array(); // no assignments of this type present
2039         }
2041         $componentstr = get_string('modulenameplural', 'assignment');
2042         $status = array();
2044         $typestr = get_string('type'.$this->type, 'assignment');
2045         // ugly hack to support pluggable assignment type titles...
2046         if($typestr === '[[type'.$this->type.']]'){
2047             $typestr = get_string('type'.$this->type, 'assignment_'.$this->type);
2048         }
2050         if (!empty($data->reset_assignment_submissions)) {
2051             $assignmentssql = "SELECT a.id
2052                                  FROM {assignment} a
2053                                 WHERE a.course=? AND a.assignmenttype=?";
2054             $params = array($data->courseid, $this->type);
2056             // now get rid of all submissions and responses
2057             $fs = get_file_storage();
2058             if ($assignments = $DB->get_records_sql($assignmentssql, $params)) {
2059                 foreach ($assignments as $assignmentid=>$unused) {
2060                     if (!$cm = get_coursemodule_from_instance('assignment', $assignmentid)) {
2061                         continue;
2062                     }
2063                     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2064                     $fs->delete_area_files($context->id, 'mod_assignment', 'submission');
2065                     $fs->delete_area_files($context->id, 'mod_assignment', 'response');
2066                 }
2067             }
2069             $DB->delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)", $params);
2071             $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
2073             if (empty($data->reset_gradebook_grades)) {
2074                 // remove all grades from gradebook
2075                 assignment_reset_gradebook($data->courseid, $this->type);
2076             }
2077         }
2079         /// updating dates - shift may be negative too
2080         if ($data->timeshift) {
2081             shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
2082             $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
2083         }
2085         return $status;
2086     }
2089     function portfolio_exportable() {
2090         return false;
2091     }
2093     /**
2094      * base implementation for backing up subtype specific information
2095      * for one single module
2096      *
2097      * @param filehandle $bf file handle for xml file to write to
2098      * @param mixed $preferences the complete backup preference object
2099      *
2100      * @return boolean
2101      *
2102      * @static
2103      */
2104     static function backup_one_mod($bf, $preferences, $assignment) {
2105         return true;
2106     }
2108     /**
2109      * base implementation for backing up subtype specific information
2110      * for one single submission
2111      *
2112      * @param filehandle $bf file handle for xml file to write to
2113      * @param mixed $preferences the complete backup preference object
2114      * @param object $submission the assignment submission db record
2115      *
2116      * @return boolean
2117      *
2118      * @static
2119      */
2120     static function backup_one_submission($bf, $preferences, $assignment, $submission) {
2121         return true;
2122     }
2124     /**
2125      * base implementation for restoring subtype specific information
2126      * for one single module
2127      *
2128      * @param array  $info the array representing the xml
2129      * @param object $restore the restore preferences
2130      *
2131      * @return boolean
2132      *
2133      * @static
2134      */
2135     static function restore_one_mod($info, $restore, $assignment) {
2136         return true;
2137     }
2139     /**
2140      * base implementation for restoring subtype specific information
2141      * for one single submission
2142      *
2143      * @param object $submission the newly created submission
2144      * @param array  $info the array representing the xml
2145      * @param object $restore the restore preferences
2146      *
2147      * @return boolean
2148      *
2149      * @static
2150      */
2151     static function restore_one_submission($info, $restore, $assignment, $submission) {
2152         return true;
2153     }
2155 } ////// End of the assignment_base class
2158 class mod_assignment_grading_form extends moodleform {
2160     function definition() {
2161         global $OUTPUT;
2162         $mform =& $this->_form;
2164         $formattr = $mform->getAttributes();
2165         $formattr['id'] = 'submitform';
2166         $mform->setAttributes($formattr);
2167         // hidden params
2168         $mform->addElement('hidden', 'offset', ($this->_customdata->offset+1));
2169         $mform->setType('offset', PARAM_INT);
2170         $mform->addElement('hidden', 'userid', $this->_customdata->userid);
2171         $mform->setType('userid', PARAM_INT);
2172         $mform->addElement('hidden', 'nextid', $this->_customdata->nextid);
2173         $mform->setType('nextid', PARAM_INT);
2174         $mform->addElement('hidden', 'id', $this->_customdata->cm->id);
2175         $mform->setType('id', PARAM_INT);
2176         $mform->addElement('hidden', 'sesskey', sesskey());
2177         $mform->setType('sesskey', PARAM_ALPHANUM);
2178         $mform->addElement('hidden', 'mode', 'grade');
2179         $mform->setType('mode', PARAM_TEXT);
2180         $mform->addElement('hidden', 'menuindex', "0");
2181         $mform->setType('menuindex', PARAM_INT);
2182         $mform->addElement('hidden', 'saveuserid', "-1");
2183         $mform->setType('saveuserid', PARAM_INT);
2184         $mform->addElement('hidden', 'filter', "0");
2185         $mform->setType('filter', PARAM_INT);
2187         $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->user),
2188                                                 fullname($this->_customdata->user, true) . '<br/>' .
2189                                                 userdate($this->_customdata->submission->timemodified) .
2190                                                 $this->_customdata->lateness );
2192         $this->add_submission_content();
2193         $this->add_grades_section();
2195         $this->add_feedback_section();
2197         if ($this->_customdata->submission->timemarked) {
2198             $datestring = userdate($this->_customdata->submission->timemarked)."&nbsp; (".format_time(time() - $this->_customdata->submission->timemarked).")";
2199             $mform->addElement('header', 'Last Grade', get_string('lastgrade', 'assignment'));
2200             $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->teacher) ,
2201                                                     fullname($this->_customdata->teacher,true).
2202                                                     '<br/>'.$datestring);
2203         }
2204         // buttons
2205         $this->add_action_buttons();
2207     }
2209     function add_grades_section() {
2210         global $CFG;
2211         $mform =& $this->_form;
2212         $attributes = array();
2213         if ($this->_customdata->gradingdisabled) {
2214             $attributes['disabled'] ='disabled';
2215         }
2217         $grademenu = make_grades_menu($this->_customdata->assignment->grade);
2218         $grademenu['-1'] = get_string('nograde');
2220         $mform->addElement('header', 'Grades', get_string('grades', 'grades'));
2221         $mform->addElement('select', 'xgrade', get_string('grade').':', $grademenu, $attributes);
2222         $mform->setDefault('xgrade', $this->_customdata->submission->grade ); //@fixme some bug when element called 'grade' makes it break
2223         $mform->setType('xgrade', PARAM_INT);
2225         if (!empty($this->_customdata->enableoutcomes)) {
2226             foreach($this->_customdata->grading_info->outcomes as $n=>$outcome) {
2227                 $options = make_grades_menu(-$outcome->scaleid);
2228                 if ($outcome->grades[$this->_customdata->submission->userid]->locked) {
2229                     $options[0] = get_string('nooutcome', 'grades');
2230                     echo $options[$outcome->grades[$this->_customdata->submission->userid]->grade];
2231                 } else {
2232                     $options[''] = get_string('nooutcome', 'grades');
2233                     $attributes = array('id' => 'menuoutcome_'.$n );
2234                     $mform->addElement('select', 'outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->name.':', $options, $attributes );
2235                     $mform->setType('outcome_'.$n.'['.$this->_customdata->userid.']', PARAM_INT);
2236                     $mform->setDefault('outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->grades[$this->_customdata->submission->userid]->grade );
2237                 }
2238             }
2239         }
2240         $course_context = get_context_instance(CONTEXT_MODULE , $this->_customdata->cm->id);
2241         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
2242             $grade = '<a href="'.$CFG->wwwroot.'/grade/report/grader/index.php?id='. $this->_customdata->courseid .'" >'.
2243                         $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade . '</a>';
2244         }else{
2245             $grade = $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade;
2246         }
2247         $mform->addElement('static', 'finalgrade', get_string('currentgrade', 'assignment').':' ,$grade);
2248         $mform->setType('finalgrade', PARAM_INT);
2249     }
2251     /**
2252      *
2253      * @global core_renderer $OUTPUT
2254      */
2255     function add_feedback_section() {
2256         global $OUTPUT;
2257         $mform =& $this->_form;
2258         $mform->addElement('header', 'Feed Back', get_string('feedback', 'grades'));
2260         if ($this->_customdata->gradingdisabled) {
2261             $mform->addElement('static', 'disabledfeedback', $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_feedback );
2262         } else {
2263             // visible elements
2265             $mform->addElement('editor', 'submissioncomment_editor', get_string('feedback', 'assignment').':', null, $this->get_editor_options() );
2266             $mform->setType('submissioncomment_editor', PARAM_RAW); // to be cleaned before display
2267             $mform->setDefault('submissioncomment_editor', $this->_customdata->submission->submissioncomment);
2268             //$mform->addRule('submissioncomment', get_string('required'), 'required', null, 'client');
2269             switch ($this->_customdata->assignment->assignmenttype) {
2270                 case 'upload' :
2271                 case 'uploadsingle' :
2272                     $mform->addElement('filemanager', 'files_filemanager', get_string('responsefiles', 'assignment'). ':', null, $this->_customdata->fileui_options);
2273                     break;
2274                 default :
2275                     break;
2276             }
2277             $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? array('checked'=>'checked') : array();
2278             $mform->addElement('hidden', 'mailinfo_h', "0");
2279             $mform->setType('mailinfo_h', PARAM_INT);
2280             $mform->addElement('checkbox', 'mailinfo',get_string('enableemailnotification','assignment').
2281             $OUTPUT->help_icon('enableemailnotification', 'assignment') .':' );
2282             $mform->updateElementAttr('mailinfo', $lastmailinfo);
2283             $mform->setType('mailinfo', PARAM_INT);
2284         }
2285     }
2287     function add_action_buttons() {
2288         $mform =& $this->_form;
2289         //if there are more to be graded.
2290         if ($this->_customdata->nextid>0) {
2291             $buttonarray=array();
2292             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2293             //@todo: fix accessibility: javascript dependency not necessary
2294             $buttonarray[] = &$mform->createElement('submit', 'saveandnext', get_string('saveandnext'));
2295             $buttonarray[] = &$mform->createElement('submit', 'next', get_string('next'));
2296             $buttonarray[] = &$mform->createElement('cancel');
2297         } else {
2298             $buttonarray=array();
2299             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2300             $buttonarray[] = &$mform->createElement('cancel');
2301         }
2302         $mform->addGroup($buttonarray, 'grading_buttonar', '', array(' '), false);
2303         $mform->closeHeaderBefore('grading_buttonar');
2304         $mform->setType('grading_buttonar', PARAM_RAW);
2305     }
2307     function add_submission_content() {
2308         $mform =& $this->_form;
2309         $mform->addElement('header', 'Submission', get_string('submission', 'assignment'));
2310         $mform->addElement('static', '', '' , $this->_customdata->submission_content );
2311     }
2313     protected function get_editor_options() {
2314         $editoroptions = array();
2315         $editoroptions['component'] = 'mod_assignment';
2316         $editoroptions['filearea'] = 'feedback';
2317         $editoroptions['noclean'] = false;
2318         $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)
2319         $editoroptions['maxbytes'] = $this->_customdata->maxbytes;
2320         return $editoroptions;
2321     }
2323     public function set_data($data) {
2324         $editoroptions = $this->get_editor_options();
2325         if (!isset($data->text)) {
2326             $data->text = '';
2327         }
2328         if (!isset($data->format)) {
2329             $data->textformat = FORMAT_HTML;
2330         } else {
2331             $data->textformat = $data->format;
2332         }
2334         if (!empty($this->_customdata->submission->id)) {
2335             $itemid = $this->_customdata->submission->id;
2336         } else {
2337             $itemid = null;
2338         }
2340         switch ($this->_customdata->assignment->assignmenttype) {
2341                 case 'upload' :
2342                 case 'uploadsingle' :
2343                     $data = file_prepare_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2344                     break;
2345                 default :
2346                     break;
2347         }
2349         $data = file_prepare_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2350         return parent::set_data($data);
2351     }
2353     public function get_data() {
2354         $data = parent::get_data();
2356         if (!empty($this->_customdata->submission->id)) {
2357             $itemid = $this->_customdata->submission->id;
2358         } else {
2359             $itemid = null; //TODO: this is wrong, itemid MUST be known when saving files!! (skodak)
2360         }
2362         if ($data) {
2363             $editoroptions = $this->get_editor_options();
2364             switch ($this->_customdata->assignment->assignmenttype) {
2365                 case 'upload' :
2366                 case 'uploadsingle' :
2367                     $data = file_postupdate_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2368                     break;
2369                 default :
2370                     break;
2371             }
2372             $data = file_postupdate_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2373         }
2374         return $data;
2375     }
2378 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
2380 /**
2381  * Deletes an assignment instance
2382  *
2383  * This is done by calling the delete_instance() method of the assignment type class
2384  */
2385 function assignment_delete_instance($id){
2386     global $CFG, $DB;
2388     if (! $assignment = $DB->get_record('assignment', array('id'=>$id))) {
2389         return false;
2390     }
2392     // fall back to base class if plugin missing
2393     $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2394     if (file_exists($classfile)) {
2395         require_once($classfile);
2396         $assignmentclass = "assignment_$assignment->assignmenttype";
2398     } else {
2399         debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
2400         $assignmentclass = "assignment_base";
2401     }
2403     $ass = new $assignmentclass();
2404     return $ass->delete_instance($assignment);
2408 /**
2409  * Updates an assignment instance
2410  *
2411  * This is done by calling the update_instance() method of the assignment type class
2412  */
2413 function assignment_update_instance($assignment){
2414     global $CFG;
2416     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2418     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2419     $assignmentclass = "assignment_$assignment->assignmenttype";
2420     $ass = new $assignmentclass();
2421     return $ass->update_instance($assignment);
2425 /**
2426  * Adds an assignment instance
2427  *
2428  * This is done by calling the add_instance() method of the assignment type class
2429  */
2430 function assignment_add_instance($assignment) {
2431     global $CFG;
2433     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2435     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2436     $assignmentclass = "assignment_$assignment->assignmenttype";
2437     $ass = new $assignmentclass();
2438     return $ass->add_instance($assignment);
2442 /**
2443  * Returns an outline of a user interaction with an assignment
2444  *
2445  * This is done by calling the user_outline() method of the assignment type class
2446  */
2447 function assignment_user_outline($course, $user, $mod, $assignment) {
2448     global $CFG;
2450     require_once("$CFG->libdir/gradelib.php");
2451     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2452     $assignmentclass = "assignment_$assignment->assignmenttype";
2453     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2454     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2455     if (!empty($grades->items[0]->grades)) {
2456         return $ass->user_outline(reset($grades->items[0]->grades));
2457     } else {
2458         return null;
2459     }
2462 /**
2463  * Prints the complete info about a user's interaction with an assignment
2464  *
2465  * This is done by calling the user_complete() method of the assignment type class
2466  */
2467 function assignment_user_complete($course, $user, $mod, $assignment) {
2468     global $CFG;
2470     require_once("$CFG->libdir/gradelib.php");
2471     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2472     $assignmentclass = "assignment_$assignment->assignmenttype";
2473     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2474     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2475     if (empty($grades->items[0]->grades)) {
2476         $grade = false;
2477     } else {
2478         $grade = reset($grades->items[0]->grades);
2479     }
2480     return $ass->user_complete($user, $grade);
2483 /**
2484  * Function to be run periodically according to the moodle cron
2485  *
2486  * Finds all assignment notifications that have yet to be mailed out, and mails them
2487  */
2488 function assignment_cron () {
2489     global $CFG, $USER, $DB;
2491     /// first execute all crons in plugins
2492     if ($plugins = get_plugin_list('assignment')) {
2493         foreach ($plugins as $plugin=>$dir) {
2494             require_once("$dir/assignment.class.php");
2495             $assignmentclass = "assignment_$plugin";
2496             $ass = new $assignmentclass();
2497             $ass->cron();
2498         }
2499     }
2501     /// Notices older than 1 day will not be mailed.  This is to avoid the problem where
2502     /// cron has not been running for a long time, and then suddenly people are flooded
2503     /// with mail from the past few weeks or months
2505     $timenow   = time();
2506     $endtime   = $timenow - $CFG->maxeditingtime;
2507     $starttime = $endtime - 24 * 3600;   /// One day earlier
2509     if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2511         $realuser = clone($USER);
2513         foreach ($submissions as $key => $submission) {
2514             if (! $DB->set_field("assignment_submissions", "mailed", "1", array("id"=>$submission->id))) {
2515                 echo "Could not update the mailed field for id $submission->id.  Not mailed.\n";
2516                 unset($submissions[$key]);
2517             }
2518         }
2520         $timenow = time();
2522         foreach ($submissions as $submission) {
2524             echo "Processing assignment submission $submission->id\n";
2526             if (! $user = $DB->get_record("user", array("id"=>$submission->userid))) {
2527                 echo "Could not find user $post->userid\n";
2528                 continue;
2529             }
2531             if (! $course = $DB->get_record("course", array("id"=>$submission->course))) {
2532                 echo "Could not find course $submission->course\n";
2533                 continue;
2534             }
2536             /// Override the language and timezone of the "current" user, so that
2537             /// mail is customised for the receiver.
2538             cron_setup_user($user, $course);
2540             if (!is_enrolled(get_context_instance(CONTEXT_COURSE, $submission->course), $user->id)) {
2541                 echo fullname($user)." not an active participant in " . format_string($course->shortname) . "\n";
2542                 continue;
2543             }
2545             if (! $teacher = $DB->get_record("user", array("id"=>$submission->teacher))) {
2546                 echo "Could not find teacher $submission->teacher\n";
2547                 continue;
2548             }
2550             if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2551                 echo "Could not find course module for assignment id $submission->assignment\n";
2552                 continue;
2553             }
2555             if (! $mod->visible) {    /// Hold mail notification for hidden assignments until later
2556                 continue;
2557             }
2559             $strassignments = get_string("modulenameplural", "assignment");
2560             $strassignment  = get_string("modulename", "assignment");
2562             $assignmentinfo = new object();
2563             $assignmentinfo->teacher = fullname($teacher);
2564             $assignmentinfo->assignment = format_string($submission->name,true);
2565             $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2567             $postsubject = "$course->shortname: $strassignments: ".format_string($submission->name,true);
2568             $posttext  = "$course->shortname -> $strassignments -> ".format_string($submission->name,true)."\n";
2569             $posttext .= "---------------------------------------------------------------------\n";
2570             $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2571             $posttext .= "---------------------------------------------------------------------\n";
2573             if ($user->mailformat == 1) {  // HTML
2574                 $posthtml = "<p><font face=\"sans-serif\">".
2575                 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> ->".
2576                 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2577                 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2578                 $posthtml .= "<hr /><font face=\"sans-serif\">";
2579                 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2580                 $posthtml .= "</font><hr />";
2581             } else {
2582                 $posthtml = "";
2583             }
2585             $eventdata = new object();
2586             $eventdata->modulename       = 'assignment';
2587             $eventdata->userfrom         = $teacher;
2588             $eventdata->userto           = $user;
2589             $eventdata->subject          = $postsubject;
2590             $eventdata->fullmessage      = $posttext;
2591             $eventdata->fullmessageformat = FORMAT_PLAIN;
2592             $eventdata->fullmessagehtml  = $posthtml;
2593             $eventdata->smallmessage     = '';
2594             message_send($eventdata);
2595         }
2597         cron_setup_user();
2598     }
2600     return true;
2603 /**
2604  * Return grade for given user or all users.
2605  *
2606  * @param int $assignmentid id of assignment
2607  * @param int $userid optional user id, 0 means all users
2608  * @return array array of grades, false if none
2609  */
2610 function assignment_get_user_grades($assignment, $userid=0) {
2611     global $CFG, $DB;
2613     if ($userid) {
2614         $user = "AND u.id = :userid";
2615         $params = array('userid'=>$userid);
2616     } else {
2617         $user = "";
2618     }
2619     $params['aid'] = $assignment->id;
2621     $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2622                    s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2623               FROM {user} u, {assignment_submissions} s
2624              WHERE u.id = s.userid AND s.assignment = :aid
2625                    $user";
2627     return $DB->get_records_sql($sql, $params);
2630 /**
2631  * Update activity grades
2632  *
2633  * @param object $assignment
2634  * @param int $userid specific user only, 0 means all
2635  */
2636 function assignment_update_grades($assignment, $userid=0, $nullifnone=true) {
2637     global $CFG, $DB;
2638     require_once($CFG->libdir.'/gradelib.php');
2640     if ($assignment->grade == 0) {
2641         assignment_grade_item_update($assignment);
2643     } else if ($grades = assignment_get_user_grades($assignment, $userid)) {
2644         foreach($grades as $k=>$v) {
2645             if ($v->rawgrade == -1) {
2646                 $grades[$k]->rawgrade = null;
2647             }
2648         }
2649         assignment_grade_item_update($assignment, $grades);
2651     } else {
2652         assignment_grade_item_update($assignment);
2653     }
2656 /**
2657  * Update all grades in gradebook.
2658  */
2659 function assignment_upgrade_grades() {
2660     global $DB;
2662     $sql = "SELECT COUNT('x')
2663               FROM {assignment} a, {course_modules} cm, {modules} m
2664              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2665     $count = $DB->count_records_sql($sql);
2667     $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
2668               FROM {assignment} a, {course_modules} cm, {modules} m
2669              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2670     if ($rs = $DB->get_recordset_sql($sql)) {
2671         // too much debug output
2672         $pbar = new progress_bar('assignmentupgradegrades', 500, true);
2673         $i=0;
2674         foreach ($rs as $assignment) {
2675             $i++;
2676             upgrade_set_timeout(60*5); // set up timeout, may also abort execution
2677             assignment_update_grades($assignment);
2678             $pbar->update($i, $count, "Updating Assignment grades ($i/$count).");
2679         }
2680         $rs->close();
2681         upgrade_set_timeout(); // reset to default timeout
2682     }
2685 /**
2686  * Create grade item for given assignment
2687  *
2688  * @param object $assignment object with extra cmidnumber
2689  * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
2690  * @return int 0 if ok, error code otherwise
2691  */
2692 function assignment_grade_item_update($assignment, $grades=NULL) {
2693     global $CFG;
2694     require_once($CFG->libdir.'/gradelib.php');
2696     if (!isset($assignment->courseid)) {
2697         $assignment->courseid = $assignment->course;
2698     }
2700     $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
2702     if ($assignment->grade > 0) {
2703         $params['gradetype'] = GRADE_TYPE_VALUE;
2704         $params['grademax']  = $assignment->grade;
2705         $params['grademin']  = 0;
2707     } else if ($assignment->grade < 0) {
2708         $params['gradetype'] = GRADE_TYPE_SCALE;
2709         $params['scaleid']   = -$assignment->grade;
2711     } else {
2712         $params['gradetype'] = GRADE_TYPE_TEXT; // allow text comments only
2713     }
2715     if ($grades  === 'reset') {
2716         $params['reset'] = true;
2717         $grades = NULL;
2718     }
2720     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades, $params);
2723 /**
2724  * Delete grade item for given assignment
2725  *
2726  * @param object $assignment object
2727  * @return object assignment
2728  */
2729 function assignment_grade_item_delete($assignment) {
2730     global $CFG;
2731     require_once($CFG->libdir.'/gradelib.php');
2733     if (!isset($assignment->courseid)) {
2734         $assignment->courseid = $assignment->course;
2735     }
2737     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
2740 /**
2741  * Returns the users with data in one assignment (students and teachers)
2742  *
2743  * @param $assignmentid int
2744  * @return array of user objects
2745  */
2746 function assignment_get_participants($assignmentid) {
2747     global $CFG, $DB;
2749     //Get students
2750     $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2751                                         FROM {user} u,
2752                                              {assignment_submissions} a
2753                                        WHERE a.assignment = ? and
2754                                              u.id = a.userid", array($assignmentid));
2755     //Get teachers
2756     $teachers = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2757                                         FROM {user} u,
2758                                              {assignment_submissions} a
2759                                        WHERE a.assignment = ? and
2760                                              u.id = a.teacher", array($assignmentid));
2762     //Add teachers to students
2763     if ($teachers) {
2764         foreach ($teachers as $teacher) {
2765             $students[$teacher->id] = $teacher;
2766         }
2767     }
2768     //Return students array (it contains an array of unique users)
2769     return ($students);
2772 /**
2773  * Serves assignment submissions and other files.
2774  *
2775  * @param object $course
2776  * @param object $cm
2777  * @param object $context
2778  * @param string $filearea
2779  * @param array $args
2780  * @param bool $forcedownload
2781  * @return bool false if file not found, does not return if found - just send the file
2782  */
2783 function assignment_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) {
2784     global $CFG, $DB;
2786     if ($context->contextlevel != CONTEXT_MODULE) {
2787         return false;
2788     }
2790     require_login($course, false, $cm);
2792     if (!$assignment = $DB->get_record('assignment', array('id'=>$cm->instance))) {
2793         return false;
2794     }
2796     require_once($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
2797     $assignmentclass = 'assignment_'.$assignment->assignmenttype;
2798     $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm, $course);
2800     return $assignmentinstance->send_file($filearea, $args);
2802 /**
2803  * Checks if a scale is being used by an assignment
2804  *
2805  * This is used by the backup code to decide whether to back up a scale
2806  * @param $assignmentid int
2807  * @param $scaleid int
2808  * @return boolean True if the scale is used by the assignment
2809  */
2810 function assignment_scale_used($assignmentid, $scaleid) {
2811     global $DB;
2813     $return = false;
2815     $rec = $DB->get_record('assignment', array('id'=>$assignmentid,'grade'=>-$scaleid));
2817     if (!empty($rec) && !empty($scaleid)) {
2818         $return = true;
2819     }
2821     return $return;
2824 /**
2825  * Checks if scale is being used by any instance of assignment
2826  *
2827  * This is used to find out if scale used anywhere
2828  * @param $scaleid int
2829  * @return boolean True if the scale is used by any assignment
2830  */
2831 function assignment_scale_used_anywhere($scaleid) {
2832     global $DB;
2834     if ($scaleid and $DB->record_exists('assignment', array('grade'=>-$scaleid))) {
2835         return true;
2836     } else {
2837         return false;
2838     }
2841 /**
2842  * Make sure up-to-date events are created for all assignment instances
2843  *
2844  * This standard function will check all instances of this module
2845  * and make sure there are up-to-date events created for each of them.
2846  * If courseid = 0, then every assignment event in the site is checked, else
2847  * only assignment events belonging to the course specified are checked.
2848  * This function is used, in its new format, by restore_refresh_events()
2849  *
2850  * @param $courseid int optional If zero then all assignments for all courses are covered
2851  * @return boolean Always returns true
2852  */
2853 function assignment_refresh_events($courseid = 0) {
2854     global $DB;
2856     if ($courseid == 0) {
2857         if (! $assignments = $DB->get_records("assignment")) {
2858             return true;
2859         }
2860     } else {
2861         if (! $assignments = $DB->get_records("assignment", array("course"=>$courseid))) {
2862             return true;
2863         }
2864     }
2865     $moduleid = $DB->get_field('modules', 'id', array('name'=>'assignment'));
2867     foreach ($assignments as $assignment) {
2868         $cm = get_coursemodule_from_id('assignment', $assignment->id);
2869         $event = new object();
2870         $event->name        = $assignment->name;
2871         $event->description = format_module_intro('assignment', $assignment, $cm->id);
2872         $event->timestart   = $assignment->timedue;
2874         if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
2875             update_event($event);
2877         } else {
2878             $event->courseid    = $assignment->course;
2879             $event->groupid     = 0;
2880             $event->userid      = 0;
2881             $event->modulename  = 'assignment';
2882             $event->instance    = $assignment->id;
2883             $event->eventtype   = 'due';
2884             $event->timeduration = 0;
2885             $event->visible     = $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$assignment->id));
2886             add_event($event);
2887         }
2889     }
2890     return true;
2893 /**
2894  * Print recent activity from all assignments in a given course
2895  *
2896  * This is used by the recent activity block
2897  */
2898 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
2899     global $CFG, $USER, $DB, $OUTPUT;
2901     // do not use log table if possible, it may be huge
2903     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
2904                                                      u.firstname, u.lastname, u.email, u.picture
2905                                                 FROM {assignment_submissions} asb
2906                                                      JOIN {assignment} a      ON a.id = asb.assignment
2907                                                      JOIN {course_modules} cm ON cm.instance = a.id
2908                                                      JOIN {modules} md        ON md.id = cm.module
2909                                                      JOIN {user} u            ON u.id = asb.userid
2910                                                WHERE asb.timemodified > ? AND
2911                                                      a.course = ? AND
2912                                                      md.name = 'assignment'
2913                                             ORDER BY asb.timemodified ASC", array($timestart, $course->id))) {
2914          return false;
2915     }
2917     $modinfo =& get_fast_modinfo($course); // reference needed because we might load the groups
2918     $show    = array();
2919     $grader  = array();
2921     foreach($submissions as $submission) {
2922         if (!array_key_exists($submission->cmid, $modinfo->cms)) {
2923             continue;
2924         }
2925         $cm = $modinfo->cms[$submission->cmid];
2926         if (!$cm->uservisible) {
2927             continue;
2928         }
2929         if ($submission->userid == $USER->id) {
2930             $show[] = $submission;
2931             continue;
2932         }
2934         // the act of sumbitting of assignment may be considered private - only graders will see it if specified
2935         if (empty($CFG->assignment_showrecentsubmissions)) {
2936             if (!array_key_exists($cm->id, $grader)) {
2937                 $grader[$cm->id] = has_capability('moodle/grade:viewall', get_context_instance(CONTEXT_MODULE, $cm->id));
2938             }
2939             if (!$grader[$cm->id]) {
2940                 continue;
2941             }
2942         }
2944         $groupmode = groups_get_activity_groupmode($cm, $course);
2946         if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2947             if (isguestuser()) {
2948                 // shortcut - guest user does not belong into any group
2949                 continue;
2950             }
2952             if (is_null($modinfo->groups)) {
2953                 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2954             }
2956             // this will be slow - show only users that share group with me in this cm
2957             if (empty($modinfo->groups[$cm->id])) {
2958                 continue;
2959             }
2960             $usersgroups =  groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
2961             if (is_array($usersgroups)) {
2962                 $usersgroups = array_keys($usersgroups);
2963                 $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2964                 if (empty($intersect)) {
2965                     continue;
2966                 }
2967             }
2968         }
2969         $show[] = $submission;
2970     }
2972     if (empty($show)) {
2973         return false;
2974     }
2976     echo $OUTPUT->heading(get_string('newsubmissions', 'assignment').':', 3);
2978     foreach ($show as $submission) {
2979         $cm = $modinfo->cms[$submission->cmid];
2980         $link = $CFG->wwwroot.'/mod/assignment/view.php?id='.$cm->id;
2981         print_recent_activity_note($submission->timemodified, $submission, $cm->name, $link, false, $viewfullnames);
2982     }
2984     return true;
2988 /**
2989  * Returns all assignments since a given time in specified forum.
2990  */
2991 function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0)  {
2992     global $CFG, $COURSE, $USER, $DB;
2994     if ($COURSE->id == $courseid) {
2995         $course = $COURSE;
2996     } else {
2997         $course = $DB->get_record('course', array('id'=>$courseid));
2998     }
3000     $modinfo =& get_fast_modinfo($course);
3002     $cm = $modinfo->cms[$cmid];
3004     $params = array();
3005     if ($userid) {
3006         $userselect = "AND u.id = :userid";
3007         $params['userid'] = $userid;
3008     } else {
3009         $userselect = "";
3010     }
3012     if ($groupid) {
3013         $groupselect = "AND gm.groupid = :groupid";
3014         $groupjoin   = "JOIN {groups_members} gm ON  gm.userid=u.id";
3015         $params['groupid'] = $groupid;
3016     } else {
3017         $groupselect = "";
3018         $groupjoin   = "";
3019     }
3021     $params['cminstance'] = $cm->instance;
3022     $params['timestart'] = $timestart;
3024     $userfields = user_picture::fields('u', null, 'userid');
3026     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified,
3027                                                      $userfields
3028                                                 FROM {assignment_submissions} asb
3029                                                 JOIN {assignment} a      ON a.id = asb.assignment
3030                                                 JOIN {user} u            ON u.id = asb.userid
3031                                           $groupjoin
3032                                                WHERE asb.timemodified > :timestart AND a.id = :cminstance
3033                                                      $userselect $groupselect
3034                                             ORDER BY asb.timemodified ASC", $params)) {
3035          return;
3036     }
3038     $groupmode       = groups_get_activity_groupmode($cm, $course);
3039     $cm_context      = get_context_instance(CONTEXT_MODULE, $cm->id);
3040     $grader          = has_capability('moodle/grade:viewall', $cm_context);
3041     $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
3042     $viewfullnames   = has_capability('moodle/site:viewfullnames', $cm_context);
3044     if (is_null($modinfo->groups)) {
3045         $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
3046     }
3048     $show = array();
3050     foreach($submissions as $submission) {
3051         if ($submission->userid == $USER->id) {
3052             $show[] = $submission;
3053             continue;
3054         }
3055         // the act of submitting of assignment may be considered private - only graders will see it if specified
3056         if (empty($CFG->assignment_showrecentsubmissions)) {
3057             if (!$grader) {
3058                 continue;
3059             }
3060         }
3062         if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
3063             if (isguestuser()) {
3064                 // shortcut - guest user does not belong into any group
3065                 continue;
3066             }
3068             // this will be slow - show only users that share group with me in this cm
3069             if (empty($modinfo->groups[$cm->id])) {
3070                 continue;
3071             }
3072             $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
3073             if (is_array($usersgroups)) {
3074                 $usersgroups = array_keys($usersgroups);
3075                 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
3076                 if (empty($intersect)) {
3077                     continue;
3078                 }
3079             }
3080         }
3081         $show[] = $submission;
3082     }
3084     if (empty($show)) {
3085         return;
3086     }
3088     if ($grader) {
3089         require_once($CFG->libdir.'/gradelib.php');
3090         $userids = array();
3091         foreach ($show as $id=>$submission) {
3092             $userids[] = $submission->userid;
3094         }
3095         $grades = grade_get_grades($courseid, 'mod', 'assignment', $cm->instance, $userids);
3096     }
3098     $aname = format_string($cm->name,true);
3099     foreach ($show as $submission) {
3100         $tmpactivity = new object();
3102         $tmpactivity->type         = 'assignment';
3103         $tmpactivity->cmid         = $cm->id;
3104         $tmpactivity->name         = $aname;
3105         $tmpactivity->sectionnum   = $cm->sectionnum;
3106         $tmpactivity->timestamp    = $submission->timemodified;
3108         if ($grader) {
3109             $tmpactivity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
3110         }
3112         $userfields = explode(',', user_picture::fields());
3113         foreach ($userfields as $userfield) {
3114             if ($userfield == 'id') {
3115                 $tmpactivity->user->{$userfield} = $submission->userid; // aliased in SQL above
3116             } else {
3117                 $tmpactivity->user->{$userfield} = $submission->{$userfield};
3118             }
3119         }
3120         $tmpactivity->user->fullname = fullname($submission, $viewfullnames);
3122         $activities[$index++] = $tmpactivity;
3123     }
3125     return;
3128 /**
3129  * Print recent activity from all assignments in a given course
3130  *
3131  * This is used by course/recent.php
3132  */
3133 function assignment_print_recent_mod_activity($activity, $courseid, $detail, $modnames)  {
3134     global $CFG, $OUTPUT;
3136     echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
3138     echo "<tr><td class=\"userpicture\" valign=\"top\">";
3139     echo $OUTPUT->user_picture($activity->user);
3140     echo "</td><td>";
3142     if ($detail) {
3143         $modname = $modnames[$activity->type];
3144         echo '<div class="title">';
3145         echo "<img src=\"" . $OUTPUT->pix_url('icon', 'assignment') . "\" ".
3146              "class=\"icon\" alt=\"$modname\">";
3147         echo "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id={$activity->cmid}\">{$activity->name}</a>";
3148         echo '</div>';
3149     }
3151     if (isset($activity->grade)) {
3152         echo '<div class="grade">';
3153         echo get_string('grade').': ';
3154         echo $activity->grade;
3155         echo '</div>';
3156     }
3158     echo '<div class="user">';
3159     echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->id}&amp;course=$courseid\">"
3160          ."{$activity->user->fullname}</a>  - ".userdate($activity->timestamp);
3161     echo '</div>';
3163     echo "</td></tr></table>";
3166 /// GENERIC SQL FUNCTIONS
3168 /**
3169  * Fetch info from logs
3170  *
3171  * @param $log object with properties ->info (the assignment id) and ->userid
3172  * @return array with assignment name and user firstname and lastname
3173  */
3174 function assignment_log_info($log) {
3175     global $CFG, $DB;
3177     return $DB->get_record_sql("SELECT a.name, u.firstname, u.lastname
3178                                   FROM {assignment} a, {user} u
3179                                  WHERE a.id = ? AND u.id = ?", array($log->info, $log->userid));
3182 /**
3183  * Return list of marked submissions that have not been mailed out for currently enrolled students
3184  *
3185  * @return array
3186  */
3187 function assignment_get_unmailed_submissions($starttime, $endtime) {
3188     global $CFG, $DB;
3190     return $DB->get_records_sql("SELECT s.*, a.course, a.name
3191                                    FROM {assignment_submissions} s,
3192                                         {assignment} a
3193                                   WHERE s.mailed = 0
3194                                         AND s.timemarked <= ?
3195                                         AND s.timemarked >= ?
3196                                         AND s.assignment = a.id", array($endtime, $starttime));
3199 /**
3200  * Counts all real assignment submissions by ENROLLED students (not empty ones)
3201  *
3202  * There are also assignment type methods count_real_submissions() wich in the default
3203  * implementation simply call this function.
3204  * @param $groupid int optional If nonzero then count is restricted to this group
3205  * @return int The number of submissions
3206  */
3207 function assignment_count_real_submissions($cm, $groupid=0) {
3208     global $CFG, $DB;
3210     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
3212     // this is all the users with this capability set, in this context or higher
3213     if ($users = get_enrolled_users($context, 'mod/assignment:submit', $groupid, 'u.id')) {
3214         $users = array_keys($users);
3215     }
3217     // if groupmembersonly used, remove users who are not in any group
3218     if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
3219         if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
3220             $users = array_intersect($users, array_keys($groupingusers));
3221         }
3222     }
3224     if (empty($users)) {
3225         return 0;
3226     }
3228     $userlists = implode(',', $users);
3230     return $DB->count_records_sql("SELECT COUNT('x')
3231                                      FROM {assignment_submissions}
3232                                     WHERE assignment = ? AND
3233                                           timemodified > 0 AND
3234                                           userid IN ($userlists)", array($cm->instance));
3238 /**
3239  * Return all assignment submissions by ENROLLED students (even empty)
3240  *
3241  * There are also assignment type methods get_submissions() wich in the default
3242  * implementation simply call this function.
3243  * @param $sort string optional field names for the ORDER BY in the sql query
3244  * @param $dir string optional specifying the sort direction, defaults to DESC
3245  * @return array The submission objects indexed by id
3246  */
3247 function assignment_get_all_submissions($assignment, $sort="", $dir="DESC") {
3248 /// Return all assignment submissions by ENROLLED students (even empty)
3249     global $CFG, $DB;
3251     if ($sort == "lastname" or $sort == "firstname") {
3252         $sort = "u.$sort $dir";
3253     } else if (empty($sort)) {
3254         $sort = "a.timemodified DESC";
3255     } else {
3256         $sort = "a.$sort $dir";
3257     }
3259     /* not sure this is needed at all since assignmenet already has a course define, so this join?
3260     $select = "s.course = '$assignment->course' AND";
3261     if ($assignment->course == SITEID) {
3262         $select = '';
3263     }*/
3265     return $DB->get_records_sql("SELECT a.*
3266                                    FROM {assignment_submissions} a, {user} u
3267                                   WHERE u.id = a.userid
3268                                         AND a.assignment = ?
3269                                ORDER BY $sort", array($assignment->id));
3273 /**
3274  * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
3275  * for the course (see resource).
3276  *
3277  * Given a course_module object, this function returns any "extra" information that may be needed
3278  * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
3279  *
3280  * @param $coursemodule object The coursemodule object (record).
3281  * @return object An object on information that the coures will know about (most noticeably, an icon).
3282  *
3283  */
3284 function assignment_get_coursemodule_info($coursemodule) {
3285     global $CFG, $DB;
3287     if (! $assignment = $DB->get_record('assignment', array('id'=>$coursemodule->instance), 'id, assignmenttype, name')) {
3288         return false;
3289     }
3291     $libfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
3293     if (file_exists($libfile)) {
3294         require_once($libfile);
3295         $assignmentclass = "assignment_$assignment->assignmenttype";
3296         $ass = new $assignmentclass('staticonly');
3297         if ($result = $ass->get_coursemodule_info($coursemodule)) {
3298             return $result;
3299         } else {
3300             $info = new object();
3301             $info->name = $assignment->name;
3302             return $info;
3303         }
3305     } else {
3306         debugging('Incorrect assignment type: '.$assignment->assignmenttype);
3307         return false;
3308     }
3313 /// OTHER GENERAL FUNCTIONS FOR ASSIGNMENTS  ///////////////////////////////////////
3315 /**
3316  * Returns an array of installed assignment types indexed and sorted by name
3317  *
3318  * @return array The index is the name of the assignment type, the value its full name from the language strings
3319  */
3320 function assignment_types() {
3321     $types = array();
3322     $names = get_plugin_list('assignment');
3323     foreach ($names as $name=>$dir) {
3324         $types[$name] = get_string('type'.$name, 'assignment');
3326         // ugly hack to support pluggable assignment type titles..
3327         if ($types[$name] == '[[type'.$name.']]') {
3328             $types[$name] = get_string('type'.$name, 'assignment_'.$name);
3329         }
3330     }
3331     asort($types);
3332     return $types;
3335 function assignment_print_overview($courses, &$htmlarray) {
3336     global $USER, $CFG, $DB;
3338     if (empty($courses) || !is_array($courses) || count($courses) == 0) {
3339         return array();
3340     }
3342     if (!$assignments = get_all_instances_in_courses('assignment',$courses)) {
3343         return;
3344     }
3346     $assignmentids = array();
3348     // Do assignment_base::isopen() here without loading the whole thing for speed
3349     foreach ($assignments as $key => $assignment) {
3350         $time = time();
3351         if ($assignment->timedue) {
3352             if ($assignment->preventlate) {
3353                 $isopen = ($assignment->timeavailable <= $time && $time <= $assignment->timedue);
3354             } else {
3355                 $isopen = ($assignment->timeavailable <= $time);
3356             }
3357         }
3358         if (empty($isopen) || empty($assignment->timedue)) {
3359             unset($assignments[$key]);
3360         } else {
3361             $assignmentids[] = $assignment->id;
3362         }
3363     }
3365     if (empty($assignmentids)){
3366         // no assigments to look at - we're done
3367         return true;
3368     }
3370     $strduedate = get_string('duedate', 'assignment');
3371     $strduedateno = get_string('duedateno', 'assignment');
3372     $strgraded = get_string('graded', 'assignment');
3373     $strnotgradedyet = get_string('notgradedyet', 'assignment');
3374 &n