eed4da006561faaa752934eb9859a697bb5a6f0a
[moodle.git] / mod / assignment / lib.php
1 <?PHP
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
18 /**
19  * assignment_base is the base class for assignment types
20  *
21  * This class provides all the functionality for an assignment
22  *
23  * @package   mod-assignment
24  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
25  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26  */
28 /** Include eventslib.php */
29 require_once($CFG->libdir.'/eventslib.php');
30 /** Include formslib.php */
31 require_once($CFG->libdir.'/formslib.php');
32 /** Include calendar/lib.php */
33 require_once($CFG->dirroot.'/calendar/lib.php');
35 /** ASSIGNMENT_COUNT_WORDS = 1 */
36 define('ASSIGNMENT_COUNT_WORDS', 1);
37 /** ASSIGNMENT_COUNT_LETTERS = 2 */
38 define('ASSIGNMENT_COUNT_LETTERS', 2);
40 /**
41  * Standard base class for all assignment submodules (assignment types).
42  *
43  * @package   mod-assignment
44  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
45  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
46  */
47 class assignment_base {
49     const FILTER_ALL             = 0;
50     const FILTER_SUBMITTED       = 1;
51     const FILTER_REQUIRE_GRADING = 2;
53     /** @var object */
54     var $cm;
55     /** @var object */
56     var $course;
57     /** @var object */
58     var $assignment;
59     /** @var string */
60     var $strassignment;
61     /** @var string */
62     var $strassignments;
63     /** @var string */
64     var $strsubmissions;
65     /** @var string */
66     var $strlastmodified;
67     /** @var string */
68     var $pagetitle;
69     /** @var bool */
70     var $usehtmleditor;
71     /**
72      * @todo document this var
73      */
74     var $defaultformat;
75     /**
76      * @todo document this var
77      */
78     var $context;
79     /** @var string */
80     var $type;
82     /**
83      * Constructor for the base assignment class
84      *
85      * Constructor for the base assignment class.
86      * If cmid is set create the cm, course, assignment objects.
87      * If the assignment is hidden and the user is not a teacher then
88      * this prints a page header and notice.
89      *
90      * @global object
91      * @global object
92      * @param int $cmid the current course module id - not set for new assignments
93      * @param object $assignment usually null, but if we have it we pass it to save db access
94      * @param object $cm usually null, but if we have it we pass it to save db access
95      * @param object $course usually null, but if we have it we pass it to save db access
96      */
97     function assignment_base($cmid='staticonly', $assignment=NULL, $cm=NULL, $course=NULL) {
98         global $COURSE, $DB;
100         if ($cmid == 'staticonly') {
101             //use static functions only!
102             return;
103         }
105         global $CFG;
107         if ($cm) {
108             $this->cm = $cm;
109         } else if (! $this->cm = get_coursemodule_from_id('assignment', $cmid)) {
110             print_error('invalidcoursemodule');
111         }
113         $this->context = get_context_instance(CONTEXT_MODULE, $this->cm->id);
115         if ($course) {
116             $this->course = $course;
117         } else if ($this->cm->course == $COURSE->id) {
118             $this->course = $COURSE;
119         } else if (! $this->course = $DB->get_record('course', array('id'=>$this->cm->course))) {
120             print_error('invalidid', 'assignment');
121         }
123         if ($assignment) {
124             $this->assignment = $assignment;
125         } else if (! $this->assignment = $DB->get_record('assignment', array('id'=>$this->cm->instance))) {
126             print_error('invalidid', 'assignment');
127         }
129         $this->assignment->cmidnumber = $this->cm->idnumber; // compatibility with modedit assignment obj
130         $this->assignment->courseid   = $this->course->id; // compatibility with modedit assignment obj
132         $this->strassignment = get_string('modulename', 'assignment');
133         $this->strassignments = get_string('modulenameplural', 'assignment');
134         $this->strsubmissions = get_string('submissions', 'assignment');
135         $this->strlastmodified = get_string('lastmodified');
136         $this->pagetitle = strip_tags($this->course->shortname.': '.$this->strassignment.': '.format_string($this->assignment->name,true));
138         // visibility handled by require_login() with $cm parameter
139         // get current group only when really needed
141     /// Set up things for a HTML editor if it's needed
142         $this->defaultformat = editors_get_preferred_format();
143     }
145     /**
146      * Display the assignment, used by view.php
147      *
148      * This in turn calls the methods producing individual parts of the page
149      */
150     function view() {
152         $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
153         require_capability('mod/assignment:view', $context);
155         add_to_log($this->course->id, "assignment", "view", "view.php?id={$this->cm->id}",
156                    $this->assignment->id, $this->cm->id);
158         $this->view_header();
160         $this->view_intro();
162         $this->view_dates();
164         $this->view_feedback();
166         $this->view_footer();
167     }
169     /**
170      * Display the header and top of a page
171      *
172      * (this doesn't change much for assignment types)
173      * This is used by the view() method to print the header of view.php but
174      * it can be used on other pages in which case the string to denote the
175      * page in the navigation trail should be passed as an argument
176      *
177      * @global object
178      * @param string $subpage Description of subpage to be used in navigation trail
179      */
180     function view_header($subpage='') {
181         global $CFG, $PAGE, $OUTPUT;
183         if ($subpage) {
184             $PAGE->navbar->add($subpage);
185         }
187         $PAGE->set_title($this->pagetitle);
188         $PAGE->set_heading($this->course->fullname);
190         echo $OUTPUT->header();
192         groups_print_activity_menu($this->cm, $CFG->wwwroot . '/mod/assignment/view.php?id=' . $this->cm->id);
194         echo '<div class="reportlink">'.$this->submittedlink().'</div>';
195         echo '<div class="clearer"></div>';
196     }
199     /**
200      * Display the assignment intro
201      *
202      * This will most likely be extended by assignment type plug-ins
203      * The default implementation prints the assignment description in a box
204      */
205     function view_intro() {
206         global $OUTPUT;
207         echo $OUTPUT->box_start('generalbox boxaligncenter', 'intro');
208         echo format_module_intro('assignment', $this->assignment, $this->cm->id);
209         echo $OUTPUT->box_end();
210         plagiarism_print_disclosure($this->cm->id);
211     }
213     /**
214      * Display the assignment dates
215      *
216      * Prints the assignment start and end dates in a box.
217      * This will be suitable for most assignment types
218      */
219     function view_dates() {
220         global $OUTPUT;
221         if (!$this->assignment->timeavailable && !$this->assignment->timedue) {
222             return;
223         }
225         echo $OUTPUT->box_start('generalbox boxaligncenter', 'dates');
226         echo '<table>';
227         if ($this->assignment->timeavailable) {
228             echo '<tr><td class="c0">'.get_string('availabledate','assignment').':</td>';
229             echo '    <td class="c1">'.userdate($this->assignment->timeavailable).'</td></tr>';
230         }
231         if ($this->assignment->timedue) {
232             echo '<tr><td class="c0">'.get_string('duedate','assignment').':</td>';
233             echo '    <td class="c1">'.userdate($this->assignment->timedue).'</td></tr>';
234         }
235         echo '</table>';
236         echo $OUTPUT->box_end();
237     }
240     /**
241      * Display the bottom and footer of a page
242      *
243      * This default method just prints the footer.
244      * This will be suitable for most assignment types
245      */
246     function view_footer() {
247         global $OUTPUT;
248         echo $OUTPUT->footer();
249     }
251     /**
252      * Display the feedback to the student
253      *
254      * This default method prints the teacher picture and name, date when marked,
255      * grade and teacher submissioncomment.
256      *
257      * @global object
258      * @global object
259      * @global object
260      * @param object $submission The submission object or NULL in which case it will be loaded
261      */
262     function view_feedback($submission=NULL) {
263         global $USER, $CFG, $DB, $OUTPUT;
264         require_once($CFG->libdir.'/gradelib.php');
266         if (!is_enrolled($this->context, $USER, 'mod/assignment:view')) {
267             // can not submit assignments -> no feedback
268             return;
269         }
271         if (!$submission) { /// Get submission for this assignment
272             $submission = $this->get_submission($USER->id);
273         }
274         // Check the user can submit
275         $cansubmit = has_capability('mod/assignment:submit', $this->context, $USER->id, false);
276         // If not then check if the user still has the view cap and has a previous submission
277         $cansubmit = $cansubmit || (!empty($submission) && has_capability('mod/assignment:view', $this->context, $USER->id, false));
279         if (!$cansubmit) {
280             // can not submit assignments -> no feedback
281             return;
282         }
284         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $USER->id);
285         $item = $grading_info->items[0];
286         $grade = $item->grades[$USER->id];
288         if ($grade->hidden or $grade->grade === false) { // hidden or error
289             return;
290         }
292         if ($grade->grade === null and empty($grade->str_feedback)) {   /// Nothing to show yet
293             return;
294         }
296         $graded_date = $grade->dategraded;
297         $graded_by   = $grade->usermodified;
299     /// We need the teacher info
300         if (!$teacher = $DB->get_record('user', array('id'=>$graded_by))) {
301             print_error('cannotfindteacher');
302         }
304     /// Print the feedback
305         echo $OUTPUT->heading(get_string('feedbackfromteacher', 'assignment', fullname($teacher)));
307         echo '<table cellspacing="0" class="feedback">';
309         echo '<tr>';
310         echo '<td class="left picture">';
311         if ($teacher) {
312             echo $OUTPUT->user_picture($teacher);
313         }
314         echo '</td>';
315         echo '<td class="topic">';
316         echo '<div class="from">';
317         if ($teacher) {
318             echo '<div class="fullname">'.fullname($teacher).'</div>';
319         }
320         echo '<div class="time">'.userdate($graded_date).'</div>';
321         echo '</div>';
322         echo '</td>';
323         echo '</tr>';
325         echo '<tr>';
326         echo '<td class="left side">&nbsp;</td>';
327         echo '<td class="content">';
328         echo '<div class="grade">';
329         echo get_string("grade").': '.$grade->str_long_grade;
330         echo '</div>';
331         echo '<div class="clearer"></div>';
333         echo '<div class="comment">';
334         echo $grade->str_feedback;
335         echo '</div>';
336         echo '</tr>';
338          if ($this->type == 'uploadsingle') { //@TODO: move to overload view_feedback method in the class or is uploadsingle merging into upload?
339             $responsefiles = $this->print_responsefiles($submission->userid, true);
340             if (!empty($responsefiles)) {
341                 echo '<tr>';
342                 echo '<td class="left side">&nbsp;</td>';
343                 echo '<td class="content">';
344                 echo $responsefiles;
345                 echo '</tr>';
346             }
347          }
349         echo '</table>';
350     }
352     /**
353      * Returns a link with info about the state of the assignment submissions
354      *
355      * This is used by view_header to put this link at the top right of the page.
356      * For teachers it gives the number of submitted assignments with a link
357      * For students it gives the time of their submission.
358      * This will be suitable for most assignment types.
359      *
360      * @global object
361      * @global object
362      * @param bool $allgroup print all groups info if user can access all groups, suitable for index.php
363      * @return string
364      */
365     function submittedlink($allgroups=false) {
366         global $USER;
367         global $CFG;
369         $submitted = '';
370         $urlbase = "{$CFG->wwwroot}/mod/assignment/";
372         $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
373         if (has_capability('mod/assignment:grade', $context)) {
374             if ($allgroups and has_capability('moodle/site:accessallgroups', $context)) {
375                 $group = 0;
376             } else {
377                 $group = groups_get_activity_group($this->cm);
378             }
379             if ($count = $this->count_real_submissions($group)) {
380                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
381                              get_string('viewsubmissions', 'assignment', $count).'</a>';
382             } else {
383                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
384                              get_string('noattempts', 'assignment').'</a>';
385             }
386         } else {
387             if (isloggedin()) {
388                 if ($submission = $this->get_submission($USER->id)) {
389                     if ($submission->timemodified) {
390                         if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
391                             $submitted = '<span class="early">'.userdate($submission->timemodified).'</span>';
392                         } else {
393                             $submitted = '<span class="late">'.userdate($submission->timemodified).'</span>';
394                         }
395                     }
396                 }
397             }
398         }
400         return $submitted;
401     }
404     /**
405      * @todo Document this function
406      */
407     function setup_elements(&$mform) {
409     }
411     /**
412      * Any preprocessing needed for the settings form for
413      * this assignment type
414      *
415      * @param array $default_values - array to fill in with the default values
416      *      in the form 'formelement' => 'value'
417      * @param object $form - the form that is to be displayed
418      * @return none
419      */
420     function form_data_preprocessing(&$default_values, $form) {
421     }
423     /**
424      * Any extra validation checks needed for the settings
425      * form for this assignment type
426      *
427      * See lib/formslib.php, 'validation' function for details
428      */
429     function form_validation($data, $files) {
430         return array();
431     }
433     /**
434      * Create a new assignment activity
435      *
436      * Given an object containing all the necessary data,
437      * (defined by the form in mod_form.php) this function
438      * will create a new instance and return the id number
439      * of the new instance.
440      * The due data is added to the calendar
441      * This is common to all assignment types.
442      *
443      * @global object
444      * @global object
445      * @param object $assignment The data from the form on mod_form.php
446      * @return int The id of the assignment
447      */
448     function add_instance($assignment) {
449         global $COURSE, $DB;
451         $assignment->timemodified = time();
452         $assignment->courseid = $assignment->course;
454         $returnid = $DB->insert_record("assignment", $assignment);
455         $assignment->id = $returnid;
457         if ($assignment->timedue) {
458             $event = new stdClass();
459             $event->name        = $assignment->name;
460             $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
461             $event->courseid    = $assignment->course;
462             $event->groupid     = 0;
463             $event->userid      = 0;
464             $event->modulename  = 'assignment';
465             $event->instance    = $returnid;
466             $event->eventtype   = 'due';
467             $event->timestart   = $assignment->timedue;
468             $event->timeduration = 0;
470             calendar_event::create($event);
471         }
473         assignment_grade_item_update($assignment);
475         return $returnid;
476     }
478     /**
479      * Deletes an assignment activity
480      *
481      * Deletes all database records, files and calendar events for this assignment.
482      *
483      * @global object
484      * @global object
485      * @param object $assignment The assignment to be deleted
486      * @return boolean False indicates error
487      */
488     function delete_instance($assignment) {
489         global $CFG, $DB;
491         $assignment->courseid = $assignment->course;
493         $result = true;
495         // now get rid of all files
496         $fs = get_file_storage();
497         if ($cm = get_coursemodule_from_instance('assignment', $assignment->id)) {
498             $context = get_context_instance(CONTEXT_MODULE, $cm->id);
499             $fs->delete_area_files($context->id);
500         }
502         if (! $DB->delete_records('assignment_submissions', array('assignment'=>$assignment->id))) {
503             $result = false;
504         }
506         if (! $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
507             $result = false;
508         }
510         if (! $DB->delete_records('assignment', array('id'=>$assignment->id))) {
511             $result = false;
512         }
513         $mod = $DB->get_field('modules','id',array('name'=>'assignment'));
515         assignment_grade_item_delete($assignment);
517         return $result;
518     }
520     /**
521      * Updates a new assignment activity
522      *
523      * Given an object containing all the necessary data,
524      * (defined by the form in mod_form.php) this function
525      * will update the assignment instance and return the id number
526      * The due date is updated in the calendar
527      * This is common to all assignment types.
528      *
529      * @global object
530      * @global object
531      * @param object $assignment The data from the form on mod_form.php
532      * @return bool success
533      */
534     function update_instance($assignment) {
535         global $COURSE, $DB;
537         $assignment->timemodified = time();
539         $assignment->id = $assignment->instance;
540         $assignment->courseid = $assignment->course;
542         $DB->update_record('assignment', $assignment);
544         if ($assignment->timedue) {
545             $event = new stdClass();
547             if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
549                 $event->name        = $assignment->name;
550                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
551                 $event->timestart   = $assignment->timedue;
553                 $calendarevent = calendar_event::load($event->id);
554                 $calendarevent->update($event);
555             } else {
556                 $event = new stdClass();
557                 $event->name        = $assignment->name;
558                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
559                 $event->courseid    = $assignment->course;
560                 $event->groupid     = 0;
561                 $event->userid      = 0;
562                 $event->modulename  = 'assignment';
563                 $event->instance    = $assignment->id;
564                 $event->eventtype   = 'due';
565                 $event->timestart   = $assignment->timedue;
566                 $event->timeduration = 0;
568                 calendar_event::create($event);
569             }
570         } else {
571             $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id));
572         }
574         // get existing grade item
575         assignment_grade_item_update($assignment);
577         return true;
578     }
580     /**
581      * Update grade item for this submission.
582      */
583     function update_grade($submission) {
584         assignment_update_grades($this->assignment, $submission->userid);
585     }
587     /**
588      * Top-level function for handling of submissions called by submissions.php
589      *
590      * This is for handling the teacher interaction with the grading interface
591      * This should be suitable for most assignment types.
592      *
593      * @global object
594      * @param string $mode Specifies the kind of teacher interaction taking place
595      */
596     function submissions($mode) {
597         ///The main switch is changed to facilitate
598         ///1) Batch fast grading
599         ///2) Skip to the next one on the popup
600         ///3) Save and Skip to the next one on the popup
602         //make user global so we can use the id
603         global $USER, $OUTPUT, $DB, $PAGE;
605         $mailinfo = optional_param('mailinfo', null, PARAM_BOOL);
607         if (optional_param('next', null, PARAM_BOOL)) {
608             $mode='next';
609         }
610         if (optional_param('saveandnext', null, PARAM_BOOL)) {
611             $mode='saveandnext';
612         }
614         if (is_null($mailinfo)) {
615             if (optional_param('sesskey', null, PARAM_BOOL)) {
616                 set_user_preference('assignment_mailinfo', $mailinfo);
617             } else {
618                 $mailinfo = get_user_preferences('assignment_mailinfo', 0);
619             }
620         } else {
621             set_user_preference('assignment_mailinfo', $mailinfo);
622         }
624         switch ($mode) {
625             case 'grade':                         // We are in a main window grading
626                 if ($submission = $this->process_feedback()) {
627                     $this->display_submissions(get_string('changessaved'));
628                 } else {
629                     $this->display_submissions();
630                 }
631                 break;
633             case 'single':                        // We are in a main window displaying one submission
634                 if ($submission = $this->process_feedback()) {
635                     $this->display_submissions(get_string('changessaved'));
636                 } else {
637                     $this->display_submission();
638                 }
639                 break;
641             case 'all':                          // Main window, display everything
642                 $this->display_submissions();
643                 break;
645             case 'fastgrade':
646                 ///do the fast grading stuff  - this process should work for all 3 subclasses
647                 $grading    = false;
648                 $commenting = false;
649                 $col        = false;
650                 if (isset($_POST['submissioncomment'])) {
651                     $col = 'submissioncomment';
652                     $commenting = true;
653                 }
654                 if (isset($_POST['menu'])) {
655                     $col = 'menu';
656                     $grading = true;
657                 }
658                 if (!$col) {
659                     //both submissioncomment and grade columns collapsed..
660                     $this->display_submissions();
661                     break;
662                 }
664                 foreach ($_POST[$col] as $id => $unusedvalue){
666                     $id = (int)$id; //clean parameter name
668                     $this->process_outcomes($id);
670                     if (!$submission = $this->get_submission($id)) {
671                         $submission = $this->prepare_new_submission($id);
672                         $newsubmission = true;
673                     } else {
674                         $newsubmission = false;
675                     }
676                     unset($submission->data1);  // Don't need to update this.
677                     unset($submission->data2);  // Don't need to update this.
679                     //for fast grade, we need to check if any changes take place
680                     $updatedb = false;
682                     if ($grading) {
683                         $grade = $_POST['menu'][$id];
684                         $updatedb = $updatedb || ($submission->grade != $grade);
685                         $submission->grade = $grade;
686                     } else {
687                         if (!$newsubmission) {
688                             unset($submission->grade);  // Don't need to update this.
689                         }
690                     }
691                     if ($commenting) {
692                         $commentvalue = trim($_POST['submissioncomment'][$id]);
693                         $updatedb = $updatedb || ($submission->submissioncomment != $commentvalue);
694                         $submission->submissioncomment = $commentvalue;
695                     } else {
696                         unset($submission->submissioncomment);  // Don't need to update this.
697                     }
699                     $submission->teacher    = $USER->id;
700                     if ($updatedb) {
701                         $submission->mailed = (int)(!$mailinfo);
702                     }
704                     $submission->timemarked = time();
706                     //if it is not an update, we don't change the last modified time etc.
707                     //this will also not write into database if no submissioncomment and grade is entered.
709                     if ($updatedb){
710                         if ($newsubmission) {
711                             if (!isset($submission->submissioncomment)) {
712                                 $submission->submissioncomment = '';
713                             }
714                             $sid = $DB->insert_record('assignment_submissions', $submission);
715                             $submission->id = $sid;
716                         } else {
717                             $DB->update_record('assignment_submissions', $submission);
718                         }
720                         // trigger grade event
721                         $this->update_grade($submission);
723                         //add to log only if updating
724                         add_to_log($this->course->id, 'assignment', 'update grades',
725                                    'submissions.php?id='.$this->cm->id.'&user='.$submission->userid,
726                                    $submission->userid, $this->cm->id);
727                     }
729                 }
731                 $message = $OUTPUT->notification(get_string('changessaved'), 'notifysuccess');
733                 $this->display_submissions($message);
734                 break;
737             case 'saveandnext':
738                 ///We are in pop up. save the current one and go to the next one.
739                 //first we save the current changes
740                 if ($submission = $this->process_feedback()) {
741                     //print_heading(get_string('changessaved'));
742                     //$extra_javascript = $this->update_main_listing($submission);
743                 }
745             case 'next':
746                 /// We are currently in pop up, but we want to skip to next one without saving.
747                 ///    This turns out to be similar to a single case
748                 /// The URL used is for the next submission.
749                 $offset = required_param('offset', PARAM_INT);
750                 $nextid = required_param('nextid', PARAM_INT);
751                 $id = required_param('id', PARAM_INT);
752                 $offset = (int)$offset+1;
753                 //$this->display_submission($offset+1 , $nextid);
754                 redirect('submissions.php?id='.$id.'&userid='. $nextid . '&mode=single&offset='.$offset);
755                 break;
757             case 'singlenosave':
758                 $this->display_submission();
759                 break;
761             default:
762                 echo "something seriously is wrong!!";
763                 break;
764         }
765     }
767     /**
768      * Helper method updating the listing on the main script from popup using javascript
769      *
770      * @global object
771      * @global object
772      * @param $submission object The submission whose data is to be updated on the main page
773      */
774     function update_main_listing($submission) {
775         global $SESSION, $CFG, $OUTPUT;
777         $output = '';
779         $perpage = get_user_preferences('assignment_perpage', 10);
781         $quickgrade = get_user_preferences('assignment_quickgrade', 0);
783         /// Run some Javascript to try and update the parent page
784         $output .= '<script type="text/javascript">'."\n<!--\n";
785         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['submissioncomment'])) {
786             if ($quickgrade){
787                 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid.'").value="'
788                 .trim($submission->submissioncomment).'";'."\n";
789              } else {
790                 $output.= 'opener.document.getElementById("com'.$submission->userid.
791                 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment)), 15)."\";\n";
792             }
793         }
795         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['grade'])) {
796             //echo optional_param('menuindex');
797             if ($quickgrade){
798                 $output.= 'opener.document.getElementById("menumenu'.$submission->userid.
799                 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT).'";'."\n";
800             } else {
801                 $output.= 'opener.document.getElementById("g'.$submission->userid.'").innerHTML="'.
802                 $this->display_grade($submission->grade)."\";\n";
803             }
804         }
805         //need to add student's assignments in there too.
806         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemodified']) &&
807             $submission->timemodified) {
808             $output.= 'opener.document.getElementById("ts'.$submission->userid.
809                  '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid)).userdate($submission->timemodified)."\";\n";
810         }
812         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemarked']) &&
813             $submission->timemarked) {
814             $output.= 'opener.document.getElementById("tt'.$submission->userid.
815                  '").innerHTML="'.userdate($submission->timemarked)."\";\n";
816         }
818         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['status'])) {
819             $output.= 'opener.document.getElementById("up'.$submission->userid.'").className="s1";';
820             $buttontext = get_string('update');
821             $url = new moodle_url('/mod/assignment/submissions.php', array(
822                     'id' => $this->cm->id,
823                     'userid' => $submission->userid,
824                     'mode' => 'single',
825                     'offset' => (optional_param('offset', '', PARAM_INT)-1)));
826             $button = $OUTPUT->action_link($url, $buttontext, new popup_action('click', $url, 'grade'.$submission->userid, array('height' => 450, 'width' => 700)), array('ttile'=>$buttontext));
828             $output .= 'opener.document.getElementById("up'.$submission->userid.'").innerHTML="'.addslashes_js($button).'";';
829         }
831         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $submission->userid);
833         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['finalgrade'])) {
834             $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid.
835             '").innerHTML="'.$grading_info->items[0]->grades[$submission->userid]->str_grade.'";'."\n";
836         }
838         if (!empty($CFG->enableoutcomes) and empty($SESSION->flextable['mod-assignment-submissions']->collapse['outcome'])) {
840             if (!empty($grading_info->outcomes)) {
841                 foreach($grading_info->outcomes as $n=>$outcome) {
842                     if ($outcome->grades[$submission->userid]->locked) {
843                         continue;
844                     }
846                     if ($quickgrade){
847                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.
848                         '").selectedIndex="'.$outcome->grades[$submission->userid]->grade.'";'."\n";
850                     } else {
851                         $options = make_grades_menu(-$outcome->scaleid);
852                         $options[0] = get_string('nooutcome', 'grades');
853                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.'").innerHTML="'.$options[$outcome->grades[$submission->userid]->grade]."\";\n";
854                     }
856                 }
857             }
858         }
860         $output .= "\n-->\n</script>";
861         return $output;
862     }
864     /**
865      *  Return a grade in user-friendly form, whether it's a scale or not
866      *
867      * @global object
868      * @param mixed $grade
869      * @return string User-friendly representation of grade
870      */
871     function display_grade($grade) {
872         global $DB;
874         static $scalegrades = array();   // Cache scales for each assignment - they might have different scales!!
876         if ($this->assignment->grade >= 0) {    // Normal number
877             if ($grade == -1) {
878                 return '-';
879             } else {
880                 return $grade.' / '.$this->assignment->grade;
881             }
883         } else {                                // Scale
884             if (empty($scalegrades[$this->assignment->id])) {
885                 if ($scale = $DB->get_record('scale', array('id'=>-($this->assignment->grade)))) {
886                     $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
887                 } else {
888                     return '-';
889                 }
890             }
891             if (isset($scalegrades[$this->assignment->id][$grade])) {
892                 return $scalegrades[$this->assignment->id][$grade];
893             }
894             return '-';
895         }
896     }
898     /**
899      *  Display a single submission, ready for grading on a popup window
900      *
901      * This default method prints the teacher info and submissioncomment box at the top and
902      * the student info and submission at the bottom.
903      * This method also fetches the necessary data in order to be able to
904      * provide a "Next submission" button.
905      * Calls preprocess_submission() to give assignment type plug-ins a chance
906      * to process submissions before they are graded
907      * This method gets its arguments from the page parameters userid and offset
908      *
909      * @global object
910      * @global object
911      * @param string $extra_javascript
912      */
913     function display_submission($offset=-1,$userid =-1, $display=true) {
914         global $CFG, $DB, $PAGE, $OUTPUT;
915         require_once($CFG->libdir.'/gradelib.php');
916         require_once($CFG->libdir.'/tablelib.php');
917         require_once("$CFG->dirroot/repository/lib.php");
918         if ($userid==-1) {
919             $userid = required_param('userid', PARAM_INT);
920         }
921         if ($offset==-1) {
922             $offset = required_param('offset', PARAM_INT);//offset for where to start looking for student.
923         }
924         $filter = optional_param('filter', 0, PARAM_INT);
926         if (!$user = $DB->get_record('user', array('id'=>$userid))) {
927             print_error('nousers');
928         }
930         if (!$submission = $this->get_submission($user->id)) {
931             $submission = $this->prepare_new_submission($userid);
932         }
933         if ($submission->timemodified > $submission->timemarked) {
934             $subtype = 'assignmentnew';
935         } else {
936             $subtype = 'assignmentold';
937         }
939         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
940         $gradingdisabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
942     /// construct SQL, using current offset to find the data of the next student
943         $course     = $this->course;
944         $assignment = $this->assignment;
945         $cm         = $this->cm;
946         $context    = get_context_instance(CONTEXT_MODULE, $cm->id);
948         /// Get all ppl that can submit assignments
950         $currentgroup = groups_get_activity_group($cm);
951         $users = get_enrolled_users($context, 'mod/assignment:view', $currentgroup, 'u.id');
952         if ($users) {
953             $users = array_keys($users);
954             // if groupmembersonly used, remove users who are not in any group
955             if (!empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
956                 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
957                     $users = array_intersect($users, array_keys($groupingusers));
958                 }
959             }
960         }
962         $nextid = 0;
963         $where = '';
964         if($filter == 'submitted') {
965             $where .= 's.timemodified > 0 AND ';
966         } else if($filter == 'requiregrading') {
967             $where .= 's.timemarked < s.timemodified AND ';
968         }
970         if ($users) {
971             $userfields = user_picture::fields('u', array('lastaccess'));
972             $select = "SELECT $userfields,
973                               s.id AS submissionid, s.grade, s.submissioncomment,
974                               s.timemodified, s.timemarked,
975                               COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ";
976             $sql = 'FROM {user} u '.
977                    'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
978                    AND s.assignment = '.$this->assignment->id.' '.
979                    'WHERE '.$where.'u.id IN ('.implode(',', $users).') ';
981             if ($sort = flexible_table::get_sort_for_table('mod-assignment-submissions')) {
982                 $sort = 'ORDER BY '.$sort.' ';
983             }
984             $auser = $DB->get_records_sql($select.$sql.$sort, null, $offset, 2);
986             if (is_array($auser) && count($auser)>1) {
987                 $nextuser = next($auser);
988             /// Calculate user status
989                 $nextuser->status = ($nextuser->timemarked > 0) && ($nextuser->timemarked >= $nextuser->timemodified);
990                 $nextid = $nextuser->id;
991             }
992         }
994         if ($submission->teacher) {
995             $teacher = $DB->get_record('user', array('id'=>$submission->teacher));
996         } else {
997             global $USER;
998             $teacher = $USER;
999         }
1001         $this->preprocess_submission($submission);
1003         $mformdata = new stdClass();
1004         $mformdata->context = $this->context;
1005         $mformdata->maxbytes = $this->course->maxbytes;
1006         $mformdata->courseid = $this->course->id;
1007         $mformdata->teacher = $teacher;
1008         $mformdata->assignment = $assignment;
1009         $mformdata->submission = $submission;
1010         $mformdata->lateness = $this->display_lateness($submission->timemodified);
1011         $mformdata->auser = $auser;
1012         $mformdata->user = $user;
1013         $mformdata->offset = $offset;
1014         $mformdata->userid = $userid;
1015         $mformdata->cm = $this->cm;
1016         $mformdata->grading_info = $grading_info;
1017         $mformdata->enableoutcomes = $CFG->enableoutcomes;
1018         $mformdata->grade = $this->assignment->grade;
1019         $mformdata->gradingdisabled = $gradingdisabled;
1020         $mformdata->nextid = $nextid;
1021         $mformdata->submissioncomment= $submission->submissioncomment;
1022         $mformdata->submissioncommentformat= FORMAT_HTML;
1023         $mformdata->submission_content= $this->print_user_files($user->id,true);
1024         $mformdata->filter = $filter;
1025          if ($assignment->assignmenttype == 'upload') {
1026             $mformdata->fileui_options = array('subdirs'=>1, 'maxbytes'=>$assignment->maxbytes, 'maxfiles'=>$assignment->var1, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL);
1027         } elseif ($assignment->assignmenttype == 'uploadsingle') {
1028             $mformdata->fileui_options = array('subdirs'=>0, 'maxbytes'=>$CFG->userquota, 'maxfiles'=>1, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL);
1029         }
1031         $submitform = new mod_assignment_grading_form( null, $mformdata );
1033          if (!$display) {
1034             $ret_data = new stdClass();
1035             $ret_data->mform = $submitform;
1036             $ret_data->fileui_options = $mformdata->fileui_options;
1037             return $ret_data;
1038         }
1040         if ($submitform->is_cancelled()) {
1041             redirect('submissions.php?id='.$this->cm->id);
1042         }
1044         $submitform->set_data($mformdata);
1046         $PAGE->set_title($this->course->fullname . ': ' .get_string('feedback', 'assignment').' - '.fullname($user, true));
1047         $PAGE->set_heading($this->course->fullname);
1048         $PAGE->navbar->add(get_string('submissions', 'assignment'), new moodle_url('/mod/assignment/submissions.php', array('id'=>$cm->id)));
1049         $PAGE->navbar->add(fullname($user, true));
1051         echo $OUTPUT->header();
1052         echo $OUTPUT->heading(get_string('feedback', 'assignment').': '.fullname($user, true));
1054         // display mform here...
1055         $submitform->display();
1057         $customfeedback = $this->custom_feedbackform($submission, true);
1058         if (!empty($customfeedback)) {
1059             echo $customfeedback;
1060         }
1062         echo $OUTPUT->footer();
1063     }
1065     /**
1066      *  Preprocess submission before grading
1067      *
1068      * Called by display_submission()
1069      * The default type does nothing here.
1070      *
1071      * @param object $submission The submission object
1072      */
1073     function preprocess_submission(&$submission) {
1074     }
1076     /**
1077      *  Display all the submissions ready for grading
1078      *
1079      * @global object
1080      * @global object
1081      * @global object
1082      * @global object
1083      * @param string $message
1084      * @return bool|void
1085      */
1086     function display_submissions($message='') {
1087         global $CFG, $DB, $USER, $DB, $OUTPUT, $PAGE;
1088         require_once($CFG->libdir.'/gradelib.php');
1090         /* first we check to see if the form has just been submitted
1091          * to request user_preference updates
1092          */
1094        $filters = array(self::FILTER_ALL             => get_string('all'),
1095                         self::FILTER_SUBMITTED       => get_string('submitted', 'assignment'),
1096                         self::FILTER_REQUIRE_GRADING => get_string('requiregrading', 'assignment'));
1098         $updatepref = optional_param('updatepref', 0, PARAM_INT);
1100         if (isset($_POST['updatepref'])){
1101             $perpage = optional_param('perpage', 10, PARAM_INT);
1102             $perpage = ($perpage <= 0) ? 10 : $perpage ;
1103             $filter = optional_param('filter', 0, PARAM_INT);
1104             set_user_preference('assignment_perpage', $perpage);
1105             set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
1106             set_user_preference('assignment_filter', $filter);
1107         }
1109         /* next we get perpage and quickgrade (allow quick grade) params
1110          * from database
1111          */
1112         $perpage    = get_user_preferences('assignment_perpage', 10);
1113         $quickgrade = get_user_preferences('assignment_quickgrade', 0);
1114         $filter = get_user_preferences('assignment_filter', 0);
1115         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);
1117         if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
1118             $uses_outcomes = true;
1119         } else {
1120             $uses_outcomes = false;
1121         }
1123         $page    = optional_param('page', 0, PARAM_INT);
1124         $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
1126     /// Some shortcuts to make the code read better
1128         $course     = $this->course;
1129         $assignment = $this->assignment;
1130         $cm         = $this->cm;
1131         $hassubmission = false;
1133         $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
1134         add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->cm->id, $this->assignment->id, $this->cm->id);
1136         $PAGE->set_title(format_string($this->assignment->name,true));
1137         $PAGE->set_heading($this->course->fullname);
1138         echo $OUTPUT->header();
1140         echo '<div class="usersubmissions">';
1142         //hook to allow plagiarism plugins to update status/print links.
1143         plagiarism_update_status($this->course, $this->cm);
1145         /// Print quickgrade form around the table
1146         if ($quickgrade) {
1147             $formattrs = array();
1148             $formattrs['action'] = new moodle_url('/mod/assignment/submissions.php');
1149             $formattrs['id'] = 'fastg';
1150             $formattrs['method'] = 'post';
1152             echo html_writer::start_tag('form', $formattrs);
1153             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'id',      'value'=> $this->cm->id));
1154             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'mode',    'value'=> 'fastgrade'));
1155             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'page',    'value'=> $page));
1156             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=> sesskey()));
1157         }
1159         $course_context = get_context_instance(CONTEXT_COURSE, $course->id);
1160         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
1161             echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">'
1162                 . get_string('seeallcoursegrades', 'grades') . '</a></div>';
1163         }
1165         if (!empty($message)) {
1166             echo $message;   // display messages here if any
1167         }
1169         $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1171     /// Check to see if groups are being used in this assignment
1173         /// find out current groups mode
1174         $groupmode = groups_get_activity_groupmode($cm);
1175         $currentgroup = groups_get_activity_group($cm, true);
1176         groups_print_activity_menu($cm, $CFG->wwwroot . '/mod/assignment/submissions.php?id=' . $this->cm->id);
1178         /// Get all ppl that are allowed to submit assignments
1179         list($esql, $params) = get_enrolled_sql($context, 'mod/assignment:view', $currentgroup);
1181         if ($filter == self::FILTER_ALL) {
1182             $sql = "SELECT u.id FROM {user} u ".
1183                    "LEFT JOIN ($esql) eu ON eu.id=u.id ".
1184                    "WHERE u.deleted = 0 AND eu.id=u.id ";
1185         } else {
1186             $wherefilter = '';
1187             if($filter == self::FILTER_SUBMITTED) {
1188                $wherefilter = ' AND s.timemodified > 0';
1189             } else if($filter == self::FILTER_REQUIRE_GRADING) {
1190                 $wherefilter = ' AND s.timemarked < s.timemodified ';
1191             }
1193             $sql = "SELECT u.id FROM {user} u ".
1194                    "LEFT JOIN ($esql) eu ON eu.id=u.id ".
1195                    "LEFT JOIN {assignment_submissions} s ON (u.id = s.userid) " .
1196                    "WHERE u.deleted = 0 AND eu.id=u.id ".
1197                    'AND s.assignment = '. $this->assignment->id .
1198                     $wherefilter;
1199         }
1201         $users = $DB->get_records_sql($sql, $params);
1202         if (!empty($users)) {
1203             $users = array_keys($users);
1204         }
1206         // if groupmembersonly used, remove users who are not in any group
1207         if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
1208             if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1209                 $users = array_intersect($users, array_keys($groupingusers));
1210             }
1211         }
1213         $tablecolumns = array('picture', 'fullname', 'grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade');
1214         if ($uses_outcomes) {
1215             $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
1216         }
1218         $tableheaders = array('',
1219                               get_string('fullnameuser'),
1220                               get_string('grade'),
1221                               get_string('comment', 'assignment'),
1222                               get_string('lastmodified').' ('.get_string('submission', 'assignment').')',
1223                               get_string('lastmodified').' ('.get_string('grade').')',
1224                               get_string('status'),
1225                               get_string('finalgrade', 'grades'));
1226         if ($uses_outcomes) {
1227             $tableheaders[] = get_string('outcome', 'grades');
1228         }
1230         require_once($CFG->libdir.'/tablelib.php');
1231         $table = new flexible_table('mod-assignment-submissions');
1233         $table->define_columns($tablecolumns);
1234         $table->define_headers($tableheaders);
1235         $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;currentgroup='.$currentgroup);
1237         $table->sortable(true, 'lastname');//sorted by lastname by default
1238         $table->collapsible(true);
1239         $table->initialbars(true);
1241         $table->column_suppress('picture');
1242         $table->column_suppress('fullname');
1244         $table->column_class('picture', 'picture');
1245         $table->column_class('fullname', 'fullname');
1246         $table->column_class('grade', 'grade');
1247         $table->column_class('submissioncomment', 'comment');
1248         $table->column_class('timemodified', 'timemodified');
1249         $table->column_class('timemarked', 'timemarked');
1250         $table->column_class('status', 'status');
1251         $table->column_class('finalgrade', 'finalgrade');
1252         if ($uses_outcomes) {
1253             $table->column_class('outcome', 'outcome');
1254         }
1256         $table->set_attribute('cellspacing', '0');
1257         $table->set_attribute('id', 'attempts');
1258         $table->set_attribute('class', 'submissions');
1259         $table->set_attribute('width', '100%');
1260         //$table->set_attribute('align', 'center');
1262         $table->no_sorting('finalgrade');
1263         $table->no_sorting('outcome');
1265         // Start working -- this is necessary as soon as the niceties are over
1266         $table->setup();
1268     /// Construct the SQL
1269         list($where, $params) = $table->get_sql_where();
1270         if ($where) {
1271             $where .= ' AND ';
1272         }
1274         if ($filter == self::FILTER_SUBMITTED) {
1275            $where .= 's.timemodified > 0 AND ';
1276         } else if($filter == self::FILTER_REQUIRE_GRADING) {
1277            $where .= 's.timemarked < s.timemodified AND ';
1278         }
1280         if ($sort = $table->get_sql_sort()) {
1281             $sort = ' ORDER BY '.$sort;
1282         }
1284         $ufields = user_picture::fields('u');
1285         if (!empty($users)) {
1286             $select = "SELECT $ufields,
1287                               s.id AS submissionid, s.grade, s.submissioncomment,
1288                               s.timemodified, s.timemarked,
1289                               COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ";
1290             $sql = 'FROM {user} u '.
1291                    'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1292                     AND s.assignment = '.$this->assignment->id.' '.
1293                    'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1295             $ausers = $DB->get_records_sql($select.$sql.$sort, $params, $table->get_page_start(), $table->get_page_size());
1297             $table->pagesize($perpage, count($users));
1299             ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1300             $offset = $page * $perpage;
1301             $strupdate = get_string('update');
1302             $strgrade  = get_string('grade');
1303             $grademenu = make_grades_menu($this->assignment->grade);
1305             if ($ausers !== false) {
1306                 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
1307                 $endposition = $offset + $perpage;
1308                 $currentposition = 0;
1309                 foreach ($ausers as $auser) {
1310                     if ($currentposition == $offset && $offset < $endposition) {
1311                         $final_grade = $grading_info->items[0]->grades[$auser->id];
1312                         $grademax = $grading_info->items[0]->grademax;
1313                         $final_grade->formatted_grade = round($final_grade->grade,2) .' / ' . round($grademax,2);
1314                         $locked_overridden = 'locked';
1315                         if ($final_grade->overridden) {
1316                             $locked_overridden = 'overridden';
1317                         }
1319                     /// Calculate user status
1320                         $auser->status = ($auser->timemarked > 0) && ($auser->timemarked >= $auser->timemodified);
1321                         $picture = $OUTPUT->user_picture($auser);
1323                         if (empty($auser->submissionid)) {
1324                             $auser->grade = -1; //no submission yet
1325                         }
1327                         if (!empty($auser->submissionid)) {
1328                             $hassubmission = true;
1329                         ///Prints student answer and student modified date
1330                         ///attach file or print link to student answer, depending on the type of the assignment.
1331                         ///Refer to print_student_answer in inherited classes.
1332                             if ($auser->timemodified > 0) {
1333                                 $studentmodified = '<div id="ts'.$auser->id.'">'.$this->print_student_answer($auser->id)
1334                                                  . userdate($auser->timemodified).'</div>';
1335                             } else {
1336                                 $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1337                             }
1338                         ///Print grade, dropdown or text
1339                             if ($auser->timemarked > 0) {
1340                                 $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
1342                                 if ($final_grade->locked or $final_grade->overridden) {
1343                                     $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1344                                 } else if ($quickgrade) {
1345                                     $attributes = array();
1346                                     $attributes['tabindex'] = $tabindex++;
1347                                     $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1348                                     $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
1349                                 } else {
1350                                     $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1351                                 }
1353                             } else {
1354                                 $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1355                                 if ($final_grade->locked or $final_grade->overridden) {
1356                                     $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1357                                 } else if ($quickgrade) {
1358                                     $attributes = array();
1359                                     $attributes['tabindex'] = $tabindex++;
1360                                     $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1361                                     $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1362                                 } else {
1363                                     $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1364                                 }
1365                             }
1366                         ///Print Comment
1367                             if ($final_grade->locked or $final_grade->overridden) {
1368                                 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';
1370                             } else if ($quickgrade) {
1371                                 $comment = '<div id="com'.$auser->id.'">'
1372                                          . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1373                                          . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1374                             } else {
1375                                 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
1376                             }
1377                         } else {
1378                             $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1379                             $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1380                             $status          = '<div id="st'.$auser->id.'">&nbsp;</div>';
1382                             if ($final_grade->locked or $final_grade->overridden) {
1383                                 $grade = '<div id="g'.$auser->id.'">'.$final_grade->formatted_grade . '</div>';
1384                                 $hassubmission = true;
1385                             } else if ($quickgrade) {   // allow editing
1386                                 $attributes = array();
1387                                 $attributes['tabindex'] = $tabindex++;
1388                                 $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1389                                 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1390                                 $hassubmission = true;
1391                             } else {
1392                                 $grade = '<div id="g'.$auser->id.'">-</div>';
1393                             }
1395                             if ($final_grade->locked or $final_grade->overridden) {
1396                                 $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
1397                             } else if ($quickgrade) {
1398                                 $comment = '<div id="com'.$auser->id.'">'
1399                                          . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1400                                          . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1401                             } else {
1402                                 $comment = '<div id="com'.$auser->id.'">&nbsp;</div>';
1403                             }
1404                         }
1406                         if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
1407                             $auser->status = 0;
1408                         } else {
1409                             $auser->status = 1;
1410                         }
1412                         $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
1414                         ///No more buttons, we use popups ;-).
1415                         $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1416                                    . '&amp;userid='.$auser->id.'&amp;mode=single'.'&amp;filter='.$filter.'&amp;offset='.$offset++;
1418                         $button = $OUTPUT->action_link($popup_url, $buttontext);
1420                         $status  = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
1422                         $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';
1424                         $outcomes = '';
1426                         if ($uses_outcomes) {
1428                             foreach($grading_info->outcomes as $n=>$outcome) {
1429                                 $outcomes .= '<div class="outcome"><label>'.$outcome->name.'</label>';
1430                                 $options = make_grades_menu(-$outcome->scaleid);
1432                                 if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
1433                                     $options[0] = get_string('nooutcome', 'grades');
1434                                     $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
1435                                 } else {
1436                                     $attributes = array();
1437                                     $attributes['tabindex'] = $tabindex++;
1438                                     $attributes['id'] = 'outcome_'.$n.'_'.$auser->id;
1439                                     $outcomes .= ' '.html_writer::select($options, 'outcome_'.$n.'['.$auser->id.']', $outcome->grades[$auser->id]->grade, array(0=>get_string('nooutcome', 'grades')), $attributes);
1440                                 }
1441                                 $outcomes .= '</div>';
1442                             }
1443                         }
1445                         $userlink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $auser->id . '&amp;course=' . $course->id . '">' . fullname($auser, has_capability('moodle/site:viewfullnames', $this->context)) . '</a>';
1446                         $row = array($picture, $userlink, $grade, $comment, $studentmodified, $teachermodified, $status, $finalgrade);
1447                         if ($uses_outcomes) {
1448                             $row[] = $outcomes;
1449                         }
1450                         $table->add_data($row);
1451                     }
1452                     $currentposition++;
1453                 }
1454             }
1455             if ($hassubmission && ($this->assignment->assignmenttype=='upload' || $this->assignment->assignmenttype=='online' || $this->assignment->assignmenttype=='uploadsingle')) { //TODO: this is an ugly hack, where is the plugin spirit? (skodak)
1456                 echo html_writer::start_tag('div', array('class' => 'mod-assignment-download-link'));
1457                 echo html_writer::link(new moodle_url('/mod/assignment/submissions.php', array('id' => $this->cm->id, 'download' => 'zip')), get_string('downloadall', 'assignment'));
1458                 echo html_writer::end_tag('div');
1459             }
1460             $table->print_html();  /// Print the whole table
1461         } else {
1462             if ($filter == self::FILTER_SUBMITTED) {
1463                 echo html_writer::tag('div', get_string('nosubmisson', 'assignment'), array('class'=>'nosubmisson'));
1464             } else if ($filter == self::FILTER_REQUIRE_GRADING) {
1465                 echo html_writer::tag('div', get_string('norequiregrading', 'assignment'), array('class'=>'norequiregrading'));
1466             }
1467         }
1469         /// Print quickgrade form around the table
1470         if ($quickgrade && $table->started_output && !empty($users)){
1471             $mailinfopref = false;
1472             if (get_user_preferences('assignment_mailinfo', 1)) {
1473                 $mailinfopref = true;
1474             }
1475             $emailnotification =  html_writer::checkbox('mailinfo', 1, $mailinfopref, get_string('enableemailnotification','assignment'));
1477             $emailnotification .= $OUTPUT->help_icon('enableemailnotification', 'assignment');
1478             echo html_writer::tag('div', $emailnotification, array('class'=>'emailnotification'));
1480             $savefeedback = html_writer::empty_tag('input', array('type'=>'submit', 'name'=>'fastg', 'value'=>get_string('saveallfeedback', 'assignment')));
1481             echo html_writer::tag('div', $savefeedback, array('class'=>'fastgbutton'));
1483             echo html_writer::end_tag('form');
1484         } else if ($quickgrade) {
1485             echo html_writer::end_tag('form');
1486         }
1488         echo '</div>';
1489         /// End of fast grading form
1491         /// Mini form for setting user preference
1493         $formaction = new moodle_url('/mod/assignment/submissions.php', array('id'=>$this->cm->id));
1494         $mform = new MoodleQuickForm('optionspref', 'post', $formaction, '', array('class'=>'optionspref'));
1496         $mform->addElement('hidden', 'updatepref');
1497         $mform->setDefault('updatepref', 1);
1498         $mform->addElement('header', 'qgprefs', get_string('optionalsettings', 'assignment'));
1499         $mform->addElement('select', 'filter', get_string('show'),  $filters);
1501         $mform->setDefault('filter', $filter);
1503         $mform->addElement('text', 'perpage', get_string('pagesize', 'assignment'), array('size'=>1));
1504         $mform->setDefault('perpage', $perpage);
1506         $mform->addElement('checkbox', 'quickgrade', get_string('quickgrade','assignment'));
1507         $mform->setDefault('quickgrade', $quickgrade);
1508         $mform->addHelpButton('quickgrade', 'quickgrade', 'assignment');
1510         $mform->addElement('submit', 'savepreferences', get_string('savepreferences'));
1512         $mform->display();
1514         echo $OUTPUT->footer();
1515     }
1517     /**
1518      *  Process teacher feedback submission
1519      *
1520      * This is called by submissions() when a grading even has taken place.
1521      * It gets its data from the submitted form.
1522      *
1523      * @global object
1524      * @global object
1525      * @global object
1526      * @return object|bool The updated submission object or false
1527      */
1528     function process_feedback($formdata=null) {
1529         global $CFG, $USER, $DB;
1530         require_once($CFG->libdir.'/gradelib.php');
1532         if (!$feedback = data_submitted() or !confirm_sesskey()) {      // No incoming data?
1533             return false;
1534         }
1536         ///For save and next, we need to know the userid to save, and the userid to go
1537         ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1538         ///as the userid to store
1539         if ((int)$feedback->saveuserid !== -1){
1540             $feedback->userid = $feedback->saveuserid;
1541         }
1543         if (!empty($feedback->cancel)) {          // User hit cancel button
1544             return false;
1545         }
1547         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);
1549         // store outcomes if needed
1550         $this->process_outcomes($feedback->userid);
1552         $submission = $this->get_submission($feedback->userid, true);  // Get or make one
1554         if (!($grading_info->items[0]->grades[$feedback->userid]->locked ||
1555             $grading_info->items[0]->grades[$feedback->userid]->overridden) ) {
1557             $submission->grade      = $feedback->xgrade;
1558             $submission->submissioncomment    = $feedback->submissioncomment_editor['text'];
1559             $submission->teacher    = $USER->id;
1560             $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1561             if (!$mailinfo) {
1562                 $submission->mailed = 1;       // treat as already mailed
1563             } else {
1564                 $submission->mailed = 0;       // Make sure mail goes out (again, even)
1565             }
1566             $submission->timemarked = time();
1568             unset($submission->data1);  // Don't need to update this.
1569             unset($submission->data2);  // Don't need to update this.
1571             if (empty($submission->timemodified)) {   // eg for offline assignments
1572                 // $submission->timemodified = time();
1573             }
1575             $DB->update_record('assignment_submissions', $submission);
1577             // triger grade event
1578             $this->update_grade($submission);
1580             add_to_log($this->course->id, 'assignment', 'update grades',
1581                        'submissions.php?id='.$this->cm->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
1582              if (!is_null($formdata)) {
1583                     if ($this->type == 'upload' || $this->type == 'uploadsingle') {
1584                         $mformdata = $formdata->mform->get_data();
1585                         $mformdata = file_postupdate_standard_filemanager($mformdata, 'files', $formdata->fileui_options, $this->context, 'mod_assignment', 'response', $submission->id);
1586                     }
1587              }
1588         }
1590         return $submission;
1592     }
1594     function process_outcomes($userid) {
1595         global $CFG, $USER;
1597         if (empty($CFG->enableoutcomes)) {
1598             return;
1599         }
1601         require_once($CFG->libdir.'/gradelib.php');
1603         if (!$formdata = data_submitted() or !confirm_sesskey()) {
1604             return;
1605         }
1607         $data = array();
1608         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
1610         if (!empty($grading_info->outcomes)) {
1611             foreach($grading_info->outcomes as $n=>$old) {
1612                 $name = 'outcome_'.$n;
1613                 if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
1614                     $data[$n] = $formdata->{$name}[$userid];
1615                 }
1616             }
1617         }
1618         if (count($data) > 0) {
1619             grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1620         }
1622     }
1624     /**
1625      * Load the submission object for a particular user
1626      *
1627      * @global object
1628      * @global object
1629      * @param $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1630      * @param $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1631      * @param bool $teachermodified student submission set if false
1632      * @return object The submission
1633      */
1634     function get_submission($userid=0, $createnew=false, $teachermodified=false) {
1635         global $USER, $DB;
1637         if (empty($userid)) {
1638             $userid = $USER->id;
1639         }
1641         $submission = $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1643         if ($submission || !$createnew) {
1644             return $submission;
1645         }
1646         $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
1647         $DB->insert_record("assignment_submissions", $newsubmission);
1649         return $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1650     }
1652     /**
1653      * Instantiates a new submission object for a given user
1654      *
1655      * Sets the assignment, userid and times, everything else is set to default values.
1656      *
1657      * @param int $userid The userid for which we want a submission object
1658      * @param bool $teachermodified student submission set if false
1659      * @return object The submission
1660      */
1661     function prepare_new_submission($userid, $teachermodified=false) {
1662         $submission = new stdClass();
1663         $submission->assignment   = $this->assignment->id;
1664         $submission->userid       = $userid;
1665         $submission->timecreated = time();
1666         // teachers should not be modifying modified date, except offline assignments
1667         if ($teachermodified) {
1668             $submission->timemodified = 0;
1669         } else {
1670             $submission->timemodified = $submission->timecreated;
1671         }
1672         $submission->numfiles     = 0;
1673         $submission->data1        = '';
1674         $submission->data2        = '';
1675         $submission->grade        = -1;
1676         $submission->submissioncomment      = '';
1677         $submission->format       = 0;
1678         $submission->teacher      = 0;
1679         $submission->timemarked   = 0;
1680         $submission->mailed       = 0;
1681         return $submission;
1682     }
1684     /**
1685      * Return all assignment submissions by ENROLLED students (even empty)
1686      *
1687      * @param string $sort optional field names for the ORDER BY in the sql query
1688      * @param string $dir optional specifying the sort direction, defaults to DESC
1689      * @return array The submission objects indexed by id
1690      */
1691     function get_submissions($sort='', $dir='DESC') {
1692         return assignment_get_all_submissions($this->assignment, $sort, $dir);
1693     }
1695     /**
1696      * Counts all real assignment submissions by ENROLLED students (not empty ones)
1697      *
1698      * @param int $groupid optional If nonzero then count is restricted to this group
1699      * @return int The number of submissions
1700      */
1701     function count_real_submissions($groupid=0) {
1702         return assignment_count_real_submissions($this->cm, $groupid);
1703     }
1705     /**
1706      * Alerts teachers by email of new or changed assignments that need grading
1707      *
1708      * First checks whether the option to email teachers is set for this assignment.
1709      * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1710      * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1711      *
1712      * @global object
1713      * @global object
1714      * @param $submission object The submission that has changed
1715      * @return void
1716      */
1717     function email_teachers($submission) {
1718         global $CFG, $DB;
1720         if (empty($this->assignment->emailteachers)) {          // No need to do anything
1721             return;
1722         }
1724         $user = $DB->get_record('user', array('id'=>$submission->userid));
1726         if ($teachers = $this->get_graders($user)) {
1728             $strassignments = get_string('modulenameplural', 'assignment');
1729             $strassignment  = get_string('modulename', 'assignment');
1730             $strsubmitted  = get_string('submitted', 'assignment');
1732             foreach ($teachers as $teacher) {
1733                 $info = new stdClass();
1734                 $info->username = fullname($user, true);
1735                 $info->assignment = format_string($this->assignment->name,true);
1736                 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
1737                 $info->timeupdated = strftime('%c',$submission->timemodified);
1739                 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1740                 $posttext = $this->email_teachers_text($info);
1741                 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
1743                 $eventdata = new stdClass();
1744                 $eventdata->modulename       = 'assignment';
1745                 $eventdata->userfrom         = $user;
1746                 $eventdata->userto           = $teacher;
1747                 $eventdata->subject          = $postsubject;
1748                 $eventdata->fullmessage      = $posttext;
1749                 $eventdata->fullmessageformat = FORMAT_PLAIN;
1750                 $eventdata->fullmessagehtml  = $posthtml;
1751                 $eventdata->smallmessage     = '';
1753                 $eventdata->name            = 'assignment_updates';
1754                 $eventdata->component       = 'mod_assignment';
1755                 $eventdata->notification    = 1;
1756                 $eventdata->contexturl      = $info->url;
1757                 $eventdata->contexturlname  = $info->assignment;
1758                 
1759                 message_send($eventdata);
1760             }
1761         }
1762     }
1764     /**
1765      * @param string $filearea
1766      * @param array $args
1767      * @return bool
1768      */
1769     function send_file($filearea, $args) {
1770         debugging('plugin does not implement file sending', DEBUG_DEVELOPER);
1771         return false;
1772     }
1774     /**
1775      * Returns a list of teachers that should be grading given submission
1776      *
1777      * @param object $user
1778      * @return array
1779      */
1780     function get_graders($user) {
1781         //potential graders
1782         $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false);
1784         $graders = array();
1785         if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) {   // Separate groups are being used
1786             if ($groups = groups_get_all_groups($this->course->id, $user->id)) {  // Try to find all groups
1787                 foreach ($groups as $group) {
1788                     foreach ($potgraders as $t) {
1789                         if ($t->id == $user->id) {
1790                             continue; // do not send self
1791                         }
1792                         if (groups_is_member($group->id, $t->id)) {
1793                             $graders[$t->id] = $t;
1794                         }
1795                     }
1796                 }
1797             } else {
1798                 // user not in group, try to find graders without group
1799                 foreach ($potgraders as $t) {
1800                     if ($t->id == $user->id) {
1801                         continue; // do not send self
1802                     }
1803                     if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
1804                         $graders[$t->id] = $t;
1805                     }
1806                 }
1807             }
1808         } else {
1809             foreach ($potgraders as $t) {
1810                 if ($t->id == $user->id) {
1811                     continue; // do not send self
1812                 }
1813                 $graders[$t->id] = $t;
1814             }
1815         }
1816         return $graders;
1817     }
1819     /**
1820      * Creates the text content for emails to teachers
1821      *
1822      * @param $info object The info used by the 'emailteachermail' language string
1823      * @return string
1824      */
1825     function email_teachers_text($info) {
1826         $posttext  = format_string($this->course->shortname).' -> '.$this->strassignments.' -> '.
1827                      format_string($this->assignment->name)."\n";
1828         $posttext .= '---------------------------------------------------------------------'."\n";
1829         $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
1830         $posttext .= "\n---------------------------------------------------------------------\n";
1831         return $posttext;
1832     }
1834      /**
1835      * Creates the html content for emails to teachers
1836      *
1837      * @param $info object The info used by the 'emailteachermailhtml' language string
1838      * @return string
1839      */
1840     function email_teachers_html($info) {
1841         global $CFG;
1842         $posthtml  = '<p><font face="sans-serif">'.
1843                      '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname).'</a> ->'.
1844                      '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
1845                      '<a href="'.$CFG->wwwroot.'/mod/assignment/view.php?id='.$this->cm->id.'">'.format_string($this->assignment->name).'</a></font></p>';
1846         $posthtml .= '<hr /><font face="sans-serif">';
1847         $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
1848         $posthtml .= '</font><hr />';
1849         return $posthtml;
1850     }
1852     /**
1853      * Produces a list of links to the files uploaded by a user
1854      *
1855      * @param $userid int optional id of the user. If 0 then $USER->id is used.
1856      * @param $return boolean optional defaults to false. If true the list is returned rather than printed
1857      * @return string optional
1858      */
1859     function print_user_files($userid=0, $return=false) {
1860         global $CFG, $USER, $OUTPUT;
1862         if (!$userid) {
1863             if (!isloggedin()) {
1864                 return '';
1865             }
1866             $userid = $USER->id;
1867         }
1869         $output = '';
1871         $fs = get_file_storage();
1873         $found = false;
1875         $submission = $this->get_submission($userid);
1877         if (($submission) && $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false)) {
1878             require_once($CFG->libdir.'/portfoliolib.php');
1879             require_once($CFG->dirroot . '/mod/assignment/locallib.php');
1880             $button = new portfolio_add_button();
1881             foreach ($files as $file) {
1882                 $filename = $file->get_filename();
1883                 $found = true;
1884                 $mimetype = $file->get_mimetype();
1885                 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/mod_assignment/submission/'.$submission->id.'/'.$filename);
1886                 $output .= '<a href="'.$path.'" ><img src="'.$OUTPUT->pix_url(file_mimetype_icon($mimetype)).'" class="icon" alt="'.$mimetype.'" />'.s($filename).'</a>';
1887                 if ($this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1888                     $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id, 'fileid' => $file->get_id()), '/mod/assignment/locallib.php');
1889                     $button->set_format_by_file($file);
1890                     $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
1891                 }
1892                 $output .= plagiarism_get_links(array('userid'=>$userid, 'file'=>$file, 'cmid'=>$this->cm->id, 'course'=>$this->course, 'assignment'=>$this->assignment));
1893                 $output .= '<br />';
1894             }
1895             if (count($files) > 1  && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1896                 $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id), '/mod/assignment/locallib.php');
1897                 $output .= '<br />'  . $button->to_html();
1898             }
1899         }
1901         $output = '<div class="files">'.$output.'</div>';
1903         if ($return) {
1904             return $output;
1905         }
1906         echo $output;
1907     }
1909     /**
1910      * Count the files uploaded by a given user
1911      *
1912      * @param $itemid int The submission's id as the file's itemid.
1913      * @return int
1914      */
1915     function count_user_files($itemid) {
1916         $fs = get_file_storage();
1917         $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $itemid, "id", false);
1918         return count($files);
1919     }
1921     /**
1922      * Returns true if the student is allowed to submit
1923      *
1924      * Checks that the assignment has started and, if the option to prevent late
1925      * submissions is set, also checks that the assignment has not yet closed.
1926      * @return boolean
1927      */
1928     function isopen() {
1929         $time = time();
1930         if ($this->assignment->preventlate && $this->assignment->timedue) {
1931             return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
1932         } else {
1933             return ($this->assignment->timeavailable <= $time);
1934         }
1935     }
1938     /**
1939      * Return true if is set description is hidden till available date
1940      *
1941      * This is needed by calendar so that hidden descriptions do not
1942      * come up in upcoming events.
1943      *
1944      * Check that description is hidden till available date
1945      * By default return false
1946      * Assignments types should implement this method if needed
1947      * @return boolen
1948      */
1949     function description_is_hidden() {
1950         return false;
1951     }
1953     /**
1954      * Return an outline of the user's interaction with the assignment
1955      *
1956      * The default method prints the grade and timemodified
1957      * @param $grade object
1958      * @return object with properties ->info and ->time
1959      */
1960     function user_outline($grade) {
1962         $result = new stdClass();
1963         $result->info = get_string('grade').': '.$grade->str_long_grade;
1964         $result->time = $grade->dategraded;
1965         return $result;
1966     }
1968     /**
1969      * Print complete information about the user's interaction with the assignment
1970      *
1971      * @param $user object
1972      */
1973     function user_complete($user, $grade=null) {
1974         global $OUTPUT;
1975         if ($grade) {
1976             echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
1977             if ($grade->str_feedback) {
1978                 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
1979             }
1980         }
1982         if ($submission = $this->get_submission($user->id)) {
1984             $fs = get_file_storage();
1986             if ($files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false)) {
1987                 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
1988                 foreach ($files as $file) {
1989                     $countfiles .= "; ".$file->get_filename();
1990                 }
1991             }
1993             echo $OUTPUT->box_start();
1994             echo get_string("lastmodified").": ";
1995             echo userdate($submission->timemodified);
1996             echo $this->display_lateness($submission->timemodified);
1998             $this->print_user_files($user->id);
2000             echo '<br />';
2002             $this->view_feedback($submission);
2004             echo $OUTPUT->box_end();
2006         } else {
2007             print_string("notsubmittedyet", "assignment");
2008         }
2009     }
2011     /**
2012      * Return a string indicating how late a submission is
2013      *
2014      * @param $timesubmitted int
2015      * @return string
2016      */
2017     function display_lateness($timesubmitted) {
2018         return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
2019     }
2021     /**
2022      * Empty method stub for all delete actions.
2023      */
2024     function delete() {
2025         //nothing by default
2026         redirect('view.php?id='.$this->cm->id);
2027     }
2029     /**
2030      * Empty custom feedback grading form.
2031      */
2032     function custom_feedbackform($submission, $return=false) {
2033         //nothing by default
2034         return '';
2035     }
2037     /**
2038      * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
2039      * for the course (see resource).
2040      *
2041      * Given a course_module object, this function returns any "extra" information that may be needed
2042      * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
2043      *
2044      * @param $coursemodule object The coursemodule object (record).
2045      * @return object An object on information that the courses will know about (most noticeably, an icon).
2046      *
2047      */
2048     function get_coursemodule_info($coursemodule) {
2049         return false;
2050     }
2052     /**
2053      * Plugin cron method - do not use $this here, create new assignment instances if needed.
2054      * @return void
2055      */
2056     function cron() {
2057         //no plugin cron by default - override if needed
2058     }
2060     /**
2061      * Reset all submissions
2062      */
2063     function reset_userdata($data) {
2064         global $CFG, $DB;
2066         if (!$DB->count_records('assignment', array('course'=>$data->courseid, 'assignmenttype'=>$this->type))) {
2067             return array(); // no assignments of this type present
2068         }
2070         $componentstr = get_string('modulenameplural', 'assignment');
2071         $status = array();
2073         $typestr = get_string('type'.$this->type, 'assignment');
2074         // ugly hack to support pluggable assignment type titles...
2075         if($typestr === '[[type'.$this->type.']]'){
2076             $typestr = get_string('type'.$this->type, 'assignment_'.$this->type);
2077         }
2079         if (!empty($data->reset_assignment_submissions)) {
2080             $assignmentssql = "SELECT a.id
2081                                  FROM {assignment} a
2082                                 WHERE a.course=? AND a.assignmenttype=?";
2083             $params = array($data->courseid, $this->type);
2085             // now get rid of all submissions and responses
2086             $fs = get_file_storage();
2087             if ($assignments = $DB->get_records_sql($assignmentssql, $params)) {
2088                 foreach ($assignments as $assignmentid=>$unused) {
2089                     if (!$cm = get_coursemodule_from_instance('assignment', $assignmentid)) {
2090                         continue;
2091                     }
2092                     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2093                     $fs->delete_area_files($context->id, 'mod_assignment', 'submission');
2094                     $fs->delete_area_files($context->id, 'mod_assignment', 'response');
2095                 }
2096             }
2098             $DB->delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)", $params);
2100             $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
2102             if (empty($data->reset_gradebook_grades)) {
2103                 // remove all grades from gradebook
2104                 assignment_reset_gradebook($data->courseid, $this->type);
2105             }
2106         }
2108         /// updating dates - shift may be negative too
2109         if ($data->timeshift) {
2110             shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
2111             $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
2112         }
2114         return $status;
2115     }
2118     function portfolio_exportable() {
2119         return false;
2120     }
2122     /**
2123      * base implementation for backing up subtype specific information
2124      * for one single module
2125      *
2126      * @param filehandle $bf file handle for xml file to write to
2127      * @param mixed $preferences the complete backup preference object
2128      *
2129      * @return boolean
2130      *
2131      * @static
2132      */
2133     static function backup_one_mod($bf, $preferences, $assignment) {
2134         return true;
2135     }
2137     /**
2138      * base implementation for backing up subtype specific information
2139      * for one single submission
2140      *
2141      * @param filehandle $bf file handle for xml file to write to
2142      * @param mixed $preferences the complete backup preference object
2143      * @param object $submission the assignment submission db record
2144      *
2145      * @return boolean
2146      *
2147      * @static
2148      */
2149     static function backup_one_submission($bf, $preferences, $assignment, $submission) {
2150         return true;
2151     }
2153     /**
2154      * base implementation for restoring subtype specific information
2155      * for one single module
2156      *
2157      * @param array  $info the array representing the xml
2158      * @param object $restore the restore preferences
2159      *
2160      * @return boolean
2161      *
2162      * @static
2163      */
2164     static function restore_one_mod($info, $restore, $assignment) {
2165         return true;
2166     }
2168     /**
2169      * base implementation for restoring subtype specific information
2170      * for one single submission
2171      *
2172      * @param object $submission the newly created submission
2173      * @param array  $info the array representing the xml
2174      * @param object $restore the restore preferences
2175      *
2176      * @return boolean
2177      *
2178      * @static
2179      */
2180     static function restore_one_submission($info, $restore, $assignment, $submission) {
2181         return true;
2182     }
2184 } ////// End of the assignment_base class
2187 class mod_assignment_grading_form extends moodleform {
2189     function definition() {
2190         global $OUTPUT;
2191         $mform =& $this->_form;
2193         $formattr = $mform->getAttributes();
2194         $formattr['id'] = 'submitform';
2195         $mform->setAttributes($formattr);
2196         // hidden params
2197         $mform->addElement('hidden', 'offset', ($this->_customdata->offset+1));
2198         $mform->setType('offset', PARAM_INT);
2199         $mform->addElement('hidden', 'userid', $this->_customdata->userid);
2200         $mform->setType('userid', PARAM_INT);
2201         $mform->addElement('hidden', 'nextid', $this->_customdata->nextid);
2202         $mform->setType('nextid', PARAM_INT);
2203         $mform->addElement('hidden', 'id', $this->_customdata->cm->id);
2204         $mform->setType('id', PARAM_INT);
2205         $mform->addElement('hidden', 'sesskey', sesskey());
2206         $mform->setType('sesskey', PARAM_ALPHANUM);
2207         $mform->addElement('hidden', 'mode', 'grade');
2208         $mform->setType('mode', PARAM_TEXT);
2209         $mform->addElement('hidden', 'menuindex', "0");
2210         $mform->setType('menuindex', PARAM_INT);
2211         $mform->addElement('hidden', 'saveuserid', "-1");
2212         $mform->setType('saveuserid', PARAM_INT);
2213         $mform->addElement('hidden', 'filter', "0");
2214         $mform->setType('filter', PARAM_INT);
2216         $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->user),
2217                                                 fullname($this->_customdata->user, true) . '<br/>' .
2218                                                 userdate($this->_customdata->submission->timemodified) .
2219                                                 $this->_customdata->lateness );
2221         $this->add_submission_content();
2222         $this->add_grades_section();
2224         $this->add_feedback_section();
2226         if ($this->_customdata->submission->timemarked) {
2227             $datestring = userdate($this->_customdata->submission->timemarked)."&nbsp; (".format_time(time() - $this->_customdata->submission->timemarked).")";
2228             $mform->addElement('header', 'Last Grade', get_string('lastgrade', 'assignment'));
2229             $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->teacher) ,
2230                                                     fullname($this->_customdata->teacher,true).
2231                                                     '<br/>'.$datestring);
2232         }
2233         // buttons
2234         $this->add_action_buttons();
2236     }
2238     function add_grades_section() {
2239         global $CFG;
2240         $mform =& $this->_form;
2241         $attributes = array();
2242         if ($this->_customdata->gradingdisabled) {
2243             $attributes['disabled'] ='disabled';
2244         }
2246         $grademenu = make_grades_menu($this->_customdata->assignment->grade);
2247         $grademenu['-1'] = get_string('nograde');
2249         $mform->addElement('header', 'Grades', get_string('grades', 'grades'));
2250         $mform->addElement('select', 'xgrade', get_string('grade').':', $grademenu, $attributes);
2251         $mform->setDefault('xgrade', $this->_customdata->submission->grade ); //@fixme some bug when element called 'grade' makes it break
2252         $mform->setType('xgrade', PARAM_INT);
2254         if (!empty($this->_customdata->enableoutcomes)) {
2255             foreach($this->_customdata->grading_info->outcomes as $n=>$outcome) {
2256                 $options = make_grades_menu(-$outcome->scaleid);
2257                 if ($outcome->grades[$this->_customdata->submission->userid]->locked) {
2258                     $options[0] = get_string('nooutcome', 'grades');
2259                     echo $options[$outcome->grades[$this->_customdata->submission->userid]->grade];
2260                 } else {
2261                     $options[''] = get_string('nooutcome', 'grades');
2262                     $attributes = array('id' => 'menuoutcome_'.$n );
2263                     $mform->addElement('select', 'outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->name.':', $options, $attributes );
2264                     $mform->setType('outcome_'.$n.'['.$this->_customdata->userid.']', PARAM_INT);
2265                     $mform->setDefault('outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->grades[$this->_customdata->submission->userid]->grade );
2266                 }
2267             }
2268         }
2269         $course_context = get_context_instance(CONTEXT_MODULE , $this->_customdata->cm->id);
2270         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
2271             $grade = '<a href="'.$CFG->wwwroot.'/grade/report/grader/index.php?id='. $this->_customdata->courseid .'" >'.
2272                         $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade . '</a>';
2273         }else{
2274             $grade = $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade;
2275         }
2276         $mform->addElement('static', 'finalgrade', get_string('currentgrade', 'assignment').':' ,$grade);
2277         $mform->setType('finalgrade', PARAM_INT);
2278     }
2280     /**
2281      *
2282      * @global core_renderer $OUTPUT
2283      */
2284     function add_feedback_section() {
2285         global $OUTPUT;
2286         $mform =& $this->_form;
2287         $mform->addElement('header', 'Feed Back', get_string('feedback', 'grades'));
2289         if ($this->_customdata->gradingdisabled) {
2290             $mform->addElement('static', 'disabledfeedback', $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_feedback );
2291         } else {
2292             // visible elements
2294             $mform->addElement('editor', 'submissioncomment_editor', get_string('feedback', 'assignment').':', null, $this->get_editor_options() );
2295             $mform->setType('submissioncomment_editor', PARAM_RAW); // to be cleaned before display
2296             $mform->setDefault('submissioncomment_editor', $this->_customdata->submission->submissioncomment);
2297             //$mform->addRule('submissioncomment', get_string('required'), 'required', null, 'client');
2298             switch ($this->_customdata->assignment->assignmenttype) {
2299                 case 'upload' :
2300                 case 'uploadsingle' :
2301                     $mform->addElement('filemanager', 'files_filemanager', get_string('responsefiles', 'assignment'). ':', null, $this->_customdata->fileui_options);
2302                     break;
2303                 default :
2304                     break;
2305             }
2306             $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? array('checked'=>'checked') : array();
2307             $mform->addElement('hidden', 'mailinfo_h', "0");
2308             $mform->setType('mailinfo_h', PARAM_INT);
2309             $mform->addElement('checkbox', 'mailinfo',get_string('enableemailnotification','assignment').
2310             $OUTPUT->help_icon('enableemailnotification', 'assignment') .':' );
2311             $mform->updateElementAttr('mailinfo', $lastmailinfo);
2312             $mform->setType('mailinfo', PARAM_INT);
2313         }
2314     }
2316     function add_action_buttons() {
2317         $mform =& $this->_form;
2318         //if there are more to be graded.
2319         if ($this->_customdata->nextid>0) {
2320             $buttonarray=array();
2321             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2322             //@todo: fix accessibility: javascript dependency not necessary
2323             $buttonarray[] = &$mform->createElement('submit', 'saveandnext', get_string('saveandnext'));
2324             $buttonarray[] = &$mform->createElement('submit', 'next', get_string('next'));
2325             $buttonarray[] = &$mform->createElement('cancel');
2326         } else {
2327             $buttonarray=array();
2328             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2329             $buttonarray[] = &$mform->createElement('cancel');
2330         }
2331         $mform->addGroup($buttonarray, 'grading_buttonar', '', array(' '), false);
2332         $mform->closeHeaderBefore('grading_buttonar');
2333         $mform->setType('grading_buttonar', PARAM_RAW);
2334     }
2336     function add_submission_content() {
2337         $mform =& $this->_form;
2338         $mform->addElement('header', 'Submission', get_string('submission', 'assignment'));
2339         $mform->addElement('static', '', '' , $this->_customdata->submission_content );
2340     }
2342     protected function get_editor_options() {
2343         $editoroptions = array();
2344         $editoroptions['component'] = 'mod_assignment';
2345         $editoroptions['filearea'] = 'feedback';
2346         $editoroptions['noclean'] = false;
2347         $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)
2348         $editoroptions['maxbytes'] = $this->_customdata->maxbytes;
2349         return $editoroptions;
2350     }
2352     public function set_data($data) {
2353         $editoroptions = $this->get_editor_options();
2354         if (!isset($data->text)) {
2355             $data->text = '';
2356         }
2357         if (!isset($data->format)) {
2358             $data->textformat = FORMAT_HTML;
2359         } else {
2360             $data->textformat = $data->format;
2361         }
2363         if (!empty($this->_customdata->submission->id)) {
2364             $itemid = $this->_customdata->submission->id;
2365         } else {
2366             $itemid = null;
2367         }
2369         switch ($this->_customdata->assignment->assignmenttype) {
2370                 case 'upload' :
2371                 case 'uploadsingle' :
2372                     $data = file_prepare_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2373                     break;
2374                 default :
2375                     break;
2376         }
2378         $data = file_prepare_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2379         return parent::set_data($data);
2380     }
2382     public function get_data() {
2383         $data = parent::get_data();
2385         if (!empty($this->_customdata->submission->id)) {
2386             $itemid = $this->_customdata->submission->id;
2387         } else {
2388             $itemid = null; //TODO: this is wrong, itemid MUST be known when saving files!! (skodak)
2389         }
2391         if ($data) {
2392             $editoroptions = $this->get_editor_options();
2393             switch ($this->_customdata->assignment->assignmenttype) {
2394                 case 'upload' :
2395                 case 'uploadsingle' :
2396                     $data = file_postupdate_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2397                     break;
2398                 default :
2399                     break;
2400             }
2401             $data = file_postupdate_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2402         }
2403         return $data;
2404     }
2407 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
2409 /**
2410  * Deletes an assignment instance
2411  *
2412  * This is done by calling the delete_instance() method of the assignment type class
2413  */
2414 function assignment_delete_instance($id){
2415     global $CFG, $DB;
2417     if (! $assignment = $DB->get_record('assignment', array('id'=>$id))) {
2418         return false;
2419     }
2421     // fall back to base class if plugin missing
2422     $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2423     if (file_exists($classfile)) {
2424         require_once($classfile);
2425         $assignmentclass = "assignment_$assignment->assignmenttype";
2427     } else {
2428         debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
2429         $assignmentclass = "assignment_base";
2430     }
2432     $ass = new $assignmentclass();
2433     return $ass->delete_instance($assignment);
2437 /**
2438  * Updates an assignment instance
2439  *
2440  * This is done by calling the update_instance() method of the assignment type class
2441  */
2442 function assignment_update_instance($assignment){
2443     global $CFG;
2445     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2447     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2448     $assignmentclass = "assignment_$assignment->assignmenttype";
2449     $ass = new $assignmentclass();
2450     return $ass->update_instance($assignment);
2454 /**
2455  * Adds an assignment instance
2456  *
2457  * This is done by calling the add_instance() method of the assignment type class
2458  */
2459 function assignment_add_instance($assignment) {
2460     global $CFG;
2462     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2464     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2465     $assignmentclass = "assignment_$assignment->assignmenttype";
2466     $ass = new $assignmentclass();
2467     return $ass->add_instance($assignment);
2471 /**
2472  * Returns an outline of a user interaction with an assignment
2473  *
2474  * This is done by calling the user_outline() method of the assignment type class
2475  */
2476 function assignment_user_outline($course, $user, $mod, $assignment) {
2477     global $CFG;
2479     require_once("$CFG->libdir/gradelib.php");
2480     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2481     $assignmentclass = "assignment_$assignment->assignmenttype";
2482     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2483     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2484     if (!empty($grades->items[0]->grades)) {
2485         return $ass->user_outline(reset($grades->items[0]->grades));
2486     } else {
2487         return null;
2488     }
2491 /**
2492  * Prints the complete info about a user's interaction with an assignment
2493  *
2494  * This is done by calling the user_complete() method of the assignment type class
2495  */
2496 function assignment_user_complete($course, $user, $mod, $assignment) {
2497     global $CFG;
2499     require_once("$CFG->libdir/gradelib.php");
2500     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2501     $assignmentclass = "assignment_$assignment->assignmenttype";
2502     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2503     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2504     if (empty($grades->items[0]->grades)) {
2505         $grade = false;
2506     } else {
2507         $grade = reset($grades->items[0]->grades);
2508     }
2509     return $ass->user_complete($user, $grade);
2512 /**
2513  * Function to be run periodically according to the moodle cron
2514  *
2515  * Finds all assignment notifications that have yet to be mailed out, and mails them
2516  */
2517 function assignment_cron () {
2518     global $CFG, $USER, $DB;
2520     /// first execute all crons in plugins
2521     if ($plugins = get_plugin_list('assignment')) {
2522         foreach ($plugins as $plugin=>$dir) {
2523             require_once("$dir/assignment.class.php");
2524             $assignmentclass = "assignment_$plugin";
2525             $ass = new $assignmentclass();
2526             $ass->cron();
2527         }
2528     }
2530     /// Notices older than 1 day will not be mailed.  This is to avoid the problem where
2531     /// cron has not been running for a long time, and then suddenly people are flooded
2532     /// with mail from the past few weeks or months
2534     $timenow   = time();
2535     $endtime   = $timenow - $CFG->maxeditingtime;
2536     $starttime = $endtime - 24 * 3600;   /// One day earlier
2538     if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2540         $realuser = clone($USER);
2542         foreach ($submissions as $key => $submission) {
2543             $DB->set_field("assignment_submissions", "mailed", "1", array("id"=>$submission->id));
2544         }
2546         $timenow = time();
2548         foreach ($submissions as $submission) {
2550             echo "Processing assignment submission $submission->id\n";
2552             if (! $user = $DB->get_record("user", array("id"=>$submission->userid))) {
2553                 echo "Could not find user $user->id\n";
2554                 continue;
2555             }
2557             if (! $course = $DB->get_record("course", array("id"=>$submission->course))) {
2558                 echo "Could not find course $submission->course\n";
2559                 continue;
2560             }
2562             /// Override the language and timezone of the "current" user, so that
2563             /// mail is customised for the receiver.
2564             cron_setup_user($user, $course);
2566             if (!is_enrolled(get_context_instance(CONTEXT_COURSE, $submission->course), $user->id)) {
2567                 echo fullname($user)." not an active participant in " . format_string($course->shortname) . "\n";
2568                 continue;
2569             }
2571             if (! $teacher = $DB->get_record("user", array("id"=>$submission->teacher))) {
2572                 echo "Could not find teacher $submission->teacher\n";
2573                 continue;
2574             }
2576             if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2577                 echo "Could not find course module for assignment id $submission->assignment\n";
2578                 continue;
2579             }
2581             if (! $mod->visible) {    /// Hold mail notification for hidden assignments until later
2582                 continue;
2583             }
2585             $strassignments = get_string("modulenameplural", "assignment");
2586             $strassignment  = get_string("modulename", "assignment");
2588             $assignmentinfo = new stdClass();
2589             $assignmentinfo->teacher = fullname($teacher);
2590             $assignmentinfo->assignment = format_string($submission->name,true);
2591             $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2593             $postsubject = "$course->shortname: $strassignments: ".format_string($submission->name,true);
2594             $posttext  = "$course->shortname -> $strassignments -> ".format_string($submission->name,true)."\n";
2595             $posttext .= "---------------------------------------------------------------------\n";
2596             $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2597             $posttext .= "---------------------------------------------------------------------\n";
2599             if ($user->mailformat == 1) {  // HTML
2600                 $posthtml = "<p><font face=\"sans-serif\">".
2601                 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> ->".
2602                 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2603                 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2604                 $posthtml .= "<hr /><font face=\"sans-serif\">";
2605                 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2606                 $posthtml .= "</font><hr />";
2607             } else {
2608                 $posthtml = "";
2609             }
2611             $eventdata = new stdClass();
2612             $eventdata->modulename       = 'assignment';
2613             $eventdata->userfrom         = $teacher;
2614             $eventdata->userto           = $user;
2615             $eventdata->subject          = $postsubject;
2616             $eventdata->fullmessage      = $posttext;
2617             $eventdata->fullmessageformat = FORMAT_PLAIN;
2618             $eventdata->fullmessagehtml  = $posthtml;
2619             $eventdata->smallmessage     = '';
2621             $eventdata->name            = 'assignment_updates';
2622             $eventdata->component       = 'mod_assignment';
2623             $eventdata->notification    = 1;
2625             message_send($eventdata);
2626         }
2628         cron_setup_user();
2629     }
2631     return true;
2634 /**
2635  * Return grade for given user or all users.
2636  *
2637  * @param int $assignmentid id of assignment
2638  * @param int $userid optional user id, 0 means all users
2639  * @return array array of grades, false if none
2640  */
2641 function assignment_get_user_grades($assignment, $userid=0) {
2642     global $CFG, $DB;
2644     if ($userid) {
2645         $user = "AND u.id = :userid";
2646         $params = array('userid'=>$userid);
2647     } else {
2648         $user = "";
2649     }
2650     $params['aid'] = $assignment->id;
2652     $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2653                    s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2654               FROM {user} u, {assignment_submissions} s
2655              WHERE u.id = s.userid AND s.assignment = :aid
2656                    $user";
2658     return $DB->get_records_sql($sql, $params);
2661 /**
2662  * Update activity grades
2663  *
2664  * @param object $assignment
2665  * @param int $userid specific user only, 0 means all
2666  */
2667 function assignment_update_grades($assignment, $userid=0, $nullifnone=true) {
2668     global $CFG, $DB;
2669     require_once($CFG->libdir.'/gradelib.php');
2671     if ($assignment->grade == 0) {
2672         assignment_grade_item_update($assignment);
2674     } else if ($grades = assignment_get_user_grades($assignment, $userid)) {
2675         foreach($grades as $k=>$v) {
2676             if ($v->rawgrade == -1) {
2677                 $grades[$k]->rawgrade = null;
2678             }
2679         }
2680         assignment_grade_item_update($assignment, $grades);
2682     } else {
2683         assignment_grade_item_update($assignment);
2684     }
2687 /**
2688  * Update all grades in gradebook.
2689  */
2690 function assignment_upgrade_grades() {
2691     global $DB;
2693     $sql = "SELECT COUNT('x')
2694               FROM {assignment} a, {course_modules} cm, {modules} m
2695              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2696     $count = $DB->count_records_sql($sql);
2698     $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
2699               FROM {assignment} a, {course_modules} cm, {modules} m
2700              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2701     $rs = $DB->get_recordset_sql($sql);
2702     if ($rs->valid()) {
2703         // too much debug output
2704         $pbar = new progress_bar('assignmentupgradegrades', 500, true);
2705         $i=0;
2706         foreach ($rs as $assignment) {
2707             $i++;
2708             upgrade_set_timeout(60*5); // set up timeout, may also abort execution
2709             assignment_update_grades($assignment);
2710             $pbar->update($i, $count, "Updating Assignment grades ($i/$count).");
2711         }
2712         upgrade_set_timeout(); // reset to default timeout
2713     }
2714     $rs->close();
2717 /**
2718  * Create grade item for given assignment
2719  *
2720  * @param object $assignment object with extra cmidnumber
2721  * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
2722  * @return int 0 if ok, error code otherwise
2723  */
2724 function assignment_grade_item_update($assignment, $grades=NULL) {
2725     global $CFG;
2726     require_once($CFG->libdir.'/gradelib.php');
2728     if (!isset($assignment->courseid)) {
2729         $assignment->courseid = $assignment->course;
2730     }
2732     $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
2734     if ($assignment->grade > 0) {
2735         $params['gradetype'] = GRADE_TYPE_VALUE;
2736         $params['grademax']  = $assignment->grade;
2737         $params['grademin']  = 0;
2739     } else if ($assignment->grade < 0) {
2740         $params['gradetype'] = GRADE_TYPE_SCALE;
2741         $params['scaleid']   = -$assignment->grade;
2743     } else {
2744         $params['gradetype'] = GRADE_TYPE_TEXT; // allow text comments only
2745     }
2747     if ($grades  === 'reset') {
2748         $params['reset'] = true;
2749         $grades = NULL;
2750     }
2752     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades, $params);
2755 /**
2756  * Delete grade item for given assignment
2757  *
2758  * @param object $assignment object
2759  * @return object assignment
2760  */
2761 function assignment_grade_item_delete($assignment) {
2762     global $CFG;
2763     require_once($CFG->libdir.'/gradelib.php');
2765     if (!isset($assignment->courseid)) {
2766         $assignment->courseid = $assignment->course;
2767     }
2769     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
2772 /**
2773  * Returns the users with data in one assignment (students and teachers)
2774  *
2775  * @todo: deprecated - to be deleted in 2.2
2776  *
2777  * @param $assignmentid int
2778  * @return array of user objects
2779  */
2780 function assignment_get_participants($assignmentid) {
2781     global $CFG, $DB;
2783     //Get students
2784     $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2785                                         FROM {user} u,
2786                                              {assignment_submissions} a
2787                                        WHERE a.assignment = ? and
2788                                              u.id = a.userid", array($assignmentid));
2789     //Get teachers
2790     $teachers = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2791                                         FROM {user} u,
2792                                              {assignment_submissions} a
2793                                        WHERE a.assignment = ? and
2794                                              u.id = a.teacher", array($assignmentid));
2796     //Add teachers to students
2797     if ($teachers) {
2798         foreach ($teachers as $teacher) {
2799             $students[$teacher->id] = $teacher;
2800         }
2801     }
2802     //Return students array (it contains an array of unique users)
2803     return ($students);
2806 /**
2807  * Serves assignment submissions and other files.
2808  *
2809  * @param object $course
2810  * @param object $cm
2811  * @param object $context
2812  * @param string $filearea
2813  * @param array $args
2814  * @param bool $forcedownload
2815  * @return bool false if file not found, does not return if found - just send the file
2816  */
2817 function assignment_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) {
2818     global $CFG, $DB;
2820     if ($context->contextlevel != CONTEXT_MODULE) {
2821         return false;
2822     }
2824     require_login($course, false, $cm);
2826     if (!$assignment = $DB->get_record('assignment', array('id'=>$cm->instance))) {
2827         return false;
2828     }
2830     require_once($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
2831     $assignmentclass = 'assignment_'.$assignment->assignmenttype;
2832     $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm, $course);
2834     return $assignmentinstance->send_file($filearea, $args);
2836 /**
2837  * Checks if a scale is being used by an assignment
2838  *
2839  * This is used by the backup code to decide whether to back up a scale
2840  * @param $assignmentid int
2841  * @param $scaleid int
2842  * @return boolean True if the scale is used by the assignment
2843  */
2844 function assignment_scale_used($assignmentid, $scaleid) {
2845     global $DB;
2847     $return = false;
2849     $rec = $DB->get_record('assignment', array('id'=>$assignmentid,'grade'=>-$scaleid));
2851     if (!empty($rec) && !empty($scaleid)) {
2852         $return = true;
2853     }
2855     return $return;
2858 /**
2859  * Checks if scale is being used by any instance of assignment
2860  *
2861  * This is used to find out if scale used anywhere
2862  * @param $scaleid int
2863  * @return boolean True if the scale is used by any assignment
2864  */
2865 function assignment_scale_used_anywhere($scaleid) {
2866     global $DB;
2868     if ($scaleid and $DB->record_exists('assignment', array('grade'=>-$scaleid))) {
2869         return true;
2870     } else {
2871         return false;
2872     }
2875 /**
2876  * Make sure up-to-date events are created for all assignment instances
2877  *
2878  * This standard function will check all instances of this module
2879  * and make sure there are up-to-date events created for each of them.
2880  * If courseid = 0, then every assignment event in the site is checked, else
2881  * only assignment events belonging to the course specified are checked.
2882  * This function is used, in its new format, by restore_refresh_events()
2883  *
2884  * @param $courseid int optional If zero then all assignments for all courses are covered
2885  * @return boolean Always returns true
2886  */
2887 function assignment_refresh_events($courseid = 0) {
2888     global $DB;
2890     if ($courseid == 0) {
2891         if (! $assignments = $DB->get_records("assignment")) {
2892             return true;
2893         }
2894     } else {
2895         if (! $assignments = $DB->get_records("assignment", array("course"=>$courseid))) {
2896             return true;
2897         }
2898     }
2899     $moduleid = $DB->get_field('modules', 'id', array('name'=>'assignment'));
2901     foreach ($assignments as $assignment) {
2902         $cm = get_coursemodule_from_id('assignment', $assignment->id);
2903         $event = new stdClass();
2904         $event->name        = $assignment->name;
2905         $event->description = format_module_intro('assignment', $assignment, $cm->id);
2906         $event->timestart   = $assignment->timedue;
2908         if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
2909             update_event($event);
2911         } else {
2912             $event->courseid    = $assignment->course;
2913             $event->groupid     = 0;
2914             $event->userid      = 0;
2915             $event->modulename  = 'assignment';
2916             $event->instance    = $assignment->id;
2917             $event->eventtype   = 'due';
2918             $event->timeduration = 0;
2919             $event->visible     = $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$assignment->id));
2920             add_event($event);
2921         }
2923     }
2924     return true;
2927 /**
2928  * Print recent activity from all assignments in a given course
2929  *
2930  * This is used by the recent activity block
2931  */
2932 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
2933     global $CFG, $USER, $DB, $OUTPUT;
2935     // do not use log table if possible, it may be huge
2937     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
2938                                                      u.firstname, u.lastname, u.email, u.picture
2939                                                 FROM {assignment_submissions} asb
2940                                                      JOIN {assignment} a      ON a.id = asb.assignment
2941                                                      JOIN {course_modules} cm ON cm.instance = a.id
2942                                                      JOIN {modules} md        ON md.id = cm.module
2943                                                      JOIN {user} u            ON u.id = asb.userid
2944                                                WHERE asb.timemodified > ? AND
2945                                                      a.course = ? AND
2946                                                      md.name = 'assignment'
2947                                             ORDER BY asb.timemodified ASC", array($timestart, $course->id))) {
2948          return false;
2949     }
2951     $modinfo =& get_fast_modinfo($course); // reference needed because we might load the groups
2952     $show    = array();
2953     $grader  = array();
2955     foreach($submissions as $submission) {
2956         if (!array_key_exists($submission->cmid, $modinfo->cms)) {
2957             continue;
2958         }
2959         $cm = $modinfo->cms[$submission->cmid];
2960         if (!$cm->uservisible) {
2961             continue;
2962         }
2963         if ($submission->userid == $USER->id) {
2964             $show[] = $submission;
2965             continue;
2966         }
2968         // the act of sumbitting of assignment may be considered private - only graders will see it if specified
2969         if (empty($CFG->assignment_showrecentsubmissions)) {
2970             if (!array_key_exists($cm->id, $grader)) {
2971                 $grader[$cm->id] = has_capability('moodle/grade:viewall', get_context_instance(CONTEXT_MODULE, $cm->id));
2972             }
2973             if (!$grader[$cm->id]) {
2974                 continue;
2975             }
2976         }
2978         $groupmode = groups_get_activity_groupmode($cm, $course);
2980         if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2981             if (isguestuser()) {
2982                 // shortcut - guest user does not belong into any group
2983                 continue;
2984             }
2986             if (is_null($modinfo->groups)) {
2987                 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2988             }
2990             // this will be slow - show only users that share group with me in this cm
2991             if (empty($modinfo->groups[$cm->id])) {
2992                 continue;
2993             }
2994             $usersgroups =  groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
2995             if (is_array($usersgroups)) {
2996                 $usersgroups = array_keys($usersgroups);
2997                 $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2998                 if (empty($intersect)) {
2999                     continue;
3000                 }
3001             }
3002         }
3003         $show[] = $submission;
3004     }
3006     if (empty($show)) {
3007         return false;
3008     }
3010     echo $OUTPUT->heading(get_string('newsubmissions', 'assignment').':', 3);
3012     foreach ($show as $submission) {
3013         $cm = $modinfo->cms[$submission->cmid];
3014         $link = $CFG->wwwroot.'/mod/assignment/view.php?id='.$cm->id;
3015         print_recent_activity_note($submission->timemodified, $submission, $cm->name, $link, false, $viewfullnames);
3016     }
3018     return true;
3022 /**
3023  * Returns all assignments since a given time in specified forum.
3024  */
3025 function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0)  {
3026     global $CFG, $COURSE, $USER, $DB;
3028     if ($COURSE->id == $courseid) {
3029         $course = $COURSE;
3030     } else {
3031         $course = $DB->get_record('course', array('id'=>$courseid));
3032     }
3034     $modinfo =& get_fast_modinfo($course);
3036     $cm = $modinfo->cms[$cmid];
3038     $params = array();
3039     if ($userid) {
3040         $userselect = "AND u.id = :userid";
3041         $params['userid'] = $userid;
3042     } else {
3043         $userselect = "";
3044     }
3046     if ($groupid) {
3047         $groupselect = "AND gm.groupid = :groupid";
3048         $groupjoin   = "JOIN {groups_members} gm ON  gm.userid=u.id";
3049         $params['groupid'] = $groupid;
3050     } else {
3051         $groupselect = "";
3052         $groupjoin   = "";
3053     }
3055     $params['cminstance'] = $cm->instance;
3056     $params['timestart'] = $timestart;
3058     $userfields = user_picture::fields('u', null, 'userid');
3060     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified,
3061                                                      $userfields
3062                                                 FROM {assignment_submissions} asb
3063                                                 JOIN {assignment} a      ON a.id = asb.assignment
3064                                                 JOIN {user} u            ON u.id = asb.userid
3065                                           $groupjoin
3066                                                WHERE asb.timemodified > :timestart AND a.id = :cminstance
3067                                                      $userselect $groupselect
3068                                             ORDER BY asb.timemodified ASC", $params)) {
3069          return;
3070     }
3072     $groupmode       = groups_get_activity_groupmode($cm, $course);
3073     $cm_context      = get_context_instance(CONTEXT_MODULE, $cm->id);
3074     $grader          = has_capability('moodle/grade:viewall', $cm_context);
3075     $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
3076     $viewfullnames   = has_capability('moodle/site:viewfullnames', $cm_context);
3078     if (is_null($modinfo->groups)) {
3079         $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
3080     }
3082     $show = array();
3084     foreach($submissions as $submission) {
3085         if ($submission->userid == $USER->id) {
3086             $show[] = $submission;
3087             continue;
3088         }
3089         // the act of submitting of assignment may be considered private - only graders will see it if specified
3090         if (empty($CFG->assignment_showrecentsubmissions)) {
3091             if (!$grader) {
3092                 continue;
3093             }
3094         }
3096         if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
3097             if (isguestuser()) {
3098                 // shortcut - guest user does not belong into any group
3099                 continue;
3100             }
3102             // this will be slow - show only users that share group with me in this cm
3103             if (empty($modinfo->groups[$cm->id])) {
3104                 continue;
3105             }
3106             $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
3107             if (is_array($usersgroups)) {
3108                 $usersgroups = array_keys($usersgroups);
3109                 $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
3110                 if (empty($intersect)) {
3111                     continue;
3112                 }
3113             }
3114         }
3115         $show[] = $submission;
3116     }
3118     if (empty($show)) {
3119         return;
3120     }
3122     if ($grader) {
3123         require_once($CFG->libdir.'/gradelib.php');
3124         $userids = array();
3125         foreach ($show as $id=>$submission) {
3126             $userids[] = $submission->userid;
3128         }
3129         $grades = grade_get_grades($courseid, 'mod', 'assignment', $cm->instance, $userids);
3130     }
3132     $aname = format_string($cm->name,true);
3133     foreach ($show as $submission) {
3134         $tmpactivity = new stdClass();
3136         $tmpactivity->type         = 'assignment';
3137         $tmpactivity->cmid         = $cm->id;
3138         $tmpactivity->name         = $aname;
3139         $tmpactivity->sectionnum   = $cm->sectionnum;
3140         $tmpactivity->timestamp    = $submission->timemodified;
3142         if ($grader) {
3143             $tmpactivity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
3144         }
3146         $userfields = explode(',', user_picture::fields());
3147         foreach ($userfields as $userfield) {
3148             if ($userfield == 'id') {
3149                 $tmpactivity->user->{$userfield} = $submission->userid; // aliased in SQL above
3150             } else {
3151                 $tmpactivity->user->{$userfield} = $submission->{$userfield};
3152             }
3153         }
3154         $tmpactivity->user->fullname = fullname($submission, $viewfullnames);
3156         $activities[$index++] = $tmpactivity;
3157     }
3159     return;
3162 /**
3163  * Print recent activity from all assignments in a given course
3164  *
3165  * This is used by course/recent.php
3166  */
3167 function assignment_print_recent_mod_activity($activity, $courseid, $detail, $modnames)  {
3168     global $CFG, $OUTPUT;
3170     echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
3172     echo "<tr><td class=\"userpicture\" valign=\"top\">";
3173     echo $OUTPUT->user_picture($activity->user);
3174     echo "</td><td>";
3176     if ($detail) {
3177         $modname = $modnames[$activity->type];
3178         echo '<div class="title">';
3179         echo "<img src=\"" . $OUTPUT->pix_url('icon', 'assignment') . "\" ".
3180              "class=\"icon\" alt=\"$modname\">";
3181         echo "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id={$activity->cmid}\">{$activity->name}</a>";
3182         echo '</div>';
3183     }
3185     if (isset($activity->grade)) {
3186         echo '<div class="grade">';
3187         echo get_string('grade').': ';
3188         echo $activity->grade;
3189         echo '</div>';
3190     }
3192     echo '<div class="user">';
3193     echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->id}&amp;course=$courseid\">"
3194          ."{$activity->user->fullname}</a>  - ".userdate($activity->timestamp);
3195     echo '</div>';
3197     echo "</td></tr></table>";
3200 /// GENERIC SQL FUNCTIONS
3202 /**
3203  * Fetch info from logs
3204  *
3205  * @param $log object with properties ->info (the assignment id) and ->userid
3206  * @return array with assignment name and user firstname and lastname
3207  */
3208 function assignment_log_info($log) {
3209     global $CFG, $DB;
3211     return $DB->get_record_sql("SELECT a.name, u.firstname, u.lastname
3212                                   FROM {assignment} a, {user} u
3213                                  WHERE a.id = ? AND u.id = ?", array($log->info, $log->userid));
3216 /**
3217  * Return list of marked submissions that have not been mailed out for currently enrolled students
3218  *
3219  * @return array
3220  */
3221 function assignment_get_unmailed_submissions($starttime, $endtime) {
3222     global $CFG, $DB;
3224     return $DB->get_records_sql("SELECT s.*, a.course, a.name
3225                                    FROM {assignment_submissions} s,
3226                                         {assignment} a
3227                                   WHERE s.mailed = 0
3228                                         AND s.timemarked <= ?
3229                                         AND s.timemarked >= ?
3230                                         AND s.assignment = a.id", array($endtime, $starttime));
3233 /**
3234  * Counts all real assignment submissions by ENROLLED students (not empty ones)
3235  *
3236  * There are also assignment type methods count_real_submissions() which in the default
3237  * implementation simply call this function.
3238  * @param $groupid int optional If nonzero then count is restricted to this group
3239  * @return int The number of submissions
3240  */
3241 function assignment_count_real_submissions($cm, $groupid=0) {
3242     global $CFG, $DB;
3244     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
3246     // this is all the users with this capability set, in this context or higher
3247     if ($users = get_enrolled_users($context, 'mod/assignment:view', $groupid, 'u.id')) {
3248         $users = array_keys($users);
3249     }
3251     // if groupmembersonly used, remove users who are not in any group
3252     if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
3253         if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
3254             $users = array_intersect($users, array_keys($groupingusers));
3255         }
3256     }
3258     if (empty($users)) {
3259         return 0;
3260     }
3262     $userlists = implode(',', $users);
3264     return $DB->count_records_sql("SELECT COUNT('x')
3265                                      FROM {assignment_submissions}
3266                                     WHERE assignment = ? AND
3267                                           timemodified > 0 AND
3268                                           userid IN ($userlists)", array($cm->instance));
3272 /**
3273  * Return all assignment submissions by ENROLLED students (even empty)
3274  *
3275  * There are also assignment type methods get_submissions() wich in the default
3276  * implementation simply call this function.
3277  * @param $sort string optional field names for the ORDER BY in the sql query
3278  * @param $dir string optional specifying the sort direction, defaults to DESC
3279  * @return array The submission objects indexed by id
3280  */
3281 function assignment_get_all_submissions($assignment, $sort="", $dir="DESC") {
3282 /// Return all assignment submissions by ENROLLED students (even empty)
3283     global $CFG, $DB;
3285     if ($sort == "lastname" or $sort == "firstname") {
3286         $sort = "u.$sort $dir";
3287     } else if (empty($sort)) {
3288         $sort = "a.timemodified DESC";
3289     } else {
3290         $sort = "a.$sort $dir";
3291     }
3293     /* not sure this is needed at all since assignment already has a course define, so this join?
3294     $select = "s.course = '$assignment->course' AND";
3295     if ($assignment->course == SITEID) {
3296         $select = '';
3297     }*/
3299     return $DB->get_records_sql("SELECT a.*
3300                                    FROM {assignment_submissions} a, {user} u
3301                                   WHERE u.id = a.userid
3302                                         AND a.assignment = ?
3303                                ORDER BY $sort", array($assignment->id));
3307 /**
3308  * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
3309  * for the course (see resource).
3310  *
3311  * Given a course_module object, this function returns any "extra" information that may be needed
3312  * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
3313  *
3314  * @param $coursemodule object The coursemodule object (record).
3315  * @return object An object on information that the courses will know about (most noticeably, an icon).
3316  *
3317  */
3318 function assignment_get_coursemodule_info($coursemodule) {
3319     global $CFG, $DB;
3321     if (! $assignment = $DB->get_record('assignment', array('id'=>$coursemodule->instance), 'id, assignmenttype, name')) {
3322         return false;
3323     }
3325     $libfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
3327     if (file_exists($libfile)) {
3328         require_once($libfile);
3329         $assignmentclass = "assignment_$assignment->assignmenttype";
3330         $ass = new $assignmentclass('staticonly');
3331         if ($result = $ass->get_coursemodule_info($coursemodule)) {
3332             return $result;
3333         } else {
3334             $info = new stdClass();
3335             $info->name = $assignment->name;
3336             return $info;
3337         }
3339     } else {
3340         debugging('Incorrect assignment type: '.$assignment->assignmenttype);
3341         return false;
3342     }
3347 /// OTHER GENERAL FUNCTIONS FOR ASSIGNMENTS  ///////////////////////////////////////
3349 /**
3350  * Returns an array of installed assignment types indexed and sorted by name
3351  *
3352  * @return array The index is the name of the assignment type, the value its full name from the language strings
3353  */
3354 function assignment_types() {
3355     $types = array();
3356     $names = get_plugin_list('assignment');
3357     foreach ($names as $name=>$dir) {
3358         $types[$name] = get_string('type'.$name, 'assignment');
3360         // ugly hack to support pluggable assignment type titles..
3361         if ($types[$name] == '[[type'.$name.']]') {
3362             $types[$name] = get_string('type'.$name, 'assignment_'.$name);
3363         }
3364     }
3365     asort($types);
3366     return $types;
3369 function assignment_print_overview($courses, &$htmlarray) {
3370     global $USER, $CFG, $DB;
3372     if (empty($courses) || !is_array($courses) || count($courses) == 0) {
3373         return array();
3374     }
3376     if (!$assignments = get_all_instances_in_courses('assignment',$courses)) {
3377         return;
3378     }
3380     $assignmentids = array();
3382     // Do assignment_base::isopen() here without loading the whole thing for speed
3383     foreach ($assignments as $key => $assignment) {
3384         $time = time();
3385         if ($assignment->timedue) {
3386             if ($assignment->preventlate) {
3387                 $isopen = ($assignment->timeavailable <= $time && $time <= $assignment->timedue);
3388             } else {
3389                 $isopen = ($assignment->timeavailable <= $time);
3390             }
3391         }
3392         if (empty($isopen) || empty($assignment->timedue)) {
3393             unset($assignments[$key]);
3394         } else {
3395             $assignmentids[] = $assignment->id;
3396         }
3397     }
3399     if (empty($assignmentids)){
3400         // no assignments to look at - we're done
3401         return true;
3402     }
3404     $strduedate = get_string('duedate', 'assignment');
3405     $strduedateno = get_string('duedateno', 'assignment');
3406     $strgraded = get_string('graded', 'assignment');
3407     $strnotgradedyet = get_string('notgradedyet', 'assignment');
3408     $strnotsubmittedyet = get_string('notsubmittedyet', 'assignment');
3409     $strsubmitted = get_string('submitted', 'assignment');
3410     $strassignment = get_string('modulename', 'assignment');
3411     $strreviewed = get_string('reviewed','assignment');
3414     // NOTE: we do all possible database work here *outside* of the loop to ensure this scales
3415     //
3416     list($sqlassignmentids, $assignmentidparams) = $DB->get_in_or_equal($assignmentids);
3418     // build up and array of unmarked submissions indexed by assignment id/ userid
3419     // for use where the user has grading rights on assignment
3420     $rs = $DB->get_recordset_sql("SELECT id, assignment, userid
3421                             FROM {assignment_submissions}
3422                             WHERE teacher = 0 AND timemarked = 0
3423                             AND assignment $sqlassignmentids", $assignmentidparams);
3425     $unmarkedsubmissions = array();
3426     foreach ($rs as $rd) {
3427         $unmarkedsubmissions[$rd->assignment][$rd->userid] = $rd->id;
3428     }
3429     $rs->close();
3432     // get all user submissions, indexed by assignment id
3433     $mysubmissions = $DB->get_records_sql("SELECT assignment, timemarked, teacher, grade
3434                                       FROM {assignment_submissions}
3435                                       WHERE userid = ? AND
3436                                       assignment $sqlassignmentids", array_merge(array($USER->id), $assignmentidparams));
3438     foreach ($assignments as $assignment) {
3439         $str = '<div class="assignment overview"><div class="name">'.$strassignment. ': '.
3440                '<a '.($assignment->visible ? '':' class="dimmed"').
3441                'title="'.$strassignment.'" href="'.$CFG->wwwroot.
3442                '/mod/assignment/view.php?id='.$assignment->coursemodule.'">'.
3443                $assignment->name.'</a></div>';
3444         if ($assignment->timedue) {
3445             $str .= '<div class="info">'.$strduedate.': '.userdate($assignment->timedue).'</div>';
3446         } else {
3447             $str .= '<div class="info">'.$strduedateno.'</div>';
3448         }
3449         $context = get_context_instance(CONTEXT_MODULE, $assignment->coursemodule);
3450         if (has_capability('mod/assignment:grade', $context)) {
3452             // count how many people can submit
3453             $submissions = 0; // init
3454             if ($students = get_enrolled_users($context, 'mod/assignment:view', 0, 'u.id')) {
3455                 foreach ($students as $student) {
3456                     if (isset($unmarkedsubmissions[$assignment->id][$student->id])) {
3457                         $submissions++;
3458                     }
3459                 }
3460             }
3462             if ($submissions) {
3463                 $link = new moodle_url('/mod/assignment/submissions.php', array('id'=>$assignment->coursemodule));
3464                 $str .= '<div class="details"><a href="'.$link.'">'.get_string('submissionsnotgraded', 'assignment', $submissions).'</a></div>';
3465             }
3466         } else {
3467             $str .= '<div class="details">';
3468             if (isset($mysubmissions[$assignment->id])) {
3470                 $submission = $mysubmissions[$assignment->id];
3472                 if ($submission->teacher == 0 && $submission->timemarked == 0) {
3473                     $str .= $strsubmitted . ', ' . $strnotgradedyet;
3474                 } else if ($submission->grade <= 0) {
3475                     $str .= $strsubmitted . ', ' . $strreviewed;
3476                 } else {
3477                     $str .= $strsubmitted . ', ' . $strgraded;
3478                 }
3479             } else {
3480                 $str .= $strnotsubmittedyet . ' ' . assignment_display_lateness(time(), $assignment->timedue);
3481             }
3482             $str .= '</div>';
3483         }
3484         $str .= '</div>';
3485         if (empty($htmlarray[$assignment->course]['assignment'])) {
3486             $htmlarray[$assignment->course]['assignment'] = $str;
3487         } else {
3488             $htmlarray[$assignment->course]['assignment'] .= $str;
3489         }
3490     }
3493 function assignment_display_lateness($timesubmitted, $timedue) {
3494     if (!$timedue) {
3495         return '';
3496     }
3497     $time = $timedue - $timesubmitted;
3498     if ($time < 0) {
3499         $timetext = get_string('late', 'assignment', format_time($time));
3500         return ' (<span class="late">'.$timetext.'</span>)';
3501     } else {
3502         $timetext = get_string('early', 'assignment', format_time($time));
3503         return ' (<span class="early">'.$timetext.'</span>)';
3504     }
3507 function assignment_get_view_actions() {
3508     return array('view');
3511 function assignment_get_post_actions() {
3512     return array('upload');
3515 function assignment_get_types() {
3516     global $CFG;
3517     $types = array();
3519     $type = new stdClass();
3520     $type->modclass = MOD_CLASS_ACTIVITY;
3521     $type->type = "assignment_group_start";
3522     $type->typestr = '--'.get_string('modulenameplural', 'assignment');
3523     $types[] = $type;
3525     $standardassignments = array('upload','online','uploadsingle','offline');
3526     foreach ($standardassignments as $assignmenttype) {
3527         $type = new stdClass();
3528         $type->modclass = MOD_CLASS_ACTIVITY;
3529         $type->type = "assignment&amp;type=$assignmenttype";
3530         $type->typestr = get_string("type$assignmenttype", 'assignment');
3531         $types[] = $type;
3532     }
3534     /// Drop-in extra assignment types
3535     $assignmenttypes = get_list_of_plugins('mod/assignment/type');
3536     foreach ($assignmenttypes as $assignmenttype) {
3537         if (!empty($CFG->{'assignment_hide_'.$assignmenttype})) {  // Not wanted
3538             continue;
3539         }
3540         if (!in_array($assignmenttype, $standardassignments)) {
3541             $type = new stdClass();
3542             $type->modclass = MOD_CLASS_ACTIVITY;
3543             $type->type = "assignment&amp;type=$assignmenttype";
3544             $type->typestr = get_string("type$assignmenttype", 'assignment_'.$assignmenttype);
3545             $types[] = $type;
3546         }
3547     }
3549     $type = new stdClass();
3550     $type->modclass = MOD_CLASS_ACTIVITY;
3551     $type->type = "assignment_group_end";
3552     $type->typestr = '--';
3553     $types[] = $type;
3555     return $types;
3558 /**
3559  * Removes all grades from gradebook
3560  * @param int $courseid
3561  * @param string optional type
3562  */
3563 function assignment_reset_gradebook($courseid, $type='') {
3564     global $CFG, $DB;
3566     $params = array('courseid'=>$courseid);
3567     if ($type) {
3568         $type = "AND a.assignmenttype= :type";
3569         $params['type'] = $type;
3570     }
3572     $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
3573               FROM {assignment} a, {course_modules} cm, {modules} m
3574              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id AND a.course=:courseid $type";
3576     if ($assignments = $DB->get_records_sql($sql, $params)) {
3577         foreach ($assignments as $assignment) {
3578             assignment_grade_item_update($assignment, 'reset');
3579         }
3580     }
3583 /**
3584  * This function is used by the reset_course_userdata function in moodlelib.
3585  * This function will remove all posts from the specified assignment
3586  * and clean up any related data.
3587  * @param $data the data submitted from the reset course.
3588  * @return array status array
3589  */
3590 function assignment_reset_userdata($data) {
3591     global $CFG;
3593     $status = array();
3594     foreach (get_plugin_list('assignment') as $type=>$dir) {
3595         require_once("$dir/assignment.class.php");
3596         $assignmentclass = "assignment_$type";
3597         $ass = new $assignmentclass();
3598         $status = array_merge($status, $ass->reset_userdata($data));
3599     }
3601     return $status;
3604 /**
3605  * Implementation of the function for printing the form elements that control
3606  * whether the course reset functionality affects the assignment.
3607  * @param $mform form passed by reference
3608  */
3609 function assignment_reset_course_form_definition(&$mform) {
3610     $mform->addElement('header', 'assignmentheader', get_string('modulenameplural', 'assignment'));
3611     $mform->addElement('advcheckbox', 'reset_assignment_submissions', get_string('deleteallsubmissions','assignment'));
3614 /**
3615  * Course reset form defaults.
3616  */
3617 function assignment_reset_course_form_defaults($course) {
3618     return array('reset_assignment_submissions'=>1);
3621 /**
3622  * Returns all other caps used in module
3623  */
3624 function assignment_get_extra_capabilities() {
3625     return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames');
3628 /**
3629  * @param string $feature FEATURE_xx constant for requested feature
3630  * @return mixed True if module supports feature, null if doesn't know
3631  */
3632 function assignment_supports($feature) {
3633     switch($feature) {
3634         case FEATURE_GROUPS:                  return true;
3635         case FEATURE_GROUPINGS:               return true;
3636         case FEATURE_GROUPMEMBERSONLY:        return true;
3637         case FEATURE_MOD_INTRO:               return true;
3638         case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
3639         case FEATURE_GRADE_HAS_GRADE:         return true;
3640         case FEATURE_GRADE_OUTCOMES:          return true;
3641         case FEATURE_GRADE_HAS_GRADE:         return true;
3642         case FEATURE_BACKUP_MOODLE2:          return true;
3644         default: return null;
3645     }
3648 /**
3649  * Adds module specific settings to the settings block
3650  *
3651  * @param settings_navigation $settings The settings navigation object
3652  * @param navigation_node $assignmentnode The node to add module settings to
3653  */
3654 function assignment_extend_settings_navigation(settings_navigation $settings, navigation_node $assignmentnode) {
3655     global $PAGE, $DB, $USER, $CFG;
3657     $assignmentrow = $DB->get_record("assignment", array("id" => $PAGE->cm->instance));
3658     require_once "$CFG->dirroot/mod/assignment/type/$assignmentrow->assignmenttype/assignment.class.php";
3660     $assignmentclass = 'assignment_'.$assignmentrow->assignmenttype;
3661     $assignmentinstance = new $assignmentclass($PAGE->cm->id, $assignmentrow, $PAGE->cm, $PAGE->course);
3663     $allgroups = false;
3665     // Add assignment submission information
3666     if (has_capability('mod/assignment:grade', $PAGE->cm->context)) {
3667         if ($allgroups && has_capability('moodle/site:accessallgroups', $PAGE->cm->context)) {
3668             $group = 0;
3669         } else {
3670             $group = groups_get_activity_group($PAGE->cm);
3671         }
3672         $link = new moodle_url('/mod/assignment/submissions.php', array('id'=>$PAGE->cm->id));
3673         if ($count = $assignmentinstance->count_real_submissions($group)) {
3674             $string = get_string('viewsubmissions', 'assignment', $count);
3675         } else {
3676             $string = get_string('noattempts', 'assignment');
3677         }
3678         $assignmentnode->add($string, $link, navigation_node::TYPE_SETTING);
3679     }
3681     if (is_object($assignmentinstance) && method_exists($assignmentinstance, 'extend_settings_navigation')) {
3682         $assignmentinstance->extend_settings_navigation($assignmentnode);
3683     }
3686 /**
3687  * generate zip file from array of given files
3688  * @param array $filesforzipping - array of files to pass into archive_to_pathname
3689  * @return path of temp file - note this returned file does not have a .zip extension - it is a temp file.
3690  */
3691 function assignment_pack_files($filesforzipping) {
3692         global $CFG;
3693         //create path for new zip file.
3694         $tempzip = tempnam($CFG->dataroot.'/temp/', 'assignment_');
3695         //zip files
3696         $zipper = new zip_packer();
3697         if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
3698             return $tempzip;
3699         }
3700         return false;
3703 /**
3704  * Lists all file areas current user may browse
3705  *
3706  * @param object $course
3707  * @param object $cm
3708  * @param object $context
3709  * @return array
3710  */
3711 function assignment_get_file_areas($course, $cm, $context) {
3712     $areas = array();
3713     if (has_capability('moodle/course:managefiles', $context)) {
3714         $areas['submission'] = get_string('assignmentsubmission', 'assignment');
3715     }
3716     return $areas;