0fd89b8a7b6e3f139ac2cd103f97a4852578b6e7
[moodle.git] / mod / assignment / lib.php
1 <?PHP
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
18 /**
19  * assignment_base is the base class for assignment types
20  *
21  * This class provides all the functionality for an assignment
22  *
23  * @package   mod-assignment
24  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
25  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26  */
28 /** Include eventslib.php */
29 require_once($CFG->libdir.'/eventslib.php');
30 /** Include formslib.php */
31 require_once($CFG->libdir.'/formslib.php');
32 /** Include calendar/lib.php */
33 require_once($CFG->dirroot.'/calendar/lib.php');
35 /** ASSIGNMENT_COUNT_WORDS = 1 */
36 DEFINE ('ASSIGNMENT_COUNT_WORDS', 1);
37 /** ASSIGNMENT_COUNT_LETTERS = 2 */
38 DEFINE ('ASSIGNMENT_COUNT_LETTERS', 2);
40 /**
41  * Standard base class for all assignment submodules (assignment types).
42  *
43  * @package   mod-assignment
44  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
45  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
46  */
47 class assignment_base {
49     /** @var object */
50     var $cm;
51     /** @var object */
52     var $course;
53     /** @var object */
54     var $assignment;
55     /** @var string */
56     var $strassignment;
57     /** @var string */
58     var $strassignments;
59     /** @var string */
60     var $strsubmissions;
61     /** @var string */
62     var $strlastmodified;
63     /** @var string */
64     var $pagetitle;
65     /** @var bool */
66     var $usehtmleditor;
67     /**
68      * @todo document this var
69      */
70     var $defaultformat;
71     /**
72      * @todo document this var
73      */
74     var $context;
75     /** @var string */
76     var $type;
78     /**
79      * Constructor for the base assignment class
80      *
81      * Constructor for the base assignment class.
82      * If cmid is set create the cm, course, assignment objects.
83      * If the assignment is hidden and the user is not a teacher then
84      * this prints a page header and notice.
85      *
86      * @global object
87      * @global object
88      * @param int $cmid the current course module id - not set for new assignments
89      * @param object $assignment usually null, but if we have it we pass it to save db access
90      * @param object $cm usually null, but if we have it we pass it to save db access
91      * @param object $course usually null, but if we have it we pass it to save db access
92      */
93     function assignment_base($cmid='staticonly', $assignment=NULL, $cm=NULL, $course=NULL) {
94         global $COURSE, $DB;
96         if ($cmid == 'staticonly') {
97             //use static functions only!
98             return;
99         }
101         global $CFG;
103         if ($cm) {
104             $this->cm = $cm;
105         } else if (! $this->cm = get_coursemodule_from_id('assignment', $cmid)) {
106             print_error('invalidcoursemodule');
107         }
109         $this->context = get_context_instance(CONTEXT_MODULE, $this->cm->id);
111         if ($course) {
112             $this->course = $course;
113         } else if ($this->cm->course == $COURSE->id) {
114             $this->course = $COURSE;
115         } else if (! $this->course = $DB->get_record('course', array('id'=>$this->cm->course))) {
116             print_error('invalidid', 'assignment');
117         }
119         if ($assignment) {
120             $this->assignment = $assignment;
121         } else if (! $this->assignment = $DB->get_record('assignment', array('id'=>$this->cm->instance))) {
122             print_error('invalidid', 'assignment');
123         }
125         $this->assignment->cmidnumber = $this->cm->idnumber; // compatibility with modedit assignment obj
126         $this->assignment->courseid   = $this->course->id; // compatibility with modedit assignment obj
128         $this->strassignment = get_string('modulename', 'assignment');
129         $this->strassignments = get_string('modulenameplural', 'assignment');
130         $this->strsubmissions = get_string('submissions', 'assignment');
131         $this->strlastmodified = get_string('lastmodified');
132         $this->pagetitle = strip_tags($this->course->shortname.': '.$this->strassignment.': '.format_string($this->assignment->name,true));
134         // visibility handled by require_login() with $cm parameter
135         // get current group only when really needed
137     /// Set up things for a HTML editor if it's needed
138         $this->defaultformat = editors_get_preferred_format();
139     }
141     /**
142      * Display the assignment, used by view.php
143      *
144      * This in turn calls the methods producing individual parts of the page
145      */
146     function view() {
148         $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
149         require_capability('mod/assignment:view', $context);
151         add_to_log($this->course->id, "assignment", "view", "view.php?id={$this->cm->id}",
152                    $this->assignment->id, $this->cm->id);
154         $this->view_header();
156         $this->view_intro();
158         $this->view_dates();
160         $this->view_feedback();
162         $this->view_footer();
163     }
165     /**
166      * Display the header and top of a page
167      *
168      * (this doesn't change much for assignment types)
169      * This is used by the view() method to print the header of view.php but
170      * it can be used on other pages in which case the string to denote the
171      * page in the navigation trail should be passed as an argument
172      *
173      * @global object
174      * @param string $subpage Description of subpage to be used in navigation trail
175      */
176     function view_header($subpage='') {
177         global $CFG, $PAGE, $OUTPUT;
179         if ($subpage) {
180             $PAGE->navbar->add($subpage);
181         }
183         $PAGE->set_title($this->pagetitle);
184         $PAGE->set_heading($this->course->fullname);
186         echo $OUTPUT->header();
188         groups_print_activity_menu($this->cm, $CFG->wwwroot . '/mod/assignment/view.php?id=' . $this->cm->id);
190         echo '<div class="reportlink">'.$this->submittedlink().'</div>';
191         echo '<div class="clearer"></div>';
192     }
195     /**
196      * Display the assignment intro
197      *
198      * This will most likely be extended by assignment type plug-ins
199      * The default implementation prints the assignment description in a box
200      */
201     function view_intro() {
202         global $OUTPUT;
203         echo $OUTPUT->box_start('generalbox boxaligncenter', 'intro');
204         echo format_module_intro('assignment', $this->assignment, $this->cm->id);
205         echo $OUTPUT->box_end();
206     }
208     /**
209      * Display the assignment dates
210      *
211      * Prints the assignment start and end dates in a box.
212      * This will be suitable for most assignment types
213      */
214     function view_dates() {
215         global $OUTPUT;
216         if (!$this->assignment->timeavailable && !$this->assignment->timedue) {
217             return;
218         }
220         echo $OUTPUT->box_start('generalbox boxaligncenter', 'dates');
221         echo '<table>';
222         if ($this->assignment->timeavailable) {
223             echo '<tr><td class="c0">'.get_string('availabledate','assignment').':</td>';
224             echo '    <td class="c1">'.userdate($this->assignment->timeavailable).'</td></tr>';
225         }
226         if ($this->assignment->timedue) {
227             echo '<tr><td class="c0">'.get_string('duedate','assignment').':</td>';
228             echo '    <td class="c1">'.userdate($this->assignment->timedue).'</td></tr>';
229         }
230         echo '</table>';
231         echo $OUTPUT->box_end();
232     }
235     /**
236      * Display the bottom and footer of a page
237      *
238      * This default method just prints the footer.
239      * This will be suitable for most assignment types
240      */
241     function view_footer() {
242         global $OUTPUT;
243         echo $OUTPUT->footer();
244     }
246     /**
247      * Display the feedback to the student
248      *
249      * This default method prints the teacher picture and name, date when marked,
250      * grade and teacher submissioncomment.
251      *
252      * @global object
253      * @global object
254      * @global object
255      * @param object $submission The submission object or NULL in which case it will be loaded
256      */
257     function view_feedback($submission=NULL) {
258         global $USER, $CFG, $DB, $OUTPUT;
259         require_once($CFG->libdir.'/gradelib.php');
261         if (!is_enrolled($this->context, $USER, 'mod/assignment:submit')) {
262             // can not submit assignments -> no feedback
263             return;
264         }
266         if (!$submission) { /// Get submission for this assignment
267             $submission = $this->get_submission($USER->id);
268         }
270         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $USER->id);
271         $item = $grading_info->items[0];
272         $grade = $item->grades[$USER->id];
274         if ($grade->hidden or $grade->grade === false) { // hidden or error
275             return;
276         }
278         if ($grade->grade === null and empty($grade->str_feedback)) {   /// Nothing to show yet
279             return;
280         }
282         $graded_date = $grade->dategraded;
283         $graded_by   = $grade->usermodified;
285     /// We need the teacher info
286         if (!$teacher = $DB->get_record('user', array('id'=>$graded_by))) {
287             print_error('cannotfindteacher');
288         }
290     /// Print the feedback
291         echo $OUTPUT->heading(get_string('feedbackfromteacher', 'assignment', fullname($teacher)));
293         echo '<table cellspacing="0" class="feedback">';
295         echo '<tr>';
296         echo '<td class="left picture">';
297         if ($teacher) {
298             echo $OUTPUT->user_picture($teacher);
299         }
300         echo '</td>';
301         echo '<td class="topic">';
302         echo '<div class="from">';
303         if ($teacher) {
304             echo '<div class="fullname">'.fullname($teacher).'</div>';
305         }
306         echo '<div class="time">'.userdate($graded_date).'</div>';
307         echo '</div>';
308         echo '</td>';
309         echo '</tr>';
311         echo '<tr>';
312         echo '<td class="left side">&nbsp;</td>';
313         echo '<td class="content">';
314         echo '<div class="grade">';
315         echo get_string("grade").': '.$grade->str_long_grade;
316         echo '</div>';
317         echo '<div class="clearer"></div>';
319         echo '<div class="comment">';
320         echo $grade->str_feedback;
321         echo '</div>';
322         echo '</tr>';
324         echo '</table>';
325     }
327     /**
328      * Returns a link with info about the state of the assignment submissions
329      *
330      * This is used by view_header to put this link at the top right of the page.
331      * For teachers it gives the number of submitted assignments with a link
332      * For students it gives the time of their submission.
333      * This will be suitable for most assignment types.
334      *
335      * @global object
336      * @global object
337      * @param bool $allgroup print all groups info if user can access all groups, suitable for index.php
338      * @return string
339      */
340     function submittedlink($allgroups=false) {
341         global $USER;
342         global $CFG;
344         $submitted = '';
345         $urlbase = "{$CFG->wwwroot}/mod/assignment/";
347         $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
348         if (has_capability('mod/assignment:grade', $context)) {
349             if ($allgroups and has_capability('moodle/site:accessallgroups', $context)) {
350                 $group = 0;
351             } else {
352                 $group = groups_get_activity_group($this->cm);
353             }
354             if ($count = $this->count_real_submissions($group)) {
355                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
356                              get_string('viewsubmissions', 'assignment', $count).'</a>';
357             } else {
358                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
359                              get_string('noattempts', 'assignment').'</a>';
360             }
361         } else {
362             if (isloggedin()) {
363                 if ($submission = $this->get_submission($USER->id)) {
364                     if ($submission->timemodified) {
365                         if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
366                             $submitted = '<span class="early">'.userdate($submission->timemodified).'</span>';
367                         } else {
368                             $submitted = '<span class="late">'.userdate($submission->timemodified).'</span>';
369                         }
370                     }
371                 }
372             }
373         }
375         return $submitted;
376     }
379     /**
380      * @todo Document this function
381      */
382     function setup_elements(&$mform) {
384     }
386     /**
387      * Any preprocessing needed for the settings form for
388      * this assignment type
389      *
390      * @param array $default_values - array to fill in with the default values
391      *      in the form 'formelement' => 'value'
392      * @param object $form - the form that is to be displayed
393      * @return none
394      */
395     function form_data_preprocessing(&$default_values, $form) {
396     }
398     /**
399      * Any extra validation checks needed for the settings
400      * form for this assignment type
401      *
402      * See lib/formslib.php, 'validation' function for details
403      */
404     function form_validation($data, $files) {
405         return array();
406     }
408     /**
409      * Create a new assignment activity
410      *
411      * Given an object containing all the necessary data,
412      * (defined by the form in mod_form.php) this function
413      * will create a new instance and return the id number
414      * of the new instance.
415      * The due data is added to the calendar
416      * This is common to all assignment types.
417      *
418      * @global object
419      * @global object
420      * @param object $assignment The data from the form on mod_form.php
421      * @return int The id of the assignment
422      */
423     function add_instance($assignment) {
424         global $COURSE, $DB;
426         $assignment->timemodified = time();
427         $assignment->courseid = $assignment->course;
429         if ($returnid = $DB->insert_record("assignment", $assignment)) {
430             $assignment->id = $returnid;
432             if ($assignment->timedue) {
433                 $event = new object();
434                 $event->name        = $assignment->name;
435                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
436                 $event->courseid    = $assignment->course;
437                 $event->groupid     = 0;
438                 $event->userid      = 0;
439                 $event->modulename  = 'assignment';
440                 $event->instance    = $returnid;
441                 $event->eventtype   = 'due';
442                 $event->timestart   = $assignment->timedue;
443                 $event->timeduration = 0;
445                 calendar_event::create($event);
446             }
448             assignment_grade_item_update($assignment);
450         }
453         return $returnid;
454     }
456     /**
457      * Deletes an assignment activity
458      *
459      * Deletes all database records, files and calendar events for this assignment.
460      *
461      * @global object
462      * @global object
463      * @param object $assignment The assignment to be deleted
464      * @return boolean False indicates error
465      */
466     function delete_instance($assignment) {
467         global $CFG, $DB;
469         $assignment->courseid = $assignment->course;
471         $result = true;
473         // now get rid of all files
474         $fs = get_file_storage();
475         if ($cm = get_coursemodule_from_instance('assignment', $assignment->id)) {
476             $context = get_context_instance(CONTEXT_MODULE, $cm->id);
477             $fs->delete_area_files($context->id);
478         }
480         if (! $DB->delete_records('assignment_submissions', array('assignment'=>$assignment->id))) {
481             $result = false;
482         }
484         if (! $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
485             $result = false;
486         }
488         if (! $DB->delete_records('assignment', array('id'=>$assignment->id))) {
489             $result = false;
490         }
491         $mod = $DB->get_field('modules','id',array('name'=>'assignment'));
493         assignment_grade_item_delete($assignment);
495         return $result;
496     }
498     /**
499      * Updates a new assignment activity
500      *
501      * Given an object containing all the necessary data,
502      * (defined by the form in mod_form.php) this function
503      * will update the assignment instance and return the id number
504      * The due date is updated in the calendar
505      * This is common to all assignment types.
506      *
507      * @global object
508      * @global object
509      * @param object $assignment The data from the form on mod_form.php
510      * @return int The assignment id
511      */
512     function update_instance($assignment) {
513         global $COURSE, $DB;
515         $assignment->timemodified = time();
517         $assignment->id = $assignment->instance;
518         $assignment->courseid = $assignment->course;
520         $DB->update_record('assignment', $assignment);
522         if ($assignment->timedue) {
523             $event = new object();
525             if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
527                 $event->name        = $assignment->name;
528                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
529                 $event->timestart   = $assignment->timedue;
531                 $calendarevent = calendar_event::load($event->id);
532                 $calendarevent->update($event);
533             } else {
534                 $event = new object();
535                 $event->name        = $assignment->name;
536                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
537                 $event->courseid    = $assignment->course;
538                 $event->groupid     = 0;
539                 $event->userid      = 0;
540                 $event->modulename  = 'assignment';
541                 $event->instance    = $assignment->id;
542                 $event->eventtype   = 'due';
543                 $event->timestart   = $assignment->timedue;
544                 $event->timeduration = 0;
546                 calendar_event::create($event);
547             }
548         } else {
549             $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id));
550         }
552         // get existing grade item
553         assignment_grade_item_update($assignment);
555         return true;
556     }
558     /**
559      * Update grade item for this submission.
560      */
561     function update_grade($submission) {
562         assignment_update_grades($this->assignment, $submission->userid);
563     }
565     /**
566      * Top-level function for handling of submissions called by submissions.php
567      *
568      * This is for handling the teacher interaction with the grading interface
569      * This should be suitable for most assignment types.
570      *
571      * @global object
572      * @param string $mode Specifies the kind of teacher interaction taking place
573      */
574     function submissions($mode) {
575         ///The main switch is changed to facilitate
576         ///1) Batch fast grading
577         ///2) Skip to the next one on the popup
578         ///3) Save and Skip to the next one on the popup
580         //make user global so we can use the id
581         global $USER, $OUTPUT, $DB, $PAGE;
583         $mailinfo = optional_param('mailinfo', null, PARAM_BOOL);
584         $saved = optional_param('saved', null, PARAM_BOOL);
586         if (optional_param('next', null, PARAM_BOOL)) {
587             $mode='next';
588         }
589         if (optional_param('saveandnext', null, PARAM_BOOL)) {
590             $mode='saveandnext';
591         }
593         if (is_null($mailinfo)) {
594             $mailinfo = get_user_preferences('assignment_mailinfo', 0);
595         } else {
596             set_user_preference('assignment_mailinfo', $mailinfo);
597         }
599         if ($saved) {
600             $OUTPUT->heading(get_string('changessaved'));
601         }
603         switch ($mode) {
604             case 'grade':                         // We are in a main window grading
605                 if ($submission = $this->process_feedback()) {
606                     $this->display_submissions(get_string('changessaved'));
607                 } else {
608                     $this->display_submissions();
609                 }
610                 break;
612             case 'single':                        // We are in a main window displaying one submission
613                 if ($submission = $this->process_feedback()) {
614                     $this->display_submissions(get_string('changessaved'));
615                 } else {
616                     $this->display_submission();
617                 }
618                 break;
620             case 'all':                          // Main window, display everything
621                 $this->display_submissions();
622                 break;
624             case 'fastgrade':
625                 ///do the fast grading stuff  - this process should work for all 3 subclasses
626                 $grading    = false;
627                 $commenting = false;
628                 $col        = false;
629                 if (isset($_POST['submissioncomment'])) {
630                     $col = 'submissioncomment';
631                     $commenting = true;
632                 }
633                 if (isset($_POST['menu'])) {
634                     $col = 'menu';
635                     $grading = true;
636                 }
637                 if (!$col) {
638                     //both submissioncomment and grade columns collapsed..
639                     $this->display_submissions();
640                     break;
641                 }
643                 foreach ($_POST[$col] as $id => $unusedvalue){
645                     $id = (int)$id; //clean parameter name
647                     $this->process_outcomes($id);
649                     if (!$submission = $this->get_submission($id)) {
650                         $submission = $this->prepare_new_submission($id);
651                         $newsubmission = true;
652                     } else {
653                         $newsubmission = false;
654                     }
655                     unset($submission->data1);  // Don't need to update this.
656                     unset($submission->data2);  // Don't need to update this.
658                     //for fast grade, we need to check if any changes take place
659                     $updatedb = false;
661                     if ($grading) {
662                         $grade = $_POST['menu'][$id];
663                         $updatedb = $updatedb || ($submission->grade != $grade);
664                         $submission->grade = $grade;
665                     } else {
666                         if (!$newsubmission) {
667                             unset($submission->grade);  // Don't need to update this.
668                         }
669                     }
670                     if ($commenting) {
671                         $commentvalue = trim($_POST['submissioncomment'][$id]);
672                         $updatedb = $updatedb || ($submission->submissioncomment != $commentvalue);
673                         $submission->submissioncomment = $commentvalue;
674                     } else {
675                         unset($submission->submissioncomment);  // Don't need to update this.
676                     }
678                     $submission->teacher    = $USER->id;
679                     if ($updatedb) {
680                         $submission->mailed = (int)(!$mailinfo);
681                     }
683                     $submission->timemarked = time();
685                     //if it is not an update, we don't change the last modified time etc.
686                     //this will also not write into database if no submissioncomment and grade is entered.
688                     if ($updatedb){
689                         if ($newsubmission) {
690                             if (!isset($submission->submissioncomment)) {
691                                 $submission->submissioncomment = '';
692                             }
693                             $sid = $DB->insert_record('assignment_submissions', $submission);
694                             $submission->id = $sid;
695                         } else {
696                             $DB->update_record('assignment_submissions', $submission);
697                         }
699                         // triger grade event
700                         $this->update_grade($submission);
702                         //add to log only if updating
703                         add_to_log($this->course->id, 'assignment', 'update grades',
704                                    'submissions.php?id='.$this->assignment->id.'&user='.$submission->userid,
705                                    $submission->userid, $this->cm->id);
706                     }
708                 }
710                 $message = $OUTPUT->notification(get_string('changessaved'), 'notifysuccess');
712                 $this->display_submissions($message);
713                 break;
716             case 'saveandnext':
717                 ///We are in pop up. save the current one and go to the next one.
718                 //first we save the current changes
719                 if ($submission = $this->process_feedback()) {
720                     //print_heading(get_string('changessaved'));
721                     //$extra_javascript = $this->update_main_listing($submission);
722                 }
724             case 'next':
725                 /// We are currently in pop up, but we want to skip to next one without saving.
726                 ///    This turns out to be similar to a single case
727                 /// The URL used is for the next submission.
728                 $offset = required_param('offset', PARAM_INT);
729                 $nextid = required_param('nextid', PARAM_INT);
730                 $id = required_param('id', PARAM_INT);
731                 $offset = (int)$offset+1;
732                 //$this->display_submission($offset+1 , $nextid);
733                 redirect('submissions.php?id='.$id.'&userid='. $nextid . '&mode=single&offset='.$offset);
734                 break;
736             default:
737                 echo "something seriously is wrong!!";
738                 break;
739         }
740     }
742     /**
743      * Helper method updating the listing on the main script from popup using javascript
744      *
745      * @global object
746      * @global object
747      * @param $submission object The submission whose data is to be updated on the main page
748      */
749     function update_main_listing($submission) {
750         global $SESSION, $CFG, $OUTPUT;
752         $output = '';
754         $perpage = get_user_preferences('assignment_perpage', 10);
756         $quickgrade = get_user_preferences('assignment_quickgrade', 0);
758         /// Run some Javascript to try and update the parent page
759         $output .= '<script type="text/javascript">'."\n<!--\n";
760         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['submissioncomment'])) {
761             if ($quickgrade){
762                 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid.'").value="'
763                 .trim($submission->submissioncomment).'";'."\n";
764              } else {
765                 $output.= 'opener.document.getElementById("com'.$submission->userid.
766                 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment)), 15)."\";\n";
767             }
768         }
770         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['grade'])) {
771             //echo optional_param('menuindex');
772             if ($quickgrade){
773                 $output.= 'opener.document.getElementById("menumenu'.$submission->userid.
774                 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT).'";'."\n";
775             } else {
776                 $output.= 'opener.document.getElementById("g'.$submission->userid.'").innerHTML="'.
777                 $this->display_grade($submission->grade)."\";\n";
778             }
779         }
780         //need to add student's assignments in there too.
781         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemodified']) &&
782             $submission->timemodified) {
783             $output.= 'opener.document.getElementById("ts'.$submission->userid.
784                  '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid)).userdate($submission->timemodified)."\";\n";
785         }
787         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemarked']) &&
788             $submission->timemarked) {
789             $output.= 'opener.document.getElementById("tt'.$submission->userid.
790                  '").innerHTML="'.userdate($submission->timemarked)."\";\n";
791         }
793         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['status'])) {
794             $output.= 'opener.document.getElementById("up'.$submission->userid.'").className="s1";';
795             $buttontext = get_string('update');
796             $url = new moodle_url('/mod/assignment/submissions.php', array(
797                     'id' => $this->cm->id,
798                     'userid' => $submission->userid,
799                     'mode' => 'single',
800                     'offset' => (optional_param('offset', '', PARAM_INT)-1)));
801             $button = $OUTPUT->action_link($url, $buttontext, new popup_action('click', $url, 'grade'.$submission->userid, array('height' => 450, 'width' => 700)), array('ttile'=>$buttontext));
803             $output .= 'opener.document.getElementById("up'.$submission->userid.'").innerHTML="'.addslashes_js($button).'";';
804         }
806         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $submission->userid);
808         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['finalgrade'])) {
809             $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid.
810             '").innerHTML="'.$grading_info->items[0]->grades[$submission->userid]->str_grade.'";'."\n";
811         }
813         if (!empty($CFG->enableoutcomes) and empty($SESSION->flextable['mod-assignment-submissions']->collapse['outcome'])) {
815             if (!empty($grading_info->outcomes)) {
816                 foreach($grading_info->outcomes as $n=>$outcome) {
817                     if ($outcome->grades[$submission->userid]->locked) {
818                         continue;
819                     }
821                     if ($quickgrade){
822                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.
823                         '").selectedIndex="'.$outcome->grades[$submission->userid]->grade.'";'."\n";
825                     } else {
826                         $options = make_grades_menu(-$outcome->scaleid);
827                         $options[0] = get_string('nooutcome', 'grades');
828                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.'").innerHTML="'.$options[$outcome->grades[$submission->userid]->grade]."\";\n";
829                     }
831                 }
832             }
833         }
835         $output .= "\n-->\n</script>";
836         return $output;
837     }
839     /**
840      *  Return a grade in user-friendly form, whether it's a scale or not
841      *
842      * @global object
843      * @param mixed $grade
844      * @return string User-friendly representation of grade
845      */
846     function display_grade($grade) {
847         global $DB;
849         static $scalegrades = array();   // Cache scales for each assignment - they might have different scales!!
851         if ($this->assignment->grade >= 0) {    // Normal number
852             if ($grade == -1) {
853                 return '-';
854             } else {
855                 return $grade.' / '.$this->assignment->grade;
856             }
858         } else {                                // Scale
859             if (empty($scalegrades[$this->assignment->id])) {
860                 if ($scale = $DB->get_record('scale', array('id'=>-($this->assignment->grade)))) {
861                     $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
862                 } else {
863                     return '-';
864                 }
865             }
866             if (isset($scalegrades[$this->assignment->id][$grade])) {
867                 return $scalegrades[$this->assignment->id][$grade];
868             }
869             return '-';
870         }
871     }
873     /**
874      *  Display a single submission, ready for grading on a popup window
875      *
876      * This default method prints the teacher info and submissioncomment box at the top and
877      * the student info and submission at the bottom.
878      * This method also fetches the necessary data in order to be able to
879      * provide a "Next submission" button.
880      * Calls preprocess_submission() to give assignment type plug-ins a chance
881      * to process submissions before they are graded
882      * This method gets its arguments from the page parameters userid and offset
883      *
884      * @global object
885      * @global object
886      * @param string $extra_javascript
887      */
888     function display_submission($offset=-1,$userid =-1) {
889         global $CFG, $DB, $PAGE, $OUTPUT;
890         require_once($CFG->libdir.'/gradelib.php');
891         require_once($CFG->libdir.'/tablelib.php');
892         if ($userid==-1) {
893             $userid = required_param('userid', PARAM_INT);
894         }
895         if ($offset==-1) {
896             $offset = required_param('offset', PARAM_INT);//offset for where to start looking for student.
897         }
899         if (!$user = $DB->get_record('user', array('id'=>$userid))) {
900             print_error('nousers');
901         }
903         if (!$submission = $this->get_submission($user->id)) {
904             $submission = $this->prepare_new_submission($userid);
905         }
906         if ($submission->timemodified > $submission->timemarked) {
907             $subtype = 'assignmentnew';
908         } else {
909             $subtype = 'assignmentold';
910         }
912         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
913         $gradingdisabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
915     /// construct SQL, using current offset to find the data of the next student
916         $course     = $this->course;
917         $assignment = $this->assignment;
918         $cm         = $this->cm;
919         $context    = get_context_instance(CONTEXT_MODULE, $cm->id);
921         /// Get all ppl that can submit assignments
923         $currentgroup = groups_get_activity_group($cm);
924         if ($users = get_enrolled_users($context, 'mod/assignment:submit', $currentgroup, 'u.id')) {
925             $users = array_keys($users);
926         }
928         // if groupmembersonly used, remove users who are not in any group
929         if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
930             if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
931                 $users = array_intersect($users, array_keys($groupingusers));
932             }
933         }
935         $nextid = 0;
937         if ($users) {
938             $userfields = user_picture::fields('u', array('lastaccess'));
939             $select = "SELECT $userfields,
940                               s.id AS submissionid, s.grade, s.submissioncomment,
941                               s.timemodified, s.timemarked,
942                               COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ";
943             $sql = 'FROM {user} u '.
944                    'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
945                                                                       AND s.assignment = '.$this->assignment->id.' '.
946                    'WHERE u.id IN ('.implode(',', $users).') ';
948             if ($sort = flexible_table::get_sort_for_table('mod-assignment-submissions')) {
949                 $sort = 'ORDER BY '.$sort.' ';
950             }
951             $auser = $DB->get_records_sql($select.$sql.$sort, null, $offset, 2);
953             if (is_array($auser) && count($auser)>1) {
954                 $nextuser = next($auser);
955             /// Calculate user status
956                 $nextuser->status = ($nextuser->timemarked > 0) && ($nextuser->timemarked >= $nextuser->timemodified);
957                 $nextid = $nextuser->id;
958             }
959         }
961         if ($submission->teacher) {
962             $teacher = $DB->get_record('user', array('id'=>$submission->teacher));
963         } else {
964             global $USER;
965             $teacher = $USER;
966         }
968         $this->preprocess_submission($submission);
970         $mformdata = new stdclass;
971         $mformdata->context = $this->context;
972         $mformdata->maxbytes = $this->course->maxbytes;
973         $mformdata->courseid = $this->course->id;
974         $mformdata->teacher = $teacher;
975         $mformdata->assignment = $assignment;
976         $mformdata->submission = $submission;
977         $mformdata->lateness = $this->display_lateness($submission->timemodified);
978         $mformdata->auser = $auser;
979         $mformdata->user = $user;
980         $mformdata->offset = $offset;
981         $mformdata->userid = $userid;
982         $mformdata->cm = $this->cm;
983         $mformdata->grading_info = $grading_info;
984         $mformdata->enableoutcomes = $CFG->enableoutcomes;
985         $mformdata->grade = $this->assignment->grade;
986         $mformdata->gradingdisabled = $gradingdisabled;
987         $mformdata->usehtmleditor = $this->usehtmleditor;
988         $mformdata->nextid = $nextid;
989         $mformdata->submissioncomment= $submission->submissioncomment;
990         $mformdata->submissioncommentformat= FORMAT_HTML;
991         $mformdata->submission_content= $this->print_user_files($user->id,true);
993         $submitform = new mod_assignment_grading_form( null, $mformdata );
995         if ($submitform->is_cancelled()) {
996             redirect('submissions.php?id='.$this->cm->id);
997         }
999         $submitform->set_data($mformdata);
1001         $PAGE->set_title($this->course->fullname . ': ' .get_string('feedback', 'assignment').' - '.fullname($user, true));
1002         $PAGE->set_heading($this->course->fullname);
1003         $PAGE->navbar->add( get_string('submissions', 'assignment') );
1005         echo $OUTPUT->header();
1006         echo $OUTPUT->heading(get_string('feedback', 'assignment').': '.fullname($user, true));
1008         // display mform here...
1009         $submitform->display();
1011         $customfeedback = $this->custom_feedbackform($submission, true);
1012         if (!empty($customfeedback)) {
1013             echo $customfeedback;
1014         }
1016         echo $OUTPUT->footer();
1017     }
1019     /**
1020      *  Preprocess submission before grading
1021      *
1022      * Called by display_submission()
1023      * The default type does nothing here.
1024      *
1025      * @param object $submission The submission object
1026      */
1027     function preprocess_submission(&$submission) {
1028     }
1030     /**
1031      *  Display all the submissions ready for grading
1032      *
1033      * @global object
1034      * @global object
1035      * @global object
1036      * @global object
1037      * @param string $message
1038      * @return bool|void
1039      */
1040     function display_submissions($message='') {
1041         global $CFG, $DB, $USER, $DB, $OUTPUT, $PAGE;
1042         require_once($CFG->libdir.'/gradelib.php');
1044         /* first we check to see if the form has just been submitted
1045          * to request user_preference updates
1046          */
1047         if (isset($_POST['updatepref'])){
1048             $perpage = optional_param('perpage', 10, PARAM_INT);
1049             $perpage = ($perpage <= 0) ? 10 : $perpage ;
1050             set_user_preference('assignment_perpage', $perpage);
1051             set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
1052         }
1054         /* next we get perpage and quickgrade (allow quick grade) params
1055          * from database
1056          */
1057         $perpage    = get_user_preferences('assignment_perpage', 10);
1059         $quickgrade = get_user_preferences('assignment_quickgrade', 0);
1061         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);
1063         if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
1064             $uses_outcomes = true;
1065         } else {
1066             $uses_outcomes = false;
1067         }
1069         $page    = optional_param('page', 0, PARAM_INT);
1070         $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
1072     /// Some shortcuts to make the code read better
1074         $course     = $this->course;
1075         $assignment = $this->assignment;
1076         $cm         = $this->cm;
1078         $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
1079         add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->cm->id, $this->assignment->id, $this->cm->id);
1081         $PAGE->set_title(format_string($this->assignment->name,true));
1082         $PAGE->set_heading($this->course->fullname);
1083         echo $OUTPUT->header();
1085         /// Print quickgrade form around the table
1086         if ($quickgrade) {
1087             echo '<form action="submissions.php" id="fastg" method="post">';
1088             echo '<div>';
1089             echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
1090             echo '<input type="hidden" name="mode" value="fastgrade" />';
1091             echo '<input type="hidden" name="page" value="'.$page.'" />';
1092             echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1093             echo '</div>';
1094         }
1096         $course_context = get_context_instance(CONTEXT_COURSE, $course->id);
1097         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
1098             echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">'
1099                 . get_string('seeallcoursegrades', 'grades') . '</a></div>';
1100         }
1102         if (!empty($message)) {
1103             echo $message;   // display messages here if any
1104         }
1106         $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1108     /// Check to see if groups are being used in this assignment
1110         /// find out current groups mode
1111         $groupmode = groups_get_activity_groupmode($cm);
1112         $currentgroup = groups_get_activity_group($cm, true);
1113         groups_print_activity_menu($cm, $CFG->wwwroot . '/mod/assignment/submissions.php?id=' . $this->cm->id);
1115         /// Get all ppl that are allowed to submit assignments
1116         if ($users = get_enrolled_users($context, 'mod/assignment:submit', $currentgroup, 'u.id')) {
1117             $users = array_keys($users);
1118         }
1120         // if groupmembersonly used, remove users who are not in any group
1121         if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
1122             if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1123                 $users = array_intersect($users, array_keys($groupingusers));
1124             }
1125         }
1127         $tablecolumns = array('picture', 'fullname', 'grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade');
1128         if ($uses_outcomes) {
1129             $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
1130         }
1132         $tableheaders = array('',
1133                               get_string('fullname'),
1134                               get_string('grade'),
1135                               get_string('comment', 'assignment'),
1136                               get_string('lastmodified').' ('.get_string('submission', 'assignment').')',
1137                               get_string('lastmodified').' ('.get_string('grade').')',
1138                               get_string('status'),
1139                               get_string('finalgrade', 'grades'));
1140         if ($uses_outcomes) {
1141             $tableheaders[] = get_string('outcome', 'grades');
1142         }
1144         require_once($CFG->libdir.'/tablelib.php');
1145         $table = new flexible_table('mod-assignment-submissions');
1147         $table->define_columns($tablecolumns);
1148         $table->define_headers($tableheaders);
1149         $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;currentgroup='.$currentgroup);
1151         $table->sortable(true, 'lastname');//sorted by lastname by default
1152         $table->collapsible(true);
1153         $table->initialbars(true);
1155         $table->column_suppress('picture');
1156         $table->column_suppress('fullname');
1158         $table->column_class('picture', 'picture');
1159         $table->column_class('fullname', 'fullname');
1160         $table->column_class('grade', 'grade');
1161         $table->column_class('submissioncomment', 'comment');
1162         $table->column_class('timemodified', 'timemodified');
1163         $table->column_class('timemarked', 'timemarked');
1164         $table->column_class('status', 'status');
1165         $table->column_class('finalgrade', 'finalgrade');
1166         if ($uses_outcomes) {
1167             $table->column_class('outcome', 'outcome');
1168         }
1170         $table->set_attribute('cellspacing', '0');
1171         $table->set_attribute('id', 'attempts');
1172         $table->set_attribute('class', 'submissions');
1173         $table->set_attribute('width', '100%');
1174         //$table->set_attribute('align', 'center');
1176         $table->no_sorting('finalgrade');
1177         $table->no_sorting('outcome');
1179         // Start working -- this is necessary as soon as the niceties are over
1180         $table->setup();
1182         if (empty($users)) {
1183             echo $OUTPUT->heading(get_string('nosubmitusers','assignment'));
1184             echo '</div>';
1185             return true;
1186         }
1187         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)
1188             echo '<div style="text-align:right"><a href="submissions.php?id='.$this->cm->id.'&amp;download=zip">'.get_string('downloadall', 'assignment').'</a></div>';
1189         }
1190     /// Construct the SQL
1192         if ($where = $table->get_sql_where()) {
1193             $where .= ' AND ';
1194         }
1196         if ($sort = $table->get_sql_sort()) {
1197             $sort = ' ORDER BY '.$sort;
1198         }
1200         $ufields = user_picture::fields('u');
1201         $select = "SELECT $ufields,
1202                           s.id AS submissionid, s.grade, s.submissioncomment,
1203                           s.timemodified, s.timemarked,
1204                           COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ";
1205         $sql = 'FROM {user} u '.
1206                'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1207                                                                   AND s.assignment = '.$this->assignment->id.' '.
1208                'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1210         $table->pagesize($perpage, count($users));
1212         ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1213         $offset = $page * $perpage;
1215         $strupdate = get_string('update');
1216         $strgrade  = get_string('grade');
1217         $grademenu = make_grades_menu($this->assignment->grade);
1219         if (($ausers = $DB->get_records_sql($select.$sql.$sort, null, $table->get_page_start(), $table->get_page_size())) !== false) {
1220             $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
1221             foreach ($ausers as $auser) {
1222                 $final_grade = $grading_info->items[0]->grades[$auser->id];
1223                 $grademax = $grading_info->items[0]->grademax;
1224                 $final_grade->formatted_grade = round($final_grade->grade,2) .' / ' . round($grademax,2);
1225                 $locked_overridden = 'locked';
1226                 if ($final_grade->overridden) {
1227                     $locked_overridden = 'overridden';
1228                 }
1230             /// Calculate user status
1231                 $auser->status = ($auser->timemarked > 0) && ($auser->timemarked >= $auser->timemodified);
1232                 $picture = $OUTPUT->user_picture($auser);
1234                 if (empty($auser->submissionid)) {
1235                     $auser->grade = -1; //no submission yet
1236                 }
1238                 if (!empty($auser->submissionid)) {
1239                 ///Prints student answer and student modified date
1240                 ///attach file or print link to student answer, depending on the type of the assignment.
1241                 ///Refer to print_student_answer in inherited classes.
1242                     if ($auser->timemodified > 0) {
1243                         $studentmodified = '<div id="ts'.$auser->id.'">'.$this->print_student_answer($auser->id)
1244                                          . userdate($auser->timemodified).'</div>';
1245                     } else {
1246                         $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1247                     }
1248                 ///Print grade, dropdown or text
1249                     if ($auser->timemarked > 0) {
1250                         $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
1252                         if ($final_grade->locked or $final_grade->overridden) {
1253                             $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1254                         } else if ($quickgrade) {
1255                             $attributes = array();
1256                             $attributes['tabindex'] = $tabindex++;
1257                             $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1258                             $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
1259                         } else {
1260                             $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1261                         }
1263                     } else {
1264                         $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1265                         if ($final_grade->locked or $final_grade->overridden) {
1266                             $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1267                         } else if ($quickgrade) {
1268                             $attributes = array();
1269                             $attributes['tabindex'] = $tabindex++;
1270                             $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1271                             $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1272                         } else {
1273                             $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1274                         }
1275                     }
1276                 ///Print Comment
1277                     if ($final_grade->locked or $final_grade->overridden) {
1278                         $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';
1280                     } else if ($quickgrade) {
1281                         $comment = '<div id="com'.$auser->id.'">'
1282                                  . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1283                                  . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1284                     } else {
1285                         $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
1286                     }
1287                 } else {
1288                     $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1289                     $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1290                     $status          = '<div id="st'.$auser->id.'">&nbsp;</div>';
1292                     if ($final_grade->locked or $final_grade->overridden) {
1293                         $grade = '<div id="g'.$auser->id.'">'.$final_grade->formatted_grade . '</div>';
1294                     } else if ($quickgrade) {   // allow editing
1295                         $attributes = array();
1296                         $attributes['tabindex'] = $tabindex++;
1297                         $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1298                         $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1299                     } else {
1300                         $grade = '<div id="g'.$auser->id.'">-</div>';
1301                     }
1303                     if ($final_grade->locked or $final_grade->overridden) {
1304                         $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
1305                     } else if ($quickgrade) {
1306                         $comment = '<div id="com'.$auser->id.'">'
1307                                  . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1308                                  . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1309                     } else {
1310                         $comment = '<div id="com'.$auser->id.'">&nbsp;</div>';
1311                     }
1312                 }
1314                 if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
1315                     $auser->status = 0;
1316                 } else {
1317                     $auser->status = 1;
1318                 }
1320                 $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
1322                 ///No more buttons, we use popups ;-).
1323                 $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1324                            . '&userid='.$auser->id.'&mode=single'.'&offset='.$offset++;
1326                 $button = $OUTPUT->action_link($popup_url, $buttontext);
1328                 $status  = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
1330                 $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';
1332                 $outcomes = '';
1334                 if ($uses_outcomes) {
1336                     foreach($grading_info->outcomes as $n=>$outcome) {
1337                         $outcomes .= '<div class="outcome"><label>'.$outcome->name.'</label>';
1338                         $options = make_grades_menu(-$outcome->scaleid);
1340                         if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
1341                             $options[0] = get_string('nooutcome', 'grades');
1342                             $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
1343                         } else {
1344                             $attributes = array();
1345                             $attributes['tabindex'] = $tabindex++;
1346                             $attributes['id'] = 'outcome_'.$n.'_'.$auser->id;
1347                             $outcomes .= ' '.html_writer::select($options, 'outcome_'.$n.'['.$auser->id.']', $outcome->grades[$auser->id]->grade, array(0=>get_string('nooutcome', 'grades')), $attributes);
1348                         }
1349                         $outcomes .= '</div>';
1350                     }
1351                 }
1353                 $userlink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $auser->id . '&amp;course=' . $course->id . '">' . fullname($auser) . '</a>';
1354                 $row = array($picture, $userlink, $grade, $comment, $studentmodified, $teachermodified, $status, $finalgrade);
1355                 if ($uses_outcomes) {
1356                     $row[] = $outcomes;
1357                 }
1359                 $table->add_data($row);
1360             }
1361         }
1363         $table->print_html();  /// Print the whole table
1365         if ($quickgrade){
1366             $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? 'checked="checked"' : '';
1367             echo '<div class="fgcontrols">';
1368             echo '<div class="emailnotification">';
1369             echo '<label for="mailinfo">'.get_string('enableemailnotification','assignment').'</label>';
1370             echo '<input type="hidden" name="mailinfo" value="0" />';
1371             echo '<input type="checkbox" id="mailinfo" name="mailinfo" value="1" '.$lastmailinfo.' />';
1372             echo $OUTPUT->help_icon('enableemailnotification', 'assignment');
1373             echo '</div>';
1374             echo '</div>';
1375             echo '<div class="fastgbutton"><input type="submit" name="fastg" value="'.get_string('saveallfeedback', 'assignment').'" /></div>';
1376             echo '</form>';
1377         }
1378         /// End of fast grading form
1380         /// Mini form for setting user preference
1381         echo '<div class="qgprefs">';
1382         echo '<form id="options" action="submissions.php?id='.$this->cm->id.'" method="post"><div>';
1383         echo '<input type="hidden" name="updatepref" value="1" />';
1384         echo '<table id="optiontable">';
1385         echo '<tr><td>';
1386         echo '<label for="perpage">'.get_string('pagesize','assignment').'</label>';
1387         echo '</td>';
1388         echo '<td>';
1389         echo '<input type="text" id="perpage" name="perpage" size="1" value="'.$perpage.'" />';
1390         echo '</td></tr>';
1391         echo '<tr><td>';
1392         echo '<label for="quickgrade">'.get_string('quickgrade','assignment').'</label>';
1393         echo '</td>';
1394         echo '<td>';
1395         $checked = $quickgrade ? 'checked="checked"' : '';
1396         echo '<input type="checkbox" id="quickgrade" name="quickgrade" value="1" '.$checked.' />';
1397         echo '<p>'.$OUTPUT->help_icon('quickgrade', 'assignment').'</p>';
1398         echo '</td>';
1399         echo '</tr>';
1400         echo '<tr><td colspan="2">';
1401         echo '<input type="submit" value="'.get_string('savepreferences').'" />';
1402         echo '</td></tr></table>';
1403         echo '</div></form></div>';
1404         ///End of mini form
1405         echo $OUTPUT->footer();
1406     }
1408     /**
1409      *  Process teacher feedback submission
1410      *
1411      * This is called by submissions() when a grading even has taken place.
1412      * It gets its data from the submitted form.
1413      *
1414      * @global object
1415      * @global object
1416      * @global object
1417      * @return object|bool The updated submission object or false
1418      */
1419     function process_feedback() {
1420         global $CFG, $USER, $DB;
1421         require_once($CFG->libdir.'/gradelib.php');
1423         if (!$feedback = data_submitted() or !confirm_sesskey()) {      // No incoming data?
1424             return false;
1425         }
1427         ///For save and next, we need to know the userid to save, and the userid to go
1428         ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1429         ///as the userid to store
1430         if ((int)$feedback->saveuserid !== -1){
1431             $feedback->userid = $feedback->saveuserid;
1432         }
1434         if (!empty($feedback->cancel)) {          // User hit cancel button
1435             return false;
1436         }
1438         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);
1440         // store outcomes if needed
1441         $this->process_outcomes($feedback->userid);
1443         $submission = $this->get_submission($feedback->userid, true);  // Get or make one
1445         if (!($grading_info->items[0]->grades[$feedback->userid]->locked ||
1446             $grading_info->items[0]->grades[$feedback->userid]->overridden) ) {
1448             $submission->grade      = $feedback->xgrade;
1449             $submission->submissioncomment    = $feedback->submissioncomment_editor['text'];
1450             $submission->format     = $feedback->format;
1451             $submission->teacher    = $USER->id;
1452             $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1453             if (!$mailinfo) {
1454                 $submission->mailed = 1;       // treat as already mailed
1455             } else {
1456                 $submission->mailed = 0;       // Make sure mail goes out (again, even)
1457             }
1458             $submission->timemarked = time();
1460             unset($submission->data1);  // Don't need to update this.
1461             unset($submission->data2);  // Don't need to update this.
1463             if (empty($submission->timemodified)) {   // eg for offline assignments
1464                 // $submission->timemodified = time();
1465             }
1467             $DB->update_record('assignment_submissions', $submission);
1469             // triger grade event
1470             $this->update_grade($submission);
1472             add_to_log($this->course->id, 'assignment', 'update grades',
1473                        'submissions.php?id='.$this->assignment->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
1474         }
1476         return $submission;
1478     }
1480     function process_outcomes($userid) {
1481         global $CFG, $USER;
1483         if (empty($CFG->enableoutcomes)) {
1484             return;
1485         }
1487         require_once($CFG->libdir.'/gradelib.php');
1489         if (!$formdata = data_submitted() or !confirm_sesskey()) {
1490             return;
1491         }
1493         $data = array();
1494         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
1496         if (!empty($grading_info->outcomes)) {
1497             foreach($grading_info->outcomes as $n=>$old) {
1498                 $name = 'outcome_'.$n;
1499                 if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
1500                     $data[$n] = $formdata->{$name}[$userid];
1501                 }
1502             }
1503         }
1504         if (count($data) > 0) {
1505             grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1506         }
1508     }
1510     /**
1511      * Load the submission object for a particular user
1512      *
1513      * @global object
1514      * @global object
1515      * @param $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1516      * @param $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1517      * @param bool $teachermodified student submission set if false
1518      * @return object The submission
1519      */
1520     function get_submission($userid=0, $createnew=false, $teachermodified=false) {
1521         global $USER, $DB;
1523         if (empty($userid)) {
1524             $userid = $USER->id;
1525         }
1527         $submission = $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1529         if ($submission || !$createnew) {
1530             return $submission;
1531         }
1532         $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
1533         $DB->insert_record("assignment_submissions", $newsubmission);
1535         return $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1536     }
1538     /**
1539      * Instantiates a new submission object for a given user
1540      *
1541      * Sets the assignment, userid and times, everything else is set to default values.
1542      *
1543      * @param int $userid The userid for which we want a submission object
1544      * @param bool $teachermodified student submission set if false
1545      * @return object The submission
1546      */
1547     function prepare_new_submission($userid, $teachermodified=false) {
1548         $submission = new Object;
1549         $submission->assignment   = $this->assignment->id;
1550         $submission->userid       = $userid;
1551         $submission->timecreated = time();
1552         // teachers should not be modifying modified date, except offline assignments
1553         if ($teachermodified) {
1554             $submission->timemodified = 0;
1555         } else {
1556             $submission->timemodified = $submission->timecreated;
1557         }
1558         $submission->numfiles     = 0;
1559         $submission->data1        = '';
1560         $submission->data2        = '';
1561         $submission->grade        = -1;
1562         $submission->submissioncomment      = '';
1563         $submission->format       = 0;
1564         $submission->teacher      = 0;
1565         $submission->timemarked   = 0;
1566         $submission->mailed       = 0;
1567         return $submission;
1568     }
1570     /**
1571      * Return all assignment submissions by ENROLLED students (even empty)
1572      *
1573      * @param string $sort optional field names for the ORDER BY in the sql query
1574      * @param string $dir optional specifying the sort direction, defaults to DESC
1575      * @return array The submission objects indexed by id
1576      */
1577     function get_submissions($sort='', $dir='DESC') {
1578         return assignment_get_all_submissions($this->assignment, $sort, $dir);
1579     }
1581     /**
1582      * Counts all real assignment submissions by ENROLLED students (not empty ones)
1583      *
1584      * @param int $groupid optional If nonzero then count is restricted to this group
1585      * @return int The number of submissions
1586      */
1587     function count_real_submissions($groupid=0) {
1588         return assignment_count_real_submissions($this->cm, $groupid);
1589     }
1591     /**
1592      * Alerts teachers by email of new or changed assignments that need grading
1593      *
1594      * First checks whether the option to email teachers is set for this assignment.
1595      * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1596      * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1597      *
1598      * @global object
1599      * @global object
1600      * @param $submission object The submission that has changed
1601      * @return void
1602      */
1603     function email_teachers($submission) {
1604         global $CFG, $DB;
1606         if (empty($this->assignment->emailteachers)) {          // No need to do anything
1607             return;
1608         }
1610         $user = $DB->get_record('user', array('id'=>$submission->userid));
1612         if ($teachers = $this->get_graders($user)) {
1614             $strassignments = get_string('modulenameplural', 'assignment');
1615             $strassignment  = get_string('modulename', 'assignment');
1616             $strsubmitted  = get_string('submitted', 'assignment');
1618             foreach ($teachers as $teacher) {
1619                 $info = new object();
1620                 $info->username = fullname($user, true);
1621                 $info->assignment = format_string($this->assignment->name,true);
1622                 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
1624                 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1625                 $posttext = $this->email_teachers_text($info);
1626                 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
1628                 $eventdata = new object();
1629                 $eventdata->modulename       = 'assignment';
1630                 $eventdata->userfrom         = $user;
1631                 $eventdata->userto           = $teacher;
1632                 $eventdata->subject          = $postsubject;
1633                 $eventdata->fullmessage      = $posttext;
1634                 $eventdata->fullmessageformat = FORMAT_PLAIN;
1635                 $eventdata->fullmessagehtml  = $posthtml;
1636                 $eventdata->smallmessage     = '';
1637                 message_send($eventdata);
1638             }
1639         }
1640     }
1642     /**
1643      * @param string $filearea
1644      * @param array $args
1645      * @return bool
1646      */
1647     function send_file($filearea, $args) {
1648         debugging('plugin does not implement file sending', DEBUG_DEVELOPER);
1649         return false;
1650     }
1652     /**
1653      * Returns a list of teachers that should be grading given submission
1654      *
1655      * @param object $user
1656      * @return array
1657      */
1658     function get_graders($user) {
1659         //potential graders
1660         $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false);
1662         $graders = array();
1663         if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) {   // Separate groups are being used
1664             if ($groups = groups_get_all_groups($this->course->id, $user->id)) {  // Try to find all groups
1665                 foreach ($groups as $group) {
1666                     foreach ($potgraders as $t) {
1667                         if ($t->id == $user->id) {
1668                             continue; // do not send self
1669                         }
1670                         if (groups_is_member($group->id, $t->id)) {
1671                             $graders[$t->id] = $t;
1672                         }
1673                     }
1674                 }
1675             } else {
1676                 // user not in group, try to find graders without group
1677                 foreach ($potgraders as $t) {
1678                     if ($t->id == $user->id) {
1679                         continue; // do not send self
1680                     }
1681                     if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
1682                         $graders[$t->id] = $t;
1683                     }
1684                 }
1685             }
1686         } else {
1687             foreach ($potgraders as $t) {
1688                 if ($t->id == $user->id) {
1689                     continue; // do not send self
1690                 }
1691                 $graders[$t->id] = $t;
1692             }
1693         }
1694         return $graders;
1695     }
1697     /**
1698      * Creates the text content for emails to teachers
1699      *
1700      * @param $info object The info used by the 'emailteachermail' language string
1701      * @return string
1702      */
1703     function email_teachers_text($info) {
1704         $posttext  = format_string($this->course->shortname).' -> '.$this->strassignments.' -> '.
1705                      format_string($this->assignment->name)."\n";
1706         $posttext .= '---------------------------------------------------------------------'."\n";
1707         $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
1708         $posttext .= "\n---------------------------------------------------------------------\n";
1709         return $posttext;
1710     }
1712      /**
1713      * Creates the html content for emails to teachers
1714      *
1715      * @param $info object The info used by the 'emailteachermailhtml' language string
1716      * @return string
1717      */
1718     function email_teachers_html($info) {
1719         global $CFG;
1720         $posthtml  = '<p><font face="sans-serif">'.
1721                      '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname).'</a> ->'.
1722                      '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
1723                      '<a href="'.$CFG->wwwroot.'/mod/assignment/view.php?id='.$this->cm->id.'">'.format_string($this->assignment->name).'</a></font></p>';
1724         $posthtml .= '<hr /><font face="sans-serif">';
1725         $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
1726         $posthtml .= '</font><hr />';
1727         return $posthtml;
1728     }
1730     /**
1731      * Produces a list of links to the files uploaded by a user
1732      *
1733      * @param $userid int optional id of the user. If 0 then $USER->id is used.
1734      * @param $return boolean optional defaults to false. If true the list is returned rather than printed
1735      * @return string optional
1736      */
1737     function print_user_files($userid=0, $return=false) {
1738         global $CFG, $USER, $OUTPUT;
1740         if (!$userid) {
1741             if (!isloggedin()) {
1742                 return '';
1743             }
1744             $userid = $USER->id;
1745         }
1747         $output = '';
1749         $fs = get_file_storage();
1751         $found = false;
1753         $submission = $this->get_submission($userid);
1755         if ($files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false)) {
1756             require_once($CFG->libdir.'/portfoliolib.php');
1757             require_once($CFG->dirroot . '/mod/assignment/locallib.php');
1758             $button = new portfolio_add_button();
1759             foreach ($files as $file) {
1760                 $filename = $file->get_filename();
1761                 $found = true;
1762                 $mimetype = $file->get_mimetype();
1763                 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/mod_assignment/submission/'.$userid.'/'.$filename);
1764                 $output .= '<a href="'.$path.'" ><img src="'.$OUTPUT->pix_url(file_mimetype_icon($mimetype)).'" class="icon" alt="'.$mimetype.'" />'.s($filename).'</a>';
1765                 if ($this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1766                     $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id, 'fileid' => $file->get_id()), '/mod/assignment/locallib.php');
1767                     $button->set_format_by_file($file);
1768                     $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
1769                 }
1770             }
1771             if (count($files) > 1  && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1772                 $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id), '/mod/assignment/locallib.php');
1773                 $output .= '<br />'  . $button->to_html();
1774             }
1775         }
1777         $output = '<div class="files">'.$output.'</div>';
1779         if ($return) {
1780             return $output;
1781         }
1782         echo $output;
1783     }
1785     /**
1786      * Count the files uploaded by a given user
1787      *
1788      * @param $userid int The user id
1789      * @return int
1790      */
1791     function count_user_files($userid) {
1792         $fs = get_file_storage();
1793         $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $userid, "id", false);
1794         return count($files);
1795     }
1797     /**
1798      * Returns true if the student is allowed to submit
1799      *
1800      * Checks that the assignment has started and, if the option to prevent late
1801      * submissions is set, also checks that the assignment has not yet closed.
1802      * @return boolean
1803      */
1804     function isopen() {
1805         $time = time();
1806         if ($this->assignment->preventlate && $this->assignment->timedue) {
1807             return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
1808         } else {
1809             return ($this->assignment->timeavailable <= $time);
1810         }
1811     }
1814     /**
1815      * Return true if is set description is hidden till available date
1816      *
1817      * This is needed by calendar so that hidden descriptions do not
1818      * come up in upcoming events.
1819      *
1820      * Check that description is hidden till available date
1821      * By default return false
1822      * Assignments types should implement this method if needed
1823      * @return boolen
1824      */
1825     function description_is_hidden() {
1826         return false;
1827     }
1829     /**
1830      * Return an outline of the user's interaction with the assignment
1831      *
1832      * The default method prints the grade and timemodified
1833      * @param $grade object
1834      * @return object with properties ->info and ->time
1835      */
1836     function user_outline($grade) {
1838         $result = new object();
1839         $result->info = get_string('grade').': '.$grade->str_long_grade;
1840         $result->time = $grade->dategraded;
1841         return $result;
1842     }
1844     /**
1845      * Print complete information about the user's interaction with the assignment
1846      *
1847      * @param $user object
1848      */
1849     function user_complete($user, $grade=null) {
1850         global $OUTPUT;
1851         if ($grade) {
1852             echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
1853             if ($grade->str_feedback) {
1854                 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
1855             }
1856         }
1858         if ($submission = $this->get_submission($user->id)) {
1860             $fs = get_file_storage();
1862             if ($files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false)) {
1863                 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
1864                 foreach ($files as $file) {
1865                     $countfiles .= "; ".$file->get_filename();
1866                 }
1867             }
1869             echo $OUTPUT->box_start();
1870             echo get_string("lastmodified").": ";
1871             echo userdate($submission->timemodified);
1872             echo $this->display_lateness($submission->timemodified);
1874             $this->print_user_files($user->id);
1876             echo '<br />';
1878             $this->view_feedback($submission);
1880             echo $OUTPUT->box_end();
1882         } else {
1883             print_string("notsubmittedyet", "assignment");
1884         }
1885     }
1887     /**
1888      * Return a string indicating how late a submission is
1889      *
1890      * @param $timesubmitted int
1891      * @return string
1892      */
1893     function display_lateness($timesubmitted) {
1894         return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
1895     }
1897     /**
1898      * Empty method stub for all delete actions.
1899      */
1900     function delete() {
1901         //nothing by default
1902         redirect('view.php?id='.$this->cm->id);
1903     }
1905     /**
1906      * Empty custom feedback grading form.
1907      */
1908     function custom_feedbackform($submission, $return=false) {
1909         //nothing by default
1910         return '';
1911     }
1913     /**
1914      * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
1915      * for the course (see resource).
1916      *
1917      * Given a course_module object, this function returns any "extra" information that may be needed
1918      * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
1919      *
1920      * @param $coursemodule object The coursemodule object (record).
1921      * @return object An object on information that the coures will know about (most noticeably, an icon).
1922      *
1923      */
1924     function get_coursemodule_info($coursemodule) {
1925         return false;
1926     }
1928     /**
1929      * Plugin cron method - do not use $this here, create new assignment instances if needed.
1930      * @return void
1931      */
1932     function cron() {
1933         //no plugin cron by default - override if needed
1934     }
1936     /**
1937      * Reset all submissions
1938      */
1939     function reset_userdata($data) {
1940         global $CFG, $DB;
1942         if (!$DB->count_records('assignment', array('course'=>$data->courseid, 'assignmenttype'=>$this->type))) {
1943             return array(); // no assignments of this type present
1944         }
1946         $componentstr = get_string('modulenameplural', 'assignment');
1947         $status = array();
1949         $typestr = get_string('type'.$this->type, 'assignment');
1950         // ugly hack to support pluggable assignment type titles...
1951         if($typestr === '[[type'.$this->type.']]'){
1952             $typestr = get_string('type'.$this->type, 'assignment_'.$this->type);
1953         }
1955         if (!empty($data->reset_assignment_submissions)) {
1956             $assignmentssql = "SELECT a.id
1957                                  FROM {assignment} a
1958                                 WHERE a.course=? AND a.assignmenttype=?";
1959             $params = array($data->courseid, $this->type);
1961             // now get rid of all submissions and responses
1962             $fs = get_file_storage();
1963             if ($assignments = $DB->get_records_sql($assignmentssql, $params)) {
1964                 foreach ($assignments as $assignmentid=>$unused) {
1965                     if (!$cm = get_coursemodule_from_instance('assignment', $assignmentid)) {
1966                         continue;
1967                     }
1968                     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1969                     $fs->delete_area_files($context->id, 'mod_assignment', 'submission');
1970                     $fs->delete_area_files($context->id, 'mod_assignment', 'response');
1971                 }
1972             }
1974             $DB->delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)", $params);
1976             $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
1978             if (empty($data->reset_gradebook_grades)) {
1979                 // remove all grades from gradebook
1980                 assignment_reset_gradebook($data->courseid, $this->type);
1981             }
1982         }
1984         /// updating dates - shift may be negative too
1985         if ($data->timeshift) {
1986             shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
1987             $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
1988         }
1990         return $status;
1991     }
1994     function portfolio_exportable() {
1995         return false;
1996     }
1998     /**
1999      * base implementation for backing up subtype specific information
2000      * for one single module
2001      *
2002      * @param filehandle $bf file handle for xml file to write to
2003      * @param mixed $preferences the complete backup preference object
2004      *
2005      * @return boolean
2006      *
2007      * @static
2008      */
2009     static function backup_one_mod($bf, $preferences, $assignment) {
2010         return true;
2011     }
2013     /**
2014      * base implementation for backing up subtype specific information
2015      * for one single submission
2016      *
2017      * @param filehandle $bf file handle for xml file to write to
2018      * @param mixed $preferences the complete backup preference object
2019      * @param object $submission the assignment submission db record
2020      *
2021      * @return boolean
2022      *
2023      * @static
2024      */
2025     static function backup_one_submission($bf, $preferences, $assignment, $submission) {
2026         return true;
2027     }
2029     /**
2030      * base implementation for restoring subtype specific information
2031      * for one single module
2032      *
2033      * @param array  $info the array representing the xml
2034      * @param object $restore the restore preferences
2035      *
2036      * @return boolean
2037      *
2038      * @static
2039      */
2040     static function restore_one_mod($info, $restore, $assignment) {
2041         return true;
2042     }
2044     /**
2045      * base implementation for restoring subtype specific information
2046      * for one single submission
2047      *
2048      * @param object $submission the newly created submission
2049      * @param array  $info the array representing the xml
2050      * @param object $restore the restore preferences
2051      *
2052      * @return boolean
2053      *
2054      * @static
2055      */
2056     static function restore_one_submission($info, $restore, $assignment, $submission) {
2057         return true;
2058     }
2060 } ////// End of the assignment_base class
2063 class mod_assignment_grading_form extends moodleform { 
2065     function definition() {
2066         global $OUTPUT;
2067         $mform =& $this->_form;
2069         $formattr = $mform->getAttributes();
2070         $formattr['id'] = 'submitform';
2071         $mform->setAttributes($formattr);
2072         // hidden params
2073         $mform->addElement('hidden', 'offset', ($this->_customdata->offset+1));
2074         $mform->setType('offset', PARAM_INT);
2075         $mform->addElement('hidden', 'userid', $this->_customdata->userid);
2076         $mform->setType('userid', PARAM_INT);
2077         $mform->addElement('hidden', 'nextid', $this->_customdata->nextid);
2078         $mform->setType('nextid', PARAM_INT);
2079         $mform->addElement('hidden', 'id', $this->_customdata->cm->id);
2080         $mform->setType('id', PARAM_INT);
2081         $mform->addElement('hidden', 'sesskey', sesskey());
2082         $mform->setType('sesskey', PARAM_ALPHANUM);
2083         $mform->addElement('hidden', 'mode', 'grade');
2084         $mform->setType('mode', PARAM_INT);
2085         $mform->addElement('hidden', 'menuindex', "0");
2086         $mform->setType('menuindex', PARAM_INT);
2087         $mform->addElement('hidden', 'saveuserid', "-1");
2088         $mform->setType('saveuserid', PARAM_INT);
2090         $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->user),
2091                                                 fullname($this->_customdata->user, true) . '<br/>' .
2092                                                 userdate($this->_customdata->submission->timemodified) .
2093                                                 $this->_customdata->lateness );
2095         $this->add_grades_section();
2097         $this->add_feedback_section();
2099         if ($this->_customdata->submission->timemarked) {
2100             $mform->addElement('header', 'Last Grade', get_string('lastgrade', 'assignment'));
2101             $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->teacher) ,
2102                                                     fullname($this->_customdata->teacher,true).
2103                                                     '<br/>'.
2104                                                     userdate($this->_customdata->submission->timemarked));
2105         }
2106         // buttons
2107         $this->add_action_buttons();
2109         $this->add_submission_content();
2110     }
2112     function add_grades_section() {
2113         global $CFG;
2114         $mform =& $this->_form;
2115         $attributes = array();
2116         if ($this->_customdata->gradingdisabled) {
2117             $attributes['disabled'] ='disabled';
2118         }
2120         $grademenu = make_grades_menu($this->_customdata->assignment->grade);
2121         $grademenu['-1'] = get_string('nograde');
2123         $mform->addElement('header', 'Grades', get_string('grades', 'grades'));
2124         $mform->addElement('select', 'xgrade', get_string('grade').':', $grademenu, $attributes);
2125         $mform->setDefault('xgrade', $this->_customdata->submission->grade ); //@fixme some bug when element called 'grade' makes it break
2126         $mform->setType('xgrade', PARAM_INT);
2128         if (!empty($this->_customdata->enableoutcomes)) {
2129             foreach($this->_customdata->grading_info->outcomes as $n=>$outcome) {
2130                 $options = make_grades_menu(-$outcome->scaleid);
2131                 if ($outcome->grades[$this->_customdata->submission->userid]->locked) {
2132                     $options[0] = get_string('nooutcome', 'grades');
2133                     echo $options[$outcome->grades[$this->_customdata->submission->userid]->grade];
2134                 } else {
2135                     $options[''] = get_string('nooutcome', 'grades');
2136                     $attributes = array('id' => 'menuoutcome_'.$n );
2137                     $mform->addElement('select', 'outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->name.':', $options, $attributes );
2138                     $mform->setType('outcome_'.$n.'['.$this->_customdata->userid.']', PARAM_INT);
2139                     $mform->setDefault('outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->grades[$this->_customdata->submission->userid]->grade );
2140                 }
2141             }
2142         }
2143         $course_context = get_context_instance(CONTEXT_MODULE , $this->_customdata->cm->id);
2144         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
2145             $grade = '<a href="'.$CFG->wwwroot.'/grade/report/grader/index.php?id='. $this->_customdata->courseid .'" >'.
2146                         $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade . '</a>';
2147         }else{
2148             $grade = $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade;
2149         }
2150         $mform->addElement('static', 'finalgrade', get_string('currentgrade', 'assignment').':' ,$grade);
2151         $mform->setType('finalgrade', PARAM_INT);
2152     }
2154     /**
2155      *
2156      * @global core_renderer $OUTPUT
2157      */
2158     function add_feedback_section() {
2159         global $OUTPUT;
2160         $mform =& $this->_form;
2161         $mform->addElement('header', 'Feed Back', get_string('feedback', 'grades'));
2163         if ($this->_customdata->gradingdisabled) {
2164             $mform->addElement('static', 'disabledfeedback', $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_feedback );
2165         } else {
2166             // visible elements
2168             $mform->addElement('editor', 'submissioncomment_editor', get_string('feedback', 'assignment').':', null, $this->get_editor_options() );
2169             $mform->setType('submissioncomment_editor', PARAM_RAW); // to be cleaned before display
2170             $mform->setDefault('submissioncomment_editor', $this->_customdata->submission->submissioncomment);
2171             //$mform->addRule('submissioncomment', get_string('required'), 'required', null, 'client');
2173             if ($this->_customdata->usehtmleditor) {
2174                 $mform->addElement('hidden', 'format', FORMAT_HTML);
2175                 $mform->setType('format', PARAM_INT);
2176             } else {
2177                 //format menu
2178                 $format_menu = format_text_menu();
2179                 $mform->addElement('select', 'format', get_string('format'), $format_menu, array('selected' => $this->_customdata->submission->format ) );
2180                 $mform->setType('format', PARAM_INT);
2181             }
2182             $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? array('checked'=>'checked') : array();
2183             $mform->addElement('hidden', 'mailinfo_h', "0");
2184             $mform->setType('mailinfo_h', PARAM_INT);
2185             $mform->addElement('checkbox', 'mailinfo',get_string('enableemailnotification','assignment').
2186                     $OUTPUT->help_icon('enableemailnotification', 'assignment') .':' );
2187             $mform->updateElementAttr('mailinfo', $lastmailinfo);
2188             $mform->setType('mailinfo', PARAM_INT);
2189         }
2190     }
2192     function add_action_buttons() {
2193         $mform =& $this->_form;
2194         $mform->addElement('header', 'Operation', get_string('operation', 'assignment'));
2195         //if there are more to be graded.
2196         if ($this->_customdata->nextid>0) {
2197             $buttonarray=array();
2198             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2199             //@todo: fix accessibility: javascript dependency not necessary
2200             $buttonarray[] = &$mform->createElement('submit', 'saveandnext', get_string('saveandnext'));
2201             $buttonarray[] = &$mform->createElement('submit', 'next', get_string('next'));
2202             $buttonarray[] = &$mform->createElement('cancel');
2203         } else {
2204             $buttonarray=array();
2205             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2206             $buttonarray[] = &$mform->createElement('cancel');
2207         }
2208         $mform->addGroup($buttonarray, 'grading_buttonar', '', array(' '), false);
2209         $mform->setType('grading_buttonar', PARAM_RAW);
2210     }
2212     function add_submission_content() {
2213         $mform =& $this->_form;
2214         $mform->addElement('header', 'Submission', get_string('submission', 'assignment'));
2215         $mform->addElement('static', '', '' , $this->_customdata->submission_content );
2216     }
2218     protected function get_editor_options() {
2219         $editoroptions = array();
2220         $editoroptions['component'] = 'mod_assignment';
2221         $editoroptions['filearea'] = 'feedback';
2222         $editoroptions['noclean'] = false;
2223         $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)
2224         $editoroptions['maxbytes'] = $this->_customdata->maxbytes;
2225         return $editoroptions;
2226     }
2228     public function set_data($data) {
2229         $editoroptions = $this->get_editor_options();
2230         if (!isset($data->text)) {
2231             $data->text = '';
2232         }
2233         if (!isset($data->format)) {
2234             $data->textformat = FORMAT_HTML;
2235         } else {
2236             $data->textformat = $data->format;
2237         }
2239         if (!empty($this->_customdata->submission->id)) {
2240             $itemid = $this->_customdata->submission->id;
2241         } else {
2242             $itemid = null;
2243         }
2245         $data = file_prepare_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2246         return parent::set_data($data);
2247     }
2249     public function get_data() {
2250         $data = parent::get_data();
2252         if (!empty($this->_customdata->submission->id)) {
2253             $itemid = $this->_customdata->submission->id;
2254         } else {
2255             $itemid = null; //TODO: this is wrong, itemid MUST be known when saving files!! (skodak)
2256         }
2258         if ($data) {
2259             $editoroptions = $this->get_editor_options();
2260             $data = file_postupdate_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2261             $data->format = $data->textformat;
2262         }
2263         return $data;
2264     }
2267 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
2269 /**
2270  * Deletes an assignment instance
2271  *
2272  * This is done by calling the delete_instance() method of the assignment type class
2273  */
2274 function assignment_delete_instance($id){
2275     global $CFG, $DB;
2277     if (! $assignment = $DB->get_record('assignment', array('id'=>$id))) {
2278         return false;
2279     }
2281     // fall back to base class if plugin missing
2282     $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2283     if (file_exists($classfile)) {
2284         require_once($classfile);
2285         $assignmentclass = "assignment_$assignment->assignmenttype";
2287     } else {
2288         debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
2289         $assignmentclass = "assignment_base";
2290     }
2292     $ass = new $assignmentclass();
2293     return $ass->delete_instance($assignment);
2297 /**
2298  * Updates an assignment instance
2299  *
2300  * This is done by calling the update_instance() method of the assignment type class
2301  */
2302 function assignment_update_instance($assignment){
2303     global $CFG;
2305     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2307     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2308     $assignmentclass = "assignment_$assignment->assignmenttype";
2309     $ass = new $assignmentclass();
2310     return $ass->update_instance($assignment);
2314 /**
2315  * Adds an assignment instance
2316  *
2317  * This is done by calling the add_instance() method of the assignment type class
2318  */
2319 function assignment_add_instance($assignment) {
2320     global $CFG;
2322     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2324     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2325     $assignmentclass = "assignment_$assignment->assignmenttype";
2326     $ass = new $assignmentclass();
2327     return $ass->add_instance($assignment);
2331 /**
2332  * Returns an outline of a user interaction with an assignment
2333  *
2334  * This is done by calling the user_outline() method of the assignment type class
2335  */
2336 function assignment_user_outline($course, $user, $mod, $assignment) {
2337     global $CFG;
2339     require_once("$CFG->libdir/gradelib.php");
2340     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2341     $assignmentclass = "assignment_$assignment->assignmenttype";
2342     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2343     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2344     if (!empty($grades->items[0]->grades)) {
2345         return $ass->user_outline(reset($grades->items[0]->grades));
2346     } else {
2347         return null;
2348     }
2351 /**
2352  * Prints the complete info about a user's interaction with an assignment
2353  *
2354  * This is done by calling the user_complete() method of the assignment type class
2355  */
2356 function assignment_user_complete($course, $user, $mod, $assignment) {
2357     global $CFG;
2359     require_once("$CFG->libdir/gradelib.php");
2360     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2361     $assignmentclass = "assignment_$assignment->assignmenttype";
2362     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2363     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2364     if (empty($grades->items[0]->grades)) {
2365         $grade = false;
2366     } else {
2367         $grade = reset($grades->items[0]->grades);
2368     }
2369     return $ass->user_complete($user, $grade);
2372 /**
2373  * Function to be run periodically according to the moodle cron
2374  *
2375  * Finds all assignment notifications that have yet to be mailed out, and mails them
2376  */
2377 function assignment_cron () {
2378     global $CFG, $USER, $DB;
2380     /// first execute all crons in plugins
2381     if ($plugins = get_plugin_list('assignment')) {
2382         foreach ($plugins as $plugin=>$dir) {
2383             require_once("$dir/assignment.class.php");
2384             $assignmentclass = "assignment_$plugin";
2385             $ass = new $assignmentclass();
2386             $ass->cron();
2387         }
2388     }
2390     /// Notices older than 1 day will not be mailed.  This is to avoid the problem where
2391     /// cron has not been running for a long time, and then suddenly people are flooded
2392     /// with mail from the past few weeks or months
2394     $timenow   = time();
2395     $endtime   = $timenow - $CFG->maxeditingtime;
2396     $starttime = $endtime - 24 * 3600;   /// One day earlier
2398     if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2400         $realuser = clone($USER);
2402         foreach ($submissions as $key => $submission) {
2403             if (! $DB->set_field("assignment_submissions", "mailed", "1", array("id"=>$submission->id))) {
2404                 echo "Could not update the mailed field for id $submission->id.  Not mailed.\n";
2405                 unset($submissions[$key]);
2406             }
2407         }
2409         $timenow = time();
2411         foreach ($submissions as $submission) {
2413             echo "Processing assignment submission $submission->id\n";
2415             if (! $user = $DB->get_record("user", array("id"=>$submission->userid))) {
2416                 echo "Could not find user $post->userid\n";
2417                 continue;
2418             }
2420             if (! $course = $DB->get_record("course", array("id"=>$submission->course))) {
2421                 echo "Could not find course $submission->course\n";
2422                 continue;
2423             }
2425             /// Override the language and timezone of the "current" user, so that
2426             /// mail is customised for the receiver.
2427             cron_setup_user($user, $course);
2429             if (!is_enrolled(get_context_instance(CONTEXT_COURSE, $submission->course), $user->id)) {
2430                 echo fullname($user)." not an active participant in " . format_string($course->shortname) . "\n";
2431                 continue;
2432             }
2434             if (! $teacher = $DB->get_record("user", array("id"=>$submission->teacher))) {
2435                 echo "Could not find teacher $submission->teacher\n";
2436                 continue;
2437             }
2439             if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2440                 echo "Could not find course module for assignment id $submission->assignment\n";
2441                 continue;
2442             }
2444             if (! $mod->visible) {    /// Hold mail notification for hidden assignments until later
2445                 continue;
2446             }
2448             $strassignments = get_string("modulenameplural", "assignment");
2449             $strassignment  = get_string("modulename", "assignment");
2451             $assignmentinfo = new object();
2452             $assignmentinfo->teacher = fullname($teacher);
2453             $assignmentinfo->assignment = format_string($submission->name,true);
2454             $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2456             $postsubject = "$course->shortname: $strassignments: ".format_string($submission->name,true);
2457             $posttext  = "$course->shortname -> $strassignments -> ".format_string($submission->name,true)."\n";
2458             $posttext .= "---------------------------------------------------------------------\n";
2459             $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2460             $posttext .= "---------------------------------------------------------------------\n";
2462             if ($user->mailformat == 1) {  // HTML
2463                 $posthtml = "<p><font face=\"sans-serif\">".
2464                 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> ->".
2465                 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2466                 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2467                 $posthtml .= "<hr /><font face=\"sans-serif\">";
2468                 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2469                 $posthtml .= "</font><hr />";
2470             } else {
2471                 $posthtml = "";
2472             }
2474             $eventdata = new object();
2475             $eventdata->modulename       = 'assignment';
2476             $eventdata->userfrom         = $teacher;
2477             $eventdata->userto           = $user;
2478             $eventdata->subject          = $postsubject;
2479             $eventdata->fullmessage      = $posttext;
2480             $eventdata->fullmessageformat = FORMAT_PLAIN;
2481             $eventdata->fullmessagehtml  = $posthtml;
2482             $eventdata->smallmessage     = '';
2483             message_send($eventdata);
2484         }
2486         cron_setup_user();
2487     }
2489     return true;
2492 /**
2493  * Return grade for given user or all users.
2494  *
2495  * @param int $assignmentid id of assignment
2496  * @param int $userid optional user id, 0 means all users
2497  * @return array array of grades, false if none
2498  */
2499 function assignment_get_user_grades($assignment, $userid=0) {
2500     global $CFG, $DB;
2502     if ($userid) {
2503         $user = "AND u.id = :userid";
2504         $params = array('userid'=>$userid);
2505     } else {
2506         $user = "";
2507     }
2508     $params['aid'] = $assignment->id;
2510     $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2511                    s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2512               FROM {user} u, {assignment_submissions} s
2513              WHERE u.id = s.userid AND s.assignment = :aid
2514                    $user";
2516     return $DB->get_records_sql($sql, $params);
2519 /**
2520  * Update activity grades
2521  *
2522  * @param object $assignment
2523  * @param int $userid specific user only, 0 means all
2524  */
2525 function assignment_update_grades($assignment, $userid=0, $nullifnone=true) {
2526     global $CFG, $DB;
2527     require_once($CFG->libdir.'/gradelib.php');
2529     if ($assignment->grade == 0) {
2530         assignment_grade_item_update($assignment);
2532     } else if ($grades = assignment_get_user_grades($assignment, $userid)) {
2533         foreach($grades as $k=>$v) {
2534             if ($v->rawgrade == -1) {
2535                 $grades[$k]->rawgrade = null;
2536             }
2537         }
2538         assignment_grade_item_update($assignment, $grades);
2540     } else {
2541         assignment_grade_item_update($assignment);
2542     }
2545 /**
2546  * Update all grades in gradebook.
2547  */
2548 function assignment_upgrade_grades() {
2549     global $DB;
2551     $sql = "SELECT COUNT('x')
2552               FROM {assignment} a, {course_modules} cm, {modules} m
2553              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2554     $count = $DB->count_records_sql($sql);
2556     $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
2557               FROM {assignment} a, {course_modules} cm, {modules} m
2558              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2559     if ($rs = $DB->get_recordset_sql($sql)) {
2560         // too much debug output
2561         $pbar = new progress_bar('assignmentupgradegrades', 500, true);
2562         $i=0;
2563         foreach ($rs as $assignment) {
2564             $i++;
2565             upgrade_set_timeout(60*5); // set up timeout, may also abort execution
2566             assignment_update_grades($assignment);
2567             $pbar->update($i, $count, "Updating Assignment grades ($i/$count).");
2568         }
2569         $rs->close();
2570         upgrade_set_timeout(); // reset to default timeout
2571     }
2574 /**
2575  * Create grade item for given assignment
2576  *
2577  * @param object $assignment object with extra cmidnumber
2578  * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
2579  * @return int 0 if ok, error code otherwise
2580  */
2581 function assignment_grade_item_update($assignment, $grades=NULL) {
2582     global $CFG;
2583     require_once($CFG->libdir.'/gradelib.php');
2585     if (!isset($assignment->courseid)) {
2586         $assignment->courseid = $assignment->course;
2587     }
2589     $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
2591     if ($assignment->grade > 0) {
2592         $params['gradetype'] = GRADE_TYPE_VALUE;
2593         $params['grademax']  = $assignment->grade;
2594         $params['grademin']  = 0;
2596     } else if ($assignment->grade < 0) {
2597         $params['gradetype'] = GRADE_TYPE_SCALE;
2598         $params['scaleid']   = -$assignment->grade;
2600     } else {
2601         $params['gradetype'] = GRADE_TYPE_TEXT; // allow text comments only
2602     }
2604     if ($grades  === 'reset') {
2605         $params['reset'] = true;
2606         $grades = NULL;
2607     }
2609     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades, $params);
2612 /**
2613  * Delete grade item for given assignment
2614  *
2615  * @param object $assignment object
2616  * @return object assignment
2617  */
2618 function assignment_grade_item_delete($assignment) {
2619     global $CFG;
2620     require_once($CFG->libdir.'/gradelib.php');
2622     if (!isset($assignment->courseid)) {
2623         $assignment->courseid = $assignment->course;
2624     }
2626     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
2629 /**
2630  * Returns the users with data in one assignment (students and teachers)
2631  *
2632  * @param $assignmentid int
2633  * @return array of user objects
2634  */
2635 function assignment_get_participants($assignmentid) {
2636     global $CFG, $DB;
2638     //Get students
2639     $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2640                                         FROM {user} u,
2641                                              {assignment_submissions} a
2642                                        WHERE a.assignment = ? and
2643                                              u.id = a.userid", array($assignmentid));
2644     //Get teachers
2645     $teachers = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2646                                         FROM {user} u,
2647                                              {assignment_submissions} a
2648                                        WHERE a.assignment = ? and
2649                                              u.id = a.teacher", array($assignmentid));
2651     //Add teachers to students
2652     if ($teachers) {
2653         foreach ($teachers as $teacher) {
2654             $students[$teacher->id] = $teacher;
2655         }
2656     }
2657     //Return students array (it contains an array of unique users)
2658     return ($students);
2661 /**
2662  * Serves assignment submissions and other files.
2663  *
2664  * @param object $course
2665  * @param object $cm
2666  * @param object $context
2667  * @param string $filearea
2668  * @param array $args
2669  * @param bool $forcedownload
2670  * @return bool false if file not found, does not return if found - just send the file
2671  */
2672 function assignment_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) {
2673     global $CFG, $DB;
2675     if ($context->contextlevel != CONTEXT_MODULE) {
2676         return false;
2677     }
2679     require_login($course, false, $cm);
2681     if (!$assignment = $DB->get_record('assignment', array('id'=>$cm->instance))) {
2682         return false;
2683     }
2685     require_once($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
2686     $assignmentclass = 'assignment_'.$assignment->assignmenttype;
2687     $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm, $course);
2689     return $assignmentinstance->send_file($filearea, $args);
2691 /**
2692  * Checks if a scale is being used by an assignment
2693  *
2694  * This is used by the backup code to decide whether to back up a scale
2695  * @param $assignmentid int
2696  * @param $scaleid int
2697  * @return boolean True if the scale is used by the assignment
2698  */
2699 function assignment_scale_used($assignmentid, $scaleid) {
2700     global $DB;
2702     $return = false;
2704     $rec = $DB->get_record('assignment', array('id'=>$assignmentid,'grade'=>-$scaleid));
2706     if (!empty($rec) && !empty($scaleid)) {
2707         $return = true;
2708     }
2710     return $return;
2713 /**
2714  * Checks if scale is being used by any instance of assignment
2715  *
2716  * This is used to find out if scale used anywhere
2717  * @param $scaleid int
2718  * @return boolean True if the scale is used by any assignment
2719  */
2720 function assignment_scale_used_anywhere($scaleid) {
2721     global $DB;
2723     if ($scaleid and $DB->record_exists('assignment', array('grade'=>-$scaleid))) {
2724         return true;
2725     } else {
2726         return false;
2727     }
2730 /**
2731  * Make sure up-to-date events are created for all assignment instances
2732  *
2733  * This standard function will check all instances of this module
2734  * and make sure there are up-to-date events created for each of them.
2735  * If courseid = 0, then every assignment event in the site is checked, else
2736  * only assignment events belonging to the course specified are checked.
2737  * This function is used, in its new format, by restore_refresh_events()
2738  *
2739  * @param $courseid int optional If zero then all assignments for all courses are covered
2740  * @return boolean Always returns true
2741  */
2742 function assignment_refresh_events($courseid = 0) {
2743     global $DB;
2745     if ($courseid == 0) {
2746         if (! $assignments = $DB->get_records("assignment")) {
2747             return true;
2748         }
2749     } else {
2750         if (! $assignments = $DB->get_records("assignment", array("course"=>$courseid))) {
2751             return true;
2752         }
2753     }
2754     $moduleid = $DB->get_field('modules', 'id', array('name'=>'assignment'));
2756     foreach ($assignments as $assignment) {
2757         $cm = get_coursemodule_from_id('assignment', $assignment->id);
2758         $event = new object();
2759         $event->name        = $assignment->name;
2760         $event->description = format_module_intro('assignment', $assignment, $cm->id);
2761         $event->timestart   = $assignment->timedue;
2763         if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
2764             update_event($event);
2766         } else {
2767             $event->courseid    = $assignment->course;
2768             $event->groupid     = 0;
2769             $event->userid      = 0;
2770             $event->modulename  = 'assignment';
2771             $event->instance    = $assignment->id;
2772             $event->eventtype   = 'due';
2773             $event->timeduration = 0;
2774             $event->visible     = $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$assignment->id));
2775             add_event($event);
2776         }
2778     }
2779     return true;
2782 /**
2783  * Print recent activity from all assignments in a given course
2784  *
2785  * This is used by the recent activity block
2786  */
2787 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
2788     global $CFG, $USER, $DB, $OUTPUT;
2790     // do not use log table if possible, it may be huge
2792     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
2793                                                      u.firstname, u.lastname, u.email, u.picture
2794                                                 FROM {assignment_submissions} asb
2795                                                      JOIN {assignment} a      ON a.id = asb.assignment
2796                                                      JOIN {course_modules} cm ON cm.instance = a.id
2797                                                      JOIN {modules} md        ON md.id = cm.module
2798                                                      JOIN {user} u            ON u.id = asb.userid
2799                                                WHERE asb.timemodified > ? AND
2800                                                      a.course = ? AND
2801                                                      md.name = 'assignment'
2802                                             ORDER BY asb.timemodified ASC", array($timestart, $course->id))) {
2803          return false;
2804     }
2806     $modinfo =& get_fast_modinfo($course); // reference needed because we might load the groups
2807     $show    = array();
2808     $grader  = array();
2810     foreach($submissions as $submission) {
2811         if (!array_key_exists($submission->cmid, $modinfo->cms)) {
2812             continue;
2813         }
2814         $cm = $modinfo->cms[$submission->cmid];
2815         if (!$cm->uservisible) {
2816             continue;
2817         }
2818         if ($submission->userid == $USER->id) {
2819             $show[] = $submission;
2820             continue;
2821         }
2823         // the act of sumbitting of assignment may be considered private - only graders will see it if specified
2824         if (empty($CFG->assignment_showrecentsubmissions)) {
2825             if (!array_key_exists($cm->id, $grader)) {
2826                 $grader[$cm->id] = has_capability('moodle/grade:viewall', get_context_instance(CONTEXT_MODULE, $cm->id));
2827             }
2828             if (!$grader[$cm->id]) {
2829                 continue;
2830             }
2831         }
2833         $groupmode = groups_get_activity_groupmode($cm, $course);
2835         if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2836             if (isguestuser()) {
2837                 // shortcut - guest user does not belong into any group
2838                 continue;
2839             }
2841             if (is_null($modinfo->groups)) {
2842                 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2843             }
2845             // this will be slow - show only users that share group with me in this cm
2846             if (empty($modinfo->groups[$cm->id])) {
2847                 continue;
2848             }
2849             $usersgroups =  groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
2850             if (is_array($usersgroups)) {
2851                 $usersgroups = array_keys($usersgroups);
2852                 $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2853                 if (empty($intersect)) {
2854                     continue;
2855                 }
2856             }
2857         }
2858         $show[] = $submission;
2859     }
2861     if (empty($show)) {
2862         return false;
2863     }
2865     echo $OUTPUT->heading(get_string('newsubmissions', 'assignment').':', 3);
2867     foreach ($show as $submission) {
2868         $cm = $modinfo->cms[$submission->cmid];
2869         $link = $CFG->wwwroot.'/mod/assignment/view.php?id='.$cm->id;
2870         print_recent_activity_note($submission->timemodified, $submission, $cm->name, $link, false, $viewfullnames);
2871     }
2873     return true;
2877 /**
2878  * Returns all assignments since a given time in specified forum.
2879  */
2880 function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0)  {
2881     global $CFG, $COURSE, $USER, $DB;
2883     if ($COURSE->id == $courseid) {
2884         $course = $COURSE;
2885     } else {
2886         $course = $DB->get_record('course', array('id'=>$courseid));
2887     }
2889     $modinfo =& get_fast_modinfo($course);
2891     $cm = $modinfo->cms[$cmid];
2893     $params = array();
2894     if ($userid) {
2895         $userselect = "AND u.id = :userid";
2896         $params['userid'] = $userid;
2897     } else {
2898         $userselect = "";
2899     }
2901     if ($groupid) {
2902         $groupselect = "AND gm.groupid = :groupid";
2903         $groupjoin   = "JOIN {groups_members} gm ON  gm.userid=u.id";
2904         $params['groupid'] = $groupid;
2905     } else {
2906         $groupselect = "";
2907         $groupjoin   = "";
2908     }
2910     $params['cminstance'] = $cm->instance;
2911     $params['timestart'] = $timestart;
2913     $userfields = user_picture::fields('u', null, 'userid');
2915     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified,
2916                                                      $userfields
2917                                                 FROM {assignment_submissions} asb
2918                                                 JOIN {assignment} a      ON a.id = asb.assignment
2919                                                 JOIN {user} u            ON u.id = asb.userid
2920                                           $groupjoin
2921                                                WHERE asb.timemodified > :timestart AND a.id = :cminstance
2922                                                      $userselect $groupselect
2923                                             ORDER BY asb.timemodified ASC", $params)) {
2924          return;
2925     }
2927     $groupmode       = groups_get_activity_groupmode($cm, $course);
2928     $cm_context      = get_context_instance(CONTEXT_MODULE, $cm->id);
2929     $grader          = has_capability('moodle/grade:viewall', $cm_context);
2930     $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
2931     $viewfullnames   = has_capability('moodle/site:viewfullnames', $cm_context);
2933     if (is_null($modinfo->groups)) {
2934         $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2935     }
2937     $show = array();
2939     foreach($submissions as $submission) {
2940         if ($submission->userid == $USER->id) {
2941             $show[] = $submission;
2942             continue;
2943         }
2944         // the act of submitting of assignment may be considered private - only graders will see it if specified
2945         if (empty($CFG->assignment_showrecentsubmissions)) {
2946             if (!$grader) {
2947                 continue;
2948             }
2949         }
2951         if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
2952             if (isguestuser()) {
2953                 // shortcut - guest user does not belong into any group
2954                 continue;
2955             }
2957             // this will be slow - show only users that share group with me in this cm
2958             if (empty($modinfo->groups[$cm->id])) {
2959                 continue;
2960             }
2961             $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
2962             if (is_array($usersgroups)) {
2963                 $usersgroups = array_keys($usersgroups);
2964                 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2965                 if (empty($intersect)) {
2966                     continue;
2967                 }
2968             }
2969         }
2970         $show[] = $submission;
2971     }
2973     if (empty($show)) {
2974         return;
2975     }
2977     if ($grader) {
2978         require_once($CFG->libdir.'/gradelib.php');
2979         $userids = array();
2980         foreach ($show as $id=>$submission) {
2981             $userids[] = $submission->userid;
2983         }
2984         $grades = grade_get_grades($courseid, 'mod', 'assignment', $cm->instance, $userids);
2985     }
2987     $aname = format_string($cm->name,true);
2988     foreach ($show as $submission) {
2989         $tmpactivity = new object();
2991         $tmpactivity->type         = 'assignment';
2992         $tmpactivity->cmid         = $cm->id;
2993         $tmpactivity->name         = $aname;
2994         $tmpactivity->sectionnum   = $cm->sectionnum;
2995         $tmpactivity->timestamp    = $submission->timemodified;
2997         if ($grader) {
2998             $tmpactivity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
2999         }
3001         $userfields = explode(',', user_picture::fields());
3002         foreach ($userfields as $userfield) {
3003             if ($userfield == 'id') {
3004                 $tmpactivity->user->{$userfield} = $submission->userid; // aliased in SQL above
3005             } else {
3006                 $tmpactivity->user->{$userfield} = $submission->{$userfield};
3007             }
3008         }
3009         $tmpactivity->user->fullname = fullname($submission, $viewfullnames);
3011         $activities[$index++] = $tmpactivity;
3012     }
3014     return;
3017 /**
3018  * Print recent activity from all assignments in a given course
3019  *
3020  * This is used by course/recent.php
3021  */
3022 function assignment_print_recent_mod_activity($activity, $courseid, $detail, $modnames)  {
3023     global $CFG, $OUTPUT;
3025     echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
3027     echo "<tr><td class=\"userpicture\" valign=\"top\">";
3028     echo $OUTPUT->user_picture($activity->user);
3029     echo "</td><td>";
3031     if ($detail) {
3032         $modname = $modnames[$activity->type];
3033         echo '<div class="title">';
3034         echo "<img src=\"" . $OUTPUT->pix_url('icon', 'assignment') . "\" ".
3035              "class=\"icon\" alt=\"$modname\">";
3036         echo "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id={$activity->cmid}\">{$activity->name}</a>";
3037         echo '</div>';
3038     }
3040     if (isset($activity->grade)) {
3041         echo '<div class="grade">';
3042         echo get_string('grade').': ';
3043         echo $activity->grade;
3044         echo '</div>';
3045     }
3047     echo '<div class="user">';
3048     echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->id}&amp;course=$courseid\">"
3049          ."{$activity->user->fullname}</a>  - ".userdate($activity->timestamp);
3050     echo '</div>';
3052     echo "</td></tr></table>";
3055 /// GENERIC SQL FUNCTIONS
3057 /**
3058  * Fetch info from logs
3059  *
3060  * @param $log object with properties ->info (the assignment id) and ->userid
3061  * @return array with assignment name and user firstname and lastname
3062  */
3063 function assignment_log_info($log) {
3064     global $CFG, $DB;
3066     return $DB->get_record_sql("SELECT a.name, u.firstname, u.lastname
3067                                   FROM {assignment} a, {user} u
3068                                  WHERE a.id = ? AND u.id = ?", array($log->info, $log->userid));
3071 /**
3072  * Return list of marked submissions that have not been mailed out for currently enrolled students
3073  *
3074  * @return array
3075  */
3076 function assignment_get_unmailed_submissions($starttime, $endtime) {
3077     global $CFG, $DB;
3079     return $DB->get_records_sql("SELECT s.*, a.course, a.name
3080                                    FROM {assignment_submissions} s,
3081                                         {assignment} a
3082                                   WHERE s.mailed = 0
3083                                         AND s.timemarked <= ?
3084                                         AND s.timemarked >= ?
3085                                         AND s.assignment = a.id", array($endtime, $starttime));
3088 /**
3089  * Counts all real assignment submissions by ENROLLED students (not empty ones)
3090  *
3091  * There are also assignment type methods count_real_submissions() wich in the default
3092  * implementation simply call this function.
3093  * @param $groupid int optional If nonzero then count is restricted to this group
3094  * @return int The number of submissions
3095  */
3096 function assignment_count_real_submissions($cm, $groupid=0) {
3097     global $CFG, $DB;
3099     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
3101     // this is all the users with this capability set, in this context or higher
3102     if ($users = get_enrolled_users($context, 'mod/assignment:submit', $groupid, 'u.id')) {
3103         $users = array_keys($users);
3104     }
3106     // if groupmembersonly used, remove users who are not in any group
3107     if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
3108         if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
3109             $users = array_intersect($users, array_keys($groupingusers));
3110         }
3111     }
3113     if (empty($users)) {
3114         return 0;
3115     }
3117     $userlists = implode(',', $users);
3119     return $DB->count_records_sql("SELECT COUNT('x')
3120                                      FROM {assignment_submissions}
3121                                     WHERE assignment = ? AND
3122                                           timemodified > 0 AND
3123                                           userid IN ($userlists)", array($cm->instance));
3127 /**
3128  * Return all assignment submissions by ENROLLED students (even empty)
3129  *
3130  * There are also assignment type methods get_submissions() wich in the default
3131  * implementation simply call this function.
3132  * @param $sort string optional field names for the ORDER BY in the sql query
3133  * @param $dir string optional specifying the sort direction, defaults to DESC
3134  * @return array The submission objects indexed by id
3135  */
3136 function assignment_get_all_submissions($assignment, $sort="", $dir="DESC") {
3137 /// Return all assignment submissions by ENROLLED students (even empty)
3138     global $CFG, $DB;
3140     if ($sort == "lastname" or $sort == "firstname") {
3141         $sort = "u.$sort $dir";
3142     } else if (empty($sort)) {
3143         $sort = "a.timemodified DESC";
3144     } else {
3145         $sort = "a.$sort $dir";
3146     }
3148     /* not sure this is needed at all since assignmenet already has a course define, so this join?
3149     $select = "s.course = '$assignment->course' AND";
3150     if ($assignment->course == SITEID) {
3151         $select = '';
3152     }*/
3154     return $DB->get_records_sql("SELECT a.*
3155                                    FROM {assignment_submissions} a, {user} u
3156                                   WHERE u.id = a.userid
3157                                         AND a.assignment = ?
3158                                ORDER BY $sort", array($assignment->id));
3162 /**
3163  * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
3164  * for the course (see resource).
3165  *
3166  * Given a course_module object, this function returns any "extra" information that may be needed
3167  * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
3168  *
3169  * @param $coursemodule object The coursemodule object (record).
3170  * @return object An object on information that the coures will know about (most noticeably, an icon).
3171  *
3172  */
3173 function assignment_get_coursemodule_info($coursemodule) {
3174     global $CFG, $DB;
3176     if (! $assignment = $DB->get_record('assignment', array('id'=>$coursemodule->instance), 'id, assignmenttype, name')) {
3177         return false;
3178     }
3180     $libfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
3182     if (file_exists($libfile)) {
3183         require_once($libfile);
3184         $assignmentclass = "assignment_$assignment->assignmenttype";
3185         $ass = new $assignmentclass('staticonly');
3186         if ($result = $ass->get_coursemodule_info($coursemodule)) {
3187             return $result;
3188         } else {
3189             $info = new object();
3190             $info->name = $assignment->name;
3191             return $info;
3192         }
3194     } else {
3195         debugging('Incorrect assignment type: '.$assignment->assignmenttype);
3196         return false;
3197     }
3202 /// OTHER GENERAL FUNCTIONS FOR ASSIGNMENTS  ///////////////////////////////////////
3204 /**
3205  * Returns an array of installed assignment types indexed and sorted by name
3206  *
3207  * @return array The index is the name of the assignment type, the value its full name from the language strings
3208  */
3209 function assignment_types() {
3210     $types = array();
3211     $names = get_plugin_list('assignment');
3212     foreach ($names as $name=>$dir) {
3213         $types[$name] = get_string('type'.$name, 'assignment');
3215         // ugly hack to support pluggable assignment type titles..
3216         if ($types[$name] == '[[type'.$name.']]') {
3217             $types[$name] = get_string('type'.$name, 'assignment_'.$name);
3218         }
3219     }
3220     asort($types);
3221     return $types;
3224 function assignment_print_overview($courses, &$htmlarray) {
3225     global $USER, $CFG, $DB;
3227     if (empty($courses) || !is_array($courses) || count($courses) == 0) {
3228         return array();
3229     }
3231     if (!$assignments = get_all_instances_in_courses('assignment',$courses)) {
3232         return;
3233     }
3235     $assignmentids = array();
3237     // Do assignment_base::isopen() here without loading the whole thing for speed
3238     foreach ($assignments as $key => $assignment) {
3239         $time = time();
3240         if ($assignment->timedue) {
3241             if ($assignment->preventlate) {
3242                 $isopen = ($assignment->timeavailable <= $time && $time <= $assignment->timedue);
3243             } else {
3244                 $isopen = ($assignment->timeavailable <= $time);
3245             }
3246         }
3247         if (empty($isopen) || empty($assignment->timedue)) {
3248             unset($assignments[$key]);
3249         } else {
3250             $assignmentids[] = $assignment->id;
3251         }
3252     }
3254     if (empty($assignmentids)){
3255         // no assigments to look at - we're done
3256         return true;
3257     }
3259     $strduedate = get_string('duedate', 'assignment');
3260     $strduedateno = get_string('duedateno', 'assignment');
3261     $strgraded = get_string('graded', 'assignment');
3262     $strnotgradedyet = get_string('notgradedyet', 'assignment');
3263     $strnotsubmittedyet = get_string('notsubmittedyet', 'assignment');
3264     $strsubmitted = get_string('submitted', 'assignment');
3265     $strassignment = get_string('modulename', 'assignment');
3266     $strreviewed = get_string('reviewed','assignment');
3269     // NOTE: we do all possible database work here *outside* of the loop to ensure this scales
3270     //
3271     list($sqlassignmentids, $assignmentidparams) = $DB->get_in_or_equal($assignmentids);
3273     // build up and array of unmarked submissions indexed by assigment id/ userid
3274     // for use where the user has grading rights on assigment
3275     $rs = $DB->get_recordset_sql("SELECT id, assignment, userid
3276                             FROM {assignment_submissions}
3277                             WHERE teacher = 0 AND timemarked = 0
3278                             AND assignment $sqlassignmentids", $assignmentidparams);
3280     $unmarkedsubmissions = array();
3281     foreach ($rs as $rd) {
3282         $unmarkedsubmissions[$rd->assignment][$rd->userid] = $rd->id;
3283     }
3284     $rs->close();
3287     // get all user submissions, indexed by assigment id
3288     $mysubmissions = $DB->get_records_sql("SELECT assignment, timemarked, teacher, grade
3289                                       FROM {assignment_submissions}
3290                                       WHERE userid = ? AND
3291                                       assignment $sqlassignmentids", array_merge(array($USER->id), $assignmentidparams));
3293     foreach ($assignments as $assignment) {
3294         $str = '<div class="assignment overview"><div class="name">'.$strassignment. ': '.
3295                '<a '.($assignment->visible ? '':' class="dimmed"').
3296                'title="'.$strassignment.'" href="'.$CFG->wwwroot.
3297                '/mod/assignment/view.php?id='.$assignment->coursemodule.'">'.
3298                $assignment->name.'</a></div>';
3299         if ($assignment->timedue) {
3300             $str .= '<div class="info">'.$strduedate.': '.userdate($assignment->timedue).'</div>';
3301         } else {
3302             $str .= '<div class="info">'.$strduedateno.'</div>';
3303         }
3304         $context = get_context_instance(CONTEXT_MODULE, $assignment->coursemodule);
3305         if (has_capability('mod/assignment:grade', $context)) {
3307             // count how many people can submit
3308             $submissions = 0; // init
3309             if ($students = get_enrolled_users($context, 'mod/assignment:submit', 0, 'u.id')) {
3310                 foreach ($students as $student) {
3311                     if (isset($unmarkedsubmissions[$assignment->id][$student->id])) {
3312                         $submissions++;
3313                     }
3314                 }
3315             }
3317             if ($submissions) {
3318                 $link = new moodle_url('/mod/assignment/submissions.php', array('id'=>$assignment->coursemodule));
3319                 $str .= '<div class="details"><a href="'.$link.'">'.get_string('submissionsnotgraded', 'assignment', $submissions).'</a></div>';
3320             }
3321         } else {
3322             $str .= '<div class="details">';
3323             if (isset($mysubmissions[$assignment->id])) {
3325                 $submission = $mysubmissions[$assignment->id];
3327                 if ($submission->teacher == 0 && $submission->timemarked == 0) {
3328                     $str .= $strsubmitted . ', ' . $strnotgradedyet;
3329                 } else if ($submission->grade <= 0) {
3330                     $str .= $strsubmitted . ', ' . $strreviewed;
3331                 } else {
3332                     $str .= $strsubmitted . ', ' . $strgraded;
3333                 }
3334             } else {
3335                 $str .= $strnotsubmittedyet . ' ' . assignment_display_lateness(time(), $assignment->timedue);
3336             }
3337             $str .= '</div>';
3338         }
3339         $str .= '</div>';
3340         if (empty($htmlarray[$assignment->course]['assignment'])) {
3341             $htmlarray[$assignment->course]['assignment'] = $str;
3342         } else {
3343             $htmlarray[$assignment->course]['assignment'] .= $str;
3344         }
3345     }
3348 function assignment_display_lateness($timesubmitted, $timedue) {
3349     if (!$timedue) {
3350         return '';
3351     }
3352     $time = $timedue - $timesubmitted;
3353     if ($time < 0) {
3354         $timetext = get_string('late', 'assignment', format_time($time));
3355         return ' (<span class="late">'.$timetext.'</span>)';
3356     } else {
3357         $timetext = get_string('early', 'assignment', format_time($time));
3358         return ' (<span class="early">'.$timetext.'</span>)';
3359     }
3362 function assignment_get_view_actions() {
3363     return array('view');
3366 function assignment_get_post_actions() {
3367     return array('upload');
3370 function assignment_get_types() {
3371     global $CFG;
3372     $types = array();
3374     $type = new object();
3375     $type->modclass = MOD_CLASS_ACTIVITY;
3376     $type->type = "assignment_group_start";
3377     $type->typestr = '--'.get_string('modulenameplural', 'assignment');
3378     $types[] = $type;
3380     $standardassignments = array('upload','online','uploadsingle','offline');
3381     foreach ($standardassignments as $assignmenttype) {
3382         $type = new object();
3383         $type->modclass = MOD_CLASS_ACTIVITY;
3384         $type->type = "assignment&amp;type=$assignmenttype";
3385         $type->typestr = get_string("type$assignmenttype", 'assignment');
3386         $types[] = $type;
3387     }
3389     /// Drop-in extra assignment types
3390