7ff052d17d40052c92fd64b19752cbe6979fd30d
[moodle.git] / mod / assignment / lib.php
1 <?PHP
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
18 /**
19  * assignment_base is the base class for assignment types
20  *
21  * This class provides all the functionality for an assignment
22  *
23  * @package   mod-assignment
24  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
25  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26  */
28 /** Include eventslib.php */
29 require_once($CFG->libdir.'/eventslib.php');
30 /** Include formslib.php */
31 require_once($CFG->libdir.'/formslib.php');
32 /** Include calendar/lib.php */
33 require_once($CFG->dirroot.'/calendar/lib.php');
35 /** ASSIGNMENT_COUNT_WORDS = 1 */
36 DEFINE ('ASSIGNMENT_COUNT_WORDS', 1);
37 /** ASSIGNMENT_COUNT_LETTERS = 2 */
38 DEFINE ('ASSIGNMENT_COUNT_LETTERS', 2);
40 /**
41  * Standard base class for all assignment submodules (assignment types).
42  *
43  * @package   mod-assignment
44  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
45  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
46  */
47 class assignment_base {
49     /** @var object */
50     var $cm;
51     /** @var object */
52     var $course;
53     /** @var object */
54     var $assignment;
55     /** @var string */
56     var $strassignment;
57     /** @var string */
58     var $strassignments;
59     /** @var string */
60     var $strsubmissions;
61     /** @var string */
62     var $strlastmodified;
63     /** @var string */
64     var $pagetitle;
65     /** @var bool */
66     var $usehtmleditor;
67     /**
68      * @todo document this var
69      */
70     var $defaultformat;
71     /**
72      * @todo document this var
73      */
74     var $context;
75     /** @var string */
76     var $type;
78     /**
79      * Constructor for the base assignment class
80      *
81      * Constructor for the base assignment class.
82      * If cmid is set create the cm, course, assignment objects.
83      * If the assignment is hidden and the user is not a teacher then
84      * this prints a page header and notice.
85      *
86      * @global object
87      * @global object
88      * @param int $cmid the current course module id - not set for new assignments
89      * @param object $assignment usually null, but if we have it we pass it to save db access
90      * @param object $cm usually null, but if we have it we pass it to save db access
91      * @param object $course usually null, but if we have it we pass it to save db access
92      */
93     function assignment_base($cmid='staticonly', $assignment=NULL, $cm=NULL, $course=NULL) {
94         global $COURSE, $DB;
96         if ($cmid == 'staticonly') {
97             //use static functions only!
98             return;
99         }
101         global $CFG;
103         if ($cm) {
104             $this->cm = $cm;
105         } else if (! $this->cm = get_coursemodule_from_id('assignment', $cmid)) {
106             print_error('invalidcoursemodule');
107         }
109         $this->context = get_context_instance(CONTEXT_MODULE, $this->cm->id);
111         if ($course) {
112             $this->course = $course;
113         } else if ($this->cm->course == $COURSE->id) {
114             $this->course = $COURSE;
115         } else if (! $this->course = $DB->get_record('course', array('id'=>$this->cm->course))) {
116             print_error('invalidid', 'assignment');
117         }
119         if ($assignment) {
120             $this->assignment = $assignment;
121         } else if (! $this->assignment = $DB->get_record('assignment', array('id'=>$this->cm->instance))) {
122             print_error('invalidid', 'assignment');
123         }
125         $this->assignment->cmidnumber = $this->cm->idnumber; // compatibility with modedit assignment obj
126         $this->assignment->courseid   = $this->course->id; // compatibility with modedit assignment obj
128         $this->strassignment = get_string('modulename', 'assignment');
129         $this->strassignments = get_string('modulenameplural', 'assignment');
130         $this->strsubmissions = get_string('submissions', 'assignment');
131         $this->strlastmodified = get_string('lastmodified');
132         $this->pagetitle = strip_tags($this->course->shortname.': '.$this->strassignment.': '.format_string($this->assignment->name,true));
134         // visibility handled by require_login() with $cm parameter
135         // get current group only when really needed
137     /// Set up things for a HTML editor if it's needed
138         $this->defaultformat = editors_get_preferred_format();
139     }
141     /**
142      * Display the assignment, used by view.php
143      *
144      * This in turn calls the methods producing individual parts of the page
145      */
146     function view() {
148         $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
149         require_capability('mod/assignment:view', $context);
151         add_to_log($this->course->id, "assignment", "view", "view.php?id={$this->cm->id}",
152                    $this->assignment->id, $this->cm->id);
154         $this->view_header();
156         $this->view_intro();
158         $this->view_dates();
160         $this->view_feedback();
162         $this->view_footer();
163     }
165     /**
166      * Display the header and top of a page
167      *
168      * (this doesn't change much for assignment types)
169      * This is used by the view() method to print the header of view.php but
170      * it can be used on other pages in which case the string to denote the
171      * page in the navigation trail should be passed as an argument
172      *
173      * @global object
174      * @param string $subpage Description of subpage to be used in navigation trail
175      */
176     function view_header($subpage='') {
177         global $CFG, $PAGE, $OUTPUT;
179         if ($subpage) {
180             $PAGE->navbar->add($subpage);
181         }
183         $PAGE->set_title($this->pagetitle);
184         $PAGE->set_heading($this->course->fullname);
186         echo $OUTPUT->header();
188         groups_print_activity_menu($this->cm, $CFG->wwwroot . '/mod/assignment/view.php?id=' . $this->cm->id);
190         echo '<div class="reportlink">'.$this->submittedlink().'</div>';
191         echo '<div class="clearer"></div>';
192     }
195     /**
196      * Display the assignment intro
197      *
198      * This will most likely be extended by assignment type plug-ins
199      * The default implementation prints the assignment description in a box
200      */
201     function view_intro() {
202         global $OUTPUT;
203         echo $OUTPUT->box_start('generalbox boxaligncenter', 'intro');
204         echo format_module_intro('assignment', $this->assignment, $this->cm->id);
205         echo $OUTPUT->box_end();
206     }
208     /**
209      * Display the assignment dates
210      *
211      * Prints the assignment start and end dates in a box.
212      * This will be suitable for most assignment types
213      */
214     function view_dates() {
215         global $OUTPUT;
216         if (!$this->assignment->timeavailable && !$this->assignment->timedue) {
217             return;
218         }
220         echo $OUTPUT->box_start('generalbox boxaligncenter', 'dates');
221         echo '<table>';
222         if ($this->assignment->timeavailable) {
223             echo '<tr><td class="c0">'.get_string('availabledate','assignment').':</td>';
224             echo '    <td class="c1">'.userdate($this->assignment->timeavailable).'</td></tr>';
225         }
226         if ($this->assignment->timedue) {
227             echo '<tr><td class="c0">'.get_string('duedate','assignment').':</td>';
228             echo '    <td class="c1">'.userdate($this->assignment->timedue).'</td></tr>';
229         }
230         echo '</table>';
231         echo $OUTPUT->box_end();
232     }
235     /**
236      * Display the bottom and footer of a page
237      *
238      * This default method just prints the footer.
239      * This will be suitable for most assignment types
240      */
241     function view_footer() {
242         global $OUTPUT;
243         echo $OUTPUT->footer();
244     }
246     /**
247      * Display the feedback to the student
248      *
249      * This default method prints the teacher picture and name, date when marked,
250      * grade and teacher submissioncomment.
251      *
252      * @global object
253      * @global object
254      * @global object
255      * @param object $submission The submission object or NULL in which case it will be loaded
256      */
257     function view_feedback($submission=NULL) {
258         global $USER, $CFG, $DB, $OUTPUT;
259         require_once($CFG->libdir.'/gradelib.php');
261         if (!is_enrolled($this->context, $USER, 'mod/assignment:submit')) {
262             // can not submit assignments -> no feedback
263             return;
264         }
266         if (!$submission) { /// Get submission for this assignment
267             $submission = $this->get_submission($USER->id);
268         }
270         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $USER->id);
271         $item = $grading_info->items[0];
272         $grade = $item->grades[$USER->id];
274         if ($grade->hidden or $grade->grade === false) { // hidden or error
275             return;
276         }
278         if ($grade->grade === null and empty($grade->str_feedback)) {   /// Nothing to show yet
279             return;
280         }
282         $graded_date = $grade->dategraded;
283         $graded_by   = $grade->usermodified;
285     /// We need the teacher info
286         if (!$teacher = $DB->get_record('user', array('id'=>$graded_by))) {
287             print_error('cannotfindteacher');
288         }
290     /// Print the feedback
291         echo $OUTPUT->heading(get_string('feedbackfromteacher', 'assignment', fullname($teacher)));
293         echo '<table cellspacing="0" class="feedback">';
295         echo '<tr>';
296         echo '<td class="left picture">';
297         if ($teacher) {
298             echo $OUTPUT->user_picture($teacher);
299         }
300         echo '</td>';
301         echo '<td class="topic">';
302         echo '<div class="from">';
303         if ($teacher) {
304             echo '<div class="fullname">'.fullname($teacher).'</div>';
305         }
306         echo '<div class="time">'.userdate($graded_date).'</div>';
307         echo '</div>';
308         echo '</td>';
309         echo '</tr>';
311         echo '<tr>';
312         echo '<td class="left side">&nbsp;</td>';
313         echo '<td class="content">';
314         echo '<div class="grade">';
315         echo get_string("grade").': '.$grade->str_long_grade;
316         echo '</div>';
317         echo '<div class="clearer"></div>';
319         echo '<div class="comment">';
320         echo $grade->str_feedback;
321         echo '</div>';
322         echo '</tr>';
324          if ($this->type == 'uploadsingle') { //@TODO: move to overload view_feedback method in the class or is uploadsingle merging into upload?
325             $responsefiles = $this->print_responsefiles($submission->userid, true);
326             if (!empty($responsefiles)) {
327                 echo '<tr>';
328                 echo '<td class="left side">&nbsp;</td>';
329                 echo '<td class="content">';
330                 echo $responsefiles;
331                 echo '</tr>';
332             }
333          }
335         echo '</table>';
336     }
338     /**
339      * Returns a link with info about the state of the assignment submissions
340      *
341      * This is used by view_header to put this link at the top right of the page.
342      * For teachers it gives the number of submitted assignments with a link
343      * For students it gives the time of their submission.
344      * This will be suitable for most assignment types.
345      *
346      * @global object
347      * @global object
348      * @param bool $allgroup print all groups info if user can access all groups, suitable for index.php
349      * @return string
350      */
351     function submittedlink($allgroups=false) {
352         global $USER;
353         global $CFG;
355         $submitted = '';
356         $urlbase = "{$CFG->wwwroot}/mod/assignment/";
358         $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
359         if (has_capability('mod/assignment:grade', $context)) {
360             if ($allgroups and has_capability('moodle/site:accessallgroups', $context)) {
361                 $group = 0;
362             } else {
363                 $group = groups_get_activity_group($this->cm);
364             }
365             if ($count = $this->count_real_submissions($group)) {
366                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
367                              get_string('viewsubmissions', 'assignment', $count).'</a>';
368             } else {
369                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
370                              get_string('noattempts', 'assignment').'</a>';
371             }
372         } else {
373             if (isloggedin()) {
374                 if ($submission = $this->get_submission($USER->id)) {
375                     if ($submission->timemodified) {
376                         if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
377                             $submitted = '<span class="early">'.userdate($submission->timemodified).'</span>';
378                         } else {
379                             $submitted = '<span class="late">'.userdate($submission->timemodified).'</span>';
380                         }
381                     }
382                 }
383             }
384         }
386         return $submitted;
387     }
390     /**
391      * @todo Document this function
392      */
393     function setup_elements(&$mform) {
395     }
397     /**
398      * Any preprocessing needed for the settings form for
399      * this assignment type
400      *
401      * @param array $default_values - array to fill in with the default values
402      *      in the form 'formelement' => 'value'
403      * @param object $form - the form that is to be displayed
404      * @return none
405      */
406     function form_data_preprocessing(&$default_values, $form) {
407     }
409     /**
410      * Any extra validation checks needed for the settings
411      * form for this assignment type
412      *
413      * See lib/formslib.php, 'validation' function for details
414      */
415     function form_validation($data, $files) {
416         return array();
417     }
419     /**
420      * Create a new assignment activity
421      *
422      * Given an object containing all the necessary data,
423      * (defined by the form in mod_form.php) this function
424      * will create a new instance and return the id number
425      * of the new instance.
426      * The due data is added to the calendar
427      * This is common to all assignment types.
428      *
429      * @global object
430      * @global object
431      * @param object $assignment The data from the form on mod_form.php
432      * @return int The id of the assignment
433      */
434     function add_instance($assignment) {
435         global $COURSE, $DB;
437         $assignment->timemodified = time();
438         $assignment->courseid = $assignment->course;
440         if ($returnid = $DB->insert_record("assignment", $assignment)) {
441             $assignment->id = $returnid;
443             if ($assignment->timedue) {
444                 $event = new object();
445                 $event->name        = $assignment->name;
446                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
447                 $event->courseid    = $assignment->course;
448                 $event->groupid     = 0;
449                 $event->userid      = 0;
450                 $event->modulename  = 'assignment';
451                 $event->instance    = $returnid;
452                 $event->eventtype   = 'due';
453                 $event->timestart   = $assignment->timedue;
454                 $event->timeduration = 0;
456                 calendar_event::create($event);
457             }
459             assignment_grade_item_update($assignment);
461         }
464         return $returnid;
465     }
467     /**
468      * Deletes an assignment activity
469      *
470      * Deletes all database records, files and calendar events for this assignment.
471      *
472      * @global object
473      * @global object
474      * @param object $assignment The assignment to be deleted
475      * @return boolean False indicates error
476      */
477     function delete_instance($assignment) {
478         global $CFG, $DB;
480         $assignment->courseid = $assignment->course;
482         $result = true;
484         // now get rid of all files
485         $fs = get_file_storage();
486         if ($cm = get_coursemodule_from_instance('assignment', $assignment->id)) {
487             $context = get_context_instance(CONTEXT_MODULE, $cm->id);
488             $fs->delete_area_files($context->id);
489         }
491         if (! $DB->delete_records('assignment_submissions', array('assignment'=>$assignment->id))) {
492             $result = false;
493         }
495         if (! $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
496             $result = false;
497         }
499         if (! $DB->delete_records('assignment', array('id'=>$assignment->id))) {
500             $result = false;
501         }
502         $mod = $DB->get_field('modules','id',array('name'=>'assignment'));
504         assignment_grade_item_delete($assignment);
506         return $result;
507     }
509     /**
510      * Updates a new assignment activity
511      *
512      * Given an object containing all the necessary data,
513      * (defined by the form in mod_form.php) this function
514      * will update the assignment instance and return the id number
515      * The due date is updated in the calendar
516      * This is common to all assignment types.
517      *
518      * @global object
519      * @global object
520      * @param object $assignment The data from the form on mod_form.php
521      * @return int The assignment id
522      */
523     function update_instance($assignment) {
524         global $COURSE, $DB;
526         $assignment->timemodified = time();
528         $assignment->id = $assignment->instance;
529         $assignment->courseid = $assignment->course;
531         $DB->update_record('assignment', $assignment);
533         if ($assignment->timedue) {
534             $event = new object();
536             if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
538                 $event->name        = $assignment->name;
539                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
540                 $event->timestart   = $assignment->timedue;
542                 $calendarevent = calendar_event::load($event->id);
543                 $calendarevent->update($event);
544             } else {
545                 $event = new object();
546                 $event->name        = $assignment->name;
547                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
548                 $event->courseid    = $assignment->course;
549                 $event->groupid     = 0;
550                 $event->userid      = 0;
551                 $event->modulename  = 'assignment';
552                 $event->instance    = $assignment->id;
553                 $event->eventtype   = 'due';
554                 $event->timestart   = $assignment->timedue;
555                 $event->timeduration = 0;
557                 calendar_event::create($event);
558             }
559         } else {
560             $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id));
561         }
563         // get existing grade item
564         assignment_grade_item_update($assignment);
566         return true;
567     }
569     /**
570      * Update grade item for this submission.
571      */
572     function update_grade($submission) {
573         assignment_update_grades($this->assignment, $submission->userid);
574     }
576     /**
577      * Top-level function for handling of submissions called by submissions.php
578      *
579      * This is for handling the teacher interaction with the grading interface
580      * This should be suitable for most assignment types.
581      *
582      * @global object
583      * @param string $mode Specifies the kind of teacher interaction taking place
584      */
585     function submissions($mode) {
586         ///The main switch is changed to facilitate
587         ///1) Batch fast grading
588         ///2) Skip to the next one on the popup
589         ///3) Save and Skip to the next one on the popup
591         //make user global so we can use the id
592         global $USER, $OUTPUT, $DB, $PAGE;
594         $mailinfo = optional_param('mailinfo', null, PARAM_BOOL);
595         $saved = optional_param('saved', null, PARAM_BOOL);
597         if (optional_param('next', null, PARAM_BOOL)) {
598             $mode='next';
599         }
600         if (optional_param('saveandnext', null, PARAM_BOOL)) {
601             $mode='saveandnext';
602         }
604         if (is_null($mailinfo)) {
605             $mailinfo = get_user_preferences('assignment_mailinfo', 0);
606         } else {
607             set_user_preference('assignment_mailinfo', $mailinfo);
608         }
610         if ($saved) {
611             $OUTPUT->heading(get_string('changessaved'));
612         }
614         switch ($mode) {
615             case 'grade':                         // We are in a main window grading
616                 if ($submission = $this->process_feedback()) {
617                     $this->display_submissions(get_string('changessaved'));
618                 } else {
619                     $this->display_submissions();
620                 }
621                 break;
623             case 'single':                        // We are in a main window displaying one submission
624                 if ($submission = $this->process_feedback()) {
625                     $this->display_submissions(get_string('changessaved'));
626                 } else {
627                     $this->display_submission();
628                 }
629                 break;
631             case 'all':                          // Main window, display everything
632                 $this->display_submissions();
633                 break;
635             case 'fastgrade':
636                 ///do the fast grading stuff  - this process should work for all 3 subclasses
637                 $grading    = false;
638                 $commenting = false;
639                 $col        = false;
640                 if (isset($_POST['submissioncomment'])) {
641                     $col = 'submissioncomment';
642                     $commenting = true;
643                 }
644                 if (isset($_POST['menu'])) {
645                     $col = 'menu';
646                     $grading = true;
647                 }
648                 if (!$col) {
649                     //both submissioncomment and grade columns collapsed..
650                     $this->display_submissions();
651                     break;
652                 }
654                 foreach ($_POST[$col] as $id => $unusedvalue){
656                     $id = (int)$id; //clean parameter name
658                     $this->process_outcomes($id);
660                     if (!$submission = $this->get_submission($id)) {
661                         $submission = $this->prepare_new_submission($id);
662                         $newsubmission = true;
663                     } else {
664                         $newsubmission = false;
665                     }
666                     unset($submission->data1);  // Don't need to update this.
667                     unset($submission->data2);  // Don't need to update this.
669                     //for fast grade, we need to check if any changes take place
670                     $updatedb = false;
672                     if ($grading) {
673                         $grade = $_POST['menu'][$id];
674                         $updatedb = $updatedb || ($submission->grade != $grade);
675                         $submission->grade = $grade;
676                     } else {
677                         if (!$newsubmission) {
678                             unset($submission->grade);  // Don't need to update this.
679                         }
680                     }
681                     if ($commenting) {
682                         $commentvalue = trim($_POST['submissioncomment'][$id]);
683                         $updatedb = $updatedb || ($submission->submissioncomment != $commentvalue);
684                         $submission->submissioncomment = $commentvalue;
685                     } else {
686                         unset($submission->submissioncomment);  // Don't need to update this.
687                     }
689                     $submission->teacher    = $USER->id;
690                     if ($updatedb) {
691                         $submission->mailed = (int)(!$mailinfo);
692                     }
694                     $submission->timemarked = time();
696                     //if it is not an update, we don't change the last modified time etc.
697                     //this will also not write into database if no submissioncomment and grade is entered.
699                     if ($updatedb){
700                         if ($newsubmission) {
701                             if (!isset($submission->submissioncomment)) {
702                                 $submission->submissioncomment = '';
703                             }
704                             $sid = $DB->insert_record('assignment_submissions', $submission);
705                             $submission->id = $sid;
706                         } else {
707                             $DB->update_record('assignment_submissions', $submission);
708                         }
710                         // triger grade event
711                         $this->update_grade($submission);
713                         //add to log only if updating
714                         add_to_log($this->course->id, 'assignment', 'update grades',
715                                    'submissions.php?id='.$this->assignment->id.'&user='.$submission->userid,
716                                    $submission->userid, $this->cm->id);
717                     }
719                 }
721                 $message = $OUTPUT->notification(get_string('changessaved'), 'notifysuccess');
723                 $this->display_submissions($message);
724                 break;
727             case 'saveandnext':
728                 ///We are in pop up. save the current one and go to the next one.
729                 //first we save the current changes
730                 if ($submission = $this->process_feedback()) {
731                     //print_heading(get_string('changessaved'));
732                     //$extra_javascript = $this->update_main_listing($submission);
733                 }
735             case 'next':
736                 /// We are currently in pop up, but we want to skip to next one without saving.
737                 ///    This turns out to be similar to a single case
738                 /// The URL used is for the next submission.
739                 $offset = required_param('offset', PARAM_INT);
740                 $nextid = required_param('nextid', PARAM_INT);
741                 $id = required_param('id', PARAM_INT);
742                 $offset = (int)$offset+1;
743                 //$this->display_submission($offset+1 , $nextid);
744                 redirect('submissions.php?id='.$id.'&userid='. $nextid . '&mode=single&offset='.$offset);
745                 break;
747             default:
748                 echo "something seriously is wrong!!";
749                 break;
750         }
751     }
753     /**
754      * Helper method updating the listing on the main script from popup using javascript
755      *
756      * @global object
757      * @global object
758      * @param $submission object The submission whose data is to be updated on the main page
759      */
760     function update_main_listing($submission) {
761         global $SESSION, $CFG, $OUTPUT;
763         $output = '';
765         $perpage = get_user_preferences('assignment_perpage', 10);
767         $quickgrade = get_user_preferences('assignment_quickgrade', 0);
769         /// Run some Javascript to try and update the parent page
770         $output .= '<script type="text/javascript">'."\n<!--\n";
771         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['submissioncomment'])) {
772             if ($quickgrade){
773                 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid.'").value="'
774                 .trim($submission->submissioncomment).'";'."\n";
775              } else {
776                 $output.= 'opener.document.getElementById("com'.$submission->userid.
777                 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment)), 15)."\";\n";
778             }
779         }
781         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['grade'])) {
782             //echo optional_param('menuindex');
783             if ($quickgrade){
784                 $output.= 'opener.document.getElementById("menumenu'.$submission->userid.
785                 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT).'";'."\n";
786             } else {
787                 $output.= 'opener.document.getElementById("g'.$submission->userid.'").innerHTML="'.
788                 $this->display_grade($submission->grade)."\";\n";
789             }
790         }
791         //need to add student's assignments in there too.
792         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemodified']) &&
793             $submission->timemodified) {
794             $output.= 'opener.document.getElementById("ts'.$submission->userid.
795                  '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid)).userdate($submission->timemodified)."\";\n";
796         }
798         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemarked']) &&
799             $submission->timemarked) {
800             $output.= 'opener.document.getElementById("tt'.$submission->userid.
801                  '").innerHTML="'.userdate($submission->timemarked)."\";\n";
802         }
804         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['status'])) {
805             $output.= 'opener.document.getElementById("up'.$submission->userid.'").className="s1";';
806             $buttontext = get_string('update');
807             $url = new moodle_url('/mod/assignment/submissions.php', array(
808                     'id' => $this->cm->id,
809                     'userid' => $submission->userid,
810                     'mode' => 'single',
811                     'offset' => (optional_param('offset', '', PARAM_INT)-1)));
812             $button = $OUTPUT->action_link($url, $buttontext, new popup_action('click', $url, 'grade'.$submission->userid, array('height' => 450, 'width' => 700)), array('ttile'=>$buttontext));
814             $output .= 'opener.document.getElementById("up'.$submission->userid.'").innerHTML="'.addslashes_js($button).'";';
815         }
817         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $submission->userid);
819         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['finalgrade'])) {
820             $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid.
821             '").innerHTML="'.$grading_info->items[0]->grades[$submission->userid]->str_grade.'";'."\n";
822         }
824         if (!empty($CFG->enableoutcomes) and empty($SESSION->flextable['mod-assignment-submissions']->collapse['outcome'])) {
826             if (!empty($grading_info->outcomes)) {
827                 foreach($grading_info->outcomes as $n=>$outcome) {
828                     if ($outcome->grades[$submission->userid]->locked) {
829                         continue;
830                     }
832                     if ($quickgrade){
833                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.
834                         '").selectedIndex="'.$outcome->grades[$submission->userid]->grade.'";'."\n";
836                     } else {
837                         $options = make_grades_menu(-$outcome->scaleid);
838                         $options[0] = get_string('nooutcome', 'grades');
839                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.'").innerHTML="'.$options[$outcome->grades[$submission->userid]->grade]."\";\n";
840                     }
842                 }
843             }
844         }
846         $output .= "\n-->\n</script>";
847         return $output;
848     }
850     /**
851      *  Return a grade in user-friendly form, whether it's a scale or not
852      *
853      * @global object
854      * @param mixed $grade
855      * @return string User-friendly representation of grade
856      */
857     function display_grade($grade) {
858         global $DB;
860         static $scalegrades = array();   // Cache scales for each assignment - they might have different scales!!
862         if ($this->assignment->grade >= 0) {    // Normal number
863             if ($grade == -1) {
864                 return '-';
865             } else {
866                 return $grade.' / '.$this->assignment->grade;
867             }
869         } else {                                // Scale
870             if (empty($scalegrades[$this->assignment->id])) {
871                 if ($scale = $DB->get_record('scale', array('id'=>-($this->assignment->grade)))) {
872                     $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
873                 } else {
874                     return '-';
875                 }
876             }
877             if (isset($scalegrades[$this->assignment->id][$grade])) {
878                 return $scalegrades[$this->assignment->id][$grade];
879             }
880             return '-';
881         }
882     }
884     /**
885      *  Display a single submission, ready for grading on a popup window
886      *
887      * This default method prints the teacher info and submissioncomment box at the top and
888      * the student info and submission at the bottom.
889      * This method also fetches the necessary data in order to be able to
890      * provide a "Next submission" button.
891      * Calls preprocess_submission() to give assignment type plug-ins a chance
892      * to process submissions before they are graded
893      * This method gets its arguments from the page parameters userid and offset
894      *
895      * @global object
896      * @global object
897      * @param string $extra_javascript
898      */
899     function display_submission($offset=-1,$userid =-1) {
900         global $CFG, $DB, $PAGE, $OUTPUT;
901         require_once($CFG->libdir.'/gradelib.php');
902         require_once($CFG->libdir.'/tablelib.php');
903         if ($userid==-1) {
904             $userid = required_param('userid', PARAM_INT);
905         }
906         if ($offset==-1) {
907             $offset = required_param('offset', PARAM_INT);//offset for where to start looking for student.
908         }
910         if (!$user = $DB->get_record('user', array('id'=>$userid))) {
911             print_error('nousers');
912         }
914         if (!$submission = $this->get_submission($user->id)) {
915             $submission = $this->prepare_new_submission($userid);
916         }
917         if ($submission->timemodified > $submission->timemarked) {
918             $subtype = 'assignmentnew';
919         } else {
920             $subtype = 'assignmentold';
921         }
923         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
924         $gradingdisabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
926     /// construct SQL, using current offset to find the data of the next student
927         $course     = $this->course;
928         $assignment = $this->assignment;
929         $cm         = $this->cm;
930         $context    = get_context_instance(CONTEXT_MODULE, $cm->id);
932         /// Get all ppl that can submit assignments
934         $currentgroup = groups_get_activity_group($cm);
935         if ($users = get_enrolled_users($context, 'mod/assignment:submit', $currentgroup, 'u.id')) {
936             $users = array_keys($users);
937         }
939         // if groupmembersonly used, remove users who are not in any group
940         if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
941             if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
942                 $users = array_intersect($users, array_keys($groupingusers));
943             }
944         }
946         $nextid = 0;
948         if ($users) {
949             $userfields = user_picture::fields('u', array('lastaccess'));
950             $select = "SELECT $userfields,
951                               s.id AS submissionid, s.grade, s.submissioncomment,
952                               s.timemodified, s.timemarked,
953                               COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ";
954             $sql = 'FROM {user} u '.
955                    'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
956                                                                       AND s.assignment = '.$this->assignment->id.' '.
957                    'WHERE u.id IN ('.implode(',', $users).') ';
959             if ($sort = flexible_table::get_sort_for_table('mod-assignment-submissions')) {
960                 $sort = 'ORDER BY '.$sort.' ';
961             }
962             $auser = $DB->get_records_sql($select.$sql.$sort, null, $offset, 2);
964             if (is_array($auser) && count($auser)>1) {
965                 $nextuser = next($auser);
966             /// Calculate user status
967                 $nextuser->status = ($nextuser->timemarked > 0) && ($nextuser->timemarked >= $nextuser->timemodified);
968                 $nextid = $nextuser->id;
969             }
970         }
972         if ($submission->teacher) {
973             $teacher = $DB->get_record('user', array('id'=>$submission->teacher));
974         } else {
975             global $USER;
976             $teacher = $USER;
977         }
979         $this->preprocess_submission($submission);
981         $mformdata = new stdclass;
982         $mformdata->context = $this->context;
983         $mformdata->maxbytes = $this->course->maxbytes;
984         $mformdata->courseid = $this->course->id;
985         $mformdata->teacher = $teacher;
986         $mformdata->assignment = $assignment;
987         $mformdata->submission = $submission;
988         $mformdata->lateness = $this->display_lateness($submission->timemodified);
989         $mformdata->auser = $auser;
990         $mformdata->user = $user;
991         $mformdata->offset = $offset;
992         $mformdata->userid = $userid;
993         $mformdata->cm = $this->cm;
994         $mformdata->grading_info = $grading_info;
995         $mformdata->enableoutcomes = $CFG->enableoutcomes;
996         $mformdata->grade = $this->assignment->grade;
997         $mformdata->gradingdisabled = $gradingdisabled;
998         $mformdata->usehtmleditor = $this->usehtmleditor;
999         $mformdata->nextid = $nextid;
1000         $mformdata->submissioncomment= $submission->submissioncomment;
1001         $mformdata->submissioncommentformat= FORMAT_HTML;
1002         $mformdata->submission_content= $this->print_user_files($user->id,true);
1004         $submitform = new mod_assignment_grading_form( null, $mformdata );
1006         if ($submitform->is_cancelled()) {
1007             redirect('submissions.php?id='.$this->cm->id);
1008         }
1010         $submitform->set_data($mformdata);
1012         $PAGE->set_title($this->course->fullname . ': ' .get_string('feedback', 'assignment').' - '.fullname($user, true));
1013         $PAGE->set_heading($this->course->fullname);
1014         $PAGE->navbar->add( get_string('submissions', 'assignment') );
1016         echo $OUTPUT->header();
1017         echo $OUTPUT->heading(get_string('feedback', 'assignment').': '.fullname($user, true));
1019         // display mform here...
1020         $submitform->display();
1022         $customfeedback = $this->custom_feedbackform($submission, true);
1023         if (!empty($customfeedback)) {
1024             echo $customfeedback;
1025         }
1027         echo $OUTPUT->footer();
1028     }
1030     /**
1031      *  Preprocess submission before grading
1032      *
1033      * Called by display_submission()
1034      * The default type does nothing here.
1035      *
1036      * @param object $submission The submission object
1037      */
1038     function preprocess_submission(&$submission) {
1039     }
1041     /**
1042      *  Display all the submissions ready for grading
1043      *
1044      * @global object
1045      * @global object
1046      * @global object
1047      * @global object
1048      * @param string $message
1049      * @return bool|void
1050      */
1051     function display_submissions($message='') {
1052         global $CFG, $DB, $USER, $DB, $OUTPUT, $PAGE;
1053         require_once($CFG->libdir.'/gradelib.php');
1055         /* first we check to see if the form has just been submitted
1056          * to request user_preference updates
1057          */
1058         if (isset($_POST['updatepref'])){
1059             $perpage = optional_param('perpage', 10, PARAM_INT);
1060             $perpage = ($perpage <= 0) ? 10 : $perpage ;
1061             set_user_preference('assignment_perpage', $perpage);
1062             set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
1063         }
1065         /* next we get perpage and quickgrade (allow quick grade) params
1066          * from database
1067          */
1068         $perpage    = get_user_preferences('assignment_perpage', 10);
1070         $quickgrade = get_user_preferences('assignment_quickgrade', 0);
1072         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);
1074         if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
1075             $uses_outcomes = true;
1076         } else {
1077             $uses_outcomes = false;
1078         }
1080         $page    = optional_param('page', 0, PARAM_INT);
1081         $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
1083     /// Some shortcuts to make the code read better
1085         $course     = $this->course;
1086         $assignment = $this->assignment;
1087         $cm         = $this->cm;
1089         $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
1090         add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->cm->id, $this->assignment->id, $this->cm->id);
1092         $PAGE->set_title(format_string($this->assignment->name,true));
1093         $PAGE->set_heading($this->course->fullname);
1094         echo $OUTPUT->header();
1096         /// Print quickgrade form around the table
1097         if ($quickgrade) {
1098             echo '<form action="submissions.php" id="fastg" method="post">';
1099             echo '<div>';
1100             echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
1101             echo '<input type="hidden" name="mode" value="fastgrade" />';
1102             echo '<input type="hidden" name="page" value="'.$page.'" />';
1103             echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1104             echo '</div>';
1105         }
1107         $course_context = get_context_instance(CONTEXT_COURSE, $course->id);
1108         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
1109             echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">'
1110                 . get_string('seeallcoursegrades', 'grades') . '</a></div>';
1111         }
1113         if (!empty($message)) {
1114             echo $message;   // display messages here if any
1115         }
1117         $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1119     /// Check to see if groups are being used in this assignment
1121         /// find out current groups mode
1122         $groupmode = groups_get_activity_groupmode($cm);
1123         $currentgroup = groups_get_activity_group($cm, true);
1124         groups_print_activity_menu($cm, $CFG->wwwroot . '/mod/assignment/submissions.php?id=' . $this->cm->id);
1126         /// Get all ppl that are allowed to submit assignments
1127         if ($users = get_enrolled_users($context, 'mod/assignment:submit', $currentgroup, 'u.id')) {
1128             $users = array_keys($users);
1129         }
1131         // if groupmembersonly used, remove users who are not in any group
1132         if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
1133             if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1134                 $users = array_intersect($users, array_keys($groupingusers));
1135             }
1136         }
1138         $tablecolumns = array('picture', 'fullname', 'grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade');
1139         if ($uses_outcomes) {
1140             $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
1141         }
1143         $tableheaders = array('',
1144                               get_string('fullname'),
1145                               get_string('grade'),
1146                               get_string('comment', 'assignment'),
1147                               get_string('lastmodified').' ('.get_string('submission', 'assignment').')',
1148                               get_string('lastmodified').' ('.get_string('grade').')',
1149                               get_string('status'),
1150                               get_string('finalgrade', 'grades'));
1151         if ($uses_outcomes) {
1152             $tableheaders[] = get_string('outcome', 'grades');
1153         }
1155         require_once($CFG->libdir.'/tablelib.php');
1156         $table = new flexible_table('mod-assignment-submissions');
1158         $table->define_columns($tablecolumns);
1159         $table->define_headers($tableheaders);
1160         $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;currentgroup='.$currentgroup);
1162         $table->sortable(true, 'lastname');//sorted by lastname by default
1163         $table->collapsible(true);
1164         $table->initialbars(true);
1166         $table->column_suppress('picture');
1167         $table->column_suppress('fullname');
1169         $table->column_class('picture', 'picture');
1170         $table->column_class('fullname', 'fullname');
1171         $table->column_class('grade', 'grade');
1172         $table->column_class('submissioncomment', 'comment');
1173         $table->column_class('timemodified', 'timemodified');
1174         $table->column_class('timemarked', 'timemarked');
1175         $table->column_class('status', 'status');
1176         $table->column_class('finalgrade', 'finalgrade');
1177         if ($uses_outcomes) {
1178             $table->column_class('outcome', 'outcome');
1179         }
1181         $table->set_attribute('cellspacing', '0');
1182         $table->set_attribute('id', 'attempts');
1183         $table->set_attribute('class', 'submissions');
1184         $table->set_attribute('width', '100%');
1185         //$table->set_attribute('align', 'center');
1187         $table->no_sorting('finalgrade');
1188         $table->no_sorting('outcome');
1190         // Start working -- this is necessary as soon as the niceties are over
1191         $table->setup();
1193         if (empty($users)) {
1194             echo $OUTPUT->heading(get_string('nosubmitusers','assignment'));
1195             echo '</div>';
1196             return true;
1197         }
1198         if ($this->assignment->assignmenttype=='upload' || $this->assignment->assignmenttype=='online' || $this->assignment->assignmenttype=='uploadsingle') { //TODO: this is an ugly hack, where is the plugin spirit? (skodak)
1199             echo '<div style="text-align:right"><a href="submissions.php?id='.$this->cm->id.'&amp;download=zip">'.get_string('downloadall', 'assignment').'</a></div>';
1200         }
1201     /// Construct the SQL
1203         if ($where = $table->get_sql_where()) {
1204             $where .= ' AND ';
1205         }
1207         if ($sort = $table->get_sql_sort()) {
1208             $sort = ' ORDER BY '.$sort;
1209         }
1211         $ufields = user_picture::fields('u');
1212         $select = "SELECT $ufields,
1213                           s.id AS submissionid, s.grade, s.submissioncomment,
1214                           s.timemodified, s.timemarked,
1215                           COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ";
1216         $sql = 'FROM {user} u '.
1217                'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1218                                                                   AND s.assignment = '.$this->assignment->id.' '.
1219                'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1221         $table->pagesize($perpage, count($users));
1223         ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1224         $offset = $page * $perpage;
1226         $strupdate = get_string('update');
1227         $strgrade  = get_string('grade');
1228         $grademenu = make_grades_menu($this->assignment->grade);
1230         if (($ausers = $DB->get_records_sql($select.$sql.$sort, null, $table->get_page_start(), $table->get_page_size())) !== false) {
1231             $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
1232             foreach ($ausers as $auser) {
1233                 $final_grade = $grading_info->items[0]->grades[$auser->id];
1234                 $grademax = $grading_info->items[0]->grademax;
1235                 $final_grade->formatted_grade = round($final_grade->grade,2) .' / ' . round($grademax,2);
1236                 $locked_overridden = 'locked';
1237                 if ($final_grade->overridden) {
1238                     $locked_overridden = 'overridden';
1239                 }
1241             /// Calculate user status
1242                 $auser->status = ($auser->timemarked > 0) && ($auser->timemarked >= $auser->timemodified);
1243                 $picture = $OUTPUT->user_picture($auser);
1245                 if (empty($auser->submissionid)) {
1246                     $auser->grade = -1; //no submission yet
1247                 }
1249                 if (!empty($auser->submissionid)) {
1250                 ///Prints student answer and student modified date
1251                 ///attach file or print link to student answer, depending on the type of the assignment.
1252                 ///Refer to print_student_answer in inherited classes.
1253                     if ($auser->timemodified > 0) {
1254                         $studentmodified = '<div id="ts'.$auser->id.'">'.$this->print_student_answer($auser->id)
1255                                          . userdate($auser->timemodified).'</div>';
1256                     } else {
1257                         $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1258                     }
1259                 ///Print grade, dropdown or text
1260                     if ($auser->timemarked > 0) {
1261                         $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
1263                         if ($final_grade->locked or $final_grade->overridden) {
1264                             $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1265                         } else if ($quickgrade) {
1266                             $attributes = array();
1267                             $attributes['tabindex'] = $tabindex++;
1268                             $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1269                             $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
1270                         } else {
1271                             $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1272                         }
1274                     } else {
1275                         $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1276                         if ($final_grade->locked or $final_grade->overridden) {
1277                             $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1278                         } else if ($quickgrade) {
1279                             $attributes = array();
1280                             $attributes['tabindex'] = $tabindex++;
1281                             $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1282                             $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1283                         } else {
1284                             $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1285                         }
1286                     }
1287                 ///Print Comment
1288                     if ($final_grade->locked or $final_grade->overridden) {
1289                         $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';
1291                     } else if ($quickgrade) {
1292                         $comment = '<div id="com'.$auser->id.'">'
1293                                  . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1294                                  . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1295                     } else {
1296                         $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
1297                     }
1298                 } else {
1299                     $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1300                     $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1301                     $status          = '<div id="st'.$auser->id.'">&nbsp;</div>';
1303                     if ($final_grade->locked or $final_grade->overridden) {
1304                         $grade = '<div id="g'.$auser->id.'">'.$final_grade->formatted_grade . '</div>';
1305                     } else if ($quickgrade) {   // allow editing
1306                         $attributes = array();
1307                         $attributes['tabindex'] = $tabindex++;
1308                         $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1309                         $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1310                     } else {
1311                         $grade = '<div id="g'.$auser->id.'">-</div>';
1312                     }
1314                     if ($final_grade->locked or $final_grade->overridden) {
1315                         $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
1316                     } else if ($quickgrade) {
1317                         $comment = '<div id="com'.$auser->id.'">'
1318                                  . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1319                                  . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1320                     } else {
1321                         $comment = '<div id="com'.$auser->id.'">&nbsp;</div>';
1322                     }
1323                 }
1325                 if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
1326                     $auser->status = 0;
1327                 } else {
1328                     $auser->status = 1;
1329                 }
1331                 $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
1333                 ///No more buttons, we use popups ;-).
1334                 $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1335                            . '&userid='.$auser->id.'&mode=single'.'&offset='.$offset++;
1337                 $button = $OUTPUT->action_link($popup_url, $buttontext);
1339                 $status  = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
1341                 $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';
1343                 $outcomes = '';
1345                 if ($uses_outcomes) {
1347                     foreach($grading_info->outcomes as $n=>$outcome) {
1348                         $outcomes .= '<div class="outcome"><label>'.$outcome->name.'</label>';
1349                         $options = make_grades_menu(-$outcome->scaleid);
1351                         if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
1352                             $options[0] = get_string('nooutcome', 'grades');
1353                             $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
1354                         } else {
1355                             $attributes = array();
1356                             $attributes['tabindex'] = $tabindex++;
1357                             $attributes['id'] = 'outcome_'.$n.'_'.$auser->id;
1358                             $outcomes .= ' '.html_writer::select($options, 'outcome_'.$n.'['.$auser->id.']', $outcome->grades[$auser->id]->grade, array(0=>get_string('nooutcome', 'grades')), $attributes);
1359                         }
1360                         $outcomes .= '</div>';
1361                     }
1362                 }
1364                 $userlink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $auser->id . '&amp;course=' . $course->id . '">' . fullname($auser) . '</a>';
1365                 $row = array($picture, $userlink, $grade, $comment, $studentmodified, $teachermodified, $status, $finalgrade);
1366                 if ($uses_outcomes) {
1367                     $row[] = $outcomes;
1368                 }
1370                 $table->add_data($row);
1371             }
1372         }
1374         $table->print_html();  /// Print the whole table
1376         if ($quickgrade){
1377             $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? 'checked="checked"' : '';
1378             echo '<div class="fgcontrols">';
1379             echo '<div class="emailnotification">';
1380             echo '<label for="mailinfo">'.get_string('enableemailnotification','assignment').'</label>';
1381             echo '<input type="hidden" name="mailinfo" value="0" />';
1382             echo '<input type="checkbox" id="mailinfo" name="mailinfo" value="1" '.$lastmailinfo.' />';
1383             echo $OUTPUT->help_icon('enableemailnotification', 'assignment');
1384             echo '</div>';
1385             echo '</div>';
1386             echo '<div class="fastgbutton"><input type="submit" name="fastg" value="'.get_string('saveallfeedback', 'assignment').'" /></div>';
1387             echo '</form>';
1388         }
1389         /// End of fast grading form
1391         /// Mini form for setting user preference
1392         echo '<div class="qgprefs">';
1393         echo '<form id="options" action="submissions.php?id='.$this->cm->id.'" method="post"><div>';
1394         echo '<input type="hidden" name="updatepref" value="1" />';
1395         echo '<table id="optiontable">';
1396         echo '<tr><td>';
1397         echo '<label for="perpage">'.get_string('pagesize','assignment').'</label>';
1398         echo '</td>';
1399         echo '<td>';
1400         echo '<input type="text" id="perpage" name="perpage" size="1" value="'.$perpage.'" />';
1401         echo '</td></tr>';
1402         echo '<tr><td>';
1403         echo '<label for="quickgrade">'.get_string('quickgrade','assignment').'</label>';
1404         echo '</td>';
1405         echo '<td>';
1406         $checked = $quickgrade ? 'checked="checked"' : '';
1407         echo '<input type="checkbox" id="quickgrade" name="quickgrade" value="1" '.$checked.' />';
1408         echo '<p>'.$OUTPUT->help_icon('quickgrade', 'assignment').'</p>';
1409         echo '</td>';
1410         echo '</tr>';
1411         echo '<tr><td colspan="2">';
1412         echo '<input type="submit" value="'.get_string('savepreferences').'" />';
1413         echo '</td></tr></table>';
1414         echo '</div></form></div>';
1415         ///End of mini form
1416         echo $OUTPUT->footer();
1417     }
1419     /**
1420      *  Process teacher feedback submission
1421      *
1422      * This is called by submissions() when a grading even has taken place.
1423      * It gets its data from the submitted form.
1424      *
1425      * @global object
1426      * @global object
1427      * @global object
1428      * @return object|bool The updated submission object or false
1429      */
1430     function process_feedback() {
1431         global $CFG, $USER, $DB;
1432         require_once($CFG->libdir.'/gradelib.php');
1434         if (!$feedback = data_submitted() or !confirm_sesskey()) {      // No incoming data?
1435             return false;
1436         }
1438         ///For save and next, we need to know the userid to save, and the userid to go
1439         ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1440         ///as the userid to store
1441         if ((int)$feedback->saveuserid !== -1){
1442             $feedback->userid = $feedback->saveuserid;
1443         }
1445         if (!empty($feedback->cancel)) {          // User hit cancel button
1446             return false;
1447         }
1449         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);
1451         // store outcomes if needed
1452         $this->process_outcomes($feedback->userid);
1454         $submission = $this->get_submission($feedback->userid, true);  // Get or make one
1456         if (!($grading_info->items[0]->grades[$feedback->userid]->locked ||
1457             $grading_info->items[0]->grades[$feedback->userid]->overridden) ) {
1459             $submission->grade      = $feedback->xgrade;
1460             $submission->submissioncomment    = $feedback->submissioncomment_editor['text'];
1461             $submission->format     = $feedback->format;
1462             $submission->teacher    = $USER->id;
1463             $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1464             if (!$mailinfo) {
1465                 $submission->mailed = 1;       // treat as already mailed
1466             } else {
1467                 $submission->mailed = 0;       // Make sure mail goes out (again, even)
1468             }
1469             $submission->timemarked = time();
1471             unset($submission->data1);  // Don't need to update this.
1472             unset($submission->data2);  // Don't need to update this.
1474             if (empty($submission->timemodified)) {   // eg for offline assignments
1475                 // $submission->timemodified = time();
1476             }
1478             $DB->update_record('assignment_submissions', $submission);
1480             // triger grade event
1481             $this->update_grade($submission);
1483             add_to_log($this->course->id, 'assignment', 'update grades',
1484                        'submissions.php?id='.$this->assignment->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
1485         }
1487         return $submission;
1489     }
1491     function process_outcomes($userid) {
1492         global $CFG, $USER;
1494         if (empty($CFG->enableoutcomes)) {
1495             return;
1496         }
1498         require_once($CFG->libdir.'/gradelib.php');
1500         if (!$formdata = data_submitted() or !confirm_sesskey()) {
1501             return;
1502         }
1504         $data = array();
1505         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
1507         if (!empty($grading_info->outcomes)) {
1508             foreach($grading_info->outcomes as $n=>$old) {
1509                 $name = 'outcome_'.$n;
1510                 if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
1511                     $data[$n] = $formdata->{$name}[$userid];
1512                 }
1513             }
1514         }
1515         if (count($data) > 0) {
1516             grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1517         }
1519     }
1521     /**
1522      * Load the submission object for a particular user
1523      *
1524      * @global object
1525      * @global object
1526      * @param $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1527      * @param $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1528      * @param bool $teachermodified student submission set if false
1529      * @return object The submission
1530      */
1531     function get_submission($userid=0, $createnew=false, $teachermodified=false) {
1532         global $USER, $DB;
1534         if (empty($userid)) {
1535             $userid = $USER->id;
1536         }
1538         $submission = $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1540         if ($submission || !$createnew) {
1541             return $submission;
1542         }
1543         $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
1544         $DB->insert_record("assignment_submissions", $newsubmission);
1546         return $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1547     }
1549     /**
1550      * Instantiates a new submission object for a given user
1551      *
1552      * Sets the assignment, userid and times, everything else is set to default values.
1553      *
1554      * @param int $userid The userid for which we want a submission object
1555      * @param bool $teachermodified student submission set if false
1556      * @return object The submission
1557      */
1558     function prepare_new_submission($userid, $teachermodified=false) {
1559         $submission = new Object;
1560         $submission->assignment   = $this->assignment->id;
1561         $submission->userid       = $userid;
1562         $submission->timecreated = time();
1563         // teachers should not be modifying modified date, except offline assignments
1564         if ($teachermodified) {
1565             $submission->timemodified = 0;
1566         } else {
1567             $submission->timemodified = $submission->timecreated;
1568         }
1569         $submission->numfiles     = 0;
1570         $submission->data1        = '';
1571         $submission->data2        = '';
1572         $submission->grade        = -1;
1573         $submission->submissioncomment      = '';
1574         $submission->format       = 0;
1575         $submission->teacher      = 0;
1576         $submission->timemarked   = 0;
1577         $submission->mailed       = 0;
1578         return $submission;
1579     }
1581     /**
1582      * Return all assignment submissions by ENROLLED students (even empty)
1583      *
1584      * @param string $sort optional field names for the ORDER BY in the sql query
1585      * @param string $dir optional specifying the sort direction, defaults to DESC
1586      * @return array The submission objects indexed by id
1587      */
1588     function get_submissions($sort='', $dir='DESC') {
1589         return assignment_get_all_submissions($this->assignment, $sort, $dir);
1590     }
1592     /**
1593      * Counts all real assignment submissions by ENROLLED students (not empty ones)
1594      *
1595      * @param int $groupid optional If nonzero then count is restricted to this group
1596      * @return int The number of submissions
1597      */
1598     function count_real_submissions($groupid=0) {
1599         return assignment_count_real_submissions($this->cm, $groupid);
1600     }
1602     /**
1603      * Alerts teachers by email of new or changed assignments that need grading
1604      *
1605      * First checks whether the option to email teachers is set for this assignment.
1606      * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1607      * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1608      *
1609      * @global object
1610      * @global object
1611      * @param $submission object The submission that has changed
1612      * @return void
1613      */
1614     function email_teachers($submission) {
1615         global $CFG, $DB;
1617         if (empty($this->assignment->emailteachers)) {          // No need to do anything
1618             return;
1619         }
1621         $user = $DB->get_record('user', array('id'=>$submission->userid));
1623         if ($teachers = $this->get_graders($user)) {
1625             $strassignments = get_string('modulenameplural', 'assignment');
1626             $strassignment  = get_string('modulename', 'assignment');
1627             $strsubmitted  = get_string('submitted', 'assignment');
1629             foreach ($teachers as $teacher) {
1630                 $info = new object();
1631                 $info->username = fullname($user, true);
1632                 $info->assignment = format_string($this->assignment->name,true);
1633                 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
1635                 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1636                 $posttext = $this->email_teachers_text($info);
1637                 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
1639                 $eventdata = new object();
1640                 $eventdata->modulename       = 'assignment';
1641                 $eventdata->userfrom         = $user;
1642                 $eventdata->userto           = $teacher;
1643                 $eventdata->subject          = $postsubject;
1644                 $eventdata->fullmessage      = $posttext;
1645                 $eventdata->fullmessageformat = FORMAT_PLAIN;
1646                 $eventdata->fullmessagehtml  = $posthtml;
1647                 $eventdata->smallmessage     = '';
1648                 message_send($eventdata);
1649             }
1650         }
1651     }
1653     /**
1654      * @param string $filearea
1655      * @param array $args
1656      * @return bool
1657      */
1658     function send_file($filearea, $args) {
1659         debugging('plugin does not implement file sending', DEBUG_DEVELOPER);
1660         return false;
1661     }
1663     /**
1664      * Returns a list of teachers that should be grading given submission
1665      *
1666      * @param object $user
1667      * @return array
1668      */
1669     function get_graders($user) {
1670         //potential graders
1671         $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false);
1673         $graders = array();
1674         if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) {   // Separate groups are being used
1675             if ($groups = groups_get_all_groups($this->course->id, $user->id)) {  // Try to find all groups
1676                 foreach ($groups as $group) {
1677                     foreach ($potgraders as $t) {
1678                         if ($t->id == $user->id) {
1679                             continue; // do not send self
1680                         }
1681                         if (groups_is_member($group->id, $t->id)) {
1682                             $graders[$t->id] = $t;
1683                         }
1684                     }
1685                 }
1686             } else {
1687                 // user not in group, try to find graders without group
1688                 foreach ($potgraders as $t) {
1689                     if ($t->id == $user->id) {
1690                         continue; // do not send self
1691                     }
1692                     if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
1693                         $graders[$t->id] = $t;
1694                     }
1695                 }
1696             }
1697         } else {
1698             foreach ($potgraders as $t) {
1699                 if ($t->id == $user->id) {
1700                     continue; // do not send self
1701                 }
1702                 $graders[$t->id] = $t;
1703             }
1704         }
1705         return $graders;
1706     }
1708     /**
1709      * Creates the text content for emails to teachers
1710      *
1711      * @param $info object The info used by the 'emailteachermail' language string
1712      * @return string
1713      */
1714     function email_teachers_text($info) {
1715         $posttext  = format_string($this->course->shortname).' -> '.$this->strassignments.' -> '.
1716                      format_string($this->assignment->name)."\n";
1717         $posttext .= '---------------------------------------------------------------------'."\n";
1718         $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
1719         $posttext .= "\n---------------------------------------------------------------------\n";
1720         return $posttext;
1721     }
1723      /**
1724      * Creates the html content for emails to teachers
1725      *
1726      * @param $info object The info used by the 'emailteachermailhtml' language string
1727      * @return string
1728      */
1729     function email_teachers_html($info) {
1730         global $CFG;
1731         $posthtml  = '<p><font face="sans-serif">'.
1732                      '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname).'</a> ->'.
1733                      '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
1734                      '<a href="'.$CFG->wwwroot.'/mod/assignment/view.php?id='.$this->cm->id.'">'.format_string($this->assignment->name).'</a></font></p>';
1735         $posthtml .= '<hr /><font face="sans-serif">';
1736         $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
1737         $posthtml .= '</font><hr />';
1738         return $posthtml;
1739     }
1741     /**
1742      * Produces a list of links to the files uploaded by a user
1743      *
1744      * @param $userid int optional id of the user. If 0 then $USER->id is used.
1745      * @param $return boolean optional defaults to false. If true the list is returned rather than printed
1746      * @return string optional
1747      */
1748     function print_user_files($userid=0, $return=false) {
1749         global $CFG, $USER, $OUTPUT;
1751         if (!$userid) {
1752             if (!isloggedin()) {
1753                 return '';
1754             }
1755             $userid = $USER->id;
1756         }
1758         $output = '';
1760         $fs = get_file_storage();
1762         $found = false;
1764         $submission = $this->get_submission($userid);
1766         if (($submission) && $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false)) {
1767             require_once($CFG->libdir.'/portfoliolib.php');
1768             require_once($CFG->dirroot . '/mod/assignment/locallib.php');
1769             $button = new portfolio_add_button();
1770             foreach ($files as $file) {
1771                 $filename = $file->get_filename();
1772                 $found = true;
1773                 $mimetype = $file->get_mimetype();
1774                 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/mod_assignment/submission/'.$submission->id.'/'.$filename);
1775                 $output .= '<a href="'.$path.'" ><img src="'.$OUTPUT->pix_url(file_mimetype_icon($mimetype)).'" class="icon" alt="'.$mimetype.'" />'.s($filename).'</a>';
1776                 if ($this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1777                     $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id, 'fileid' => $file->get_id()), '/mod/assignment/locallib.php');
1778                     $button->set_format_by_file($file);
1779                     $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
1780                 }
1781             }
1782             if (count($files) > 1  && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1783                 $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id), '/mod/assignment/locallib.php');
1784                 $output .= '<br />'  . $button->to_html();
1785             }
1786         }
1788         $output = '<div class="files">'.$output.'</div>';
1790         if ($return) {
1791             return $output;
1792         }
1793         echo $output;
1794     }
1796     /**
1797      * Count the files uploaded by a given user
1798      *
1799      * @param $userid int The user id
1800      * @return int
1801      */
1802     function count_user_files($userid) {
1803         $fs = get_file_storage();
1804         $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $userid, "id", false);
1805         return count($files);
1806     }
1808     /**
1809      * Returns true if the student is allowed to submit
1810      *
1811      * Checks that the assignment has started and, if the option to prevent late
1812      * submissions is set, also checks that the assignment has not yet closed.
1813      * @return boolean
1814      */
1815     function isopen() {
1816         $time = time();
1817         if ($this->assignment->preventlate && $this->assignment->timedue) {
1818             return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
1819         } else {
1820             return ($this->assignment->timeavailable <= $time);
1821         }
1822     }
1825     /**
1826      * Return true if is set description is hidden till available date
1827      *
1828      * This is needed by calendar so that hidden descriptions do not
1829      * come up in upcoming events.
1830      *
1831      * Check that description is hidden till available date
1832      * By default return false
1833      * Assignments types should implement this method if needed
1834      * @return boolen
1835      */
1836     function description_is_hidden() {
1837         return false;
1838     }
1840     /**
1841      * Return an outline of the user's interaction with the assignment
1842      *
1843      * The default method prints the grade and timemodified
1844      * @param $grade object
1845      * @return object with properties ->info and ->time
1846      */
1847     function user_outline($grade) {
1849         $result = new object();
1850         $result->info = get_string('grade').': '.$grade->str_long_grade;
1851         $result->time = $grade->dategraded;
1852         return $result;
1853     }
1855     /**
1856      * Print complete information about the user's interaction with the assignment
1857      *
1858      * @param $user object
1859      */
1860     function user_complete($user, $grade=null) {
1861         global $OUTPUT;
1862         if ($grade) {
1863             echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
1864             if ($grade->str_feedback) {
1865                 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
1866             }
1867         }
1869         if ($submission = $this->get_submission($user->id)) {
1871             $fs = get_file_storage();
1873             if ($files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false)) {
1874                 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
1875                 foreach ($files as $file) {
1876                     $countfiles .= "; ".$file->get_filename();
1877                 }
1878             }
1880             echo $OUTPUT->box_start();
1881             echo get_string("lastmodified").": ";
1882             echo userdate($submission->timemodified);
1883             echo $this->display_lateness($submission->timemodified);
1885             $this->print_user_files($user->id);
1887             echo '<br />';
1889             $this->view_feedback($submission);
1891             echo $OUTPUT->box_end();
1893         } else {
1894             print_string("notsubmittedyet", "assignment");
1895         }
1896     }
1898     /**
1899      * Return a string indicating how late a submission is
1900      *
1901      * @param $timesubmitted int
1902      * @return string
1903      */
1904     function display_lateness($timesubmitted) {
1905         return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
1906     }
1908     /**
1909      * Empty method stub for all delete actions.
1910      */
1911     function delete() {
1912         //nothing by default
1913         redirect('view.php?id='.$this->cm->id);
1914     }
1916     /**
1917      * Empty custom feedback grading form.
1918      */
1919     function custom_feedbackform($submission, $return=false) {
1920         //nothing by default
1921         return '';
1922     }
1924     /**
1925      * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
1926      * for the course (see resource).
1927      *
1928      * Given a course_module object, this function returns any "extra" information that may be needed
1929      * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
1930      *
1931      * @param $coursemodule object The coursemodule object (record).
1932      * @return object An object on information that the coures will know about (most noticeably, an icon).
1933      *
1934      */
1935     function get_coursemodule_info($coursemodule) {
1936         return false;
1937     }
1939     /**
1940      * Plugin cron method - do not use $this here, create new assignment instances if needed.
1941      * @return void
1942      */
1943     function cron() {
1944         //no plugin cron by default - override if needed
1945     }
1947     /**
1948      * Reset all submissions
1949      */
1950     function reset_userdata($data) {
1951         global $CFG, $DB;
1953         if (!$DB->count_records('assignment', array('course'=>$data->courseid, 'assignmenttype'=>$this->type))) {
1954             return array(); // no assignments of this type present
1955         }
1957         $componentstr = get_string('modulenameplural', 'assignment');
1958         $status = array();
1960         $typestr = get_string('type'.$this->type, 'assignment');
1961         // ugly hack to support pluggable assignment type titles...
1962         if($typestr === '[[type'.$this->type.']]'){
1963             $typestr = get_string('type'.$this->type, 'assignment_'.$this->type);
1964         }
1966         if (!empty($data->reset_assignment_submissions)) {
1967             $assignmentssql = "SELECT a.id
1968                                  FROM {assignment} a
1969                                 WHERE a.course=? AND a.assignmenttype=?";
1970             $params = array($data->courseid, $this->type);
1972             // now get rid of all submissions and responses
1973             $fs = get_file_storage();
1974             if ($assignments = $DB->get_records_sql($assignmentssql, $params)) {
1975                 foreach ($assignments as $assignmentid=>$unused) {
1976                     if (!$cm = get_coursemodule_from_instance('assignment', $assignmentid)) {
1977                         continue;
1978                     }
1979                     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1980                     $fs->delete_area_files($context->id, 'mod_assignment', 'submission');
1981                     $fs->delete_area_files($context->id, 'mod_assignment', 'response');
1982                 }
1983             }
1985             $DB->delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)", $params);
1987             $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
1989             if (empty($data->reset_gradebook_grades)) {
1990                 // remove all grades from gradebook
1991                 assignment_reset_gradebook($data->courseid, $this->type);
1992             }
1993         }
1995         /// updating dates - shift may be negative too
1996         if ($data->timeshift) {
1997             shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
1998             $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
1999         }
2001         return $status;
2002     }
2005     function portfolio_exportable() {
2006         return false;
2007     }
2009     /**
2010      * base implementation for backing up subtype specific information
2011      * for one single module
2012      *
2013      * @param filehandle $bf file handle for xml file to write to
2014      * @param mixed $preferences the complete backup preference object
2015      *
2016      * @return boolean
2017      *
2018      * @static
2019      */
2020     static function backup_one_mod($bf, $preferences, $assignment) {
2021         return true;
2022     }
2024     /**
2025      * base implementation for backing up subtype specific information
2026      * for one single submission
2027      *
2028      * @param filehandle $bf file handle for xml file to write to
2029      * @param mixed $preferences the complete backup preference object
2030      * @param object $submission the assignment submission db record
2031      *
2032      * @return boolean
2033      *
2034      * @static
2035      */
2036     static function backup_one_submission($bf, $preferences, $assignment, $submission) {
2037         return true;
2038     }
2040     /**
2041      * base implementation for restoring subtype specific information
2042      * for one single module
2043      *
2044      * @param array  $info the array representing the xml
2045      * @param object $restore the restore preferences
2046      *
2047      * @return boolean
2048      *
2049      * @static
2050      */
2051     static function restore_one_mod($info, $restore, $assignment) {
2052         return true;
2053     }
2055     /**
2056      * base implementation for restoring subtype specific information
2057      * for one single submission
2058      *
2059      * @param object $submission the newly created submission
2060      * @param array  $info the array representing the xml
2061      * @param object $restore the restore preferences
2062      *
2063      * @return boolean
2064      *
2065      * @static
2066      */
2067     static function restore_one_submission($info, $restore, $assignment, $submission) {
2068         return true;
2069     }
2071 } ////// End of the assignment_base class
2074 class mod_assignment_grading_form extends moodleform { 
2076     function definition() {
2077         global $OUTPUT;
2078         $mform =& $this->_form;
2080         $formattr = $mform->getAttributes();
2081         $formattr['id'] = 'submitform';
2082         $mform->setAttributes($formattr);
2083         // hidden params
2084         $mform->addElement('hidden', 'offset', ($this->_customdata->offset+1));
2085         $mform->setType('offset', PARAM_INT);
2086         $mform->addElement('hidden', 'userid', $this->_customdata->userid);
2087         $mform->setType('userid', PARAM_INT);
2088         $mform->addElement('hidden', 'nextid', $this->_customdata->nextid);
2089         $mform->setType('nextid', PARAM_INT);
2090         $mform->addElement('hidden', 'id', $this->_customdata->cm->id);
2091         $mform->setType('id', PARAM_INT);
2092         $mform->addElement('hidden', 'sesskey', sesskey());
2093         $mform->setType('sesskey', PARAM_ALPHANUM);
2094         $mform->addElement('hidden', 'mode', 'grade');
2095         $mform->setType('mode', PARAM_INT);
2096         $mform->addElement('hidden', 'menuindex', "0");
2097         $mform->setType('menuindex', PARAM_INT);
2098         $mform->addElement('hidden', 'saveuserid', "-1");
2099         $mform->setType('saveuserid', PARAM_INT);
2101         $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->user),
2102                                                 fullname($this->_customdata->user, true) . '<br/>' .
2103                                                 userdate($this->_customdata->submission->timemodified) .
2104                                                 $this->_customdata->lateness );
2106         $this->add_grades_section();
2108         $this->add_feedback_section();
2110         if ($this->_customdata->submission->timemarked) {
2111             $mform->addElement('header', 'Last Grade', get_string('lastgrade', 'assignment'));
2112             $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->teacher) ,
2113                                                     fullname($this->_customdata->teacher,true).
2114                                                     '<br/>'.
2115                                                     userdate($this->_customdata->submission->timemarked));
2116         }
2117         // buttons
2118         $this->add_action_buttons();
2120         $this->add_submission_content();
2121     }
2123     function add_grades_section() {
2124         global $CFG;
2125         $mform =& $this->_form;
2126         $attributes = array();
2127         if ($this->_customdata->gradingdisabled) {
2128             $attributes['disabled'] ='disabled';
2129         }
2131         $grademenu = make_grades_menu($this->_customdata->assignment->grade);
2132         $grademenu['-1'] = get_string('nograde');
2134         $mform->addElement('header', 'Grades', get_string('grades', 'grades'));
2135         $mform->addElement('select', 'xgrade', get_string('grade').':', $grademenu, $attributes);
2136         $mform->setDefault('xgrade', $this->_customdata->submission->grade ); //@fixme some bug when element called 'grade' makes it break
2137         $mform->setType('xgrade', PARAM_INT);
2139         if (!empty($this->_customdata->enableoutcomes)) {
2140             foreach($this->_customdata->grading_info->outcomes as $n=>$outcome) {
2141                 $options = make_grades_menu(-$outcome->scaleid);
2142                 if ($outcome->grades[$this->_customdata->submission->userid]->locked) {
2143                     $options[0] = get_string('nooutcome', 'grades');
2144                     echo $options[$outcome->grades[$this->_customdata->submission->userid]->grade];
2145                 } else {
2146                     $options[''] = get_string('nooutcome', 'grades');
2147                     $attributes = array('id' => 'menuoutcome_'.$n );
2148                     $mform->addElement('select', 'outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->name.':', $options, $attributes );
2149                     $mform->setType('outcome_'.$n.'['.$this->_customdata->userid.']', PARAM_INT);
2150                     $mform->setDefault('outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->grades[$this->_customdata->submission->userid]->grade );
2151                 }
2152             }
2153         }
2154         $course_context = get_context_instance(CONTEXT_MODULE , $this->_customdata->cm->id);
2155         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
2156             $grade = '<a href="'.$CFG->wwwroot.'/grade/report/grader/index.php?id='. $this->_customdata->courseid .'" >'.
2157                         $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade . '</a>';
2158         }else{
2159             $grade = $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade;
2160         }
2161         $mform->addElement('static', 'finalgrade', get_string('currentgrade', 'assignment').':' ,$grade);
2162         $mform->setType('finalgrade', PARAM_INT);
2163     }
2165     /**
2166      *
2167      * @global core_renderer $OUTPUT
2168      */
2169     function add_feedback_section() {
2170         global $OUTPUT;
2171         $mform =& $this->_form;
2172         $mform->addElement('header', 'Feed Back', get_string('feedback', 'grades'));
2174         if ($this->_customdata->gradingdisabled) {
2175             $mform->addElement('static', 'disabledfeedback', $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_feedback );
2176         } else {
2177             // visible elements
2179             $mform->addElement('editor', 'submissioncomment_editor', get_string('feedback', 'assignment').':', null, $this->get_editor_options() );
2180             $mform->setType('submissioncomment_editor', PARAM_RAW); // to be cleaned before display
2181             $mform->setDefault('submissioncomment_editor', $this->_customdata->submission->submissioncomment);
2182             //$mform->addRule('submissioncomment', get_string('required'), 'required', null, 'client');
2184             if ($this->_customdata->usehtmleditor) {
2185                 $mform->addElement('hidden', 'format', FORMAT_HTML);
2186                 $mform->setType('format', PARAM_INT);
2187             } else {
2188                 //format menu
2189                 $format_menu = format_text_menu();
2190                 $mform->addElement('select', 'format', get_string('format'), $format_menu, array('selected' => $this->_customdata->submission->format ) );
2191                 $mform->setType('format', PARAM_INT);
2192             }
2193             $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? array('checked'=>'checked') : array();
2194             $mform->addElement('hidden', 'mailinfo_h', "0");
2195             $mform->setType('mailinfo_h', PARAM_INT);
2196             $mform->addElement('checkbox', 'mailinfo',get_string('enableemailnotification','assignment').
2197                     $OUTPUT->help_icon('enableemailnotification', 'assignment') .':' );
2198             $mform->updateElementAttr('mailinfo', $lastmailinfo);
2199             $mform->setType('mailinfo', PARAM_INT);
2200         }
2201     }
2203     function add_action_buttons() {
2204         $mform =& $this->_form;
2205         $mform->addElement('header', 'Operation', get_string('operation', 'assignment'));
2206         //if there are more to be graded.
2207         if ($this->_customdata->nextid>0) {
2208             $buttonarray=array();
2209             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2210             //@todo: fix accessibility: javascript dependency not necessary
2211             $buttonarray[] = &$mform->createElement('submit', 'saveandnext', get_string('saveandnext'));
2212             $buttonarray[] = &$mform->createElement('submit', 'next', get_string('next'));
2213             $buttonarray[] = &$mform->createElement('cancel');
2214         } else {
2215             $buttonarray=array();
2216             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2217             $buttonarray[] = &$mform->createElement('cancel');
2218         }
2219         $mform->addGroup($buttonarray, 'grading_buttonar', '', array(' '), false);
2220         $mform->setType('grading_buttonar', PARAM_RAW);
2221     }
2223     function add_submission_content() {
2224         $mform =& $this->_form;
2225         $mform->addElement('header', 'Submission', get_string('submission', 'assignment'));
2226         $mform->addElement('static', '', '' , $this->_customdata->submission_content );
2227     }
2229     protected function get_editor_options() {
2230         $editoroptions = array();
2231         $editoroptions['component'] = 'mod_assignment';
2232         $editoroptions['filearea'] = 'feedback';
2233         $editoroptions['noclean'] = false;
2234         $editoroptions['maxfiles'] = 0; //TODO: no files for now, we need to first implement assignment_feedback area, integration with gradebook, files support in quickgrading, etc. (skodak)
2235         $editoroptions['maxbytes'] = $this->_customdata->maxbytes;
2236         return $editoroptions;
2237     }
2239     public function set_data($data) {
2240         $editoroptions = $this->get_editor_options();
2241         if (!isset($data->text)) {
2242             $data->text = '';
2243         }
2244         if (!isset($data->format)) {
2245             $data->textformat = FORMAT_HTML;
2246         } else {
2247             $data->textformat = $data->format;
2248         }
2250         if (!empty($this->_customdata->submission->id)) {
2251             $itemid = $this->_customdata->submission->id;
2252         } else {
2253             $itemid = null;
2254         }
2256         $data = file_prepare_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2257         return parent::set_data($data);
2258     }
2260     public function get_data() {
2261         $data = parent::get_data();
2263         if (!empty($this->_customdata->submission->id)) {
2264             $itemid = $this->_customdata->submission->id;
2265         } else {
2266             $itemid = null; //TODO: this is wrong, itemid MUST be known when saving files!! (skodak)
2267         }
2269         if ($data) {
2270             $editoroptions = $this->get_editor_options();
2271             $data = file_postupdate_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2272             $data->format = $data->textformat;
2273         }
2274         return $data;
2275     }
2278 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
2280 /**
2281  * Deletes an assignment instance
2282  *
2283  * This is done by calling the delete_instance() method of the assignment type class
2284  */
2285 function assignment_delete_instance($id){
2286     global $CFG, $DB;
2288     if (! $assignment = $DB->get_record('assignment', array('id'=>$id))) {
2289         return false;
2290     }
2292     // fall back to base class if plugin missing
2293     $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2294     if (file_exists($classfile)) {
2295         require_once($classfile);
2296         $assignmentclass = "assignment_$assignment->assignmenttype";
2298     } else {
2299         debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
2300         $assignmentclass = "assignment_base";
2301     }
2303     $ass = new $assignmentclass();
2304     return $ass->delete_instance($assignment);
2308 /**
2309  * Updates an assignment instance
2310  *
2311  * This is done by calling the update_instance() method of the assignment type class
2312  */
2313 function assignment_update_instance($assignment){
2314     global $CFG;
2316     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2318     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2319     $assignmentclass = "assignment_$assignment->assignmenttype";
2320     $ass = new $assignmentclass();
2321     return $ass->update_instance($assignment);
2325 /**
2326  * Adds an assignment instance
2327  *
2328  * This is done by calling the add_instance() method of the assignment type class
2329  */
2330 function assignment_add_instance($assignment) {
2331     global $CFG;
2333     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2335     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2336     $assignmentclass = "assignment_$assignment->assignmenttype";
2337     $ass = new $assignmentclass();
2338     return $ass->add_instance($assignment);
2342 /**
2343  * Returns an outline of a user interaction with an assignment
2344  *
2345  * This is done by calling the user_outline() method of the assignment type class
2346  */
2347 function assignment_user_outline($course, $user, $mod, $assignment) {
2348     global $CFG;
2350     require_once("$CFG->libdir/gradelib.php");
2351     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2352     $assignmentclass = "assignment_$assignment->assignmenttype";
2353     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2354     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2355     if (!empty($grades->items[0]->grades)) {
2356         return $ass->user_outline(reset($grades->items[0]->grades));
2357     } else {
2358         return null;
2359     }
2362 /**
2363  * Prints the complete info about a user's interaction with an assignment
2364  *
2365  * This is done by calling the user_complete() method of the assignment type class
2366  */
2367 function assignment_user_complete($course, $user, $mod, $assignment) {
2368     global $CFG;
2370     require_once("$CFG->libdir/gradelib.php");
2371     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2372     $assignmentclass = "assignment_$assignment->assignmenttype";
2373     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2374     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2375     if (empty($grades->items[0]->grades)) {
2376         $grade = false;
2377     } else {
2378         $grade = reset($grades->items[0]->grades);
2379     }
2380     return $ass->user_complete($user, $grade);
2383 /**
2384  * Function to be run periodically according to the moodle cron
2385  *
2386  * Finds all assignment notifications that have yet to be mailed out, and mails them
2387  */
2388 function assignment_cron () {
2389     global $CFG, $USER, $DB;
2391     /// first execute all crons in plugins
2392     if ($plugins = get_plugin_list('assignment')) {
2393         foreach ($plugins as $plugin=>$dir) {
2394             require_once("$dir/assignment.class.php");
2395             $assignmentclass = "assignment_$plugin";
2396             $ass = new $assignmentclass();
2397             $ass->cron();
2398         }
2399     }
2401     /// Notices older than 1 day will not be mailed.  This is to avoid the problem where
2402     /// cron has not been running for a long time, and then suddenly people are flooded
2403     /// with mail from the past few weeks or months
2405     $timenow   = time();
2406     $endtime   = $timenow - $CFG->maxeditingtime;
2407     $starttime = $endtime - 24 * 3600;   /// One day earlier
2409     if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2411         $realuser = clone($USER);
2413         foreach ($submissions as $key => $submission) {
2414             if (! $DB->set_field("assignment_submissions", "mailed", "1", array("id"=>$submission->id))) {
2415                 echo "Could not update the mailed field for id $submission->id.  Not mailed.\n";
2416                 unset($submissions[$key]);
2417             }
2418         }
2420         $timenow = time();
2422         foreach ($submissions as $submission) {
2424             echo "Processing assignment submission $submission->id\n";
2426             if (! $user = $DB->get_record("user", array("id"=>$submission->userid))) {
2427                 echo "Could not find user $post->userid\n";
2428                 continue;
2429             }
2431             if (! $course = $DB->get_record("course", array("id"=>$submission->course))) {
2432                 echo "Could not find course $submission->course\n";
2433                 continue;
2434             }
2436             /// Override the language and timezone of the "current" user, so that
2437             /// mail is customised for the receiver.
2438             cron_setup_user($user, $course);
2440             if (!is_enrolled(get_context_instance(CONTEXT_COURSE, $submission->course), $user->id)) {
2441                 echo fullname($user)." not an active participant in " . format_string($course->shortname) . "\n";
2442                 continue;
2443             }
2445             if (! $teacher = $DB->get_record("user", array("id"=>$submission->teacher))) {
2446                 echo "Could not find teacher $submission->teacher\n";
2447                 continue;
2448             }
2450             if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2451                 echo "Could not find course module for assignment id $submission->assignment\n";
2452                 continue;
2453             }
2455             if (! $mod->visible) {    /// Hold mail notification for hidden assignments until later
2456                 continue;
2457             }
2459             $strassignments = get_string("modulenameplural", "assignment");
2460             $strassignment  = get_string("modulename", "assignment");
2462             $assignmentinfo = new object();
2463             $assignmentinfo->teacher = fullname($teacher);
2464             $assignmentinfo->assignment = format_string($submission->name,true);
2465             $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2467             $postsubject = "$course->shortname: $strassignments: ".format_string($submission->name,true);
2468             $posttext  = "$course->shortname -> $strassignments -> ".format_string($submission->name,true)."\n";
2469             $posttext .= "---------------------------------------------------------------------\n";
2470             $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2471             $posttext .= "---------------------------------------------------------------------\n";
2473             if ($user->mailformat == 1) {  // HTML
2474                 $posthtml = "<p><font face=\"sans-serif\">".
2475                 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> ->".
2476                 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2477                 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2478                 $posthtml .= "<hr /><font face=\"sans-serif\">";
2479                 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2480                 $posthtml .= "</font><hr />";
2481             } else {
2482                 $posthtml = "";
2483             }
2485             $eventdata = new object();
2486             $eventdata->modulename       = 'assignment';
2487             $eventdata->userfrom         = $teacher;
2488             $eventdata->userto           = $user;
2489             $eventdata->subject          = $postsubject;
2490             $eventdata->fullmessage      = $posttext;
2491             $eventdata->fullmessageformat = FORMAT_PLAIN;
2492             $eventdata->fullmessagehtml  = $posthtml;
2493             $eventdata->smallmessage     = '';
2494             message_send($eventdata);
2495         }
2497         cron_setup_user();
2498     }
2500     return true;
2503 /**
2504  * Return grade for given user or all users.
2505  *
2506  * @param int $assignmentid id of assignment
2507  * @param int $userid optional user id, 0 means all users
2508  * @return array array of grades, false if none
2509  */
2510 function assignment_get_user_grades($assignment, $userid=0) {
2511     global $CFG, $DB;
2513     if ($userid) {
2514         $user = "AND u.id = :userid";
2515         $params = array('userid'=>$userid);
2516     } else {
2517         $user = "";
2518     }
2519     $params['aid'] = $assignment->id;
2521     $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2522                    s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2523               FROM {user} u, {assignment_submissions} s
2524              WHERE u.id = s.userid AND s.assignment = :aid
2525                    $user";
2527     return $DB->get_records_sql($sql, $params);
2530 /**
2531  * Update activity grades
2532  *
2533  * @param object $assignment
2534  * @param int $userid specific user only, 0 means all
2535  */
2536 function assignment_update_grades($assignment, $userid=0, $nullifnone=true) {
2537     global $CFG, $DB;
2538     require_once($CFG->libdir.'/gradelib.php');
2540     if ($assignment->grade == 0) {
2541         assignment_grade_item_update($assignment);
2543     } else if ($grades = assignment_get_user_grades($assignment, $userid)) {
2544         foreach($grades as $k=>$v) {
2545             if ($v->rawgrade == -1) {
2546                 $grades[$k]->rawgrade = null;
2547             }
2548         }
2549         assignment_grade_item_update($assignment, $grades);
2551     } else {
2552         assignment_grade_item_update($assignment);
2553     }
2556 /**
2557  * Update all grades in gradebook.
2558  */
2559 function assignment_upgrade_grades() {
2560     global $DB;
2562     $sql = "SELECT COUNT('x')
2563               FROM {assignment} a, {course_modules} cm, {modules} m
2564              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2565     $count = $DB->count_records_sql($sql);
2567     $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
2568               FROM {assignment} a, {course_modules} cm, {modules} m
2569              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2570     if ($rs = $DB->get_recordset_sql($sql)) {
2571         // too much debug output
2572         $pbar = new progress_bar('assignmentupgradegrades', 500, true);
2573         $i=0;
2574         foreach ($rs as $assignment) {
2575             $i++;
2576             upgrade_set_timeout(60*5); // set up timeout, may also abort execution
2577             assignment_update_grades($assignment);
2578             $pbar->update($i, $count, "Updating Assignment grades ($i/$count).");
2579         }
2580         $rs->close();
2581         upgrade_set_timeout(); // reset to default timeout
2582     }
2585 /**
2586  * Create grade item for given assignment
2587  *
2588  * @param object $assignment object with extra cmidnumber
2589  * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
2590  * @return int 0 if ok, error code otherwise
2591  */
2592 function assignment_grade_item_update($assignment, $grades=NULL) {
2593     global $CFG;
2594     require_once($CFG->libdir.'/gradelib.php');
2596     if (!isset($assignment->courseid)) {
2597         $assignment->courseid = $assignment->course;
2598     }
2600     $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
2602     if ($assignment->grade > 0) {
2603         $params['gradetype'] = GRADE_TYPE_VALUE;
2604         $params['grademax']  = $assignment->grade;
2605         $params['grademin']  = 0;
2607     } else if ($assignment->grade < 0) {
2608         $params['gradetype'] = GRADE_TYPE_SCALE;
2609         $params['scaleid']   = -$assignment->grade;
2611     } else {
2612         $params['gradetype'] = GRADE_TYPE_TEXT; // allow text comments only
2613     }
2615     if ($grades  === 'reset') {
2616         $params['reset'] = true;
2617         $grades = NULL;
2618     }
2620     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades, $params);
2623 /**
2624  * Delete grade item for given assignment
2625  *
2626  * @param object $assignment object
2627  * @return object assignment
2628  */
2629 function assignment_grade_item_delete($assignment) {
2630     global $CFG;
2631     require_once($CFG->libdir.'/gradelib.php');
2633     if (!isset($assignment->courseid)) {
2634         $assignment->courseid = $assignment->course;
2635     }
2637     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
2640 /**
2641  * Returns the users with data in one assignment (students and teachers)
2642  *
2643  * @param $assignmentid int
2644  * @return array of user objects
2645  */
2646 function assignment_get_participants($assignmentid) {
2647     global $CFG, $DB;
2649     //Get students
2650     $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2651                                         FROM {user} u,
2652                                              {assignment_submissions} a
2653                                        WHERE a.assignment = ? and
2654                                              u.id = a.userid", array($assignmentid));
2655     //Get teachers
2656     $teachers = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2657                                         FROM {user} u,
2658                                              {assignment_submissions} a
2659                                        WHERE a.assignment = ? and
2660                                              u.id = a.teacher", array($assignmentid));
2662     //Add teachers to students
2663     if ($teachers) {
2664         foreach ($teachers as $teacher) {
2665             $students[$teacher->id] = $teacher;
2666         }
2667     }
2668     //Return students array (it contains an array of unique users)
2669     return ($students);
2672 /**
2673  * Serves assignment submissions and other files.
2674  *
2675  * @param object $course
2676  * @param object $cm
2677  * @param object $context
2678  * @param string $filearea
2679  * @param array $args
2680  * @param bool $forcedownload
2681  * @return bool false if file not found, does not return if found - just send the file
2682  */
2683 function assignment_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) {
2684     global $CFG, $DB;
2686     if ($context->contextlevel != CONTEXT_MODULE) {
2687         return false;
2688     }
2690     require_login($course, false, $cm);
2692     if (!$assignment = $DB->get_record('assignment', array('id'=>$cm->instance))) {
2693         return false;
2694     }
2696     require_once($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
2697     $assignmentclass = 'assignment_'.$assignment->assignmenttype;
2698     $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm, $course);
2700     return $assignmentinstance->send_file($filearea, $args);
2702 /**
2703  * Checks if a scale is being used by an assignment
2704  *
2705  * This is used by the backup code to decide whether to back up a scale
2706  * @param $assignmentid int
2707  * @param $scaleid int
2708  * @return boolean True if the scale is used by the assignment
2709  */
2710 function assignment_scale_used($assignmentid, $scaleid) {
2711     global $DB;
2713     $return = false;
2715     $rec = $DB->get_record('assignment', array('id'=>$assignmentid,'grade'=>-$scaleid));
2717     if (!empty($rec) && !empty($scaleid)) {
2718         $return = true;
2719     }
2721     return $return;
2724 /**
2725  * Checks if scale is being used by any instance of assignment
2726  *
2727  * This is used to find out if scale used anywhere
2728  * @param $scaleid int
2729  * @return boolean True if the scale is used by any assignment
2730  */
2731 function assignment_scale_used_anywhere($scaleid) {
2732     global $DB;
2734     if ($scaleid and $DB->record_exists('assignment', array('grade'=>-$scaleid))) {
2735         return true;
2736     } else {
2737         return false;
2738     }
2741 /**
2742  * Make sure up-to-date events are created for all assignment instances
2743  *
2744  * This standard function will check all instances of this module
2745  * and make sure there are up-to-date events created for each of them.
2746  * If courseid = 0, then every assignment event in the site is checked, else
2747  * only assignment events belonging to the course specified are checked.
2748  * This function is used, in its new format, by restore_refresh_events()
2749  *
2750  * @param $courseid int optional If zero then all assignments for all courses are covered
2751  * @return boolean Always returns true
2752  */
2753 function assignment_refresh_events($courseid = 0) {
2754     global $DB;
2756     if ($courseid == 0) {
2757         if (! $assignments = $DB->get_records("assignment")) {
2758             return true;
2759         }
2760     } else {
2761         if (! $assignments = $DB->get_records("assignment", array("course"=>$courseid))) {
2762             return true;
2763         }
2764     }
2765     $moduleid = $DB->get_field('modules', 'id', array('name'=>'assignment'));
2767     foreach ($assignments as $assignment) {
2768         $cm = get_coursemodule_from_id('assignment', $assignment->id);
2769         $event = new object();
2770         $event->name        = $assignment->name;
2771         $event->description = format_module_intro('assignment', $assignment, $cm->id);
2772         $event->timestart   = $assignment->timedue;
2774         if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
2775             update_event($event);
2777         } else {
2778             $event->courseid    = $assignment->course;
2779             $event->groupid     = 0;
2780             $event->userid      = 0;
2781             $event->modulename  = 'assignment';
2782             $event->instance    = $assignment->id;
2783             $event->eventtype   = 'due';
2784             $event->timeduration = 0;
2785             $event->visible     = $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$assignment->id));
2786             add_event($event);
2787         }
2789     }
2790     return true;
2793 /**
2794  * Print recent activity from all assignments in a given course
2795  *
2796  * This is used by the recent activity block
2797  */
2798 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
2799     global $CFG, $USER, $DB, $OUTPUT;
2801     // do not use log table if possible, it may be huge
2803     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
2804                                                      u.firstname, u.lastname, u.email, u.picture
2805                                                 FROM {assignment_submissions} asb
2806                                                      JOIN {assignment} a      ON a.id = asb.assignment
2807                                                      JOIN {course_modules} cm ON cm.instance = a.id
2808                                                      JOIN {modules} md        ON md.id = cm.module
2809                                                      JOIN {user} u            ON u.id = asb.userid
2810                                                WHERE asb.timemodified > ? AND
2811                                                      a.course = ? AND
2812                                                      md.name = 'assignment'
2813                                             ORDER BY asb.timemodified ASC", array($timestart, $course->id))) {
2814          return false;
2815     }
2817     $modinfo =& get_fast_modinfo($course); // reference needed because we might load the groups
2818     $show    = array();
2819     $grader  = array();
2821     foreach($submissions as $submission) {
2822         if (!array_key_exists($submission->cmid, $modinfo->cms)) {
2823             continue;
2824         }
2825         $cm = $modinfo->cms[$submission->cmid];
2826         if (!$cm->uservisible) {
2827             continue;
2828         }
2829         if ($submission->userid == $USER->id) {
2830             $show[] = $submission;
2831             continue;
2832         }
2834         // the act of sumbitting of assignment may be considered private - only graders will see it if specified
2835         if (empty($CFG->assignment_showrecentsubmissions)) {
2836             if (!array_key_exists($cm->id, $grader)) {
2837                 $grader[$cm->id] = has_capability('moodle/grade:viewall', get_context_instance(CONTEXT_MODULE, $cm->id));
2838             }
2839             if (!$grader[$cm->id]) {
2840                 continue;
2841             }
2842         }
2844         $groupmode = groups_get_activity_groupmode($cm, $course);
2846         if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2847             if (isguestuser()) {
2848                 // shortcut - guest user does not belong into any group
2849                 continue;
2850             }
2852             if (is_null($modinfo->groups)) {
2853                 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2854             }
2856             // this will be slow - show only users that share group with me in this cm
2857             if (empty($modinfo->groups[$cm->id])) {
2858                 continue;
2859             }
2860             $usersgroups =  groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
2861             if (is_array($usersgroups)) {
2862                 $usersgroups = array_keys($usersgroups);
2863                 $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2864                 if (empty($intersect)) {
2865                     continue;
2866                 }
2867             }
2868         }
2869         $show[] = $submission;
2870     }
2872     if (empty($show)) {
2873         return false;
2874     }
2876     echo $OUTPUT->heading(get_string('newsubmissions', 'assignment').':', 3);
2878     foreach ($show as $submission) {
2879         $cm = $modinfo->cms[$submission->cmid];
2880         $link = $CFG->wwwroot.'/mod/assignment/view.php?id='.$cm->id;
2881         print_recent_activity_note($submission->timemodified, $submission, $cm->name, $link, false, $viewfullnames);
2882     }
2884     return true;
2888 /**
2889  * Returns all assignments since a given time in specified forum.
2890  */
2891 function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0)  {
2892     global $CFG, $COURSE, $USER, $DB;
2894     if ($COURSE->id == $courseid) {
2895         $course = $COURSE;
2896     } else {
2897         $course = $DB->get_record('course', array('id'=>$courseid));
2898     }
2900     $modinfo =& get_fast_modinfo($course);
2902     $cm = $modinfo->cms[$cmid];
2904     $params = array();
2905     if ($userid) {
2906         $userselect = "AND u.id = :userid";
2907         $params['userid'] = $userid;
2908     } else {
2909         $userselect = "";
2910     }
2912     if ($groupid) {
2913         $groupselect = "AND gm.groupid = :groupid";
2914         $groupjoin   = "JOIN {groups_members} gm ON  gm.userid=u.id";
2915         $params['groupid'] = $groupid;
2916     } else {
2917         $groupselect = "";
2918         $groupjoin   = "";
2919     }
2921     $params['cminstance'] = $cm->instance;
2922     $params['timestart'] = $timestart;
2924     $userfields = user_picture::fields('u', null, 'userid');
2926     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified,
2927                                                      $userfields
2928                                                 FROM {assignment_submissions} asb
2929                                                 JOIN {assignment} a      ON a.id = asb.assignment
2930                                                 JOIN {user} u            ON u.id = asb.userid
2931                                           $groupjoin
2932                                                WHERE asb.timemodified > :timestart AND a.id = :cminstance
2933                                                      $userselect $groupselect
2934                                             ORDER BY asb.timemodified ASC", $params)) {
2935          return;
2936     }
2938     $groupmode       = groups_get_activity_groupmode($cm, $course);
2939     $cm_context      = get_context_instance(CONTEXT_MODULE, $cm->id);
2940     $grader          = has_capability('moodle/grade:viewall', $cm_context);
2941     $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
2942     $viewfullnames   = has_capability('moodle/site:viewfullnames', $cm_context);
2944     if (is_null($modinfo->groups)) {
2945         $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2946     }
2948     $show = array();
2950     foreach($submissions as $submission) {
2951         if ($submission->userid == $USER->id) {
2952             $show[] = $submission;
2953             continue;
2954         }
2955         // the act of submitting of assignment may be considered private - only graders will see it if specified
2956         if (empty($CFG->assignment_showrecentsubmissions)) {
2957             if (!$grader) {
2958                 continue;
2959             }
2960         }
2962         if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
2963             if (isguestuser()) {
2964                 // shortcut - guest user does not belong into any group
2965                 continue;
2966             }
2968             // this will be slow - show only users that share group with me in this cm
2969             if (empty($modinfo->groups[$cm->id])) {
2970                 continue;
2971             }
2972             $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
2973             if (is_array($usersgroups)) {
2974                 $usersgroups = array_keys($usersgroups);
2975                 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2976                 if (empty($intersect)) {
2977                     continue;
2978                 }
2979             }
2980         }
2981         $show[] = $submission;
2982     }
2984     if (empty($show)) {
2985         return;
2986     }
2988     if ($grader) {
2989         require_once($CFG->libdir.'/gradelib.php');
2990         $userids = array();
2991         foreach ($show as $id=>$submission) {
2992             $userids[] = $submission->userid;
2994         }
2995         $grades = grade_get_grades($courseid, 'mod', 'assignment', $cm->instance, $userids);
2996     }
2998     $aname = format_string($cm->name,true);
2999     foreach ($show as $submission) {
3000         $tmpactivity = new object();
3002         $tmpactivity->type         = 'assignment';
3003         $tmpactivity->cmid         = $cm->id;
3004         $tmpactivity->name         = $aname;
3005         $tmpactivity->sectionnum   = $cm->sectionnum;
3006         $tmpactivity->timestamp    = $submission->timemodified;
3008         if ($grader) {
3009             $tmpactivity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
3010         }
3012         $userfields = explode(',', user_picture::fields());
3013         foreach ($userfields as $userfield) {
3014             if ($userfield == 'id') {
3015                 $tmpactivity->user->{$userfield} = $submission->userid; // aliased in SQL above
3016             } else {
3017                 $tmpactivity->user->{$userfield} = $submission->{$userfield};
3018             }
3019         }
3020         $tmpactivity->user->fullname = fullname($submission, $viewfullnames);
3022         $activities[$index++] = $tmpactivity;
3023     }
3025     return;
3028 /**
3029  * Print recent activity from all assignments in a given course
3030  *
3031  * This is used by course/recent.php
3032  */
3033 function assignment_print_recent_mod_activity($activity, $courseid, $detail, $modnames)  {
3034     global $CFG, $OUTPUT;
3036     echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
3038     echo "<tr><td class=\"userpicture\" valign=\"top\">";
3039     echo $OUTPUT->user_picture($activity->user);
3040     echo "</td><td>";
3042     if ($detail) {
3043         $modname = $modnames[$activity->type];
3044         echo '<div class="title">';
3045         echo "<img src=\"" . $OUTPUT->pix_url('icon', 'assignment') . "\" ".
3046              "class=\"icon\" alt=\"$modname\">";
3047         echo "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id={$activity->cmid}\">{$activity->name}</a>";
3048         echo '</div>';
3049     }
3051     if (isset($activity->grade)) {
3052         echo '<div class="grade">';
3053         echo get_string('grade').': ';
3054         echo $activity->grade;
3055         echo '</div>';
3056     }
3058     echo '<div class="user">';
3059     echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->id}&amp;course=$courseid\">"
3060          ."{$activity->user->fullname}</a>  - ".userdate($activity->timestamp);
3061     echo '</div>';
3063     echo "</td></tr></table>";
3066 /// GENERIC SQL FUNCTIONS
3068 /**
3069  * Fetch info from logs
3070  *
3071  * @param $log object with properties ->info (the assignment id) and ->userid
3072  * @return array with assignment name and user firstname and lastname
3073  */
3074 function assignment_log_info($log) {
3075     global $CFG, $DB;
3077     return $DB->get_record_sql("SELECT a.name, u.firstname, u.lastname
3078                                   FROM {assignment} a, {user} u
3079                                  WHERE a.id = ? AND u.id = ?", array($log->info, $log->userid));
3082 /**
3083  * Return list of marked submissions that have not been mailed out for currently enrolled students
3084  *
3085  * @return array
3086  */
3087 function assignment_get_unmailed_submissions($starttime, $endtime) {
3088     global $CFG, $DB;
3090     return $DB->get_records_sql("SELECT s.*, a.course, a.name
3091                                    FROM {assignment_submissions} s,
3092                                         {assignment} a
3093                                   WHERE s.mailed = 0
3094                                         AND s.timemarked <= ?
3095                                         AND s.timemarked >= ?
3096                                         AND s.assignment = a.id", array($endtime, $starttime));
3099 /**
3100  * Counts all real assignment submissions by ENROLLED students (not empty ones)
3101  *
3102  * There are also assignment type methods count_real_submissions() wich in the default
3103  * implementation simply call this function.
3104  * @param $groupid int optional If nonzero then count is restricted to this group
3105  * @return int The number of submissions
3106  */
3107 function assignment_count_real_submissions($cm, $groupid=0) {
3108     global $CFG, $DB;
3110     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
3112     // this is all the users with this capability set, in this context or higher
3113     if ($users = get_enrolled_users($context, 'mod/assignment:submit', $groupid, 'u.id')) {
3114         $users = array_keys($users);
3115     }
3117     // if groupmembersonly used, remove users who are not in any group
3118     if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
3119         if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
3120             $users = array_intersect($users, array_keys($groupingusers));
3121         }
3122     }
3124     if (empty($users)) {
3125         return 0;
3126     }
3128     $userlists = implode(',', $users);
3130     return $DB->count_records_sql("SELECT COUNT('x')
3131                                      FROM {assignment_submissions}
3132                                     WHERE assignment = ? AND
3133                                           timemodified > 0 AND
3134                                           userid IN ($userlists)", array($cm->instance));
3138 /**
3139  * Return all assignment submissions by ENROLLED students (even empty)
3140  *
3141  * There are also assignment type methods get_submissions() wich in the default
3142  * implementation simply call this function.
3143  * @param $sort string optional field names for the ORDER BY in the sql query
3144  * @param $dir string optional specifying the sort direction, defaults to DESC
3145  * @return array The submission objects indexed by id
3146  */
3147 function assignment_get_all_submissions($assignment, $sort="", $dir="DESC") {
3148 /// Return all assignment submissions by ENROLLED students (even empty)
3149     global $CFG, $DB;
3151     if ($sort == "lastname" or $sort == "firstname") {
3152         $sort = "u.$sort $dir";
3153     } else if (empty($sort)) {
3154         $sort = "a.timemodified DESC";
3155     } else {
3156         $sort = "a.$sort $dir";
3157     }
3159     /* not sure this is needed at all since assignmenet already has a course define, so this join?
3160     $select = "s.course = '$assignment->course' AND";
3161     if ($assignment->course == SITEID) {
3162         $select = '';
3163     }*/
3165     return $DB->get_records_sql("SELECT a.*
3166                                    FROM {assignment_submissions} a, {user} u
3167                                   WHERE u.id = a.userid
3168                                         AND a.assignment = ?
3169                                ORDER BY $sort", array($assignment->id));
3173 /**
3174  * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
3175  * for the course (see resource).
3176  *
3177  * Given a course_module object, this function returns any "extra" information that may be needed
3178  * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
3179  *
3180  * @param $coursemodule object The coursemodule object (record).
3181  * @return object An object on information that the coures will know about (most noticeably, an icon).
3182  *
3183  */
3184 function assignment_get_coursemodule_info($coursemodule) {
3185     global $CFG, $DB;
3187     if (! $assignment = $DB->get_record('assignment', array('id'=>$coursemodule->instance), 'id, assignmenttype, name')) {
3188         return false;
3189     }
3191     $libfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
3193     if (file_exists($libfile)) {
3194         require_once($libfile);
3195         $assignmentclass = "assignment_$assignment->assignmenttype";
3196         $ass = new $assignmentclass('staticonly');
3197         if ($result = $ass->get_coursemodule_info($coursemodule)) {
3198             return $result;
3199         } else {
3200             $info = new object();
3201             $info->name = $assignment->name;
3202             return $info;
3203         }
3205     } else {
3206         debugging('Incorrect assignment type: '.$assignment->assignmenttype);
3207         return false;
3208     }
3213 /// OTHER GENERAL FUNCTIONS FOR ASSIGNMENTS  ///////////////////////////////////////
3215 /**
3216  * Returns an array of installed assignment types indexed and sorted by name
3217  *
3218  * @return array The index is the name of the assignment type, the value its full name from the language strings
3219  */
3220 function assignment_types() {
3221     $types = array();
3222     $names = get_plugin_list('assignment');
3223     foreach ($names as $name=>$dir) {
3224         $types[$name] = get_string('type'.$name, 'assignment');
3226         // ugly hack to support pluggable assignment type titles..
3227         if ($types[$name] == '[[type'.$name.']]') {
3228             $types[$name] = get_string('type'.$name, 'assignment_'.$name);
3229         }
3230     }
3231     asort($types);
3232     return $types;
3235 function assignment_print_overview($courses, &$htmlarray) {
3236     global $USER, $CFG, $DB;
3238     if (empty($courses) || !is_array($courses) || count($courses) == 0) {
3239         return array();
3240     }
3242     if (!$assignments = get_all_instances_in_courses('assignment',$courses)) {
3243         return;
3244     }
3246     $assignmentids = array();
3248     // Do assignment_base::isopen() here without loading the whole thing for speed
3249     foreach ($assignments as $key => $assignment) {
3250         $time = time();
3251         if ($assignment->timedue) {
3252             if ($assignment->preventlate) {
3253                 $isopen = ($assignment->timeavailable <= $time && $time <= $assignment->timedue);
3254             } else {
3255                 $isopen = ($assignment->timeavailable <= $time);
3256             }
3257         }
3258         if (empty($isopen) || empty($assignment->timedue)) {
3259             unset($assignments[$key]);
3260         } else {
3261             $assignmentids[] = $assignment->id;
3262         }
3263     }
3265     if (empty($assignmentids)){
3266         // no assigments to look at - we're done
3267         return true;
3268     }
3270     $strduedate = get_string('duedate', 'assignment');
3271     $strduedateno = get_string('duedateno', 'assignment');
3272     $strgraded = get_string('graded', 'assignment');
3273     $strnotgradedyet = get_string('notgradedyet', 'assignment');
3274     $strnotsubmittedyet = get_string('notsubmittedyet', 'assignment');
3275     $strsubmitted = get_string('submitted', 'assignment');
3276     $strassignment = get_string('modulename', 'assignment');
3277     $strreviewed = get_string('reviewed','assignment');
3280     // NOTE: we do all possible database work here *outside* of the loop to ensure this scales
3281     //
3282     list($sqlassignmentids, $assignmentidparams) = $DB->get_in_or_equal($assignmentids);
3284     // build up and array of unmarked submissions indexed by assigment id/ userid
3285     // for use where the user has grading rights on assigment
3286     $rs = $DB->get_recordset_sql("SELECT id, assignment, userid
3287                             FROM {assignment_submissions}
3288                             WHERE teacher = 0 AND timemarked = 0
3289                             AND assignment $sqlassignmentids", $assignmentidparams);
3291     $unmarkedsubmissions = array();
3292     foreach ($rs as $rd) {
3293         $unmarkedsubmissions[$rd->assignment][$rd->userid] = $rd->id;
3294     }
3295     $rs->close();
3298     // get all user submissions, indexed by assigment id
3299     $mysubmissions = $DB->get_records_sql("SELECT assignment, timemarked, teacher, grade
3300                                       FROM {assignment_submissions}
3301                                       WHERE userid = ? AND
3302                                       assignment $sqlassignmentids", array_merge(array($USER->id), $assignmentidparams));
3304     foreach ($assignments as $assignment) {
3305         $str = '<div class="assignment overview"><div class="name">'.$strassignment. ': '.
3306                '<a '.($assignment->visible ? '':' class="dimmed"').
3307                'title="'.$strassignment.'" href="'.$CFG->wwwroot.
3308                '/mod/assignment/view.php?id='.$assignment->coursemodule.'">'.
3309                $assignment->name.'</a></div>';
3310         if ($assignment->timedue) {
3311             $str .= '<div class="info">'.$strduedate.': '.userdate($assignment->timedue).'</div>';
3312         } else {
3313             $str .= '<div class="info">'.$strduedateno.'</div>';
3314         }
3315         $context = get_context_instance(CONTEXT_MODULE, $assignment->coursemodule);
3316         if (has_capability('mod/assignment:grade', $context)) {
3318             // count how many people can submit
3319             $submissions = 0; // init
3320             if ($students = get_enrolled_users($context, 'mod/assignment:submit', 0, 'u.id')) {
3321                 foreach ($students as $student) {
3322                     if (isset($unmarkedsubmissions[$assignment->id][$student->id])) {
3323                         $submissions++;
3324                     }
3325                 }
3326             }
3328             if ($submissions) {
3329                 $link = new moodle_url('/mod/assignment/submissions.php', array('id'=>$assignment->coursemodule));
3330                 $str .= '<div class="details"><a href="'.$link.'">'.get_string('submissionsnotgraded', 'assignment', $submissions).'</a></div>';
3331             }
3332         } else {
3333             $str .= '<div class="details">';
3334             if (isset($mysubmissions[$assignment->id])) {
3336                 $submission = $mysubmissions[$assignment->id];
3338                 if ($submission->teacher == 0 && $submission->timemarked == 0) {
3339                     $str .= $strsubmitted . ', ' . $strnotgradedyet;
3340                 } else if ($submission->grade <= 0) {
3341                     $str .= $strsubmitted . ', ' . $strreviewed;
3342                 } else {
3343                     $str .= $strsubmitted . ', ' . $strgraded;
3344                 }
3345             } else {
3346                 $str .= $strnotsubmittedyet . ' ' . assignment_display_lateness(time(), $assignment->timedue);
3347             }
3348             $str .= '</div>';
3349         }
3350         $str .= '</div>';
3351         if (empty($htmlarray[$assignment->course]['assignment'])) {
3352             $htmlarray[$assignment->course]['assignment'] = $str;
3353         } else {
3354             $htmlarray[$assignment->course]['assignment'] .= $str;
3355         }
3356     }
3359 function assignment_display_lateness($timesubmitted, $timedue) {
3360     if (!$timedue) {
3361         return '';
3362     }
3363     $time = $timedue - $timesubmitted;
3364     if ($time < 0) {
3365         $timetext = get_string('late', 'assignment', format_time($time));
3366         return ' (<span class="late">'.$timetext.'</span>)';
3367     } else {
3368         $timetext = get_string('early', 'assignment', format_time($time));
3369         return ' (<span class="early">'.$timetext.'</span>)';
3370     }
3373 function assignment_get_view_actions() {
3374     return array('view');
3377 function assignment_get_post_actions() {
3378     return array('upload');
3381 function assignment_get_types() {
3382     global $CFG;
3383     $types = array();
3385     $type = new object();
3386     $type->modclass = MOD_CLASS_ACTIVITY;
3387     $type->type = "assignment_group_start";
3388     $type->typestr = '--'.get_string('modulenameplural', 'assignment');
3389     $types[] = $type;
3391     $standardassignments = array('upload','online','uploadsingle','offline');
3392     foreach ($standardassignments as $assignmenttype) {
3393         $type = new object();
3394         $type->modclass = MOD_CLASS_ACTIVITY;
3395         $type->type = "assignment&amp;type=$assignmenttype";
3396         $type->typestr = get_string("type$assignmenttype", 'assignment');
3397         $types[] = $type;
3398     }
3400     /// Drop-in extra assignment types
3401     $assignmenttypes = get_list_of_plugins('mod/assignment/type');
3402     foreach ($assignmenttypes as $assignmenttype) {
3403         if (!empty($CFG->{'assignment_hide_'.$assignmenttype})) {  // Not wanted
3404             continue;
3405         }
3406         if (!in_array($assignmenttype, $standardassignments)) {
3407             $type = new object();
3408             $type->modclass = MOD_CLASS_ACTIVITY;
3409             $type->type = "assignment&amp;type=$assignmenttype";
3410             $type->typestr = get_string("type$assignmenttype", 'assignment_'.$assignmenttype);
3411             $types[] = $type;
3412         }
3413     }
3415     $type = new object();
3416     $type->modclass = MOD_CLASS_ACTIVITY;
3417     $type->type = "assignment_group_end";
3418     $type->typestr = '--';
3419     $types[] = $type;
3421     return $types;
3424 /**
3425  * Removes all grades from gradebook
3426  * @param int $courseid
3427  * @param string optional type
3428  */
3429 function assignment_reset_gradebook($courseid, $type='') {
3430     global $CFG, $DB;
3432     $params = array('courseid'=>$courseid);
3433     if ($type) {
3434         $type = "AND a.assignmenttype= :type";
3435         $params['type'] = $type;
3436     }
3438     $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
3439               FROM {assignment} a, {course_modules} cm, {modules} m
3440              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id AND a.course=:courseid $type";
3442     if ($assignments = $DB->get_records_sql($sql, $params)) {
3443         foreach ($assignments as $assignment) {
3444             assignment_grade_item_update($assignment, 'reset');
3445         }
3446     }
3449 /**
3450  * This function is used by the reset_course_userdata function in moodlelib.
3451  * This function will remove all posts from the specified assignment
3452  * and clean up any related data.
3453  * @param $data the data submitted from the reset course.
3454  * @return array status array
3455  */
3456 function assignment_reset_userdata($data) {
3457     global $CFG;
3459     $status = array();
3461     foreach (get_plugin_list('mod/assignment/type') as $type=>$dir) {
3462         require_once("$dir/assignment.class.php");
3463         $assignmentclass = "assignment_$type";
3464         $ass = new $assignmentclass();
3465         $status = array_merge($status, $ass->reset_userdata($data));
3466     }
3468     return $status;
3471 /**
3472  * Implementation of the function for printing the form elements that control
3473  * whether the course reset functionality affects the assignment.
3474  * @param $mform form passed by reference
3475  */
3476 function assignment_reset_course_form_definition(&$mform) {
3477     $mform->addElement('header', 'assignmentheader', get_string('modulenameplural', 'assignment'));
3478     $mform->addElement('advcheckbox', 'reset_assignment_submissions', get_string('deleteallsubmissions','assignment'));
3481 /**
3482  * Course reset form defaults.
3483  */
3484 function assignment_reset_course_form_defaults($course) {
3485     return array('reset_assignment_submissions'=>1);
3488 /**
3489  * Returns all other caps used in module
3490  */
3491 function assignment_get_extra_capabilities() {
3492     return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames');
3495 /**
3496  * @param string $feature FEATURE_xx constant for requested feature
3497  * @return mixed True if module supports feature, null if doesn't know
3498  */
3499 function assignment_supports($feature) {
3500     switch($feature) {
3501         case FEATURE_GROUPS:                  return true;
3502         case FEATURE_GROUPINGS:               return true;
3503         case FEATURE_GROUPMEMBERSONLY:        return true;
3504         case FEATURE_MOD_INTRO:               return true;
3505         case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
3506         case FEATURE_GRADE_HAS_GRADE:         return true;
3507         case FEATURE_GRADE_OUTCOMES:          return true;
3508         case FEATURE_GRADE_HAS_GRADE:         return true;
3509         case FEATURE_BACKUP_MOODLE2:          return true;
3511         default: return null;
3512     }
3515 /**
3516  * Adds module specific settings to the settings block
3517  *
3518  * @param settings_navigation $settings The settings navigation object
3519  * @param navigation_node $assignmentnode The node to add module settings to
3520  */
3521 function assignment_extend_settings_navigation(settings_navigation $settings, navigation_node $assignmentnode) {
3522     global $PAGE, $DB, $USER, $CFG;
3524     $assignmentrow = $DB->get_record("assignment", array("id" => $PAGE->cm->instance));
3525     require_once "$CFG->dirroot/mod/assignment/type/$assignmentrow->assignmenttype/assignment.class.php";
3527     $assignmentclass = 'assignment_'.$assignmentrow->assignmenttype;
3528     $assignmentinstance = new $assignmentclass($PAGE->cm->id, $assignmentrow, $PAGE->cm, $PAGE->course);
3530     $allgroups = false;
3532     // Add assignment submission information
3533     if (has_capability('mod/assignment:grade', $PAGE->cm->context)) {
3534         if ($allgroups && has_capability('moodle/site:accessallgroups', $PAGE->cm->context)) {
3535             $group = 0;
3536         } else {
3537             $group = groups_get_activity_group($PAGE->cm);
3538         }
3539         $link = new moodle_url('/mod/assignment/submissions.php', array('id'=>$PAGE->cm->id));
3540         if ($count = $assignmentinstance->count_real_submissions($group)) {
3541             $string = get_string('viewsubmissions', 'assignment', $count);
3542         } else {
3543             $string = get_string('noattempts', 'assignment');
3544         }
3545         $assignmentnode->add($string, $link, navigation_node::TYPE_SETTING);
3546     }
3548     if (is_object($assignmentinstance) && method_exists($assignmentinstance, 'extend_settings_navigation')) {
3549         $assignmentinstance->extend_settings_navigation($assignmentnode);
3550     }
3553 /**
3554  * generate zip file from array of given files
3555  * @param array $filesforzipping - array of files to pass into archive_to_pathname
3556  * @return path of temp file - note this returned file does not have a .zip extension - it is a temp file.
3557  */
3558 function assignment_pack_files($filesforzipping) {
3559         global $CFG;
3560         //create path for new zip file.
3561         $tempzip = tempnam($CFG->dataroot.'/temp/', 'assignment_');
3562         //zip files
3563         $zipper = new zip_packer();
3564         if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
3565             return $tempzip;
3566         }
3567         return false;
3569 //TODO - this is a copy of the function my_mktempdir in admin/uploadpicture.php - it would be good to have as a core function.
3570 /**
3571  * Create a unique temporary directory with a given prefix name,
3572  * inside a given directory, with given permissions. Return the
3573  * full path to the newly created temp directory.
3574  *
3575  * @param string $dir where to create the temp directory.
3576  * @param string $prefix prefix for the temp directory name (default '')
3577  * @param string $mode permissions for the temp directory (default 700)
3578  *
3579  * @return string The full path to the temp directory.
3580  */
3581 function assignment_create_temp_dir($dir, $prefix='', $mode=0700) {
3582     if (substr($dir, -1) != '/') {
3583         $dir .= '/';
3584     }
3586     do {
3587         $path = $dir.$prefix.mt_rand(0, 9999999);
3588     } while (!mkdir($path, $mode));
3590     return $path;
3592 /**
3593  * Lists all file areas current user may browse
3594  *
3595  * @param object $course
3596  * @param object $cm
3597  * @param object $context
3598  * @return array
3599  */
3600 function assignment_get_file_areas($course, $cm, $context) {
3601     $areas = array();
3602     if (has_capability('moodle/course:managefiles', $context)) {
3603         $areas['submission'] = get_string('assignmentsubmission', 'assignment');
3604     }
3605     return $areas;