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