71e2d79dae5f046db5c5069c4b0dfd8ace7a8622
[moodle.git] / mod / assignment / lib.php
1 <?PHP
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
18 /**
19  * assignment_base is the base class for assignment types
20  *
21  * This class provides all the functionality for an assignment
22  *
23  * @package   mod-assignment
24  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
25  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26  */
28 /** Include eventslib.php */
29 require_once($CFG->libdir.'/eventslib.php');
30 /** Include formslib.php */
31 require_once($CFG->libdir.'/formslib.php');
32 /** Include calendar/lib.php */
33 require_once($CFG->dirroot.'/calendar/lib.php');
35 /** ASSIGNMENT_COUNT_WORDS = 1 */
36 DEFINE ('ASSIGNMENT_COUNT_WORDS', 1);
37 /** ASSIGNMENT_COUNT_LETTERS = 2 */
38 DEFINE ('ASSIGNMENT_COUNT_LETTERS', 2);
40 /**
41  * Standard base class for all assignment submodules (assignment types).
42  *
43  * @package   mod-assignment
44  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
45  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
46  */
47 class assignment_base {
49     /** @var object */
50     var $cm;
51     /** @var object */
52     var $course;
53     /** @var object */
54     var $assignment;
55     /** @var string */
56     var $strassignment;
57     /** @var string */
58     var $strassignments;
59     /** @var string */
60     var $strsubmissions;
61     /** @var string */
62     var $strlastmodified;
63     /** @var string */
64     var $pagetitle;
65     /** @var bool */
66     var $usehtmleditor;
67     /**
68      * @todo document this var
69      */
70     var $defaultformat;
71     /**
72      * @todo document this var
73      */
74     var $context;
75     /** @var string */
76     var $type;
78     /**
79      * Constructor for the base assignment class
80      *
81      * Constructor for the base assignment class.
82      * If cmid is set create the cm, course, assignment objects.
83      * If the assignment is hidden and the user is not a teacher then
84      * this prints a page header and notice.
85      *
86      * @global object
87      * @global object
88      * @param int $cmid the current course module id - not set for new assignments
89      * @param object $assignment usually null, but if we have it we pass it to save db access
90      * @param object $cm usually null, but if we have it we pass it to save db access
91      * @param object $course usually null, but if we have it we pass it to save db access
92      */
93     function assignment_base($cmid='staticonly', $assignment=NULL, $cm=NULL, $course=NULL) {
94         global $COURSE, $DB;
96         if ($cmid == 'staticonly') {
97             //use static functions only!
98             return;
99         }
101         global $CFG;
103         if ($cm) {
104             $this->cm = $cm;
105         } else if (! $this->cm = get_coursemodule_from_id('assignment', $cmid)) {
106             print_error('invalidcoursemodule');
107         }
109         $this->context = get_context_instance(CONTEXT_MODULE, $this->cm->id);
111         if ($course) {
112             $this->course = $course;
113         } else if ($this->cm->course == $COURSE->id) {
114             $this->course = $COURSE;
115         } else if (! $this->course = $DB->get_record('course', array('id'=>$this->cm->course))) {
116             print_error('invalidid', 'assignment');
117         }
119         if ($assignment) {
120             $this->assignment = $assignment;
121         } else if (! $this->assignment = $DB->get_record('assignment', array('id'=>$this->cm->instance))) {
122             print_error('invalidid', 'assignment');
123         }
125         $this->assignment->cmidnumber = $this->cm->idnumber; // compatibility with modedit assignment obj
126         $this->assignment->courseid   = $this->course->id; // compatibility with modedit assignment obj
128         $this->strassignment = get_string('modulename', 'assignment');
129         $this->strassignments = get_string('modulenameplural', 'assignment');
130         $this->strsubmissions = get_string('submissions', 'assignment');
131         $this->strlastmodified = get_string('lastmodified');
132         $this->pagetitle = strip_tags($this->course->shortname.': '.$this->strassignment.': '.format_string($this->assignment->name,true));
134         // visibility handled by require_login() with $cm parameter
135         // get current group only when really needed
137     /// Set up things for a HTML editor if it's needed
138         if ($this->usehtmleditor = can_use_html_editor()) {
139             $this->defaultformat = FORMAT_HTML;
140         } else {
141             $this->defaultformat = FORMAT_MOODLE;
142         }
143     }
145     /**
146      * Display the assignment, used by view.php
147      *
148      * This in turn calls the methods producing individual parts of the page
149      */
150     function view() {
152         $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
153         require_capability('mod/assignment:view', $context);
155         add_to_log($this->course->id, "assignment", "view", "view.php?id={$this->cm->id}",
156                    $this->assignment->id, $this->cm->id);
158         $this->view_header();
160         $this->view_intro();
162         $this->view_dates();
164         $this->view_feedback();
166         $this->view_footer();
167     }
169     /**
170      * Display the header and top of a page
171      *
172      * (this doesn't change much for assignment types)
173      * This is used by the view() method to print the header of view.php but
174      * it can be used on other pages in which case the string to denote the
175      * page in the navigation trail should be passed as an argument
176      *
177      * @global object
178      * @param string $subpage Description of subpage to be used in navigation trail
179      */
180     function view_header($subpage='') {
181         global $CFG, $PAGE, $OUTPUT;
183         if ($subpage) {
184             $PAGE->navbar->add($subpage);
185         }
187         $PAGE->set_title($this->pagetitle);
188         $PAGE->set_heading($this->course->fullname);
190         echo $OUTPUT->header();
192         groups_print_activity_menu($this->cm, $CFG->wwwroot . '/mod/assignment/view.php?id=' . $this->cm->id);
194         echo '<div class="reportlink">'.$this->submittedlink().'</div>';
195         echo '<div class="clearer"></div>';
196     }
199     /**
200      * Display the assignment intro
201      *
202      * This will most likely be extended by assignment type plug-ins
203      * The default implementation prints the assignment description in a box
204      */
205     function view_intro() {
206         global $OUTPUT;
207         echo $OUTPUT->box_start('generalbox boxaligncenter', 'intro');
208         echo format_module_intro('assignment', $this->assignment, $this->cm->id);
209         echo $OUTPUT->box_end();
210     }
212     /**
213      * Display the assignment dates
214      *
215      * Prints the assignment start and end dates in a box.
216      * This will be suitable for most assignment types
217      */
218     function view_dates() {
219         global $OUTPUT;
220         if (!$this->assignment->timeavailable && !$this->assignment->timedue) {
221             return;
222         }
224         echo $OUTPUT->box_start('generalbox boxaligncenter', 'dates');
225         echo '<table>';
226         if ($this->assignment->timeavailable) {
227             echo '<tr><td class="c0">'.get_string('availabledate','assignment').':</td>';
228             echo '    <td class="c1">'.userdate($this->assignment->timeavailable).'</td></tr>';
229         }
230         if ($this->assignment->timedue) {
231             echo '<tr><td class="c0">'.get_string('duedate','assignment').':</td>';
232             echo '    <td class="c1">'.userdate($this->assignment->timedue).'</td></tr>';
233         }
234         echo '</table>';
235         echo $OUTPUT->box_end();
236     }
239     /**
240      * Display the bottom and footer of a page
241      *
242      * This default method just prints the footer.
243      * This will be suitable for most assignment types
244      */
245     function view_footer() {
246         global $OUTPUT;
247         echo $OUTPUT->footer();
248     }
250     /**
251      * Display the feedback to the student
252      *
253      * This default method prints the teacher picture and name, date when marked,
254      * grade and teacher submissioncomment.
255      *
256      * @global object
257      * @global object
258      * @global object
259      * @param object $submission The submission object or NULL in which case it will be loaded
260      */
261     function view_feedback($submission=NULL) {
262         global $USER, $CFG, $DB, $OUTPUT;
263         require_once($CFG->libdir.'/gradelib.php');
265         if (!has_capability('mod/assignment:submit', $this->context, $USER->id, false)) {
266             // can not submit assignments -> no feedback
267             return;
268         }
270         if (!$submission) { /// Get submission for this assignment
271             $submission = $this->get_submission($USER->id);
272         }
274         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $USER->id);
275         $item = $grading_info->items[0];
276         $grade = $item->grades[$USER->id];
278         if ($grade->hidden or $grade->grade === false) { // hidden or error
279             return;
280         }
282         if ($grade->grade === null and empty($grade->str_feedback)) {   /// Nothing to show yet
283             return;
284         }
286         $graded_date = $grade->dategraded;
287         $graded_by   = $grade->usermodified;
289     /// We need the teacher info
290         if (!$teacher = $DB->get_record('user', array('id'=>$graded_by))) {
291             print_error('cannotfindteacher');
292         }
294     /// Print the feedback
295         echo $OUTPUT->heading(get_string('feedbackfromteacher', 'assignment', fullname($teacher)));
297         echo '<table cellspacing="0" class="feedback">';
299         echo '<tr>';
300         echo '<td class="left picture">';
301         if ($teacher) {
302             echo $OUTPUT->user_picture($teacher);
303         }
304         echo '</td>';
305         echo '<td class="topic">';
306         echo '<div class="from">';
307         if ($teacher) {
308             echo '<div class="fullname">'.fullname($teacher).'</div>';
309         }
310         echo '<div class="time">'.userdate($graded_date).'</div>';
311         echo '</div>';
312         echo '</td>';
313         echo '</tr>';
315         echo '<tr>';
316         echo '<td class="left side">&nbsp;</td>';
317         echo '<td class="content">';
318         echo '<div class="grade">';
319         echo get_string("grade").': '.$grade->str_long_grade;
320         echo '</div>';
321         echo '<div class="clearer"></div>';
323         echo '<div class="comment">';
324         echo $grade->str_feedback;
325         echo '</div>';
326         echo '</tr>';
328         echo '</table>';
329     }
331     /**
332      * Returns a link with info about the state of the assignment submissions
333      *
334      * This is used by view_header to put this link at the top right of the page.
335      * For teachers it gives the number of submitted assignments with a link
336      * For students it gives the time of their submission.
337      * This will be suitable for most assignment types.
338      *
339      * @global object
340      * @global object
341      * @param bool $allgroup print all groups info if user can access all groups, suitable for index.php
342      * @return string
343      */
344     function submittedlink($allgroups=false) {
345         global $USER;
346         global $CFG;
348         $submitted = '';
349         $urlbase = "{$CFG->wwwroot}/mod/assignment/";
351         $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
352         if (has_capability('mod/assignment:grade', $context)) {
353             if ($allgroups and has_capability('moodle/site:accessallgroups', $context)) {
354                 $group = 0;
355             } else {
356                 $group = groups_get_activity_group($this->cm);
357             }
358             if ($count = $this->count_real_submissions($group)) {
359                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
360                              get_string('viewsubmissions', 'assignment', $count).'</a>';
361             } else {
362                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
363                              get_string('noattempts', 'assignment').'</a>';
364             }
365         } else {
366             if (isloggedin()) {
367                 if ($submission = $this->get_submission($USER->id)) {
368                     if ($submission->timemodified) {
369                         if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
370                             $submitted = '<span class="early">'.userdate($submission->timemodified).'</span>';
371                         } else {
372                             $submitted = '<span class="late">'.userdate($submission->timemodified).'</span>';
373                         }
374                     }
375                 }
376             }
377         }
379         return $submitted;
380     }
383     /**
384      * @todo Document this function
385      */
386     function setup_elements(&$mform) {
388     }
390     /**
391      * Create a new assignment activity
392      *
393      * Given an object containing all the necessary data,
394      * (defined by the form in mod_form.php) this function
395      * will create a new instance and return the id number
396      * of the new instance.
397      * The due data is added to the calendar
398      * This is common to all assignment types.
399      *
400      * @global object
401      * @global object
402      * @param object $assignment The data from the form on mod_form.php
403      * @return int The id of the assignment
404      */
405     function add_instance($assignment) {
406         global $COURSE, $DB;
408         $assignment->timemodified = time();
409         $assignment->courseid = $assignment->course;
411         if ($returnid = $DB->insert_record("assignment", $assignment)) {
412             $assignment->id = $returnid;
414             if ($assignment->timedue) {
415                 $event = new object();
416                 $event->name        = $assignment->name;
417                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
418                 $event->courseid    = $assignment->course;
419                 $event->groupid     = 0;
420                 $event->userid      = 0;
421                 $event->modulename  = 'assignment';
422                 $event->instance    = $returnid;
423                 $event->eventtype   = 'due';
424                 $event->timestart   = $assignment->timedue;
425                 $event->timeduration = 0;
427                 calendar_event::create($event);
428             }
430             assignment_grade_item_update($assignment);
432         }
435         return $returnid;
436     }
438     /**
439      * Deletes an assignment activity
440      *
441      * Deletes all database records, files and calendar events for this assignment.
442      *
443      * @global object
444      * @global object
445      * @param object $assignment The assignment to be deleted
446      * @return boolean False indicates error
447      */
448     function delete_instance($assignment) {
449         global $CFG, $DB;
451         $assignment->courseid = $assignment->course;
453         $result = true;
455         // now get rid of all files
456         $fs = get_file_storage();
457         if ($cm = get_coursemodule_from_instance('assignment', $assignment->id)) {
458             $context = get_context_instance(CONTEXT_MODULE, $cm->id);
459             $fs->delete_area_files($context->id);
460         }
462         if (! $DB->delete_records('assignment_submissions', array('assignment'=>$assignment->id))) {
463             $result = false;
464         }
466         if (! $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
467             $result = false;
468         }
470         if (! $DB->delete_records('assignment', array('id'=>$assignment->id))) {
471             $result = false;
472         }
473         $mod = $DB->get_field('modules','id',array('name'=>'assignment'));
475         assignment_grade_item_delete($assignment);
477         return $result;
478     }
480     /**
481      * Updates a new assignment activity
482      *
483      * Given an object containing all the necessary data,
484      * (defined by the form in mod_form.php) this function
485      * will update the assignment instance and return the id number
486      * The due date is updated in the calendar
487      * This is common to all assignment types.
488      *
489      * @global object
490      * @global object
491      * @param object $assignment The data from the form on mod_form.php
492      * @return int The assignment id
493      */
494     function update_instance($assignment) {
495         global $COURSE, $DB;
497         $assignment->timemodified = time();
499         $assignment->id = $assignment->instance;
500         $assignment->courseid = $assignment->course;
502         $DB->update_record('assignment', $assignment);
504         if ($assignment->timedue) {
505             $event = new object();
507             if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
509                 $event->name        = $assignment->name;
510                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
511                 $event->timestart   = $assignment->timedue;
513                 $calendarevent = calendar_event::load($event->id);
514                 $calendarevent->update($event);
515             } else {
516                 $event = new object();
517                 $event->name        = $assignment->name;
518                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
519                 $event->courseid    = $assignment->course;
520                 $event->groupid     = 0;
521                 $event->userid      = 0;
522                 $event->modulename  = 'assignment';
523                 $event->instance    = $assignment->id;
524                 $event->eventtype   = 'due';
525                 $event->timestart   = $assignment->timedue;
526                 $event->timeduration = 0;
528                 calendar_event::create($event);
529             }
530         } else {
531             $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id));
532         }
534         // get existing grade item
535         assignment_grade_item_update($assignment);
537         return true;
538     }
540     /**
541      * Update grade item for this submission.
542      */
543     function update_grade($submission) {
544         assignment_update_grades($this->assignment, $submission->userid);
545     }
547     /**
548      * Top-level function for handling of submissions called by submissions.php
549      *
550      * This is for handling the teacher interaction with the grading interface
551      * This should be suitable for most assignment types.
552      *
553      * @global object
554      * @param string $mode Specifies the kind of teacher interaction taking place
555      */
556     function submissions($mode) {
557         ///The main switch is changed to facilitate
558         ///1) Batch fast grading
559         ///2) Skip to the next one on the popup
560         ///3) Save and Skip to the next one on the popup
562         //make user global so we can use the id
563         global $USER, $OUTPUT, $DB, $PAGE;
565         $mailinfo = optional_param('mailinfo', null, PARAM_BOOL);
566         $saved = optional_param('saved', null, PARAM_BOOL);
568         if(optional_param('next', null, PARAM_BOOL)) {
569             $mode='next';
570         }
571         if(optional_param('saveandnext', null, PARAM_BOOL)) {
572             $mode='saveandnext';
573         }
575         if (is_null($mailinfo)) {
576             $mailinfo = get_user_preferences('assignment_mailinfo', 0);
577         } else {
578             set_user_preference('assignment_mailinfo', $mailinfo);
579         }
581         if($saved) {
582             $OUTPUT->heading(get_string('changessaved'));
583         }
585         switch ($mode) {
586             case 'grade':                         // We are in a main window grading
587                 if ($submission = $this->process_feedback()) {
588                     $this->display_submissions(get_string('changessaved'));
589                 } else {
590                     $this->display_submissions();
591                 }
592                 break;
594             case 'single':                        // We are in a main window displaying one submission
595                 if ($submission = $this->process_feedback()) {
596                     $this->display_submissions(get_string('changessaved'));
597                 } else {
598                     $this->display_submission();
599                 }
600                 break;
602             case 'all':                          // Main window, display everything
603                 $this->display_submissions();
604                 break;
606             case 'fastgrade':
607                 ///do the fast grading stuff  - this process should work for all 3 subclasses
608                 $grading    = false;
609                 $commenting = false;
610                 $col        = false;
611                 if (isset($_POST['submissioncomment'])) {
612                     $col = 'submissioncomment';
613                     $commenting = true;
614                 }
615                 if (isset($_POST['menu'])) {
616                     $col = 'menu';
617                     $grading = true;
618                 }
619                 if (!$col) {
620                     //both submissioncomment and grade columns collapsed..
621                     $this->display_submissions();
622                     break;
623                 }
625                 foreach ($_POST[$col] as $id => $unusedvalue){
627                     $id = (int)$id; //clean parameter name
629                     $this->process_outcomes($id);
631                     if (!$submission = $this->get_submission($id)) {
632                         $submission = $this->prepare_new_submission($id);
633                         $newsubmission = true;
634                     } else {
635                         $newsubmission = false;
636                     }
637                     unset($submission->data1);  // Don't need to update this.
638                     unset($submission->data2);  // Don't need to update this.
640                     //for fast grade, we need to check if any changes take place
641                     $updatedb = false;
643                     if ($grading) {
644                         $grade = $_POST['menu'][$id];
645                         $updatedb = $updatedb || ($submission->grade != $grade);
646                         $submission->grade = $grade;
647                     } else {
648                         if (!$newsubmission) {
649                             unset($submission->grade);  // Don't need to update this.
650                         }
651                     }
652                     if ($commenting) {
653                         $commentvalue = trim($_POST['submissioncomment'][$id]);
654                         $updatedb = $updatedb || ($submission->submissioncomment != $commentvalue);
655                         $submission->submissioncomment = $commentvalue;
656                     } else {
657                         unset($submission->submissioncomment);  // Don't need to update this.
658                     }
660                     $submission->teacher    = $USER->id;
661                     if ($updatedb) {
662                         $submission->mailed = (int)(!$mailinfo);
663                     }
665                     $submission->timemarked = time();
667                     //if it is not an update, we don't change the last modified time etc.
668                     //this will also not write into database if no submissioncomment and grade is entered.
670                     if ($updatedb){
671                         if ($newsubmission) {
672                             if (!isset($submission->submissioncomment)) {
673                                 $submission->submissioncomment = '';
674                             }
675                             $sid = $DB->insert_record('assignment_submissions', $submission);
676                             $submission->id = $sid;
677                         } else {
678                             $DB->update_record('assignment_submissions', $submission);
679                         }
681                         // triger grade event
682                         $this->update_grade($submission);
684                         //add to log only if updating
685                         add_to_log($this->course->id, 'assignment', 'update grades',
686                                    'submissions.php?id='.$this->assignment->id.'&user='.$submission->userid,
687                                    $submission->userid, $this->cm->id);
688                     }
690                 }
692                 $message = $OUTPUT->notification(get_string('changessaved'), 'notifysuccess');
694                 $this->display_submissions($message);
695                 break;
698             case 'saveandnext':
699                 ///We are in pop up. save the current one and go to the next one.
700                 //first we save the current changes
701                 if ($submission = $this->process_feedback()) {
702                     //print_heading(get_string('changessaved'));
703                     //$extra_javascript = $this->update_main_listing($submission);
704                 }
706             case 'next':
707                 /// We are currently in pop up, but we want to skip to next one without saving.
708                 ///    This turns out to be similar to a single case
709                 /// The URL used is for the next submission.
710                 $offset = required_param('offset', PARAM_INT);
711                 $nextid = required_param('nextid', PARAM_INT);
712                 $id = required_param('id', PARAM_INT);
713                 $offset = (int)$offset+1;
714                 //$this->display_submission($offset+1 , $nextid);
715                 redirect('submissions.php?id='.$id.'&userid='. $nextid . '&mode=single&offset='.$offset);
716                 break;
718             default:
719                 echo "something seriously is wrong!!";
720                 break;
721         }
722     }
724     /**
725      * Helper method updating the listing on the main script from popup using javascript
726      *
727      * @global object
728      * @global object
729      * @param $submission object The submission whose data is to be updated on the main page
730      */
731     function update_main_listing($submission) {
732         global $SESSION, $CFG, $OUTPUT;
734         $output = '';
736         $perpage = get_user_preferences('assignment_perpage', 10);
738         $quickgrade = get_user_preferences('assignment_quickgrade', 0);
740         /// Run some Javascript to try and update the parent page
741         $output .= '<script type="text/javascript">'."\n<!--\n";
742         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['submissioncomment'])) {
743             if ($quickgrade){
744                 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid.'").value="'
745                 .trim($submission->submissioncomment).'";'."\n";
746              } else {
747                 $output.= 'opener.document.getElementById("com'.$submission->userid.
748                 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment)), 15)."\";\n";
749             }
750         }
752         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['grade'])) {
753             //echo optional_param('menuindex');
754             if ($quickgrade){
755                 $output.= 'opener.document.getElementById("menumenu'.$submission->userid.
756                 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT).'";'."\n";
757             } else {
758                 $output.= 'opener.document.getElementById("g'.$submission->userid.'").innerHTML="'.
759                 $this->display_grade($submission->grade)."\";\n";
760             }
761         }
762         //need to add student's assignments in there too.
763         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemodified']) &&
764             $submission->timemodified) {
765             $output.= 'opener.document.getElementById("ts'.$submission->userid.
766                  '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid)).userdate($submission->timemodified)."\";\n";
767         }
769         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemarked']) &&
770             $submission->timemarked) {
771             $output.= 'opener.document.getElementById("tt'.$submission->userid.
772                  '").innerHTML="'.userdate($submission->timemarked)."\";\n";
773         }
775         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['status'])) {
776             $output.= 'opener.document.getElementById("up'.$submission->userid.'").className="s1";';
777             $buttontext = get_string('update');
778             $url = new moodle_url('/mod/assignment/submissions.php', array(
779                     'id' => $this->cm->id,
780                     'userid' => $submission->userid,
781                     'mode' => 'single',
782                     'offset' => (optional_param('offset', '', PARAM_INT)-1)));
783             $button = $OUTPUT->action_link($url, $buttontext, new popup_action('click', $url, 'grade'.$submission->userid, array('height' => 450, 'width' => 700)), array('ttile'=>$buttontext));
785             $output .= 'opener.document.getElementById("up'.$submission->userid.'").innerHTML="'.addslashes_js($button).'";';
786         }
788         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $submission->userid);
790         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['finalgrade'])) {
791             $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid.
792             '").innerHTML="'.$grading_info->items[0]->grades[$submission->userid]->str_grade.'";'."\n";
793         }
795         if (!empty($CFG->enableoutcomes) and empty($SESSION->flextable['mod-assignment-submissions']->collapse['outcome'])) {
797             if (!empty($grading_info->outcomes)) {
798                 foreach($grading_info->outcomes as $n=>$outcome) {
799                     if ($outcome->grades[$submission->userid]->locked) {
800                         continue;
801                     }
803                     if ($quickgrade){
804                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.
805                         '").selectedIndex="'.$outcome->grades[$submission->userid]->grade.'";'."\n";
807                     } else {
808                         $options = make_grades_menu(-$outcome->scaleid);
809                         $options[0] = get_string('nooutcome', 'grades');
810                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.'").innerHTML="'.$options[$outcome->grades[$submission->userid]->grade]."\";\n";
811                     }
813                 }
814             }
815         }
817         $output .= "\n-->\n</script>";
818         return $output;
819     }
821     /**
822      *  Return a grade in user-friendly form, whether it's a scale or not
823      *
824      * @global object
825      * @param mixed $grade
826      * @return string User-friendly representation of grade
827      */
828     function display_grade($grade) {
829         global $DB;
831         static $scalegrades = array();   // Cache scales for each assignment - they might have different scales!!
833         if ($this->assignment->grade >= 0) {    // Normal number
834             if ($grade == -1) {
835                 return '-';
836             } else {
837                 return $grade.' / '.$this->assignment->grade;
838             }
840         } else {                                // Scale
841             if (empty($scalegrades[$this->assignment->id])) {
842                 if ($scale = $DB->get_record('scale', array('id'=>-($this->assignment->grade)))) {
843                     $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
844                 } else {
845                     return '-';
846                 }
847             }
848             if (isset($scalegrades[$this->assignment->id][$grade])) {
849                 return $scalegrades[$this->assignment->id][$grade];
850             }
851             return '-';
852         }
853     }
855     /**
856      *  Display a single submission, ready for grading on a popup window
857      *
858      * This default method prints the teacher info and submissioncomment box at the top and
859      * the student info and submission at the bottom.
860      * This method also fetches the necessary data in order to be able to
861      * provide a "Next submission" button.
862      * Calls preprocess_submission() to give assignment type plug-ins a chance
863      * to process submissions before they are graded
864      * This method gets its arguments from the page parameters userid and offset
865      *
866      * @global object
867      * @global object
868      * @param string $extra_javascript
869      */
870     function display_submission( $offset=-1 , $userid =-1) {
871         global $CFG, $DB, $PAGE, $OUTPUT;
872         require_once($CFG->libdir.'/gradelib.php');
873         require_once($CFG->libdir.'/tablelib.php');
874         if($userid==-1) $userid = required_param('userid', PARAM_INT);
875         if($offset==-1) $offset = required_param('offset', PARAM_INT);//offset for where to start looking for student.
877         if (!$user = $DB->get_record('user', array('id'=>$userid))) {
878             print_error('nousers');
879         }
881         if (!$submission = $this->get_submission($user->id)) {
882             $submission = $this->prepare_new_submission($userid);
883         }
884         if ($submission->timemodified > $submission->timemarked) {
885             $subtype = 'assignmentnew';
886         } else {
887             $subtype = 'assignmentold';
888         }
890         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
891         $gradingdisabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
893     /// construct SQL, using current offset to find the data of the next student
894         $course     = $this->course;
895         $assignment = $this->assignment;
896         $cm         = $this->cm;
897         $context    = get_context_instance(CONTEXT_MODULE, $cm->id);
899         /// Get all ppl that can submit assignments
901         $currentgroup = groups_get_activity_group($cm);
902         if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $currentgroup, '', false)) {
903             $users = array_keys($users);
904         }
906         // if groupmembersonly used, remove users who are not in any group
907         if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
908             if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
909                 $users = array_intersect($users, array_keys($groupingusers));
910             }
911         }
913         $nextid = 0;
915         if ($users) {
916             $select = 'SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt,
917                               s.id AS submissionid, s.grade, s.submissioncomment,
918                               s.timemodified, s.timemarked,
919                               COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ';
920             $sql = 'FROM {user} u '.
921                    'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
922                                                                       AND s.assignment = '.$this->assignment->id.' '.
923                    'WHERE u.id IN ('.implode(',', $users).') ';
925             if ($sort = flexible_table::get_sort_for_table('mod-assignment-submissions')) {
926                 $sort = 'ORDER BY '.$sort.' ';
927             }
928             $auser = $DB->get_records_sql($select.$sql.$sort, null, $offset, 2);
930             if (is_array($auser) && count($auser)>1) {
931                 $nextuser = next($auser);
932             /// Calculate user status
933                 $nextuser->status = ($nextuser->timemarked > 0) && ($nextuser->timemarked >= $nextuser->timemodified);
934                 $nextid = $nextuser->id;
935             }
936         }
938         if ($submission->teacher) {
939             $teacher = $DB->get_record('user', array('id'=>$submission->teacher));
940         } else {
941             global $USER;
942             $teacher = $USER;
943         }
945         $this->preprocess_submission($submission);
947         $mformdata = new stdclass;
948         $mformdata->context = $this->context;
949         $mformdata->maxbytes = $this->course->maxbytes;
950         $mformdata->courseid = $this->course->id;
951         $mformdata->teacher = $teacher;
952         $mformdata->assignment = $assignment;
953         $mformdata->submission = $submission;
954         $mformdata->lateness = $this->display_lateness($submission->timemodified);
955         $mformdata->auser = $auser;
956         $mformdata->user = $user;
957         $mformdata->offset = $offset;
958         $mformdata->userid = $userid;
959         $mformdata->cm = $this->cm;
960         $mformdata->grading_info = $grading_info;
961         $mformdata->enableoutcomes = $CFG->enableoutcomes;
962         $mformdata->grade = $this->assignment->grade;
963         $mformdata->gradingdisabled = $gradingdisabled;
964         $mformdata->usehtmleditor = $this->usehtmleditor;
965         $mformdata->nextid = $nextid;
966         $mformdata->submissioncomment= $submission->submissioncomment;
967         $mformdata->submissioncommentformat= FORMAT_HTML;
968         $mformdata->submission_content= $this->print_user_files($user->id, true);
970         $submitform = new mod_assignment_online_grading_form( null, $mformdata );
972         if($submitform->is_cancelled()) {
973             redirect('submissions.php?id='.$this->cm->id);
974         }
976         $submitform->set_data($mformdata);
978         $PAGE->set_title($this->course->fullname . ': ' .get_string('feedback', 'assignment').' - '.fullname($user, true));
979         $PAGE->set_heading($this->course->fullname);
980         $PAGE->navbar->add( get_string('submissions', 'assignment') );
982         echo $OUTPUT->header();
983         echo $OUTPUT->heading(get_string('feedback', 'assignment').': '.fullname($user, true));
985         // display mform here...
986         $submitform->display();
988         $customfeedback = $this->custom_feedbackform($submission, true);
989         if (!empty($customfeedback)) {
990             echo $customfeedback;
991         }
993         echo $OUTPUT->footer();
994     }
996     /**
997      *  Preprocess submission before grading
998      *
999      * Called by display_submission()
1000      * The default type does nothing here.
1001      *
1002      * @param object $submission The submission object
1003      */
1004     function preprocess_submission(&$submission) {
1005     }
1007     /**
1008      *  Display all the submissions ready for grading
1009      *
1010      * @global object
1011      * @global object
1012      * @global object
1013      * @global object
1014      * @param string $message
1015      * @return bool|void
1016      */
1017     function display_submissions($message='') {
1018         global $CFG, $DB, $USER, $DB, $OUTPUT, $PAGE;
1019         require_once($CFG->libdir.'/gradelib.php');
1021         /* first we check to see if the form has just been submitted
1022          * to request user_preference updates
1023          */
1024         if (isset($_POST['updatepref'])){
1025             $perpage = optional_param('perpage', 10, PARAM_INT);
1026             $perpage = ($perpage <= 0) ? 10 : $perpage ;
1027             set_user_preference('assignment_perpage', $perpage);
1028             set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
1029         }
1031         /* next we get perpage and quickgrade (allow quick grade) params
1032          * from database
1033          */
1034         $perpage    = get_user_preferences('assignment_perpage', 10);
1036         $quickgrade = get_user_preferences('assignment_quickgrade', 0);
1038         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);
1040         if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
1041             $uses_outcomes = true;
1042         } else {
1043             $uses_outcomes = false;
1044         }
1046         $page    = optional_param('page', 0, PARAM_INT);
1047         $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
1049     /// Some shortcuts to make the code read better
1051         $course     = $this->course;
1052         $assignment = $this->assignment;
1053         $cm         = $this->cm;
1055         $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
1056         add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->cm->id, $this->assignment->id, $this->cm->id);
1057         
1058         $PAGE->set_title(format_string($this->assignment->name,true));
1059         $PAGE->set_heading($this->course->fullname);
1060         echo $OUTPUT->header();
1062         /// Print quickgrade form around the table
1063         if ($quickgrade){
1064             echo '<form action="submissions.php" id="fastg" method="post">';
1065             echo '<div>';
1066             echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
1067             echo '<input type="hidden" name="mode" value="fastgrade" />';
1068             echo '<input type="hidden" name="page" value="'.$page.'" />';
1069             echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1070             echo '</div>';
1071         }
1073         $course_context = get_context_instance(CONTEXT_COURSE, $course->id);
1074         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
1075             echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">'
1076                 . get_string('seeallcoursegrades', 'grades') . '</a></div>';
1077         }
1079         if (!empty($message)) {
1080             echo $message;   // display messages here if any
1081         }
1083         $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1085     /// Check to see if groups are being used in this assignment
1087         /// find out current groups mode
1088         $groupmode = groups_get_activity_groupmode($cm);
1089         $currentgroup = groups_get_activity_group($cm, true);
1090         groups_print_activity_menu($cm, $CFG->wwwroot . '/mod/assignment/submissions.php?id=' . $this->cm->id);
1092         /// Get all ppl that are allowed to submit assignments
1093         if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $currentgroup, '', false)) {
1094             $users = array_keys($users);
1095         }
1097         // if groupmembersonly used, remove users who are not in any group
1098         if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
1099             if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1100                 $users = array_intersect($users, array_keys($groupingusers));
1101             }
1102         }
1104         $tablecolumns = array('picture', 'fullname', 'grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade');
1105         if ($uses_outcomes) {
1106             $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
1107         }
1109         $tableheaders = array('',
1110                               get_string('fullname'),
1111                               get_string('grade'),
1112                               get_string('comment', 'assignment'),
1113                               get_string('lastmodified').' ('.get_string('submission', 'assignment').')',
1114                               get_string('lastmodified').' ('.get_string('grade').')',
1115                               get_string('status'),
1116                               get_string('finalgrade', 'grades'));
1117         if ($uses_outcomes) {
1118             $tableheaders[] = get_string('outcome', 'grades');
1119         }
1121         require_once($CFG->libdir.'/tablelib.php');
1122         $table = new flexible_table('mod-assignment-submissions');
1124         $table->define_columns($tablecolumns);
1125         $table->define_headers($tableheaders);
1126         $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;currentgroup='.$currentgroup);
1128         $table->sortable(true, 'lastname');//sorted by lastname by default
1129         $table->collapsible(true);
1130         $table->initialbars(true);
1132         $table->column_suppress('picture');
1133         $table->column_suppress('fullname');
1135         $table->column_class('picture', 'picture');
1136         $table->column_class('fullname', 'fullname');
1137         $table->column_class('grade', 'grade');
1138         $table->column_class('submissioncomment', 'comment');
1139         $table->column_class('timemodified', 'timemodified');
1140         $table->column_class('timemarked', 'timemarked');
1141         $table->column_class('status', 'status');
1142         $table->column_class('finalgrade', 'finalgrade');
1143         if ($uses_outcomes) {
1144             $table->column_class('outcome', 'outcome');
1145         }
1147         $table->set_attribute('cellspacing', '0');
1148         $table->set_attribute('id', 'attempts');
1149         $table->set_attribute('class', 'submissions');
1150         $table->set_attribute('width', '100%');
1151         //$table->set_attribute('align', 'center');
1153         $table->no_sorting('finalgrade');
1154         $table->no_sorting('outcome');
1156         // Start working -- this is necessary as soon as the niceties are over
1157         $table->setup();
1159         if (empty($users)) {
1160             echo $OUTPUT->heading(get_string('nosubmitusers','assignment'));
1161             echo '</div>';
1162             return true;
1163         }
1164         if ($this->assignment->assignmenttype=='upload' || $this->assignment->assignmenttype=='online' || $this->assignment->assignmenttype=='uploadsingle') {
1165             echo '<div style="text-align:right"><a href="submissions.php?id='.$this->cm->id.'&amp;download=zip">'.get_string('downloadall', 'assignment').'</a></div>';
1166         }
1167     /// Construct the SQL
1169         if ($where = $table->get_sql_where()) {
1170             $where .= ' AND ';
1171         }
1173         if ($sort = $table->get_sql_sort()) {
1174             $sort = ' ORDER BY '.$sort;
1175         }
1177         $select = 'SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt,
1178                           s.id AS submissionid, s.grade, s.submissioncomment,
1179                           s.timemodified, s.timemarked,
1180                           COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ';
1181         $sql = 'FROM {user} u '.
1182                'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1183                                                                   AND s.assignment = '.$this->assignment->id.' '.
1184                'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1186         $table->pagesize($perpage, count($users));
1188         ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1189         $offset = $page * $perpage;
1191         $strupdate = get_string('update');
1192         $strgrade  = get_string('grade');
1193         $grademenu = make_grades_menu($this->assignment->grade);
1195         if (($ausers = $DB->get_records_sql($select.$sql.$sort, null, $table->get_page_start(), $table->get_page_size())) !== false) {
1196             $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
1197             foreach ($ausers as $auser) {
1198                 $final_grade = $grading_info->items[0]->grades[$auser->id];
1199                 $grademax = $grading_info->items[0]->grademax;
1200                 $final_grade->formatted_grade = round($final_grade->grade,2) .' / ' . round($grademax,2);
1201                 $locked_overridden = 'locked';
1202                 if ($final_grade->overridden) {
1203                     $locked_overridden = 'overridden';
1204                 }
1206             /// Calculate user status
1207                 $auser->status = ($auser->timemarked > 0) && ($auser->timemarked >= $auser->timemodified);
1208                 $picture = $OUTPUT->user_picture($auser);
1210                 if (empty($auser->submissionid)) {
1211                     $auser->grade = -1; //no submission yet
1212                 }
1214                 if (!empty($auser->submissionid)) {
1215                 ///Prints student answer and student modified date
1216                 ///attach file or print link to student answer, depending on the type of the assignment.
1217                 ///Refer to print_student_answer in inherited classes.
1218                     if ($auser->timemodified > 0) {
1219                         $studentmodified = '<div id="ts'.$auser->id.'">'.$this->print_student_answer($auser->id)
1220                                          . userdate($auser->timemodified).'</div>';
1221                     } else {
1222                         $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1223                     }
1224                 ///Print grade, dropdown or text
1225                     if ($auser->timemarked > 0) {
1226                         $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
1228                         if ($final_grade->locked or $final_grade->overridden) {
1229                             $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1230                         } else if ($quickgrade) {
1231                             $attributes = array();
1232                             $attributes['tabindex'] = $tabindex++;
1233                             $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1234                             $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
1235                         } else {
1236                             $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1237                         }
1239                     } else {
1240                         $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1241                         if ($final_grade->locked or $final_grade->overridden) {
1242                             $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1243                         } else if ($quickgrade) {
1244                             $attributes = array();
1245                             $attributes['tabindex'] = $tabindex++;
1246                             $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1247                             $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1248                         } else {
1249                             $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1250                         }
1251                     }
1252                 ///Print Comment
1253                     if ($final_grade->locked or $final_grade->overridden) {
1254                         $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';
1256                     } else if ($quickgrade) {
1257                         $comment = '<div id="com'.$auser->id.'">'
1258                                  . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1259                                  . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1260                     } else {
1261                         $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
1262                     }
1263                 } else {
1264                     $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1265                     $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1266                     $status          = '<div id="st'.$auser->id.'">&nbsp;</div>';
1268                     if ($final_grade->locked or $final_grade->overridden) {
1269                         $grade = '<div id="g'.$auser->id.'">'.$final_grade->formatted_grade . '</div>';
1270                     } else if ($quickgrade) {   // allow editing
1271                         $attributes = array();
1272                         $attributes['tabindex'] = $tabindex++;
1273                         $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1274                         $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1275                     } else {
1276                         $grade = '<div id="g'.$auser->id.'">-</div>';
1277                     }
1279                     if ($final_grade->locked or $final_grade->overridden) {
1280                         $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
1281                     } else if ($quickgrade) {
1282                         $comment = '<div id="com'.$auser->id.'">'
1283                                  . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1284                                  . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1285                     } else {
1286                         $comment = '<div id="com'.$auser->id.'">&nbsp;</div>';
1287                     }
1288                 }
1290                 if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
1291                     $auser->status = 0;
1292                 } else {
1293                     $auser->status = 1;
1294                 }
1296                 $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
1298                 ///No more buttons, we use popups ;-).
1299                 $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1300                            . '&userid='.$auser->id.'&mode=single'.'&offset='.$offset++;
1302                     $button = $OUTPUT->action_link($popup_url, $buttontext);
1304                 $status  = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
1306                 $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';
1308                 $outcomes = '';
1310                 if ($uses_outcomes) {
1312                     foreach($grading_info->outcomes as $n=>$outcome) {
1313                         $outcomes .= '<div class="outcome"><label>'.$outcome->name.'</label>';
1314                         $options = make_grades_menu(-$outcome->scaleid);
1316                         if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
1317                             $options[0] = get_string('nooutcome', 'grades');
1318                             $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
1319                         } else {
1320                             $attributes = array();
1321                             $attributes['tabindex'] = $tabindex++;
1322                             $attributes['id'] = 'outcome_'.$n.'_'.$auser->id;
1323                             $outcomes .= ' '.html_writer::select($options, 'outcome_'.$n.'['.$auser->id.']', $outcome->grades[$auser->id]->grade, array(0=>get_string('nooutcome', 'grades')), $attributes);
1324                         }
1325                         $outcomes .= '</div>';
1326                     }
1327                 }
1329                 $userlink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $auser->id . '&amp;course=' . $course->id . '">' . fullname($auser) . '</a>';
1330                 $row = array($picture, $userlink, $grade, $comment, $studentmodified, $teachermodified, $status, $finalgrade);
1331                 if ($uses_outcomes) {
1332                     $row[] = $outcomes;
1333                 }
1335                 $table->add_data($row);
1336             }
1337         }
1339         $table->print_html();  /// Print the whole table
1341         if ($quickgrade){
1342             $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? 'checked="checked"' : '';
1343             echo '<div class="fgcontrols">';
1344             echo '<div class="emailnotification">';
1345             echo '<label for="mailinfo">'.get_string('enableemailnotification','assignment').'</label>';
1346             echo '<input type="hidden" name="mailinfo" value="0" />';
1347             echo '<input type="checkbox" id="mailinfo" name="mailinfo" value="1" '.$lastmailinfo.' />';
1348             echo $OUTPUT->help_icon('enableemailnotification', 'assignment');
1349             echo '</div>';
1350             echo '</div>';
1351             echo '<div class="fastgbutton"><input type="submit" name="fastg" value="'.get_string('saveallfeedback', 'assignment').'" /></div>';
1352             echo '</form>';
1353         }
1354         /// End of fast grading form
1356         /// Mini form for setting user preference
1357         echo '<div class="qgprefs">';
1358         echo '<form id="options" action="submissions.php?id='.$this->cm->id.'" method="post"><div>';
1359         echo '<input type="hidden" name="updatepref" value="1" />';
1360         echo '<table id="optiontable">';
1361         echo '<tr><td>';
1362         echo '<label for="perpage">'.get_string('pagesize','assignment').'</label>';
1363         echo '</td>';
1364         echo '<td>';
1365         echo '<input type="text" id="perpage" name="perpage" size="1" value="'.$perpage.'" />';
1366         echo '</td></tr>';
1367         echo '<tr><td>';
1368         echo '<label for="quickgrade">'.get_string('quickgrade','assignment').'</label>';
1369         echo '</td>';
1370         echo '<td>';
1371         $checked = $quickgrade ? 'checked="checked"' : '';
1372         echo '<input type="checkbox" id="quickgrade" name="quickgrade" value="1" '.$checked.' />';
1373         echo '<p>'.$OUTPUT->help_icon('quickgrade', 'assignment').'</p>';
1374         echo '</td>';
1375         echo '</tr>';
1376         echo '<tr><td colspan="2">';
1377         echo '<input type="submit" value="'.get_string('savepreferences').'" />';
1378         echo '</td></tr></table>';
1379         echo '</div></form></div>';
1380         ///End of mini form
1381         echo $OUTPUT->footer();
1382     }
1384     /**
1385      *  Process teacher feedback submission
1386      *
1387      * This is called by submissions() when a grading even has taken place.
1388      * It gets its data from the submitted form.
1389      *
1390      * @global object
1391      * @global object
1392      * @global object
1393      * @return object|bool The updated submission object or false
1394      */
1395     function process_feedback() {
1396         global $CFG, $USER, $DB;
1397         require_once($CFG->libdir.'/gradelib.php');
1399         if (!$feedback = data_submitted() or !confirm_sesskey()) {      // No incoming data?
1400             return false;
1401         }
1403         ///For save and next, we need to know the userid to save, and the userid to go
1404         ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1405         ///as the userid to store
1406         if ((int)$feedback->saveuserid !== -1){
1407             $feedback->userid = $feedback->saveuserid;
1408         }
1410         if (!empty($feedback->cancel)) {          // User hit cancel button
1411             return false;
1412         }
1414         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);
1416         // store outcomes if needed
1417         $this->process_outcomes($feedback->userid);
1419         $submission = $this->get_submission($feedback->userid, true);  // Get or make one
1421         if (!($grading_info->items[0]->grades[$feedback->userid]->locked ||
1422             $grading_info->items[0]->grades[$feedback->userid]->overridden) ) {
1424             $submission->grade      = $feedback->xgrade;
1425             $submission->submissioncomment    = $feedback->submissioncomment_editor['text'];
1426             $submission->format     = $feedback->format;
1427             $submission->teacher    = $USER->id;
1428             $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1429             if (!$mailinfo) {
1430                 $submission->mailed = 1;       // treat as already mailed
1431             } else {
1432                 $submission->mailed = 0;       // Make sure mail goes out (again, even)
1433             }
1434             $submission->timemarked = time();
1436             unset($submission->data1);  // Don't need to update this.
1437             unset($submission->data2);  // Don't need to update this.
1439             if (empty($submission->timemodified)) {   // eg for offline assignments
1440                 // $submission->timemodified = time();
1441             }
1443             $DB->update_record('assignment_submissions', $submission);
1445             // triger grade event
1446             $this->update_grade($submission);
1448             add_to_log($this->course->id, 'assignment', 'update grades',
1449                        'submissions.php?id='.$this->assignment->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
1450         }
1452         return $submission;
1454     }
1456     function process_outcomes($userid) {
1457         global $CFG, $USER;
1459         if (empty($CFG->enableoutcomes)) {
1460             return;
1461         }
1463         require_once($CFG->libdir.'/gradelib.php');
1465         if (!$formdata = data_submitted() or !confirm_sesskey()) {
1466             return;
1467         }
1469         $data = array();
1470         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
1472         if (!empty($grading_info->outcomes)) {
1473             foreach($grading_info->outcomes as $n=>$old) {
1474                 $name = 'outcome_'.$n;
1475                 if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
1476                     $data[$n] = $formdata->{$name}[$userid];
1477                 }
1478             }
1479         }
1480         if (count($data) > 0) {
1481             grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1482         }
1484     }
1486     /**
1487      * Load the submission object for a particular user
1488      *
1489      * @global object
1490      * @global object
1491      * @param $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1492      * @param $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1493      * @param bool $teachermodified student submission set if false
1494      * @return object The submission
1495      */
1496     function get_submission($userid=0, $createnew=false, $teachermodified=false) {
1497         global $USER, $DB;
1499         if (empty($userid)) {
1500             $userid = $USER->id;
1501         }
1503         $submission = $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1505         if ($submission || !$createnew) {
1506             return $submission;
1507         }
1508         $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
1509         $DB->insert_record("assignment_submissions", $newsubmission);
1511         return $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1512     }
1514     /**
1515      * Instantiates a new submission object for a given user
1516      *
1517      * Sets the assignment, userid and times, everything else is set to default values.
1518      *
1519      * @param int $userid The userid for which we want a submission object
1520      * @param bool $teachermodified student submission set if false
1521      * @return object The submission
1522      */
1523     function prepare_new_submission($userid, $teachermodified=false) {
1524         $submission = new Object;
1525         $submission->assignment   = $this->assignment->id;
1526         $submission->userid       = $userid;
1527         $submission->timecreated = time();
1528         // teachers should not be modifying modified date, except offline assignments
1529         if ($teachermodified) {
1530             $submission->timemodified = 0;
1531         } else {
1532             $submission->timemodified = $submission->timecreated;
1533         }
1534         $submission->numfiles     = 0;
1535         $submission->data1        = '';
1536         $submission->data2        = '';
1537         $submission->grade        = -1;
1538         $submission->submissioncomment      = '';
1539         $submission->format       = 0;
1540         $submission->teacher      = 0;
1541         $submission->timemarked   = 0;
1542         $submission->mailed       = 0;
1543         return $submission;
1544     }
1546     /**
1547      * Return all assignment submissions by ENROLLED students (even empty)
1548      *
1549      * @param string $sort optional field names for the ORDER BY in the sql query
1550      * @param string $dir optional specifying the sort direction, defaults to DESC
1551      * @return array The submission objects indexed by id
1552      */
1553     function get_submissions($sort='', $dir='DESC') {
1554         return assignment_get_all_submissions($this->assignment, $sort, $dir);
1555     }
1557     /**
1558      * Counts all real assignment submissions by ENROLLED students (not empty ones)
1559      *
1560      * @param int $groupid optional If nonzero then count is restricted to this group
1561      * @return int The number of submissions
1562      */
1563     function count_real_submissions($groupid=0) {
1564         return assignment_count_real_submissions($this->cm, $groupid);
1565     }
1567     /**
1568      * Alerts teachers by email of new or changed assignments that need grading
1569      *
1570      * First checks whether the option to email teachers is set for this assignment.
1571      * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1572      * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1573      *
1574      * @global object
1575      * @global object
1576      * @param $submission object The submission that has changed
1577      * @return void
1578      */
1579     function email_teachers($submission) {
1580         global $CFG, $DB;
1582         if (empty($this->assignment->emailteachers)) {          // No need to do anything
1583             return;
1584         }
1586         $user = $DB->get_record('user', array('id'=>$submission->userid));
1588         if ($teachers = $this->get_graders($user)) {
1590             $strassignments = get_string('modulenameplural', 'assignment');
1591             $strassignment  = get_string('modulename', 'assignment');
1592             $strsubmitted  = get_string('submitted', 'assignment');
1594             foreach ($teachers as $teacher) {
1595                 $info = new object();
1596                 $info->username = fullname($user, true);
1597                 $info->assignment = format_string($this->assignment->name,true);
1598                 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
1600                 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1601                 $posttext = $this->email_teachers_text($info);
1602                 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
1604                 $eventdata = new object();
1605                 $eventdata->modulename       = 'assignment';
1606                 $eventdata->userfrom         = $user;
1607                 $eventdata->userto           = $teacher;
1608                 $eventdata->subject          = $postsubject;
1609                 $eventdata->fullmessage      = $posttext;
1610                 $eventdata->fullmessageformat = FORMAT_PLAIN;
1611                 $eventdata->fullmessagehtml  = $posthtml;
1612                 $eventdata->smallmessage     = '';
1613                 message_send($eventdata);
1614             }
1615         }
1616     }
1618     /**
1619      * @param string $filearea
1620      * @param array $args
1621      * @return bool
1622      */
1623     function send_file($filearea, $args) {
1624         debugging('plugin does not implement file sending', DEBUG_DEVELOPER);
1625         return false;
1626     }
1628     /**
1629      * Returns a list of teachers that should be grading given submission
1630      *
1631      * @param object $user
1632      * @return array
1633      */
1634     function get_graders($user) {
1635         //potential graders
1636         $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false);
1638         $graders = array();
1639         if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) {   // Separate groups are being used
1640             if ($groups = groups_get_all_groups($this->course->id, $user->id)) {  // Try to find all groups
1641                 foreach ($groups as $group) {
1642                     foreach ($potgraders as $t) {
1643                         if ($t->id == $user->id) {
1644                             continue; // do not send self
1645                         }
1646                         if (groups_is_member($group->id, $t->id)) {
1647                             $graders[$t->id] = $t;
1648                         }
1649                     }
1650                 }
1651             } else {
1652                 // user not in group, try to find graders without group
1653                 foreach ($potgraders as $t) {
1654                     if ($t->id == $user->id) {
1655                         continue; // do not send self
1656                     }
1657                     if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
1658                         $graders[$t->id] = $t;
1659                     }
1660                 }
1661             }
1662         } else {
1663             foreach ($potgraders as $t) {
1664                 if ($t->id == $user->id) {
1665                     continue; // do not send self
1666                 }
1667                 $graders[$t->id] = $t;
1668             }
1669         }
1670         return $graders;
1671     }
1673     /**
1674      * Creates the text content for emails to teachers
1675      *
1676      * @param $info object The info used by the 'emailteachermail' language string
1677      * @return string
1678      */
1679     function email_teachers_text($info) {
1680         $posttext  = format_string($this->course->shortname).' -> '.$this->strassignments.' -> '.
1681                      format_string($this->assignment->name)."\n";
1682         $posttext .= '---------------------------------------------------------------------'."\n";
1683         $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
1684         $posttext .= "\n---------------------------------------------------------------------\n";
1685         return $posttext;
1686     }
1688      /**
1689      * Creates the html content for emails to teachers
1690      *
1691      * @param $info object The info used by the 'emailteachermailhtml' language string
1692      * @return string
1693      */
1694     function email_teachers_html($info) {
1695         global $CFG;
1696         $posthtml  = '<p><font face="sans-serif">'.
1697                      '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname).'</a> ->'.
1698                      '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
1699                      '<a href="'.$CFG->wwwroot.'/mod/assignment/view.php?id='.$this->cm->id.'">'.format_string($this->assignment->name).'</a></font></p>';
1700         $posthtml .= '<hr /><font face="sans-serif">';
1701         $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
1702         $posthtml .= '</font><hr />';
1703         return $posthtml;
1704     }
1706     /**
1707      * Produces a list of links to the files uploaded by a user
1708      *
1709      * @param $userid int optional id of the user. If 0 then $USER->id is used.
1710      * @param $return boolean optional defaults to false. If true the list is returned rather than printed
1711      * @return string optional
1712      */
1713     function print_user_files($userid=0, $return=false) {
1714         global $CFG, $USER, $OUTPUT;
1716         if (!$userid) {
1717             if (!isloggedin()) {
1718                 return '';
1719             }
1720             $userid = $USER->id;
1721         }
1723         $output = '';
1725         $fs = get_file_storage();
1726         $browser = get_file_browser();
1728         $found = false;
1730         if ($files = $fs->get_area_files($this->context->id, 'assignment_submission', $userid, "timemodified", false)) {
1731             require_once($CFG->libdir.'/portfoliolib.php');
1732             require_once($CFG->dirroot . '/mod/assignment/locallib.php');
1733             $button = new portfolio_add_button();
1734             foreach ($files as $file) {
1735                 $filename = $file->get_filename();
1736                 $found = true;
1737                 $mimetype = $file->get_mimetype();
1738                 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/assignment_submission/'.$userid.'/'.$filename);
1739                 $output .= '<a href="'.$path.'" ><img src="'.$OUTPUT->pix_url(file_mimetype_icon($mimetype)).'" class="icon" alt="'.$mimetype.'" />'.s($filename).'</a>';
1740                 if ($this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1741                     $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id, 'fileid' => $file->get_id()), '/mod/assignment/locallib.php');
1742                     $button->set_format_by_file($file);
1743                     $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
1744                 }
1745             }
1746             if (count($files) > 1  && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1747                 $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id), '/mod/assignment/locallib.php');
1748                 $output .= '<br />'  . $button->to_html();
1749             }
1750         }
1752         $output = '<div class="files">'.$output.'</div>';
1754         if ($return) {
1755             return $output;
1756         }
1757         echo $output;
1758     }
1760     /**
1761      * Count the files uploaded by a given user
1762      *
1763      * @param $userid int The user id
1764      * @return int
1765      */
1766     function count_user_files($userid) {
1767         $fs = get_file_storage();
1768         $files = $fs->get_area_files($this->context->id, 'assignment_submission', $userid, "id", false);
1769         return count($files);
1770     }
1772     /**
1773      * Returns true if the student is allowed to submit
1774      *
1775      * Checks that the assignment has started and, if the option to prevent late
1776      * submissions is set, also checks that the assignment has not yet closed.
1777      * @return boolean
1778      */
1779     function isopen() {
1780         $time = time();
1781         if ($this->assignment->preventlate && $this->assignment->timedue) {
1782             return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
1783         } else {
1784             return ($this->assignment->timeavailable <= $time);
1785         }
1786     }
1789     /**
1790      * Return true if is set description is hidden till available date
1791      *
1792      * This is needed by calendar so that hidden descriptions do not
1793      * come up in upcoming events.
1794      *
1795      * Check that description is hidden till available date
1796      * By default return false
1797      * Assignments types should implement this method if needed
1798      * @return boolen
1799      */
1800     function description_is_hidden() {
1801         return false;
1802     }
1804     /**
1805      * Return an outline of the user's interaction with the assignment
1806      *
1807      * The default method prints the grade and timemodified
1808      * @param $grade object
1809      * @return object with properties ->info and ->time
1810      */
1811     function user_outline($grade) {
1813         $result = new object();
1814         $result->info = get_string('grade').': '.$grade->str_long_grade;
1815         $result->time = $grade->dategraded;
1816         return $result;
1817     }
1819     /**
1820      * Print complete information about the user's interaction with the assignment
1821      *
1822      * @param $user object
1823      */
1824     function user_complete($user, $grade=null) {
1825         global $OUTPUT;
1826         if ($grade) {
1827             echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
1828             if ($grade->str_feedback) {
1829                 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
1830             }
1831         }
1833         if ($submission = $this->get_submission($user->id)) {
1835             $fs = get_file_storage();
1836             $browser = get_file_browser();
1838             if ($files = $fs->get_area_files($this->context->id, 'assignment_submission', $user->id, "timemodified", false)) {
1839                 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
1840                 foreach ($files as $file) {
1841                     $countfiles .= "; ".$file->get_filename();
1842                 }
1843             }
1845             echo $OUTPUT->box_start();
1846             echo get_string("lastmodified").": ";
1847             echo userdate($submission->timemodified);
1848             echo $this->display_lateness($submission->timemodified);
1850             $this->print_user_files($user->id);
1852             echo '<br />';
1854             $this->view_feedback($submission);
1856             echo $OUTPUT->box_end();
1858         } else {
1859             print_string("notsubmittedyet", "assignment");
1860         }
1861     }
1863     /**
1864      * Return a string indicating how late a submission is
1865      *
1866      * @param $timesubmitted int
1867      * @return string
1868      */
1869     function display_lateness($timesubmitted) {
1870         return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
1871     }
1873     /**
1874      * Empty method stub for all delete actions.
1875      */
1876     function delete() {
1877         //nothing by default
1878         redirect('view.php?id='.$this->cm->id);
1879     }
1881     /**
1882      * Empty custom feedback grading form.
1883      */
1884     function custom_feedbackform($submission, $return=false) {
1885         //nothing by default
1886         return '';
1887     }
1889     /**
1890      * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
1891      * for the course (see resource).
1892      *
1893      * Given a course_module object, this function returns any "extra" information that may be needed
1894      * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
1895      *
1896      * @param $coursemodule object The coursemodule object (record).
1897      * @return object An object on information that the coures will know about (most noticeably, an icon).
1898      *
1899      */
1900     function get_coursemodule_info($coursemodule) {
1901         return false;
1902     }
1904     /**
1905      * Plugin cron method - do not use $this here, create new assignment instances if needed.
1906      * @return void
1907      */
1908     function cron() {
1909         //no plugin cron by default - override if needed
1910     }
1912     /**
1913      * Reset all submissions
1914      */
1915     function reset_userdata($data) {
1916         global $CFG, $DB;
1918         if (!$DB->count_records('assignment', array('course'=>$data->courseid, 'assignmenttype'=>$this->type))) {
1919             return array(); // no assignments of this type present
1920         }
1922         $componentstr = get_string('modulenameplural', 'assignment');
1923         $status = array();
1925         $typestr = get_string('type'.$this->type, 'assignment');
1926         // ugly hack to support pluggable assignment type titles...
1927         if($typestr === '[[type'.$this->type.']]'){
1928             $typestr = get_string('type'.$this->type, 'assignment_'.$this->type);
1929         }
1931         if (!empty($data->reset_assignment_submissions)) {
1932             $assignmentssql = "SELECT a.id
1933                                  FROM {assignment} a
1934                                 WHERE a.course=? AND a.assignmenttype=?";
1935             $params = array($data->courseid, $this->type);
1937             // now get rid of all submissions and responses
1938             $fs = get_file_storage();
1939             if ($assignments = $DB->get_records_sql($assignmentssql, $params)) {
1940                 foreach ($assignments as $assignmentid=>$unused) {
1941                     if (!$cm = get_coursemodule_from_instance('assignment', $assignmentid)) {
1942                         continue;
1943                     }
1944                     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1945                     $fs->delete_area_files($context->id, 'assignment_submission');
1946                     $fs->delete_area_files($context->id, 'assignment_response');
1947                 }
1948             }
1950             $DB->delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)", $params);
1952             $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
1954             if (empty($data->reset_gradebook_grades)) {
1955                 // remove all grades from gradebook
1956                 assignment_reset_gradebook($data->courseid, $this->type);
1957             }
1958         }
1960         /// updating dates - shift may be negative too
1961         if ($data->timeshift) {
1962             shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
1963             $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
1964         }
1966         return $status;
1967     }
1970     function portfolio_exportable() {
1971         return false;
1972     }
1974     /**
1975      * base implementation for backing up subtype specific information
1976      * for one single module
1977      *
1978      * @param filehandle $bf file handle for xml file to write to
1979      * @param mixed $preferences the complete backup preference object
1980      *
1981      * @return boolean
1982      *
1983      * @static
1984      */
1985     static function backup_one_mod($bf, $preferences, $assignment) {
1986         return true;
1987     }
1989     /**
1990      * base implementation for backing up subtype specific information
1991      * for one single submission
1992      *
1993      * @param filehandle $bf file handle for xml file to write to
1994      * @param mixed $preferences the complete backup preference object
1995      * @param object $submission the assignment submission db record
1996      *
1997      * @return boolean
1998      *
1999      * @static
2000      */
2001     static function backup_one_submission($bf, $preferences, $assignment, $submission) {
2002         return true;
2003     }
2005     /**
2006      * base implementation for restoring subtype specific information
2007      * for one single module
2008      *
2009      * @param array  $info the array representing the xml
2010      * @param object $restore the restore preferences
2011      *
2012      * @return boolean
2013      *
2014      * @static
2015      */
2016     static function restore_one_mod($info, $restore, $assignment) {
2017         return true;
2018     }
2020     /**
2021      * base implementation for restoring subtype specific information
2022      * for one single submission
2023      *
2024      * @param object $submission the newly created submission
2025      * @param array  $info the array representing the xml
2026      * @param object $restore the restore preferences
2027      *
2028      * @return boolean
2029      *
2030      * @static
2031      */
2032     static function restore_one_submission($info, $restore, $assignment, $submission) {
2033         return true;
2034     }
2036 } ////// End of the assignment_base class
2038 /**
2039  * @package   mod-assignment
2040  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
2041  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2042  */
2043 class mod_assignment_upload_file_form extends moodleform {
2044     function definition() {
2045         $mform = $this->_form;
2046         $instance = $this->_customdata;
2048         //TODO: improve upload size checking
2049         $mform->setMaxFileSize($instance->assignment->maxbytes);
2051         // visible elements
2052         $mform->addElement('file', 'newfile', get_string('uploadafile'));
2054         // hidden params
2055         $mform->addElement('hidden', 'id', $instance->cm->id);
2056         $mform->setType('id', PARAM_INT);
2057         $mform->addElement('hidden', 'action', 'uploadfile');
2058         $mform->setType('action', PARAM_ALPHA);
2060         // buttons
2061         $this->add_action_buttons(false, get_string('uploadthisfile'));
2062     }
2066 class mod_assignment_online_grading_form extends moodleform {
2068     function definition() {
2069         global $OUTPUT;
2070         $mform =& $this->_form;
2072         $formattr = $mform->getAttributes();
2073         $formattr['id'] = 'submitform';
2074         $mform->setAttributes($formattr);
2075         // hidden params
2076         $mform->addElement('hidden', 'offset', ($this->_customdata->offset+1));
2077         $mform->setType('offset', PARAM_INT);
2078         $mform->addElement('hidden', 'userid', $this->_customdata->userid);
2079         $mform->setType('userid', PARAM_INT);
2080         $mform->addElement('hidden', 'nextid', $this->_customdata->nextid);
2081         $mform->setType('nextid', PARAM_INT);
2082         $mform->addElement('hidden', 'id', $this->_customdata->cm->id);
2083         $mform->setType('id', PARAM_INT);
2084         $mform->addElement('hidden', 'sesskey', sesskey());
2085         $mform->setType('sesskey', PARAM_ALPHANUM);
2086         $mform->addElement('hidden', 'mode', 'grade');
2087         $mform->setType('mode', PARAM_INT);
2088         $mform->addElement('hidden', 'menuindex', "0");
2089         $mform->setType('menuindex', PARAM_INT);
2090         $mform->addElement('hidden', 'saveuserid', "-1");
2091         $mform->setType('saveuserid', PARAM_INT);
2093         $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->user),
2094                                                 fullname($this->_customdata->user, true) . '<br/>' .
2095                                                 userdate($this->_customdata->submission->timemodified) .
2096                                                 $this->_customdata->lateness );
2098         $this->add_grades_section();
2100         $this->add_feedback_section();
2102         if($this->_customdata->submission->timemarked){
2103             $mform->addElement('header', 'Last Grade', get_string('lastgrade', 'assignment'));
2104             $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->teacher) ,
2105                                                     fullname($this->_customdata->teacher,true).
2106                                                     '<br/>'.
2107                                                     userdate($this->_customdata->submission->timemarked));
2108         }
2109         // buttons
2110         $this->add_action_buttons();
2112         $this->add_submission_content();
2113     }
2115     function add_grades_section() {
2116         global $CFG;
2117         $mform =& $this->_form;
2118         $attributes = array();
2119         if($this->_customdata->gradingdisabled) $attributes['disabled'] ='disabled';
2121         $grademenu = make_grades_menu($this->_customdata->assignment->grade);
2122         $grademenu['-1'] = get_string('nograde');
2124         $mform->addElement('header', 'Grades', get_string('grades', 'grades'));
2125         $mform->addElement('select', 'xgrade', get_string('grade').':', $grademenu, $attributes);
2126         $mform->setDefault('xgrade', $this->_customdata->submission->grade ); //@fixme some bug when element called 'grade' makes it break
2127         $mform->setType('xgrade', PARAM_INT);
2129         if(!empty($this->_customdata->enableoutcomes)){
2130             foreach($this->_customdata->grading_info->outcomes as $n=>$outcome) {
2131                 $options = make_grades_menu(-$outcome->scaleid);
2132                 if ($outcome->grades[$this->_customdata->submission->userid]->locked) {
2133                     $options[0] = get_string('nooutcome', 'grades');
2134                     echo $options[$outcome->grades[$this->_customdata->submission->userid]->grade];
2135                 } else {
2136                     $options[''] = get_string('nooutcome', 'grades');
2137                     $attributes = array('id' => 'menuoutcome_'.$n );
2138                     $mform->addElement('select', 'outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->name.':', $options, $attributes );
2139                     $mform->setType('outcome_'.$n.'['.$this->_customdata->userid.']', PARAM_INT);
2140                     $mform->setDefault('outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->grades[$this->_customdata->submission->userid]->grade );
2141                 }
2142             }
2143         }
2144         $mform->addElement('static', 'finalgrade', get_string('currentgrade', 'assignment').':' ,
2145                      '<a href="'.$CFG->wwwroot.'/grade/report/grader/index.php?id='. $this->_customdata->courseid .'" >'.
2146                         $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade . '</a>');
2147         $mform->setType('finalgrade', PARAM_INT);
2148     }
2150     /**
2151      *
2152      * @global core_renderer $OUTPUT
2153      */
2154     function add_feedback_section() {
2155         global $OUTPUT;
2156         $mform =& $this->_form;
2157         $mform->addElement('header', 'Feed Back', get_string('feedback', 'grades'));
2159         if($this->_customdata->gradingdisabled){
2160             $mform->addElement('static', 'disabledfeedback', $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_feedback );
2161         } else {
2162             // visible elements
2164             $mform->addElement('editor', 'submissioncomment_editor', get_string('feedback', 'assignment').':', null, $this->get_editor_options() );
2165             $mform->setType('submissioncomment_editor', PARAM_RAW); // to be cleaned before display
2166             $mform->setDefault('submissioncomment_editor', $this->_customdata->submission->submissioncomment);
2167             //$mform->addRule('submissioncomment', get_string('required'), 'required', null, 'client');
2169             if ($this->_customdata->usehtmleditor) {
2170                 $mform->addElement('hidden', 'format', FORMAT_HTML);
2171                 $mform->setType('format', PARAM_INT);
2172             } else {
2173                 //format menu
2174                 $format_menu = format_text_menu();
2175                 $mform->addElement('select', 'format', get_string('format'), $format_menu, array('selected' => $this->_customdata->submission->format ) );
2176                 $mform->setType('format', PARAM_INT);
2177             }
2178             $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? array('checked'=>'checked') : array();
2179             $mform->addElement('hidden', 'mailinfo_h', "0");
2180             $mform->setType('mailinfo_h', PARAM_INT);
2181             $mform->addElement('checkbox', 'mailinfo',get_string('enableemailnotification','assignment').
2182                     $OUTPUT->help_icon('enableemailnotification', 'assignment') .':' );
2183             $mform->updateElementAttr('mailinfo', $lastmailinfo);
2184             $mform->setType('mailinfo', PARAM_INT);
2185         }
2186     }
2188     function add_action_buttons() {
2189         $mform =& $this->_form;
2190         $mform->addElement('header', 'Operation', get_string('operation', 'assignment'));
2191         //if there are more to be graded.
2192         if($this->_customdata->nextid>0){
2193             $buttonarray=array();
2194             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2195             //@todo: fix accessibility: javascript dependency not necessary
2196             $buttonarray[] = &$mform->createElement('submit', 'saveandnext', get_string('saveandnext'));
2197             $buttonarray[] = &$mform->createElement('submit', 'next', get_string('next'));
2198             $buttonarray[] = &$mform->createElement('cancel');
2199         } else {
2200             $buttonarray=array();
2201             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2202             $buttonarray[] = &$mform->createElement('cancel');
2203         }
2204         $mform->addGroup($buttonarray, 'grading_buttonar', '', array(' '), false);
2205         $mform->setType('grading_buttonar', PARAM_RAW);
2206     }
2208     function add_submission_content() {
2209         $mform =& $this->_form;
2210         $mform->addElement('header', 'Submission', get_string('submission', 'assignment'));
2211         $mform->addElement('static', '', '' , $this->_customdata->submission_content );
2212     }
2213     
2214     protected function get_editor_options() {
2215         $editoroptions = array();
2216         $editoroptions['filearea'] = 'assignment_online_submission';
2217         $editoroptions['noclean'] = false;
2218         $editoroptions['maxfiles'] = EDITOR_UNLIMITED_FILES;
2219         $editoroptions['maxbytes'] = $this->_customdata->maxbytes;
2220         return $editoroptions;
2221     }
2223     public function set_data($data) {
2224         $editoroptions = $this->get_editor_options();
2225         if (!isset($data->text)) {
2226             $data->text = '';
2227         }
2228         if (!isset($data->format)) {
2229             $data->textformat = FORMAT_HTML;
2230         } else {
2231             $data->textformat = $data->format;
2232         }
2234         if (!empty($this->_customdata->submission->id)) {
2235             $itemid = $this->_customdata->submission->id;
2236         } else {
2237             $itemid = null;
2238         }
2240         $data = file_prepare_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['filearea'], $itemid);
2241         return parent::set_data($data);
2242     }
2244     public function get_data() {
2245         $data = parent::get_data();
2247         if (!empty($this->_customdata->submission->id)) {
2248             $itemid = $this->_customdata->submission->id;
2249         } else {
2250             $itemid = null;
2251         }
2253         if ($data) {
2254             $editoroptions = $this->get_editor_options();
2255             $data = file_postupdate_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['filearea'], $itemid);
2256             $data->format = $data->textformat;
2257         }
2258         return $data;
2259     }
2262 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
2264 /**
2265  * Deletes an assignment instance
2266  *
2267  * This is done by calling the delete_instance() method of the assignment type class
2268  */
2269 function assignment_delete_instance($id){
2270     global $CFG, $DB;
2272     if (! $assignment = $DB->get_record('assignment', array('id'=>$id))) {
2273         return false;
2274     }
2276     // fall back to base class if plugin missing
2277     $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2278     if (file_exists($classfile)) {
2279         require_once($classfile);
2280         $assignmentclass = "assignment_$assignment->assignmenttype";
2282     } else {
2283         debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
2284         $assignmentclass = "assignment_base";
2285     }
2287     $ass = new $assignmentclass();
2288     return $ass->delete_instance($assignment);
2292 /**
2293  * Updates an assignment instance
2294  *
2295  * This is done by calling the update_instance() method of the assignment type class
2296  */
2297 function assignment_update_instance($assignment){
2298     global $CFG;
2300     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2302     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2303     $assignmentclass = "assignment_$assignment->assignmenttype";
2304     $ass = new $assignmentclass();
2305     return $ass->update_instance($assignment);
2309 /**
2310  * Adds an assignment instance
2311  *
2312  * This is done by calling the add_instance() method of the assignment type class
2313  */
2314 function assignment_add_instance($assignment) {
2315     global $CFG;
2317     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2319     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2320     $assignmentclass = "assignment_$assignment->assignmenttype";
2321     $ass = new $assignmentclass();
2322     return $ass->add_instance($assignment);
2326 /**
2327  * Returns an outline of a user interaction with an assignment
2328  *
2329  * This is done by calling the user_outline() method of the assignment type class
2330  */
2331 function assignment_user_outline($course, $user, $mod, $assignment) {
2332     global $CFG;
2334     require_once("$CFG->libdir/gradelib.php");
2335     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2336     $assignmentclass = "assignment_$assignment->assignmenttype";
2337     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2338     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2339     if (!empty($grades->items[0]->grades)) {
2340         return $ass->user_outline(reset($grades->items[0]->grades));
2341     } else {
2342         return null;
2343     }
2346 /**
2347  * Prints the complete info about a user's interaction with an assignment
2348  *
2349  * This is done by calling the user_complete() method of the assignment type class
2350  */
2351 function assignment_user_complete($course, $user, $mod, $assignment) {
2352     global $CFG;
2354     require_once("$CFG->libdir/gradelib.php");
2355     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2356     $assignmentclass = "assignment_$assignment->assignmenttype";
2357     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2358     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2359     if (empty($grades->items[0]->grades)) {
2360         $grade = false;
2361     } else {
2362         $grade = reset($grades->items[0]->grades);
2363     }
2364     return $ass->user_complete($user, $grade);
2367 /**
2368  * Function to be run periodically according to the moodle cron
2369  *
2370  * Finds all assignment notifications that have yet to be mailed out, and mails them
2371  */
2372 function assignment_cron () {
2373     global $CFG, $USER, $DB;
2375     /// first execute all crons in plugins
2376     if ($plugins = get_plugin_list('assignment')) {
2377         foreach ($plugins as $plugin=>$dir) {
2378             require_once("$dir/assignment.class.php");
2379             $assignmentclass = "assignment_$plugin";
2380             $ass = new $assignmentclass();
2381             $ass->cron();
2382         }
2383     }
2385     /// Notices older than 1 day will not be mailed.  This is to avoid the problem where
2386     /// cron has not been running for a long time, and then suddenly people are flooded
2387     /// with mail from the past few weeks or months
2389     $timenow   = time();
2390     $endtime   = $timenow - $CFG->maxeditingtime;
2391     $starttime = $endtime - 24 * 3600;   /// One day earlier
2393     if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2395         $realuser = clone($USER);
2397         foreach ($submissions as $key => $submission) {
2398             if (! $DB->set_field("assignment_submissions", "mailed", "1", array("id"=>$submission->id))) {
2399                 echo "Could not update the mailed field for id $submission->id.  Not mailed.\n";
2400                 unset($submissions[$key]);
2401             }
2402         }
2404         $timenow = time();
2406         foreach ($submissions as $submission) {
2408             echo "Processing assignment submission $submission->id\n";
2410             if (! $user = $DB->get_record("user", array("id"=>$submission->userid))) {
2411                 echo "Could not find user $post->userid\n";
2412                 continue;
2413             }
2415             if (! $course = $DB->get_record("course", array("id"=>$submission->course))) {
2416                 echo "Could not find course $submission->course\n";
2417                 continue;
2418             }
2420             /// Override the language and timezone of the "current" user, so that
2421             /// mail is customised for the receiver.
2422             cron_setup_user($user, $course);
2424             if (!is_enrolled(get_context_instance(CONTEXT_COURSE, $submission->course), $user->id)) {
2425                 echo fullname($user)." not an active participant in " . format_string($course->shortname) . "\n";
2426                 continue;
2427             }
2429             if (! $teacher = $DB->get_record("user", array("id"=>$submission->teacher))) {
2430                 echo "Could not find teacher $submission->teacher\n";
2431                 continue;
2432             }
2434             if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2435                 echo "Could not find course module for assignment id $submission->assignment\n";
2436                 continue;
2437             }
2439             if (! $mod->visible) {    /// Hold mail notification for hidden assignments until later
2440                 continue;
2441             }
2443             $strassignments = get_string("modulenameplural", "assignment");
2444             $strassignment  = get_string("modulename", "assignment");
2446             $assignmentinfo = new object();
2447             $assignmentinfo->teacher = fullname($teacher);
2448             $assignmentinfo->assignment = format_string($submission->name,true);
2449             $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2451             $postsubject = "$course->shortname: $strassignments: ".format_string($submission->name,true);
2452             $posttext  = "$course->shortname -> $strassignments -> ".format_string($submission->name,true)."\n";
2453             $posttext .= "---------------------------------------------------------------------\n";
2454             $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2455             $posttext .= "---------------------------------------------------------------------\n";
2457             if ($user->mailformat == 1) {  // HTML
2458                 $posthtml = "<p><font face=\"sans-serif\">".
2459                 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> ->".
2460                 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2461                 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2462                 $posthtml .= "<hr /><font face=\"sans-serif\">";
2463                 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2464                 $posthtml .= "</font><hr />";
2465             } else {
2466                 $posthtml = "";
2467             }
2469             $eventdata = new object();
2470             $eventdata->modulename       = 'assignment';
2471             $eventdata->userfrom         = $teacher;
2472             $eventdata->userto           = $user;
2473             $eventdata->subject          = $postsubject;
2474             $eventdata->fullmessage      = $posttext;
2475             $eventdata->fullmessageformat = FORMAT_PLAIN;
2476             $eventdata->fullmessagehtml  = $posthtml;
2477             $eventdata->smallmessage     = '';
2478             message_send($eventdata);
2479         }
2481         cron_setup_user();
2482     }
2484     return true;
2487 /**
2488  * Return grade for given user or all users.
2489  *
2490  * @param int $assignmentid id of assignment
2491  * @param int $userid optional user id, 0 means all users
2492  * @return array array of grades, false if none
2493  */
2494 function assignment_get_user_grades($assignment, $userid=0) {
2495     global $CFG, $DB;
2497     if ($userid) {
2498         $user = "AND u.id = :userid";
2499         $params = array('userid'=>$userid);
2500     } else {
2501         $user = "";
2502     }
2503     $params['aid'] = $assignment->id;
2505     $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2506                    s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2507               FROM {user} u, {assignment_submissions} s
2508              WHERE u.id = s.userid AND s.assignment = :aid
2509                    $user";
2511     return $DB->get_records_sql($sql, $params);
2514 /**
2515  * Update activity grades
2516  *
2517  * @param object $assignment
2518  * @param int $userid specific user only, 0 means all
2519  */
2520 function assignment_update_grades($assignment, $userid=0, $nullifnone=true) {
2521     global $CFG, $DB;
2522     require_once($CFG->libdir.'/gradelib.php');
2524     if ($assignment->grade == 0) {
2525         assignment_grade_item_update($assignment);
2527     } else if ($grades = assignment_get_user_grades($assignment, $userid)) {
2528         foreach($grades as $k=>$v) {
2529             if ($v->rawgrade == -1) {
2530                 $grades[$k]->rawgrade = null;
2531             }
2532         }
2533         assignment_grade_item_update($assignment, $grades);
2535     } else {
2536         assignment_grade_item_update($assignment);
2537     }
2540 /**
2541  * Update all grades in gradebook.
2542  */
2543 function assignment_upgrade_grades() {
2544     global $DB;
2546     $sql = "SELECT COUNT('x')
2547               FROM {assignment} a, {course_modules} cm, {modules} m
2548              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2549     $count = $DB->count_records_sql($sql);
2551     $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
2552               FROM {assignment} a, {course_modules} cm, {modules} m
2553              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2554     if ($rs = $DB->get_recordset_sql($sql)) {
2555         // too much debug output
2556         $pbar = new progress_bar('assignmentupgradegrades', 500, true);
2557         $i=0;
2558         foreach ($rs as $assignment) {
2559             $i++;
2560             upgrade_set_timeout(60*5); // set up timeout, may also abort execution
2561             assignment_update_grades($assignment);
2562             $pbar->update($i, $count, "Updating Assignment grades ($i/$count).");
2563         }
2564         $rs->close();
2565         upgrade_set_timeout(); // reset to default timeout
2566     }
2569 /**
2570  * Create grade item for given assignment
2571  *
2572  * @param object $assignment object with extra cmidnumber
2573  * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
2574  * @return int 0 if ok, error code otherwise
2575  */
2576 function assignment_grade_item_update($assignment, $grades=NULL) {
2577     global $CFG;
2578     require_once($CFG->libdir.'/gradelib.php');
2580     if (!isset($assignment->courseid)) {
2581         $assignment->courseid = $assignment->course;
2582     }
2584     $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
2586     if ($assignment->grade > 0) {
2587         $params['gradetype'] = GRADE_TYPE_VALUE;
2588         $params['grademax']  = $assignment->grade;
2589         $params['grademin']  = 0;
2591     } else if ($assignment->grade < 0) {
2592         $params['gradetype'] = GRADE_TYPE_SCALE;
2593         $params['scaleid']   = -$assignment->grade;
2595     } else {
2596         $params['gradetype'] = GRADE_TYPE_TEXT; // allow text comments only
2597     }
2599     if ($grades  === 'reset') {
2600         $params['reset'] = true;
2601         $grades = NULL;
2602     }
2604     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades, $params);
2607 /**
2608  * Delete grade item for given assignment
2609  *
2610  * @param object $assignment object
2611  * @return object assignment
2612  */
2613 function assignment_grade_item_delete($assignment) {
2614     global $CFG;
2615     require_once($CFG->libdir.'/gradelib.php');
2617     if (!isset($assignment->courseid)) {
2618         $assignment->courseid = $assignment->course;
2619     }
2621     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
2624 /**
2625  * Returns the users with data in one assignment (students and teachers)
2626  *
2627  * @param $assignmentid int
2628  * @return array of user objects
2629  */
2630 function assignment_get_participants($assignmentid) {
2631     global $CFG, $DB;
2633     //Get students
2634     $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2635                                         FROM {user} u,
2636                                              {assignment_submissions} a
2637                                        WHERE a.assignment = ? and
2638                                              u.id = a.userid", array($assignmentid));
2639     //Get teachers
2640     $teachers = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2641                                         FROM {user} u,
2642                                              {assignment_submissions} a
2643                                        WHERE a.assignment = ? and
2644                                              u.id = a.teacher", array($assignmentid));
2646     //Add teachers to students
2647     if ($teachers) {
2648         foreach ($teachers as $teacher) {
2649             $students[$teacher->id] = $teacher;
2650         }
2651     }
2652     //Return students array (it contains an array of unique users)
2653     return ($students);
2656 /**
2657  * Serves assingment submissions and otehr files.
2658  *
2659  * @param object $course
2660  * @param object $cminfo
2661  * @param object $context
2662  * @param string $filearea
2663  * @param array $args
2664  * @param bool $forcedownload
2665  * @return bool false if file not found, does not return if found - justsend the file
2666  */
2667 function assignment_pluginfile($course, $cminfo, $context, $filearea, $args, $forcedownload) {
2668     global $CFG, $DB;
2670     if (!$assignment = $DB->get_record('assignment', array('id'=>$cminfo->instance))) {
2671         return false;
2672     }
2673     if (!$cm = get_coursemodule_from_instance('assignment', $assignment->id, $course->id)) {
2674         return false;
2675     }
2677     require_login($course, false, $cm);
2679     require_once($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
2680     $assignmentclass = 'assignment_'.$assignment->assignmenttype;
2681     $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm, $course);
2683     return $assignmentinstance->send_file($filearea, $args);
2685 /**
2686  * Checks if a scale is being used by an assignment
2687  *
2688  * This is used by the backup code to decide whether to back up a scale
2689  * @param $assignmentid int
2690  * @param $scaleid int
2691  * @return boolean True if the scale is used by the assignment
2692  */
2693 function assignment_scale_used($assignmentid, $scaleid) {
2694     global $DB;
2696     $return = false;
2698     $rec = $DB->get_record('assignment', array('id'=>$assignmentid,'grade'=>-$scaleid));
2700     if (!empty($rec) && !empty($scaleid)) {
2701         $return = true;
2702     }
2704     return $return;
2707 /**
2708  * Checks if scale is being used by any instance of assignment
2709  *
2710  * This is used to find out if scale used anywhere
2711  * @param $scaleid int
2712  * @return boolean True if the scale is used by any assignment
2713  */
2714 function assignment_scale_used_anywhere($scaleid) {
2715     global $DB;
2717     if ($scaleid and $DB->record_exists('assignment', array('grade'=>-$scaleid))) {
2718         return true;
2719     } else {
2720         return false;
2721     }
2724 /**
2725  * Make sure up-to-date events are created for all assignment instances
2726  *
2727  * This standard function will check all instances of this module
2728  * and make sure there are up-to-date events created for each of them.
2729  * If courseid = 0, then every assignment event in the site is checked, else
2730  * only assignment events belonging to the course specified are checked.
2731  * This function is used, in its new format, by restore_refresh_events()
2732  *
2733  * @param $courseid int optional If zero then all assignments for all courses are covered
2734  * @return boolean Always returns true
2735  */
2736 function assignment_refresh_events($courseid = 0) {
2737     global $DB;
2739     if ($courseid == 0) {
2740         if (! $assignments = $DB->get_records("assignment")) {
2741             return true;
2742         }
2743     } else {
2744         if (! $assignments = $DB->get_records("assignment", array("course"=>$courseid))) {
2745             return true;
2746         }
2747     }
2748     $moduleid = $DB->get_field('modules', 'id', array('name'=>'assignment'));
2750     foreach ($assignments as $assignment) {
2751         $cm = get_coursemodule_from_id('assignment', $assignment->id);
2752         $event = new object();
2753         $event->name        = $assignment->name;
2754         $event->description = format_module_intro('assignment', $assignment, $cm->id);
2755         $event->timestart   = $assignment->timedue;
2757         if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
2758             update_event($event);
2760         } else {
2761             $event->courseid    = $assignment->course;
2762             $event->groupid     = 0;
2763             $event->userid      = 0;
2764             $event->modulename  = 'assignment';
2765             $event->instance    = $assignment->id;
2766             $event->eventtype   = 'due';
2767             $event->timeduration = 0;
2768             $event->visible     = $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$assignment->id));
2769             add_event($event);
2770         }
2772     }
2773     return true;
2776 /**
2777  * Print recent activity from all assignments in a given course
2778  *
2779  * This is used by the recent activity block
2780  */
2781 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
2782     global $CFG, $USER, $DB, $OUTPUT;
2784     // do not use log table if possible, it may be huge
2786     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
2787                                                      u.firstname, u.lastname, u.email, u.picture
2788                                                 FROM {assignment_submissions} asb
2789                                                      JOIN {assignment} a      ON a.id = asb.assignment
2790                                                      JOIN {course_modules} cm ON cm.instance = a.id
2791                                                      JOIN {modules} md        ON md.id = cm.module
2792                                                      JOIN {user} u            ON u.id = asb.userid
2793                                                WHERE asb.timemodified > ? AND
2794                                                      a.course = ? AND
2795                                                      md.name = 'assignment'
2796                                             ORDER BY asb.timemodified ASC", array($timestart, $course->id))) {
2797          return false;
2798     }
2800     $modinfo =& get_fast_modinfo($course); // reference needed because we might load the groups
2801     $show    = array();
2802     $grader  = array();
2804     foreach($submissions as $submission) {
2805         if (!array_key_exists($submission->cmid, $modinfo->cms)) {
2806             continue;
2807         }
2808         $cm = $modinfo->cms[$submission->cmid];
2809         if (!$cm->uservisible) {
2810             continue;
2811         }
2812         if ($submission->userid == $USER->id) {
2813             $show[] = $submission;
2814             continue;
2815         }
2817         // the act of sumbitting of assignment may be considered private - only graders will see it if specified
2818         if (empty($CFG->assignment_showrecentsubmissions)) {
2819             if (!array_key_exists($cm->id, $grader)) {
2820                 $grader[$cm->id] = has_capability('moodle/grade:viewall', get_context_instance(CONTEXT_MODULE, $cm->id));
2821             }
2822             if (!$grader[$cm->id]) {
2823                 continue;
2824             }
2825         }
2827         $groupmode = groups_get_activity_groupmode($cm, $course);
2829         if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2830             if (isguestuser()) {
2831                 // shortcut - guest user does not belong into any group
2832                 continue;
2833             }
2835             if (is_null($modinfo->groups)) {
2836                 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2837             }
2839             // this will be slow - show only users that share group with me in this cm
2840             if (empty($modinfo->groups[$cm->id])) {
2841                 continue;
2842             }
2843             $usersgroups =  groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
2844             if (is_array($usersgroups)) {
2845                 $usersgroups = array_keys($usersgroups);
2846                 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2847                 if (empty($intersect)) {
2848                     continue;
2849                 }
2850             }
2851         }
2852         $show[] = $submission;
2853     }
2855     if (empty($show)) {
2856         return false;
2857     }
2859     echo $OUTPUT->heading(get_string('newsubmissions', 'assignment').':');
2861     foreach ($show as $submission) {
2862         $cm = $modinfo->cms[$submission->cmid];
2863         $link = $CFG->wwwroot.'/mod/assignment/view.php?id='.$cm->id;
2864         print_recent_activity_note($submission->timemodified, $submission, $cm->name, $link, false, $viewfullnames);
2865     }
2867     return true;
2871 /**
2872  * Returns all assignments since a given time in specified forum.
2873  */
2874 function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0)  {
2875     global $CFG, $COURSE, $USER, $DB;
2877     if ($COURSE->id == $courseid) {
2878         $course = $COURSE;
2879     } else {
2880         $course = $DB->get_record('course', array('id'=>$courseid));
2881     }
2883     $modinfo =& get_fast_modinfo($course);
2885     $cm = $modinfo->cms[$cmid];
2887     $params = array();
2888     if ($userid) {
2889         $userselect = "AND u.id = :userid";
2890         $params['userid'] = $userid;
2891     } else {
2892         $userselect = "";
2893     }
2895     if ($groupid) {
2896         $groupselect = "AND gm.groupid = :groupid";
2897         $groupjoin   = "JOIN {groups_members} gm ON  gm.userid=u.id";
2898         $params['groupid'] = $groupid;
2899     } else {
2900         $groupselect = "";
2901         $groupjoin   = "";
2902     }
2904     $params['cminstance'] = $cm->instance;
2905     $params['timestart'] = $timestart;
2907     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, asb.userid,
2908                                                      u.firstname, u.lastname, u.email, u.picture
2909                                                 FROM {assignment_submissions} asb
2910                                                 JOIN {assignment} a      ON a.id = asb.assignment
2911                                                 JOIN {user} u            ON u.id = asb.userid
2912                                           $groupjoin
2913                                                WHERE asb.timemodified > :timestart AND a.id = :cminstance
2914                                                      $userselect $groupselect
2915                                             ORDER BY asb.timemodified ASC", $params)) {
2916          return;
2917     }
2919     $groupmode       = groups_get_activity_groupmode($cm, $course);
2920     $cm_context      = get_context_instance(CONTEXT_MODULE, $cm->id);
2921     $grader          = has_capability('moodle/grade:viewall', $cm_context);
2922     $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
2923     $viewfullnames   = has_capability('moodle/site:viewfullnames', $cm_context);
2925     if (is_null($modinfo->groups)) {
2926         $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2927     }
2929     $show = array();
2931     foreach($submissions as $submission) {
2932         if ($submission->userid == $USER->id) {
2933             $show[] = $submission;
2934             continue;
2935         }
2936         // the act of submitting of assignment may be considered private - only graders will see it if specified
2937         if (empty($CFG->assignment_showrecentsubmissions)) {
2938             if (!$grader) {
2939                 continue;
2940             }
2941         }
2943         if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
2944             if (isguestuser()) {
2945                 // shortcut - guest user does not belong into any group
2946                 continue;
2947             }
2949             // this will be slow - show only users that share group with me in this cm
2950             if (empty($modinfo->groups[$cm->id])) {
2951                 continue;
2952             }
2953             $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
2954             if (is_array($usersgroups)) {
2955                 $usersgroups = array_keys($usersgroups);
2956                 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2957                 if (empty($intersect)) {
2958                     continue;
2959                 }
2960             }
2961         }
2962         $show[] = $submission;
2963     }
2965     if (empty($show)) {
2966         return;
2967     }
2969     if ($grader) {
2970         require_once($CFG->libdir.'/gradelib.php');
2971         $userids = array();
2972         foreach ($show as $id=>$submission) {
2973             $userids[] = $submission->userid;
2975         }
2976         $grades = grade_get_grades($courseid, 'mod', 'assignment', $cm->instance, $userids);
2977     }
2979     $aname = format_string($cm->name,true);
2980     foreach ($show as $submission) {
2981         $tmpactivity = new object();
2983         $tmpactivity->type         = 'assignment';
2984         $tmpactivity->cmid         = $cm->id;
2985         $tmpactivity->name         = $aname;
2986         $tmpactivity->sectionnum   = $cm->sectionnum;
2987         $tmpactivity->timestamp    = $submission->timemodified;
2989         if ($grader) {
2990             $tmpactivity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
2991         }
2993         $tmpactivity->user->userid   = $submission->userid;
2994         $tmpactivity->user->fullname = fullname($submission, $viewfullnames);
2995         $tmpactivity->user->picture  = $submission->picture;
2997         $activities[$index++] = $tmpactivity;
2998     }
3000     return;
3003 /**
3004  * Print recent activity from all assignments in a given course
3005  *
3006  * This is used by course/recent.php
3007  */
3008 function assignment_print_recent_mod_activity($activity, $courseid, $detail, $modnames)  {
3009     global $CFG, $OUTPUT;
3011     echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
3013     echo "<tr><td class=\"userpicture\" valign=\"top\">";
3014     echo $OUTPUT->user_picture($activity->user);
3015     echo "</td><td>";
3017     if ($detail) {
3018         $modname = $modnames[$activity->type];
3019         echo '<div class="title">';
3020         echo "<img src=\"" . $OUTPUT->pix_url('icon', 'assignment') . "\" ".
3021              "class=\"icon\" alt=\"$modname\">";
3022         echo "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id={$activity->cmid}\">{$activity->name}</a>";
3023         echo '</div>';
3024     }
3026     if (isset($activity->grade)) {
3027         echo '<div class="grade">';
3028         echo get_string('grade').': ';
3029         echo $activity->grade;
3030         echo '</div>';
3031     }
3033     echo '<div class="user">';
3034     echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->userid}&amp;course=$courseid\">"
3035          ."{$activity->user->fullname}</a>  - ".userdate($activity->timestamp);
3036     echo '</div>';
3038     echo "</td></tr></table>";
3041 /// GENERIC SQL FUNCTIONS
3043 /**
3044  * Fetch info from logs
3045  *
3046  * @param $log object with properties ->info (the assignment id) and ->userid
3047  * @return array with assignment name and user firstname and lastname
3048  */
3049 function assignment_log_info($log) {
3050     global $CFG, $DB;
3052     return $DB->get_record_sql("SELECT a.name, u.firstname, u.lastname
3053                                   FROM {assignment} a, {user} u
3054                                  WHERE a.id = ? AND u.id = ?", array($log->info, $log->userid));
3057 /**
3058  * Return list of marked submissions that have not been mailed out for currently enrolled students
3059  *
3060  * @return array
3061  */
3062 function assignment_get_unmailed_submissions($starttime, $endtime) {
3063     global $CFG, $DB;
3065     return $DB->get_records_sql("SELECT s.*, a.course, a.name
3066                                    FROM {assignment_submissions} s,
3067                                         {assignment} a
3068                                   WHERE s.mailed = 0
3069                                         AND s.timemarked <= ?
3070                                         AND s.timemarked >= ?
3071                                         AND s.assignment = a.id", array($endtime, $starttime));
3074 /**
3075  * Counts all real assignment submissions by ENROLLED students (not empty ones)
3076  *
3077  * There are also assignment type methods count_real_submissions() wich in the default
3078  * implementation simply call this function.
3079  * @param $groupid int optional If nonzero then count is restricted to this group
3080  * @return int The number of submissions
3081  */
3082 function assignment_count_real_submissions($cm, $groupid=0) {
3083     global $CFG, $DB;
3085     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
3087     // this is all the users with this capability set, in this context or higher
3088     if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $groupid, '', false)) {
3089         $users = array_keys($users);
3090     }
3092     // if groupmembersonly used, remove users who are not in any group
3093     if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
3094         if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
3095             $users = array_intersect($users, array_keys($groupingusers));
3096         }
3097     }
3099     if (empty($users)) {
3100         return 0;
3101     }
3103     $userlists = implode(',', $users);
3105     return $DB->count_records_sql("SELECT COUNT('x')
3106                                      FROM {assignment_submissions}
3107                                     WHERE assignment = ? AND
3108                                           timemodified > 0 AND
3109                                           userid IN ($userlists)", array($cm->instance));
3113 /**
3114  * Return all assignment submissions by ENROLLED students (even empty)
3115  *
3116  * There are also assignment type methods get_submissions() wich in the default
3117  * implementation simply call this function.
3118  * @param $sort string optional field names for the ORDER BY in the sql query
3119  * @param $dir string optional specifying the sort direction, defaults to DESC
3120  * @return array The submission objects indexed by id
3121  */
3122 function assignment_get_all_submissions($assignment, $sort="", $dir="DESC") {
3123 /// Return all assignment submissions by ENROLLED students (even empty)
3124     global $CFG, $DB;
3126     if ($sort == "lastname" or $sort == "firstname") {
3127         $sort = "u.$sort $dir";
3128     } else if (empty($sort)) {
3129         $sort = "a.timemodified DESC";
3130     } else {
3131         $sort = "a.$sort $dir";
3132     }
3134     /* not sure this is needed at all since assignmenet already has a course define, so this join?
3135     $select = "s.course = '$assignment->course' AND";
3136     if ($assignment->course == SITEID) {
3137         $select = '';
3138     }*/
3140     return $DB->get_records_sql("SELECT a.*
3141                                    FROM {assignment_submissions} a, {user} u
3142                                   WHERE u.id = a.userid
3143                                         AND a.assignment = ?
3144                                ORDER BY $sort", array($assignment->id));
3148 /**
3149  * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
3150  * for the course (see resource).
3151  *
3152  * Given a course_module object, this function returns any "extra" information that may be needed
3153  * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
3154  *
3155  * @param $coursemodule object The coursemodule object (record).
3156  * @return object An object on information that the coures will know about (most noticeably, an icon).
3157  *
3158  */
3159 function assignment_get_coursemodule_info($coursemodule) {
3160     global $CFG, $DB;
3162     if (! $assignment = $DB->get_record('assignment', array('id'=>$coursemodule->instance), 'id, assignmenttype, name')) {
3163         return false;
3164     }
3166     $libfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
3168     if (file_exists($libfile)) {
3169         require_once($libfile);
3170         $assignmentclass = "assignment_$assignment->assignmenttype";
3171         $ass = new $assignmentclass('staticonly');
3172         if ($result = $ass->get_coursemodule_info($coursemodule)) {
3173             return $result;
3174         } else {
3175             $info = new object();
3176             $info->name = $assignment->name;
3177             return $info;
3178         }
3180     } else {
3181         debugging('Incorrect assignment type: '.$assignment->assignmenttype);
3182         return false;
3183     }
3188 /// OTHER GENERAL FUNCTIONS FOR ASSIGNMENTS  ///////////////////////////////////////
3190 /**
3191  * Returns an array of installed assignment types indexed and sorted by name
3192  *
3193  * @return array The index is the name of the assignment type, the value its full name from the language strings
3194  */
3195 function assignment_types() {
3196     $types = array();
3197     $names = get_plugin_list('assignment');
3198     foreach ($names as $name=>$dir) {
3199         $types[$name] = get_string('type'.$name, 'assignment');
3201         // ugly hack to support pluggable assignment type titles..
3202         if ($types[$name] == '[[type'.$name.']]') {
3203             $types[$name] = get_string('type'.$name, 'assignment_'.$name);
3204         }
3205     }
3206     asort($types);
3207     return $types;
3210 function assignment_print_overview($courses, &$htmlarray) {
3211     global $USER, $CFG, $DB;
3213     if (empty($courses) || !is_array($courses) || count($courses) == 0) {
3214         return array();
3215     }
3217     if (!$assignments = get_all_instances_in_courses('assignment',$courses)) {
3218         return;
3219     }
3221     $assignmentids = array();
3223     // Do assignment_base::isopen() here without loading the whole thing for speed
3224     foreach ($assignments as $key => $assignment) {
3225         $time = time();
3226         if ($assignment->timedue) {
3227             if ($assignment->preventlate) {
3228                 $isopen = ($assignment->timeavailable <= $time && $time <= $assignment->timedue);
3229             } else {
3230                 $isopen = ($assignment->timeavailable <= $time);
3231             }
3232         }
3233         if (empty($isopen) || empty($assignment->timedue)) {
3234             unset($assignments[$key]);
3235         }else{
3236             $assignmentids[] = $assignment->id;
3237         }
3238     }
3240     if(empty($assignmentids)){
3241         // no assigments to look at - we're done
3242         return true;
3243     }
3245     $strduedate = get_string('duedate', 'assignment');
3246     $strduedateno = get_string('duedateno', 'assignment');
3247     $strgraded = get_string('graded', 'assignment');
3248     $strnotgradedyet = get_string('notgradedyet', 'assignment');
3249     $strnotsubmittedyet = get_string('notsubmittedyet', 'assignment');
3250     $strsubmitted = get_string('submitted', 'assignment');
3251     $strassignment = get_string('modulename', 'assignment');
3252     $strreviewed = get_string('reviewed','assignment');
3255     // NOTE: we do all possible database work here *outside* of the loop to ensure this scales
3256     //
3257     list($sqlassignmentids, $assignmentidparams) = $DB->get_in_or_equal($assignmentids);
3259     // build up and array of unmarked submissions indexed by assigment id/ userid
3260     // for use where the user has grading rights on assigment
3261     $rs = $DB->get_recordset_sql("SELECT id, assignment, userid
3262                             FROM {assignment_submissions}
3263                             WHERE teacher = 0 AND timemarked = 0
3264                             AND assignment $sqlassignmentids", $assignmentidparams);
3266     $unmarkedsubmissions = array();
3267     foreach ($rs as $rd) {
3268         $unmarkedsubmissions[$rd->assignment][$rd->userid] = $rd->id;
3269     }
3270     $rs->close();
3273     // get all user submissions, indexed by assigment id
3274     $mysubmissions = $DB->get_records_sql("SELECT assignment, timemarked, teacher, grade
3275                                       FROM {assignment_submissions}
3276                                       WHERE userid = ? AND
3277                                       assignment $sqlassignmentids", array_merge(array($USER->id), $assignmentidparams));
3279     foreach ($assignments as $assignment) {
3280         $str = '<div class="assignment overview"><div class="name">'.$strassignment. ': '.
3281                '<a '.($assignment->visible ? '':' class="dimmed"').
3282                'title="'.$strassignment.'" href="'.$CFG->wwwroot.
3283                '/mod/assignment/view.php?id='.$assignment->coursemodule.'">'.
3284                $assignment->name.'</a></div>';
3285         if ($assignment->timedue) {
3286             $str .= '<div class="info">'.$strduedate.': '.userdate($assignment->timedue).'</div>';
3287         } else {
3288             $str .= '<div class="info">'.$strduedateno.'</div>';
3289         }
3290         $context = get_context_instance(CONTEXT_MODULE, $assignment->coursemodule);
3291         if (has_capability('mod/assignment:grade', $context)) {
3293             // count how many people can submit
3294             $submissions = 0; // init
3295             if ($students = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', 0, '', false)) {
3296                 foreach($students as $student){
3297                     if(isset($unmarkedsubmissions[$assignment->id][$student->id])){
3298                         $submissions++;
3299                     }
3300                 }
3301             }
3303             if ($submissions) {
3304                 $str .= get_string('submissionsnotgraded', 'assignment', $submissions);
3305             }
3306         } else {
3307             if(isset($mysubmissions[$assignment->id])){
3309                 $submission = $mysubmissions[$assignment->id];
3311                 if ($submission->teacher == 0 && $submission->timemarked == 0) {
3312                     $str .= $strsubmitted . ', ' . $strnotgradedyet;
3313                 } else if ($submission->grade <= 0) {
3314                     $str .= $strsubmitted . ', ' . $strreviewed;
3315                 } else {
3316                     $str .= $strsubmitted . ', ' . $strgraded;
3317                 }
3318             } else {
3319                 $str .= $strnotsubmittedyet . ' ' . assignment_display_lateness(time(), $assignment->timedue);
3320             }
3321         }
3322         $str .= '</div>';
3323         if (empty($htmlarray[$assignment->course]['assignment'])) {
3324             $htmlarray[$assignment->course]['assignment'] = $str;
3325         } else {
3326             $htmlarray[$assignment->course]['assignment'] .= $str;
3327         }
3328     }
3331 function assignment_display_lateness($timesubmitted, $timedue) {
3332     if (!$timedue) {
3333         return '';
3334     }
3335     $time = $timedue - $timesubmitted;
3336     if ($time < 0) {
3337         $timetext = get_string('late', 'assignment', format_time($time));
3338         return ' (<span class="late">'.$timetext.'</span>)';
3339     } else {
3340         $timetext = get_string('early', 'assignment', format_time($time));
3341         return ' (<span class="early">'.$timetext.'</span>)';
3342     }
3345 function assignment_get_view_actions() {
3346     return array('view');
3349 function assignment_get_post_actions() {
3350     return array('upload');
3353 function assignment_get_types() {
3354     global $CFG;
3355     $types = array();
3357     $type = new object();
3358     $type->modclass = MOD_CLASS_ACTIVITY;
3359     $type->type = "assignment_group_start";
3360     $type->typestr = '--'.get_string('modulenameplural', 'assignment');
3361     $types[] = $type;
3363     $standardassignments = array('upload','online','uploadsingle','offline');
3364     foreach ($standardassignments as $assignmenttype) {
3365         $type = new object();
3366         $type->modclass = MOD_CLASS_ACTIVITY;
3367         $type->type = "assignment&amp;type=$assignmenttype";
3368         $type->typestr = get_string("type$assignmenttype", 'assignment');
3369         $types[] = $type;
3370     }
3372     /// Drop-in extra assignment types
3373     $assignmenttypes = get_list_of_plugins('mod/assignment/type');
3374     foreach ($assignmenttypes as $assignmenttype) {
3375         if (!empty($CFG->{'assignment_hide_'.$assignmenttype})) {  // Not wanted
3376             continue;
3377         }
3378         if (!in_array($assignmenttype, $standardassignments)) {
3379             $type = new object();
3380             $type->modclass = MOD_CLASS_ACTIVITY;
3381             $type->type = "assignment&amp;type=$assignmenttype";
3382             $type->typestr = get_string("type$assignmenttype", 'assignment_'.$assignmenttype);
3383             $types[] = $type;
3384         }
3385     }
3387     $type = new object();
3388     $type->modclass = MOD_CLASS_ACTIVITY;
3389     $type->type = "assignment_group_end";
3390     $type->typestr = '--';
3391     $types[] = $type;
3393     return $types;
3396 /**
3397  * Removes all grades from gradebook
3398  * @param int $courseid
3399  * @param string optional type
3400  */
3401 function assignment_reset_gradebook($courseid, $type='') {
3402     global $CFG, $DB;
3404     $params = array('courseid'=>$courseid);
3405     if ($type) {
3406         $type = "AND a.assignmenttype= :type";
3407         $params['type'] = $type;
3408     }
3410     $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
3411               FROM {assignment} a, {course_modules} cm, {modules} m
3412              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id AND a.course=:courseid $type";
3414     if ($assignments = $DB->get_records_sql($sql, $params)) {
3415         foreach ($assignments as $assignment) {
3416             assignment_grade_item_update($assignment, 'reset');
3417         }
3418     }
3421 /**
3422  * This function is used by the reset_course_userdata function in moodlelib.
3423  * This function will remove all posts from the specified assignment
3424  * and clean up any related data.
3425  * @param $data the data submitted from the reset course.
3426  * @return array status array
3427  */
3428 function assignment_reset_userdata($data) {
3429     global $CFG;
3431     $status = array();
3433     foreach (get_plugin_list('mod/assignment/type') as $type=>$dir) {
3434         require_once("$dir/assignment.class.php");
3435         $assignmentclass = "assignment_$type";
3436         $ass = new $assignmentclass();
3437         $status = array_merge($status, $ass->reset_userdata($data));
3438     }
3440     return $status;
3443 /**
3444  * Implementation of the function for printing the form elements that control
3445  * whether the course reset functionality affects the assignment.
3446  * @param $mform form passed by reference
3447  */
3448 function assignment_reset_course_form_definition(&$mform) {
3449     $mform->addElement('header', 'assignmentheader', get_string('modulenameplural', 'assignment'));
3450     $mform->addElement('advcheckbox', 'reset_assignment_submissions', get_string('deleteallsubmissions','assignment'));
3453 /**
3454  * Course reset form defaults.
3455  */
3456 function assignment_reset_course_form_defaults($course) {
3457     return array('reset_assignment_submissions'=>1);
3460 /**
3461  * Returns all other caps used in module
3462  */
3463 function assignment_get_extra_capabilities() {
3464     return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames');
3467 /**
3468  * @param string $feature FEATURE_xx constant for requested feature
3469  * @return mixed True if module supports feature, null if doesn't know
3470  */
3471 function assignment_supports($feature) {
3472     switch($feature) {
3473         case FEATURE_GROUPS:                  return true;
3474         case FEATURE_GROUPINGS:               return true;
3475         case FEATURE_GROUPMEMBERSONLY:        return true;
3476         case FEATURE_MOD_INTRO:               return true;
3477         case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
3478         case FEATURE_GRADE_HAS_GRADE:         return true;
3479         case FEATURE_GRADE_OUTCOMES:          return true;
3480         case FEATURE_GRADE_HAS_GRADE:         return true;
3482         default: return null;
3483     }
3486 /**
3487  * Adds module specific settings to the settings block
3488  * 
3489  * @param settings_navigation $settings The settings navigation object
3490  * @param navigation_node $assignmentnode The node to add module settings to
3491  */
3492 function assignment_extend_settings_navigation(settings_navigation $settings, navigation_node $assignmentnode) {
3493     global $PAGE, $DB, $USER, $CFG;
3495     $assignmentrow = $DB->get_record("assignment", array("id" => $PAGE->cm->instance));
3496     require_once "$CFG->dirroot/mod/assignment/type/$assignmentrow->assignmenttype/assignment.class.php";
3497     
3498     $assignmentclass = 'assignment_'.$assignmentrow->assignmenttype;
3499     $assignmentinstance = new $assignmentclass($PAGE->cm->id, $assignmentrow, $PAGE->cm, $PAGE->course);
3501     $allgroups = false;
3503     // Add assignment submission information
3504     if (has_capability('mod/assignment:grade', $PAGE->cm->context)) {
3505         if ($allgroups && has_capability('moodle/site:accessallgroups', $PAGE->cm->context)) {
3506             $group = 0;
3507         } else {
3508             $group = groups_get_activity_group($PAGE->cm);
3509         }
3510         $link = new moodle_url('/mod/assignment/submissions.php', array('id'=>$PAGE->cm->id));
3511         if ($count = $assignmentinstance->count_real_submissions($group)) {
3512             $string = get_string('viewsubmissions', 'assignment', $count);
3513         } else {
3514             $string = get_string('noattempts', 'assignment');
3515         }
3516         $assignmentnode->add($string, $link, navigation_node::TYPE_SETTING);
3517     }
3519     if (is_object($assignmentinstance) && method_exists($assignmentinstance, 'extend_settings_navigation')) {
3520         $assignmentinstance->extend_settings_navigation($assignmentnode);
3521     }
3524 /**
3525  * generate zip file from array of given files
3526  * @param array $filesforzipping - array of files to pass into archive_to_pathname
3527  * @return path of temp file - note this returned file does not have a .zip extension - it is a temp file.
3528  */
3529 function assignment_pack_files($filesforzipping) {
3530         global $CFG;
3531         //create path for new zip file.
3532         $tempzip = tempnam($CFG->dataroot.'/temp/', 'assignment_');
3533         //zip files
3534         $zipper = new zip_packer();
3535         if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
3536             return $tempzip;
3537         }
3538         return false;
3540 //TODO - this is a copy of the function my_mktempdir in admin/uploadpicture.php - it would be good to have as a core function.
3541 /**
3542  * Create a unique temporary directory with a given prefix name,
3543  * inside a given directory, with given permissions. Return the
3544  * full path to the newly created temp directory.
3545  *
3546  * @param string $dir where to create the temp directory.
3547  * @param string $prefix prefix for the temp directory name (default '')
3548  * @param string $mode permissions for the temp directory (default 700)
3549  *
3550  * @return string The full path to the temp directory.
3551  */
3552 function assignment_create_temp_dir($dir, $prefix='', $mode=0700) {
3553     if (substr($dir, -1) != '/') {
3554         $dir .= '/';
3555     }
3557     do {
3558         $path = $dir.$prefix.mt_rand(0, 9999999);
3559     } while (!mkdir($path, $mode));
3561     return $path;
3563 /**
3564  * Lists all file areas current user may browse
3565  *
3566  * @param object $course
3567  * @param object $cm
3568  * @param object $context
3569  * @return array
3570  */
3571 function assignment_get_file_areas($course, $cm, $context) {
3572     $areas = array();
3573     if (has_capability('moodle/course:managefiles', $context)) {
3574         $areas['assignment_submission'] = get_string('assignmentsubmission', 'assignment');
3575     }
3576     return $areas;