MDL-38254 Assignment Module: add avaialble message to all assignment types
[moodle.git] / mod / assignment / lib.php
1 <?PHP
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
18 /**
19  * assignment_base is the base class for assignment types
20  *
21  * This class provides all the functionality for an assignment
22  *
23  * @package   mod-assignment
24  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
25  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26  */
28 /** Include eventslib.php */
29 require_once($CFG->libdir.'/eventslib.php');
30 /** Include formslib.php */
31 require_once($CFG->libdir.'/formslib.php');
32 /** Include calendar/lib.php */
33 require_once($CFG->dirroot.'/calendar/lib.php');
35 /** ASSIGNMENT_COUNT_WORDS = 1 */
36 define('ASSIGNMENT_COUNT_WORDS', 1);
37 /** ASSIGNMENT_COUNT_LETTERS = 2 */
38 define('ASSIGNMENT_COUNT_LETTERS', 2);
40 /**
41  * Standard base class for all assignment submodules (assignment types).
42  *
43  * @package   mod-assignment
44  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
45  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
46  */
47 class assignment_base {
49     const FILTER_ALL             = 0;
50     const FILTER_SUBMITTED       = 1;
51     const FILTER_REQUIRE_GRADING = 2;
53     /** @var object */
54     var $cm;
55     /** @var object */
56     var $course;
57     /** @var stdClass */
58     var $coursecontext;
59     /** @var object */
60     var $assignment;
61     /** @var string */
62     var $strassignment;
63     /** @var string */
64     var $strassignments;
65     /** @var string */
66     var $strsubmissions;
67     /** @var string */
68     var $strlastmodified;
69     /** @var string */
70     var $pagetitle;
71     /** @var bool */
72     var $usehtmleditor;
73     /**
74      * @todo document this var
75      */
76     var $defaultformat;
77     /**
78      * @todo document this var
79      */
80     var $context;
81     /** @var string */
82     var $type;
84     /**
85      * Constructor for the base assignment class
86      *
87      * Constructor for the base assignment class.
88      * If cmid is set create the cm, course, assignment objects.
89      * If the assignment is hidden and the user is not a teacher then
90      * this prints a page header and notice.
91      *
92      * @global object
93      * @global object
94      * @param int $cmid the current course module id - not set for new assignments
95      * @param object $assignment usually null, but if we have it we pass it to save db access
96      * @param object $cm usually null, but if we have it we pass it to save db access
97      * @param object $course usually null, but if we have it we pass it to save db access
98      */
99     function assignment_base($cmid='staticonly', $assignment=NULL, $cm=NULL, $course=NULL) {
100         global $COURSE, $DB;
102         if ($cmid == 'staticonly') {
103             //use static functions only!
104             return;
105         }
107         global $CFG;
109         if ($cm) {
110             $this->cm = $cm;
111         } else if (! $this->cm = get_coursemodule_from_id('assignment', $cmid)) {
112             print_error('invalidcoursemodule');
113         }
115         $this->context = context_module::instance($this->cm->id);
117         if ($course) {
118             $this->course = $course;
119         } else if ($this->cm->course == $COURSE->id) {
120             $this->course = $COURSE;
121         } else if (! $this->course = $DB->get_record('course', array('id'=>$this->cm->course))) {
122             print_error('invalidid', 'assignment');
123         }
124         $this->coursecontext = context_course::instance($this->course->id);
125         $courseshortname = format_text($this->course->shortname, true, array('context' => $this->coursecontext));
127         if ($assignment) {
128             $this->assignment = $assignment;
129         } else if (! $this->assignment = $DB->get_record('assignment', array('id'=>$this->cm->instance))) {
130             print_error('invalidid', 'assignment');
131         }
133         $this->assignment->cmidnumber = $this->cm->idnumber; // compatibility with modedit assignment obj
134         $this->assignment->courseid   = $this->course->id; // compatibility with modedit assignment obj
136         $this->strassignment = get_string('modulename', 'assignment');
137         $this->strassignments = get_string('modulenameplural', 'assignment');
138         $this->strsubmissions = get_string('submissions', 'assignment');
139         $this->strlastmodified = get_string('lastmodified');
140         $this->pagetitle = strip_tags($courseshortname.': '.$this->strassignment.': '.format_string($this->assignment->name, true, array('context' => $this->context)));
142         // visibility handled by require_login() with $cm parameter
143         // get current group only when really needed
145     /// Set up things for a HTML editor if it's needed
146         $this->defaultformat = editors_get_preferred_format();
147     }
149     /**
150      * Display the assignment, used by view.php
151      *
152      * This in turn calls the methods producing individual parts of the page
153      */
154     function view() {
156         $context = context_module::instance($this->cm->id);
157         require_capability('mod/assignment:view', $context);
159         add_to_log($this->course->id, "assignment", "view", "view.php?id={$this->cm->id}",
160                    $this->assignment->id, $this->cm->id);
162         $this->view_header();
164         $this->view_intro();
166         $this->view_dates();
168         if ($this->isopen() && $this->assignment->timedue > 0 && $this->assignment->timedue < time()) {
169             echo $OUTPUT->heading(get_string('closedassignment','assignment'), 3);
170         } else if ($this->assignment->timeavailable > time()) {
171             echo $OUTPUT->heading(get_string('futureaassignment','assignment'), 3);
172         }
174         $this->view_feedback();
176         $this->view_footer();
177     }
179     /**
180      * Display the header and top of a page
181      *
182      * (this doesn't change much for assignment types)
183      * This is used by the view() method to print the header of view.php but
184      * it can be used on other pages in which case the string to denote the
185      * page in the navigation trail should be passed as an argument
186      *
187      * @global object
188      * @param string $subpage Description of subpage to be used in navigation trail
189      */
190     function view_header($subpage='') {
191         global $CFG, $PAGE, $OUTPUT;
193         if ($subpage) {
194             $PAGE->navbar->add($subpage);
195         }
197         $PAGE->set_title($this->pagetitle);
198         $PAGE->set_heading($this->course->fullname);
200         echo $OUTPUT->header();
202         groups_print_activity_menu($this->cm, $CFG->wwwroot . '/mod/assignment/view.php?id=' . $this->cm->id);
204         echo '<div class="reportlink">'.$this->submittedlink().'</div>';
205         echo '<div class="clearer"></div>';
206         if (has_capability('moodle/site:config', context_system::instance())) {
207             echo $OUTPUT->notification(get_string('upgradenotification', 'assignment'));
208             $adminurl = new moodle_url('/admin/tool/assignmentupgrade/listnotupgraded.php');
209             echo $OUTPUT->single_button($adminurl, get_string('viewassignmentupgradetool', 'assignment'));
210         }
211     }
214     /**
215      * Display the assignment intro
216      *
217      * This will most likely be extended by assignment type plug-ins
218      * The default implementation prints the assignment description in a box
219      */
220     function view_intro() {
221         global $OUTPUT;
222         echo $OUTPUT->box_start('generalbox boxaligncenter', 'intro');
223         echo format_module_intro('assignment', $this->assignment, $this->cm->id);
224         echo $OUTPUT->box_end();
225         echo plagiarism_print_disclosure($this->cm->id);
226     }
228     /**
229      * Display the assignment dates
230      *
231      * Prints the assignment start and end dates in a box.
232      * This will be suitable for most assignment types
233      */
234     function view_dates() {
235         global $OUTPUT;
236         if (!$this->assignment->timeavailable && !$this->assignment->timedue) {
237             return;
238         }
240         echo $OUTPUT->box_start('generalbox boxaligncenter', 'dates');
241         echo '<table>';
242         if ($this->assignment->timeavailable) {
243             echo '<tr><td class="c0">'.get_string('availabledate','assignment').':</td>';
244             echo '    <td class="c1">'.userdate($this->assignment->timeavailable).'</td></tr>';
245         }
246         if ($this->assignment->timedue) {
247             echo '<tr><td class="c0">'.get_string('duedate','assignment').':</td>';
248             echo '    <td class="c1">'.userdate($this->assignment->timedue).'</td></tr>';
249         }
250         echo '</table>';
251         echo $OUTPUT->box_end();
252     }
255     /**
256      * Display the bottom and footer of a page
257      *
258      * This default method just prints the footer.
259      * This will be suitable for most assignment types
260      */
261     function view_footer() {
262         global $OUTPUT;
263         echo $OUTPUT->footer();
264     }
266     /**
267      * Display the feedback to the student
268      *
269      * This default method prints the teacher picture and name, date when marked,
270      * grade and teacher submissioncomment.
271      * If advanced grading is used the method render_grade from the
272      * advanced grading controller is called to display the grade.
273      *
274      * @global object
275      * @global object
276      * @global object
277      * @param object $submission The submission object or NULL in which case it will be loaded
278      * @return bool
279      */
280     function view_feedback($submission=NULL) {
281         global $USER, $CFG, $DB, $OUTPUT, $PAGE;
282         require_once($CFG->libdir.'/gradelib.php');
283         require_once("$CFG->dirroot/grade/grading/lib.php");
285         if (!$submission) { /// Get submission for this assignment
286             $userid = $USER->id;
287             $submission = $this->get_submission($userid);
288         } else {
289             $userid = $submission->userid;
290         }
291         // Check the user can submit
292         $canviewfeedback = ($userid == $USER->id && has_capability('mod/assignment:submit', $this->context, $USER->id, false));
293         // If not then check if the user still has the view cap and has a previous submission
294         $canviewfeedback = $canviewfeedback || (!empty($submission) && $submission->userid == $USER->id && has_capability('mod/assignment:view', $this->context));
295         // Or if user can grade (is a teacher or admin)
296         $canviewfeedback = $canviewfeedback || has_capability('mod/assignment:grade', $this->context);
298         if (!$canviewfeedback) {
299             // can not view or submit assignments -> no feedback
300             return false;
301         }
303         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
304         $item = $grading_info->items[0];
305         $grade = $item->grades[$userid];
307         if ($grade->hidden or $grade->grade === false) { // hidden or error
308             return false;
309         }
311         if ($grade->grade === null and empty($grade->str_feedback)) { // No grade to show yet
312             // If sumbission then check if feedback is avaiable to show else return.
313             if (!$submission) {
314                 return false;
315             }
317             $fs = get_file_storage();
318             $noresponsefiles = $fs->is_area_empty($this->context->id, 'mod_assignment', 'response', $submission->id);
319             if (empty($submission->submissioncomment) && $noresponsefiles) { // Nothing to show yet
320                 return false;
321             }
323             // We need the teacher info
324             if (!$teacher = $DB->get_record('user', array('id'=>$submission->teacher))) {
325                 print_error('cannotfindteacher');
326             }
328             $feedbackdate = $submission->timemarked;
329             $feedback = format_text($submission->submissioncomment, $submission->format);
330             $strlonggrade = '-';
331         }
332         else {
333             // We need the teacher info
334             if (!$teacher = $DB->get_record('user', array('id'=>$grade->usermodified))) {
335                 print_error('cannotfindteacher');
336             }
338             $feedbackdate = $grade->dategraded;
339             $feedback = $grade->str_feedback;
340             $strlonggrade = $grade->str_long_grade;
341         }
343         // Print the feedback
344         echo $OUTPUT->heading(get_string('submissionfeedback', 'assignment'), 3);
346         echo '<table cellspacing="0" class="feedback">';
348         echo '<tr>';
349         echo '<td class="left picture">';
350         if ($teacher) {
351             echo $OUTPUT->user_picture($teacher);
352         }
353         echo '</td>';
354         echo '<td class="topic">';
355         echo '<div class="from">';
356         if ($teacher) {
357             echo '<div class="fullname">'.fullname($teacher).'</div>';
358         }
359         echo '<div class="time">'.userdate($feedbackdate).'</div>';
360         echo '</div>';
361         echo '</td>';
362         echo '</tr>';
364         echo '<tr>';
365         echo '<td class="left side">&nbsp;</td>';
366         echo '<td class="content">';
368         if ($this->assignment->grade) {
369             $gradestr = '<div class="grade">'. get_string("grade").': '.$strlonggrade. '</div>';
370             if (!empty($submission) && $controller = get_grading_manager($this->context, 'mod_assignment', 'submission')->get_active_controller()) {
371                 $controller->set_grade_range(make_grades_menu($this->assignment->grade));
372                 echo $controller->render_grade($PAGE, $submission->id, $item, $gradestr, has_capability('mod/assignment:grade', $this->context));
373             } else {
374                 echo $gradestr;
375             }
376             echo '<div class="clearer"></div>';
377         }
379         echo '<div class="comment">';
380         echo $feedback;
381         echo '</div>';
382         echo '</tr>';
383         if (method_exists($this, 'view_responsefile')) {
384             $this->view_responsefile($submission);
385         }
386         echo '</table>';
388         return true;
389     }
391     /**
392      * Returns a link with info about the state of the assignment submissions
393      *
394      * This is used by view_header to put this link at the top right of the page.
395      * For teachers it gives the number of submitted assignments with a link
396      * For students it gives the time of their submission.
397      * This will be suitable for most assignment types.
398      *
399      * @global object
400      * @global object
401      * @param bool $allgroup print all groups info if user can access all groups, suitable for index.php
402      * @return string
403      */
404     function submittedlink($allgroups=false) {
405         global $USER;
406         global $CFG;
408         $submitted = '';
409         $urlbase = "{$CFG->wwwroot}/mod/assignment/";
411         $context = context_module::instance($this->cm->id);
412         if (has_capability('mod/assignment:grade', $context)) {
413             if ($allgroups and has_capability('moodle/site:accessallgroups', $context)) {
414                 $group = 0;
415             } else {
416                 $group = groups_get_activity_group($this->cm);
417             }
418             if ($this->type == 'offline') {
419                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
420                              get_string('viewfeedback', 'assignment').'</a>';
421             } else if ($count = $this->count_real_submissions($group)) {
422                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
423                              get_string('viewsubmissions', 'assignment', $count).'</a>';
424             } else {
425                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
426                              get_string('noattempts', 'assignment').'</a>';
427             }
428         } else {
429             if (isloggedin()) {
430                 if ($submission = $this->get_submission($USER->id)) {
431                     // If the submission has been completed
432                     if ($this->is_submitted_with_required_data($submission)) {
433                         if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
434                             $submitted = '<span class="early">'.userdate($submission->timemodified).'</span>';
435                         } else {
436                             $submitted = '<span class="late">'.userdate($submission->timemodified).'</span>';
437                         }
438                     }
439                 }
440             }
441         }
443         return $submitted;
444     }
446     /**
447      * Returns whether the assigment supports lateness information
448      *
449      * @return bool This assignment type supports lateness (true, default) or no (false)
450      */
451     function supports_lateness() {
452         return true;
453     }
455     /**
456      * @todo Document this function
457      */
458     function setup_elements(&$mform) {
460     }
462     /**
463      * Any preprocessing needed for the settings form for
464      * this assignment type
465      *
466      * @param array $default_values - array to fill in with the default values
467      *      in the form 'formelement' => 'value'
468      * @param object $form - the form that is to be displayed
469      * @return none
470      */
471     function form_data_preprocessing(&$default_values, $form) {
472     }
474     /**
475      * Any extra validation checks needed for the settings
476      * form for this assignment type
477      *
478      * See lib/formslib.php, 'validation' function for details
479      */
480     function form_validation($data, $files) {
481         return array();
482     }
484     /**
485      * Create a new assignment activity
486      *
487      * Given an object containing all the necessary data,
488      * (defined by the form in mod_form.php) this function
489      * will create a new instance and return the id number
490      * of the new instance.
491      * The due data is added to the calendar
492      * This is common to all assignment types.
493      *
494      * @global object
495      * @global object
496      * @param object $assignment The data from the form on mod_form.php
497      * @return int The id of the assignment
498      */
499     function add_instance($assignment) {
500         global $COURSE, $DB;
502         $assignment->timemodified = time();
503         $assignment->courseid = $assignment->course;
505         $returnid = $DB->insert_record("assignment", $assignment);
506         $assignment->id = $returnid;
508         if ($assignment->timedue) {
509             $event = new stdClass();
510             $event->name        = $assignment->name;
511             $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
512             $event->courseid    = $assignment->course;
513             $event->groupid     = 0;
514             $event->userid      = 0;
515             $event->modulename  = 'assignment';
516             $event->instance    = $returnid;
517             $event->eventtype   = 'due';
518             $event->timestart   = $assignment->timedue;
519             $event->timeduration = 0;
521             calendar_event::create($event);
522         }
524         assignment_grade_item_update($assignment);
526         return $returnid;
527     }
529     /**
530      * Deletes an assignment activity
531      *
532      * Deletes all database records, files and calendar events for this assignment.
533      *
534      * @global object
535      * @global object
536      * @param object $assignment The assignment to be deleted
537      * @return boolean False indicates error
538      */
539     function delete_instance($assignment) {
540         global $CFG, $DB;
542         $assignment->courseid = $assignment->course;
544         $result = true;
546         // now get rid of all files
547         $fs = get_file_storage();
548         if ($cm = get_coursemodule_from_instance('assignment', $assignment->id)) {
549             $context = context_module::instance($cm->id);
550             $fs->delete_area_files($context->id);
551         }
553         if (! $DB->delete_records('assignment_submissions', array('assignment'=>$assignment->id))) {
554             $result = false;
555         }
557         if (! $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
558             $result = false;
559         }
561         if (! $DB->delete_records('assignment', array('id'=>$assignment->id))) {
562             $result = false;
563         }
564         $mod = $DB->get_field('modules','id',array('name'=>'assignment'));
566         assignment_grade_item_delete($assignment);
568         return $result;
569     }
571     /**
572      * Updates a new assignment activity
573      *
574      * Given an object containing all the necessary data,
575      * (defined by the form in mod_form.php) this function
576      * will update the assignment instance and return the id number
577      * The due date is updated in the calendar
578      * This is common to all assignment types.
579      *
580      * @global object
581      * @global object
582      * @param object $assignment The data from the form on mod_form.php
583      * @return bool success
584      */
585     function update_instance($assignment) {
586         global $COURSE, $DB;
588         $assignment->timemodified = time();
590         $assignment->id = $assignment->instance;
591         $assignment->courseid = $assignment->course;
593         $DB->update_record('assignment', $assignment);
595         if ($assignment->timedue) {
596             $event = new stdClass();
598             if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
600                 $event->name        = $assignment->name;
601                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
602                 $event->timestart   = $assignment->timedue;
604                 $calendarevent = calendar_event::load($event->id);
605                 $calendarevent->update($event);
606             } else {
607                 $event = new stdClass();
608                 $event->name        = $assignment->name;
609                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
610                 $event->courseid    = $assignment->course;
611                 $event->groupid     = 0;
612                 $event->userid      = 0;
613                 $event->modulename  = 'assignment';
614                 $event->instance    = $assignment->id;
615                 $event->eventtype   = 'due';
616                 $event->timestart   = $assignment->timedue;
617                 $event->timeduration = 0;
619                 calendar_event::create($event);
620             }
621         } else {
622             $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id));
623         }
625         // get existing grade item
626         assignment_grade_item_update($assignment);
628         return true;
629     }
631     /**
632      * Update grade item for this submission.
633      *
634      * @param stdClass $submission The submission instance
635      */
636     function update_grade($submission) {
637         assignment_update_grades($this->assignment, $submission->userid);
638     }
640     /**
641      * Top-level function for handling of submissions called by submissions.php
642      *
643      * This is for handling the teacher interaction with the grading interface
644      * This should be suitable for most assignment types.
645      *
646      * @global object
647      * @param string $mode Specifies the kind of teacher interaction taking place
648      */
649     function submissions($mode) {
650         ///The main switch is changed to facilitate
651         ///1) Batch fast grading
652         ///2) Skip to the next one on the popup
653         ///3) Save and Skip to the next one on the popup
655         //make user global so we can use the id
656         global $USER, $OUTPUT, $DB, $PAGE;
658         $mailinfo = optional_param('mailinfo', null, PARAM_BOOL);
660         if (optional_param('next', null, PARAM_BOOL)) {
661             $mode='next';
662         }
663         if (optional_param('saveandnext', null, PARAM_BOOL)) {
664             $mode='saveandnext';
665         }
667         if (is_null($mailinfo)) {
668             if (optional_param('sesskey', null, PARAM_BOOL)) {
669                 set_user_preference('assignment_mailinfo', 0);
670             } else {
671                 $mailinfo = get_user_preferences('assignment_mailinfo', 0);
672             }
673         } else {
674             set_user_preference('assignment_mailinfo', $mailinfo);
675         }
677         if (!($this->validate_and_preprocess_feedback())) {
678             // form was submitted ('Save' or 'Save and next' was pressed, but validation failed)
679             $this->display_submission();
680             return;
681         }
683         switch ($mode) {
684             case 'grade':                         // We are in a main window grading
685                 if ($submission = $this->process_feedback()) {
686                     $this->display_submissions(get_string('changessaved'));
687                 } else {
688                     $this->display_submissions();
689                 }
690                 break;
692             case 'single':                        // We are in a main window displaying one submission
693                 if ($submission = $this->process_feedback()) {
694                     $this->display_submissions(get_string('changessaved'));
695                 } else {
696                     $this->display_submission();
697                 }
698                 break;
700             case 'all':                          // Main window, display everything
701                 $this->display_submissions();
702                 break;
704             case 'fastgrade':
705                 ///do the fast grading stuff  - this process should work for all 3 subclasses
706                 $grading    = false;
707                 $commenting = false;
708                 $col        = false;
709                 if (isset($_POST['submissioncomment'])) {
710                     $col = 'submissioncomment';
711                     $commenting = true;
712                 }
713                 if (isset($_POST['menu'])) {
714                     $col = 'menu';
715                     $grading = true;
716                 }
717                 if (!$col) {
718                     //both submissioncomment and grade columns collapsed..
719                     $this->display_submissions();
720                     break;
721                 }
723                 foreach ($_POST[$col] as $id => $unusedvalue){
725                     $id = (int)$id; //clean parameter name
727                     $this->process_outcomes($id);
729                     if (!$submission = $this->get_submission($id)) {
730                         $submission = $this->prepare_new_submission($id);
731                         $newsubmission = true;
732                     } else {
733                         $newsubmission = false;
734                     }
735                     unset($submission->data1);  // Don't need to update this.
736                     unset($submission->data2);  // Don't need to update this.
738                     //for fast grade, we need to check if any changes take place
739                     $updatedb = false;
741                     if ($grading) {
742                         $grade = $_POST['menu'][$id];
743                         $updatedb = $updatedb || ($submission->grade != $grade);
744                         $submission->grade = $grade;
745                     } else {
746                         if (!$newsubmission) {
747                             unset($submission->grade);  // Don't need to update this.
748                         }
749                     }
750                     if ($commenting) {
751                         $commentvalue = trim($_POST['submissioncomment'][$id]);
752                         $updatedb = $updatedb || ($submission->submissioncomment != $commentvalue);
753                         $submission->submissioncomment = $commentvalue;
754                     } else {
755                         unset($submission->submissioncomment);  // Don't need to update this.
756                     }
758                     $submission->teacher    = $USER->id;
759                     if ($updatedb) {
760                         $submission->mailed = (int)(!$mailinfo);
761                     }
763                     $submission->timemarked = time();
765                     //if it is not an update, we don't change the last modified time etc.
766                     //this will also not write into database if no submissioncomment and grade is entered.
768                     if ($updatedb){
769                         if ($newsubmission) {
770                             if (!isset($submission->submissioncomment)) {
771                                 $submission->submissioncomment = '';
772                             }
773                             $sid = $DB->insert_record('assignment_submissions', $submission);
774                             $submission->id = $sid;
775                         } else {
776                             $DB->update_record('assignment_submissions', $submission);
777                         }
779                         // trigger grade event
780                         $this->update_grade($submission);
782                         //add to log only if updating
783                         add_to_log($this->course->id, 'assignment', 'update grades',
784                                    'submissions.php?id='.$this->cm->id.'&user='.$submission->userid,
785                                    $submission->userid, $this->cm->id);
786                     }
788                 }
790                 $message = $OUTPUT->notification(get_string('changessaved'), 'notifysuccess');
792                 $this->display_submissions($message);
793                 break;
796             case 'saveandnext':
797                 ///We are in pop up. save the current one and go to the next one.
798                 //first we save the current changes
799                 if ($submission = $this->process_feedback()) {
800                     //print_heading(get_string('changessaved'));
801                     //$extra_javascript = $this->update_main_listing($submission);
802                 }
804             case 'next':
805                 /// We are currently in pop up, but we want to skip to next one without saving.
806                 ///    This turns out to be similar to a single case
807                 /// The URL used is for the next submission.
808                 $offset = required_param('offset', PARAM_INT);
809                 $nextid = required_param('nextid', PARAM_INT);
810                 $id = required_param('id', PARAM_INT);
811                 $filter = optional_param('filter', self::FILTER_ALL, PARAM_INT);
813                 if ($mode == 'next' || $filter !== self::FILTER_REQUIRE_GRADING) {
814                     $offset = (int)$offset+1;
815                 }
816                 $redirect = new moodle_url('submissions.php',
817                         array('id' => $id, 'offset' => $offset, 'userid' => $nextid,
818                         'mode' => 'single', 'filter' => $filter));
820                 redirect($redirect);
821                 break;
823             case 'singlenosave':
824                 $this->display_submission();
825                 break;
827             default:
828                 echo "something seriously is wrong!!";
829                 break;
830         }
831     }
833     /**
834      * Checks if grading method allows quickgrade mode. At the moment it is hardcoded
835      * that advanced grading methods do not allow quickgrade.
836      *
837      * Assignment type plugins are not allowed to override this method
838      *
839      * @return boolean
840      */
841     public final function quickgrade_mode_allowed() {
842         global $CFG;
843         require_once("$CFG->dirroot/grade/grading/lib.php");
844         if ($controller = get_grading_manager($this->context, 'mod_assignment', 'submission')->get_active_controller()) {
845             return false;
846         }
847         return true;
848     }
850     /**
851      * Helper method updating the listing on the main script from popup using javascript
852      *
853      * @global object
854      * @global object
855      * @param $submission object The submission whose data is to be updated on the main page
856      */
857     function update_main_listing($submission) {
858         global $SESSION, $CFG, $OUTPUT;
860         $output = '';
862         $perpage = get_user_preferences('assignment_perpage', 10);
864         $quickgrade = get_user_preferences('assignment_quickgrade', 0) && $this->quickgrade_mode_allowed();
866         /// Run some Javascript to try and update the parent page
867         $output .= '<script type="text/javascript">'."\n<!--\n";
868         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['submissioncomment'])) {
869             if ($quickgrade){
870                 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid.'").value="'
871                 .trim($submission->submissioncomment).'";'."\n";
872              } else {
873                 $output.= 'opener.document.getElementById("com'.$submission->userid.
874                 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment)), 15)."\";\n";
875             }
876         }
878         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['grade'])) {
879             //echo optional_param('menuindex');
880             if ($quickgrade){
881                 $output.= 'opener.document.getElementById("menumenu'.$submission->userid.
882                 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT).'";'."\n";
883             } else {
884                 $output.= 'opener.document.getElementById("g'.$submission->userid.'").innerHTML="'.
885                 $this->display_grade($submission->grade)."\";\n";
886             }
887         }
888         //need to add student's assignments in there too.
889         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemodified']) &&
890             $submission->timemodified) {
891             $output.= 'opener.document.getElementById("ts'.$submission->userid.
892                  '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid)).userdate($submission->timemodified)."\";\n";
893         }
895         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemarked']) &&
896             $submission->timemarked) {
897             $output.= 'opener.document.getElementById("tt'.$submission->userid.
898                  '").innerHTML="'.userdate($submission->timemarked)."\";\n";
899         }
901         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['status'])) {
902             $output.= 'opener.document.getElementById("up'.$submission->userid.'").className="s1";';
903             $buttontext = get_string('update');
904             $url = new moodle_url('/mod/assignment/submissions.php', array(
905                     'id' => $this->cm->id,
906                     'userid' => $submission->userid,
907                     'mode' => 'single',
908                     'offset' => (optional_param('offset', '', PARAM_INT)-1)));
909             $button = $OUTPUT->action_link($url, $buttontext, new popup_action('click', $url, 'grade'.$submission->userid, array('height' => 450, 'width' => 700)), array('ttile'=>$buttontext));
911             $output .= 'opener.document.getElementById("up'.$submission->userid.'").innerHTML="'.addslashes_js($button).'";';
912         }
914         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $submission->userid);
916         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['finalgrade'])) {
917             $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid.
918             '").innerHTML="'.$grading_info->items[0]->grades[$submission->userid]->str_grade.'";'."\n";
919         }
921         if (!empty($CFG->enableoutcomes) and empty($SESSION->flextable['mod-assignment-submissions']->collapse['outcome'])) {
923             if (!empty($grading_info->outcomes)) {
924                 foreach($grading_info->outcomes as $n=>$outcome) {
925                     if ($outcome->grades[$submission->userid]->locked) {
926                         continue;
927                     }
929                     if ($quickgrade){
930                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.
931                         '").selectedIndex="'.$outcome->grades[$submission->userid]->grade.'";'."\n";
933                     } else {
934                         $options = make_grades_menu(-$outcome->scaleid);
935                         $options[0] = get_string('nooutcome', 'grades');
936                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.'").innerHTML="'.$options[$outcome->grades[$submission->userid]->grade]."\";\n";
937                     }
939                 }
940             }
941         }
943         $output .= "\n-->\n</script>";
944         return $output;
945     }
947     /**
948      *  Return a grade in user-friendly form, whether it's a scale or not
949      *
950      * @global object
951      * @param mixed $grade
952      * @return string User-friendly representation of grade
953      */
954     function display_grade($grade) {
955         global $DB;
957         static $scalegrades = array();   // Cache scales for each assignment - they might have different scales!!
959         if ($this->assignment->grade >= 0) {    // Normal number
960             if ($grade == -1) {
961                 return '-';
962             } else {
963                 return $grade.' / '.$this->assignment->grade;
964             }
966         } else {                                // Scale
967             if (empty($scalegrades[$this->assignment->id])) {
968                 if ($scale = $DB->get_record('scale', array('id'=>-($this->assignment->grade)))) {
969                     $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
970                 } else {
971                     return '-';
972                 }
973             }
974             if (isset($scalegrades[$this->assignment->id][$grade])) {
975                 return $scalegrades[$this->assignment->id][$grade];
976             }
977             return '-';
978         }
979     }
981     /**
982      *  Display a single submission, ready for grading on a popup window
983      *
984      * This default method prints the teacher info and submissioncomment box at the top and
985      * the student info and submission at the bottom.
986      * This method also fetches the necessary data in order to be able to
987      * provide a "Next submission" button.
988      * Calls preprocess_submission() to give assignment type plug-ins a chance
989      * to process submissions before they are graded
990      * This method gets its arguments from the page parameters userid and offset
991      *
992      * @global object
993      * @global object
994      * @param string $extra_javascript
995      */
996     function display_submission($offset=-1,$userid =-1, $display=true) {
997         global $CFG, $DB, $PAGE, $OUTPUT, $USER;
998         require_once($CFG->libdir.'/gradelib.php');
999         require_once($CFG->libdir.'/tablelib.php');
1000         require_once("$CFG->dirroot/repository/lib.php");
1001         require_once("$CFG->dirroot/grade/grading/lib.php");
1002         if ($userid==-1) {
1003             $userid = required_param('userid', PARAM_INT);
1004         }
1005         if ($offset==-1) {
1006             $offset = required_param('offset', PARAM_INT);//offset for where to start looking for student.
1007         }
1008         $filter = optional_param('filter', 0, PARAM_INT);
1010         if (!$user = $DB->get_record('user', array('id'=>$userid))) {
1011             print_error('nousers');
1012         }
1014         if (!$submission = $this->get_submission($user->id)) {
1015             $submission = $this->prepare_new_submission($userid);
1016         }
1017         if ($submission->timemodified > $submission->timemarked) {
1018             $subtype = 'assignmentnew';
1019         } else {
1020             $subtype = 'assignmentold';
1021         }
1023         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
1024         $gradingdisabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
1026     /// construct SQL, using current offset to find the data of the next student
1027         $course     = $this->course;
1028         $assignment = $this->assignment;
1029         $cm         = $this->cm;
1030         $context    = context_module::instance($cm->id);
1032         //reset filter to all for offline assignment
1033         if ($assignment->assignmenttype == 'offline' && $filter == self::FILTER_SUBMITTED) {
1034             $filter = self::FILTER_ALL;
1035         }
1036         /// Get all ppl that can submit assignments
1038         $currentgroup = groups_get_activity_group($cm);
1039         $users = get_enrolled_users($context, 'mod/assignment:submit', $currentgroup, 'u.id');
1040         if ($users) {
1041             $users = array_keys($users);
1042             // if groupmembersonly used, remove users who are not in any group
1043             if (!empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
1044                 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1045                     $users = array_intersect($users, array_keys($groupingusers));
1046                 }
1047             }
1048         }
1050         $nextid = 0;
1051         $where = '';
1052         if($filter == self::FILTER_SUBMITTED) {
1053             $where .= 's.timemodified > 0 AND ';
1054         } else if($filter == self::FILTER_REQUIRE_GRADING) {
1055             $where .= 's.timemarked < s.timemodified AND ';
1056         }
1058         if ($users) {
1059             $userfields = user_picture::fields('u', array('lastaccess'));
1060             $select = "SELECT $userfields,
1061                               s.id AS submissionid, s.grade, s.submissioncomment,
1062                               s.timemodified, s.timemarked,
1063                               CASE WHEN s.timemarked > 0 AND s.timemarked >= s.timemodified THEN 1
1064                                    ELSE 0 END AS status ";
1066             $sql = 'FROM {user} u '.
1067                    'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1068                    AND s.assignment = '.$this->assignment->id.' '.
1069                    'WHERE '.$where.'u.id IN ('.implode(',', $users).') ';
1071             if ($sort = flexible_table::get_sort_for_table('mod-assignment-submissions')) {
1072                 $sort = 'ORDER BY '.$sort.' ';
1073             }
1074             $auser = $DB->get_records_sql($select.$sql.$sort, null, $offset, 2);
1076             if (is_array($auser) && count($auser)>1) {
1077                 $nextuser = next($auser);
1078                 $nextid = $nextuser->id;
1079             }
1080         }
1082         if ($submission->teacher) {
1083             $teacher = $DB->get_record('user', array('id'=>$submission->teacher));
1084         } else {
1085             global $USER;
1086             $teacher = $USER;
1087         }
1089         $this->preprocess_submission($submission);
1091         $mformdata = new stdClass();
1092         $mformdata->context = $this->context;
1093         $mformdata->maxbytes = $this->course->maxbytes;
1094         $mformdata->courseid = $this->course->id;
1095         $mformdata->teacher = $teacher;
1096         $mformdata->assignment = $assignment;
1097         $mformdata->submission = $submission;
1098         $mformdata->lateness = $this->display_lateness($submission->timemodified);
1099         $mformdata->auser = $auser;
1100         $mformdata->user = $user;
1101         $mformdata->offset = $offset;
1102         $mformdata->userid = $userid;
1103         $mformdata->cm = $this->cm;
1104         $mformdata->grading_info = $grading_info;
1105         $mformdata->enableoutcomes = $CFG->enableoutcomes;
1106         $mformdata->grade = $this->assignment->grade;
1107         $mformdata->gradingdisabled = $gradingdisabled;
1108         $mformdata->nextid = $nextid;
1109         $mformdata->submissioncomment= $submission->submissioncomment;
1110         $mformdata->submissioncommentformat= FORMAT_HTML;
1111         $mformdata->submission_content= $this->print_user_files($user->id,true);
1112         $mformdata->filter = $filter;
1113         $mformdata->mailinfo = get_user_preferences('assignment_mailinfo', 0);
1114          if ($assignment->assignmenttype == 'upload') {
1115             $mformdata->fileui_options = array('subdirs'=>1, 'maxbytes'=>$assignment->maxbytes, 'maxfiles'=>$assignment->var1, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL);
1116         } elseif ($assignment->assignmenttype == 'uploadsingle') {
1117             $mformdata->fileui_options = array('subdirs'=>0, 'maxbytes'=>$CFG->userquota, 'maxfiles'=>1, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL);
1118         }
1119         $advancedgradingwarning = false;
1120         $gradingmanager = get_grading_manager($this->context, 'mod_assignment', 'submission');
1121         if ($gradingmethod = $gradingmanager->get_active_method()) {
1122             $controller = $gradingmanager->get_controller($gradingmethod);
1123             if ($controller->is_form_available()) {
1124                 $itemid = null;
1125                 if (!empty($submission->id)) {
1126                     $itemid = $submission->id;
1127                 }
1128                 if ($gradingdisabled && $itemid) {
1129                     $mformdata->advancedgradinginstance = $controller->get_current_instance($USER->id, $itemid);
1130                 } else if (!$gradingdisabled) {
1131                     $instanceid = optional_param('advancedgradinginstanceid', 0, PARAM_INT);
1132                     $mformdata->advancedgradinginstance = $controller->get_or_create_instance($instanceid, $USER->id, $itemid);
1133                 }
1134             } else {
1135                 $advancedgradingwarning = $controller->form_unavailable_notification();
1136             }
1137         }
1139         $submitform = new assignment_grading_form( null, $mformdata );
1141          if (!$display) {
1142             $ret_data = new stdClass();
1143             $ret_data->mform = $submitform;
1144             if (isset($mformdata->fileui_options)) {
1145                 $ret_data->fileui_options = $mformdata->fileui_options;
1146             }
1147             return $ret_data;
1148         }
1150         if ($submitform->is_cancelled()) {
1151             redirect('submissions.php?id='.$this->cm->id);
1152         }
1154         $submitform->set_data($mformdata);
1156         $PAGE->set_title($this->course->fullname . ': ' .get_string('feedback', 'assignment').' - '.fullname($user, true));
1157         $PAGE->set_heading($this->course->fullname);
1158         $PAGE->navbar->add(get_string('submissions', 'assignment'), new moodle_url('/mod/assignment/submissions.php', array('id'=>$cm->id)));
1159         $PAGE->navbar->add(fullname($user, true));
1161         echo $OUTPUT->header();
1162         echo $OUTPUT->heading(get_string('feedback', 'assignment').': '.fullname($user, true));
1164         // display mform here...
1165         if ($advancedgradingwarning) {
1166             echo $OUTPUT->notification($advancedgradingwarning, 'error');
1167         }
1168         $submitform->display();
1170         $customfeedback = $this->custom_feedbackform($submission, true);
1171         if (!empty($customfeedback)) {
1172             echo $customfeedback;
1173         }
1175         echo $OUTPUT->footer();
1176     }
1178     /**
1179      *  Preprocess submission before grading
1180      *
1181      * Called by display_submission()
1182      * The default type does nothing here.
1183      *
1184      * @param object $submission The submission object
1185      */
1186     function preprocess_submission(&$submission) {
1187     }
1189     /**
1190      *  Display all the submissions ready for grading
1191      *
1192      * @global object
1193      * @global object
1194      * @global object
1195      * @global object
1196      * @param string $message
1197      * @return bool|void
1198      */
1199     function display_submissions($message='') {
1200         global $CFG, $DB, $USER, $DB, $OUTPUT, $PAGE;
1201         require_once($CFG->libdir.'/gradelib.php');
1203         /* first we check to see if the form has just been submitted
1204          * to request user_preference updates
1205          */
1207        $filters = array(self::FILTER_ALL             => get_string('all'),
1208                         self::FILTER_REQUIRE_GRADING => get_string('requiregrading', 'assignment'));
1210         $updatepref = optional_param('updatepref', 0, PARAM_BOOL);
1211         if ($updatepref) {
1212             $perpage = optional_param('perpage', 10, PARAM_INT);
1213             $perpage = ($perpage <= 0) ? 10 : $perpage ;
1214             $filter = optional_param('filter', 0, PARAM_INT);
1215             set_user_preference('assignment_perpage', $perpage);
1216             set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
1217             set_user_preference('assignment_filter', $filter);
1218         }
1220         /* next we get perpage and quickgrade (allow quick grade) params
1221          * from database
1222          */
1223         $perpage    = get_user_preferences('assignment_perpage', 10);
1224         $quickgrade = get_user_preferences('assignment_quickgrade', 0) && $this->quickgrade_mode_allowed();
1225         $filter = get_user_preferences('assignment_filter', 0);
1226         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);
1228         if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
1229             $uses_outcomes = true;
1230         } else {
1231             $uses_outcomes = false;
1232         }
1234         $page    = optional_param('page', 0, PARAM_INT);
1235         $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
1237     /// Some shortcuts to make the code read better
1239         $course     = $this->course;
1240         $assignment = $this->assignment;
1241         $cm         = $this->cm;
1242         $hassubmission = false;
1244         // reset filter to all for offline assignment only.
1245         if ($assignment->assignmenttype == 'offline') {
1246             if ($filter == self::FILTER_SUBMITTED) {
1247                 $filter = self::FILTER_ALL;
1248             }
1249         } else {
1250             $filters[self::FILTER_SUBMITTED] = get_string('submitted', 'assignment');
1251         }
1253         $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
1254         add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->cm->id, $this->assignment->id, $this->cm->id);
1256         $PAGE->set_title(format_string($this->assignment->name,true));
1257         $PAGE->set_heading($this->course->fullname);
1258         echo $OUTPUT->header();
1260         echo '<div class="usersubmissions">';
1262         //hook to allow plagiarism plugins to update status/print links.
1263         echo plagiarism_update_status($this->course, $this->cm);
1265         $course_context = context_course::instance($course->id);
1266         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
1267             echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">'
1268                 . get_string('seeallcoursegrades', 'grades') . '</a></div>';
1269         }
1271         if (!empty($message)) {
1272             echo $message;   // display messages here if any
1273         }
1275         $context = context_module::instance($cm->id);
1277     /// Check to see if groups are being used in this assignment
1279         /// find out current groups mode
1280         $groupmode = groups_get_activity_groupmode($cm);
1281         $currentgroup = groups_get_activity_group($cm, true);
1282         groups_print_activity_menu($cm, $CFG->wwwroot . '/mod/assignment/submissions.php?id=' . $this->cm->id);
1284         /// Print quickgrade form around the table
1285         if ($quickgrade) {
1286             $formattrs = array();
1287             $formattrs['action'] = new moodle_url('/mod/assignment/submissions.php');
1288             $formattrs['id'] = 'fastg';
1289             $formattrs['method'] = 'post';
1291             echo html_writer::start_tag('form', $formattrs);
1292             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'id',      'value'=> $this->cm->id));
1293             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'mode',    'value'=> 'fastgrade'));
1294             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'page',    'value'=> $page));
1295             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=> sesskey()));
1296         }
1298         /// Get all ppl that are allowed to submit assignments
1299         list($esql, $params) = get_enrolled_sql($context, 'mod/assignment:submit', $currentgroup);
1301         if ($filter == self::FILTER_ALL) {
1302             $sql = "SELECT u.id FROM {user} u ".
1303                    "LEFT JOIN ($esql) eu ON eu.id=u.id ".
1304                    "WHERE u.deleted = 0 AND eu.id=u.id ";
1305         } else {
1306             $wherefilter = ' AND s.assignment = '. $this->assignment->id;
1307             $assignmentsubmission = "LEFT JOIN {assignment_submissions} s ON (u.id = s.userid) ";
1308             if($filter == self::FILTER_SUBMITTED) {
1309                 $wherefilter .= ' AND s.timemodified > 0 ';
1310             } else if($filter == self::FILTER_REQUIRE_GRADING && $assignment->assignmenttype != 'offline') {
1311                 $wherefilter .= ' AND s.timemarked < s.timemodified ';
1312             } else { // require grading for offline assignment
1313                 $assignmentsubmission = "";
1314                 $wherefilter = "";
1315             }
1317             $sql = "SELECT u.id FROM {user} u ".
1318                    "LEFT JOIN ($esql) eu ON eu.id=u.id ".
1319                    $assignmentsubmission.
1320                    "WHERE u.deleted = 0 AND eu.id=u.id ".
1321                    $wherefilter;
1322         }
1324         $users = $DB->get_records_sql($sql, $params);
1325         if (!empty($users)) {
1326             if($assignment->assignmenttype == 'offline' && $filter == self::FILTER_REQUIRE_GRADING) {
1327                 //remove users who has submitted their assignment
1328                 foreach ($this->get_submissions() as $submission) {
1329                     if (array_key_exists($submission->userid, $users)) {
1330                         unset($users[$submission->userid]);
1331                     }
1332                 }
1333             }
1334             $users = array_keys($users);
1335         }
1337         // if groupmembersonly used, remove users who are not in any group
1338         if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
1339             if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1340                 $users = array_intersect($users, array_keys($groupingusers));
1341             }
1342         }
1344         $extrafields = get_extra_user_fields($context);
1345         $tablecolumns = array_merge(array('picture', 'fullname'), $extrafields,
1346                 array('grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade'));
1347         if ($uses_outcomes) {
1348             $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
1349         }
1351         $extrafieldnames = array();
1352         foreach ($extrafields as $field) {
1353             $extrafieldnames[] = get_user_field_name($field);
1354         }
1355         $tableheaders = array_merge(
1356                 array('', get_string('fullnameuser')),
1357                 $extrafieldnames,
1358                 array(
1359                     get_string('grade'),
1360                     get_string('comment', 'assignment'),
1361                     get_string('lastmodified').' ('.get_string('submission', 'assignment').')',
1362                     get_string('lastmodified').' ('.get_string('grade').')',
1363                     get_string('status'),
1364                     get_string('finalgrade', 'grades'),
1365                 ));
1366         if ($uses_outcomes) {
1367             $tableheaders[] = get_string('outcome', 'grades');
1368         }
1370         require_once($CFG->libdir.'/tablelib.php');
1371         $table = new flexible_table('mod-assignment-submissions');
1373         $table->define_columns($tablecolumns);
1374         $table->define_headers($tableheaders);
1375         $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;currentgroup='.$currentgroup);
1377         $table->sortable(true, 'lastname');//sorted by lastname by default
1378         $table->collapsible(true);
1379         $table->initialbars(true);
1381         $table->column_suppress('picture');
1382         $table->column_suppress('fullname');
1384         $table->column_class('picture', 'picture');
1385         $table->column_class('fullname', 'fullname');
1386         foreach ($extrafields as $field) {
1387             $table->column_class($field, $field);
1388         }
1389         $table->column_class('grade', 'grade');
1390         $table->column_class('submissioncomment', 'comment');
1391         $table->column_class('timemodified', 'timemodified');
1392         $table->column_class('timemarked', 'timemarked');
1393         $table->column_class('status', 'status');
1394         $table->column_class('finalgrade', 'finalgrade');
1395         if ($uses_outcomes) {
1396             $table->column_class('outcome', 'outcome');
1397         }
1399         $table->set_attribute('cellspacing', '0');
1400         $table->set_attribute('id', 'attempts');
1401         $table->set_attribute('class', 'submissions');
1402         $table->set_attribute('width', '100%');
1404         $table->no_sorting('finalgrade');
1405         $table->no_sorting('outcome');
1406         $table->text_sorting('submissioncomment');
1408         // Start working -- this is necessary as soon as the niceties are over
1409         $table->setup();
1411         /// Construct the SQL
1412         list($where, $params) = $table->get_sql_where();
1413         if ($where) {
1414             $where .= ' AND ';
1415         }
1417         if ($filter == self::FILTER_SUBMITTED) {
1418            $where .= 's.timemodified > 0 AND ';
1419         } else if($filter == self::FILTER_REQUIRE_GRADING) {
1420             $where = '';
1421             if ($assignment->assignmenttype != 'offline') {
1422                $where .= 's.timemarked < s.timemodified AND ';
1423             }
1424         }
1426         if ($sort = $table->get_sql_sort()) {
1427             $sort = ' ORDER BY '.$sort;
1428         }
1430         $ufields = user_picture::fields('u', $extrafields);
1431         if (!empty($users)) {
1432             $select = "SELECT $ufields,
1433                               s.id AS submissionid, s.grade, s.submissioncomment,
1434                               s.timemodified, s.timemarked,
1435                               CASE WHEN s.timemarked > 0 AND s.timemarked >= s.timemodified THEN 1
1436                                    ELSE 0 END AS status ";
1438             $sql = 'FROM {user} u '.
1439                    'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1440                     AND s.assignment = '.$this->assignment->id.' '.
1441                    'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1443             $ausers = $DB->get_records_sql($select.$sql.$sort, $params, $table->get_page_start(), $table->get_page_size());
1445             $table->pagesize($perpage, count($users));
1447             ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1448             $offset = $page * $perpage;
1449             $strupdate = get_string('update');
1450             $strgrade  = get_string('grade');
1451             $strview  = get_string('view');
1452             $grademenu = make_grades_menu($this->assignment->grade);
1454             if ($ausers !== false) {
1455                 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
1456                 $endposition = $offset + $perpage;
1457                 $currentposition = 0;
1458                 foreach ($ausers as $auser) {
1459                     if ($currentposition == $offset && $offset < $endposition) {
1460                         $rowclass = null;
1461                         $final_grade = $grading_info->items[0]->grades[$auser->id];
1462                         $grademax = $grading_info->items[0]->grademax;
1463                         $final_grade->formatted_grade = round($final_grade->grade,2) .' / ' . round($grademax,2);
1464                         $locked_overridden = 'locked';
1465                         if ($final_grade->overridden) {
1466                             $locked_overridden = 'overridden';
1467                         }
1469                         // TODO add here code if advanced grading grade must be reviewed => $auser->status=0
1471                         $picture = $OUTPUT->user_picture($auser);
1473                         if (empty($auser->submissionid)) {
1474                             $auser->grade = -1; //no submission yet
1475                         }
1477                         if (!empty($auser->submissionid)) {
1478                             $hassubmission = true;
1479                         ///Prints student answer and student modified date
1480                         ///attach file or print link to student answer, depending on the type of the assignment.
1481                         ///Refer to print_student_answer in inherited classes.
1482                             if ($auser->timemodified > 0) {
1483                                 $studentmodifiedcontent = $this->print_student_answer($auser->id)
1484                                         . userdate($auser->timemodified);
1485                                 if ($assignment->timedue && $auser->timemodified > $assignment->timedue && $this->supports_lateness()) {
1486                                     $studentmodifiedcontent .= $this->display_lateness($auser->timemodified);
1487                                     $rowclass = 'late';
1488                                 }
1489                             } else {
1490                                 $studentmodifiedcontent = '&nbsp;';
1491                             }
1492                             $studentmodified = html_writer::tag('div', $studentmodifiedcontent, array('id' => 'ts' . $auser->id));
1493                         ///Print grade, dropdown or text
1494                             if ($auser->timemarked > 0) {
1495                                 $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
1497                                 if ($final_grade->locked or $final_grade->overridden) {
1498                                     $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1499                                 } else if ($quickgrade) {
1500                                     $attributes = array();
1501                                     $attributes['tabindex'] = $tabindex++;
1502                                     $menu = html_writer::label(get_string('assignment:grade', 'assignment'), 'menumenu'. $auser->id, false, array('class' => 'accesshide'));
1503                                     $menu .= html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1504                                     $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
1505                                 } else {
1506                                     $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1507                                 }
1509                             } else {
1510                                 $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1511                                 if ($final_grade->locked or $final_grade->overridden) {
1512                                     $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1513                                 } else if ($quickgrade) {
1514                                     $attributes = array();
1515                                     $attributes['tabindex'] = $tabindex++;
1516                                     $menu = html_writer::label(get_string('assignment:grade', 'assignment'), 'menumenu'. $auser->id, false, array('class' => 'accesshide'));
1517                                     $menu .= html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1518                                     $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1519                                 } else {
1520                                     $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1521                                 }
1522                             }
1523                         ///Print Comment
1524                             if ($final_grade->locked or $final_grade->overridden) {
1525                                 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';
1527                             } else if ($quickgrade) {
1528                                 $comment = '<div id="com'.$auser->id.'">'
1529                                          . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1530                                          . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1531                             } else {
1532                                 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
1533                             }
1534                         } else {
1535                             $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1536                             $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1537                             $status          = '<div id="st'.$auser->id.'">&nbsp;</div>';
1539                             if ($final_grade->locked or $final_grade->overridden) {
1540                                 $grade = '<div id="g'.$auser->id.'">'.$final_grade->formatted_grade . '</div>';
1541                                 $hassubmission = true;
1542                             } else if ($quickgrade) {   // allow editing
1543                                 $attributes = array();
1544                                 $attributes['tabindex'] = $tabindex++;
1545                                 $menu = html_writer::label(get_string('assignment:grade', 'assignment'), 'menumenu'. $auser->id, false, array('class' => 'accesshide'));
1546                                 $menu .= html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1547                                 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1548                                 $hassubmission = true;
1549                             } else {
1550                                 $grade = '<div id="g'.$auser->id.'">-</div>';
1551                             }
1553                             if ($final_grade->locked or $final_grade->overridden) {
1554                                 $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
1555                             } else if ($quickgrade) {
1556                                 $comment = '<div id="com'.$auser->id.'">'
1557                                          . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1558                                          . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1559                             } else {
1560                                 $comment = '<div id="com'.$auser->id.'">&nbsp;</div>';
1561                             }
1562                         }
1564                         if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
1565                             $auser->status = 0;
1566                         } else {
1567                             $auser->status = 1;
1568                         }
1570                         $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
1571                         if ($final_grade->locked or $final_grade->overridden) {
1572                             $buttontext = $strview;
1573                         }
1575                         ///No more buttons, we use popups ;-).
1576                         $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1577                                    . '&amp;userid='.$auser->id.'&amp;mode=single'.'&amp;filter='.$filter.'&amp;offset='.$offset++;
1579                         $button = $OUTPUT->action_link($popup_url, $buttontext);
1581                         $status  = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
1583                         $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';
1585                         $outcomes = '';
1587                         if ($uses_outcomes) {
1589                             foreach($grading_info->outcomes as $n=>$outcome) {
1590                                 $outcomes .= '<div class="outcome"><label for="'. 'outcome_'.$n.'_'.$auser->id .'">'.$outcome->name.'</label>';
1591                                 $options = make_grades_menu(-$outcome->scaleid);
1593                                 if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
1594                                     $options[0] = get_string('nooutcome', 'grades');
1595                                     $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
1596                                 } else {
1597                                     $attributes = array();
1598                                     $attributes['tabindex'] = $tabindex++;
1599                                     $attributes['id'] = 'outcome_'.$n.'_'.$auser->id;
1600                                     $outcomes .= ' '.html_writer::select($options, 'outcome_'.$n.'['.$auser->id.']', $outcome->grades[$auser->id]->grade, array(0=>get_string('nooutcome', 'grades')), $attributes);
1601                                 }
1602                                 $outcomes .= '</div>';
1603                             }
1604                         }
1606                         $userlink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $auser->id . '&amp;course=' . $course->id . '">' . fullname($auser, has_capability('moodle/site:viewfullnames', $this->context)) . '</a>';
1607                         $extradata = array();
1608                         foreach ($extrafields as $field) {
1609                             $extradata[] = $auser->{$field};
1610                         }
1611                         $row = array_merge(array($picture, $userlink), $extradata,
1612                                 array($grade, $comment, $studentmodified, $teachermodified,
1613                                 $status, $finalgrade));
1614                         if ($uses_outcomes) {
1615                             $row[] = $outcomes;
1616                         }
1617                         $table->add_data($row, $rowclass);
1618                     }
1619                     $currentposition++;
1620                 }
1621                 if ($hassubmission && method_exists($this, 'download_submissions')) {
1622                     echo html_writer::start_tag('div', array('class' => 'mod-assignment-download-link'));
1623                     echo html_writer::link(new moodle_url('/mod/assignment/submissions.php', array('id' => $this->cm->id, 'download' => 'zip')), get_string('downloadall', 'assignment'));
1624                     echo html_writer::end_tag('div');
1625                 }
1626                 $table->print_html();  /// Print the whole table
1627             } else {
1628                 if ($filter == self::FILTER_SUBMITTED) {
1629                     echo html_writer::tag('div', get_string('nosubmisson', 'assignment'), array('class'=>'nosubmisson'));
1630                 } else if ($filter == self::FILTER_REQUIRE_GRADING) {
1631                     echo html_writer::tag('div', get_string('norequiregrading', 'assignment'), array('class'=>'norequiregrading'));
1632                 }
1633             }
1634         }
1636         /// Print quickgrade form around the table
1637         if ($quickgrade && $table->started_output && !empty($users)){
1638             $mailinfopref = false;
1639             if (get_user_preferences('assignment_mailinfo', 1)) {
1640                 $mailinfopref = true;
1641             }
1642             $emailnotification =  html_writer::checkbox('mailinfo', 1, $mailinfopref, get_string('enablenotification','assignment'));
1644             $emailnotification .= $OUTPUT->help_icon('enablenotification', 'assignment');
1645             echo html_writer::tag('div', $emailnotification, array('class'=>'emailnotification'));
1647             $savefeedback = html_writer::empty_tag('input', array('type'=>'submit', 'name'=>'fastg', 'value'=>get_string('saveallfeedback', 'assignment')));
1648             echo html_writer::tag('div', $savefeedback, array('class'=>'fastgbutton'));
1650             echo html_writer::end_tag('form');
1651         } else if ($quickgrade) {
1652             echo html_writer::end_tag('form');
1653         }
1655         echo '</div>';
1656         /// End of fast grading form
1658         /// Mini form for setting user preference
1660         $formaction = new moodle_url('/mod/assignment/submissions.php', array('id'=>$this->cm->id));
1661         $mform = new MoodleQuickForm('optionspref', 'post', $formaction, '', array('class'=>'optionspref'));
1663         $mform->addElement('hidden', 'updatepref');
1664         $mform->setDefault('updatepref', 1);
1665         $mform->addElement('header', 'qgprefs', get_string('optionalsettings', 'assignment'));
1666         $mform->addElement('select', 'filter', get_string('show'),  $filters);
1668         $mform->setDefault('filter', $filter);
1670         $mform->addElement('text', 'perpage', get_string('pagesize', 'assignment'), array('size'=>1));
1671         $mform->setDefault('perpage', $perpage);
1673         if ($this->quickgrade_mode_allowed()) {
1674             $mform->addElement('checkbox', 'quickgrade', get_string('quickgrade','assignment'));
1675             $mform->setDefault('quickgrade', $quickgrade);
1676             $mform->addHelpButton('quickgrade', 'quickgrade', 'assignment');
1677         }
1679         $mform->addElement('submit', 'savepreferences', get_string('savepreferences'));
1681         $mform->display();
1683         echo $OUTPUT->footer();
1684     }
1686     /**
1687      * If the form was cancelled ('Cancel' or 'Next' was pressed), call cancel method
1688      * from advanced grading (if applicable) and returns true
1689      * If the form was submitted, validates it and returns false if validation did not pass.
1690      * If validation passes, preprocess advanced grading (if applicable) and returns true.
1691      *
1692      * Note to the developers: This is NOT the correct way to implement advanced grading
1693      * in grading form. The assignment grading was written long time ago and unfortunately
1694      * does not fully use the mforms. Usually function is_validated() is called to
1695      * validate the form and get_data() is called to get the data from the form.
1696      *
1697      * Here we have to push the calculated grade to $_POST['xgrade'] because further processing
1698      * of the form gets the data not from form->get_data(), but from $_POST (using statement
1699      * like  $feedback = data_submitted() )
1700      */
1701     protected function validate_and_preprocess_feedback() {
1702         global $USER, $CFG;
1703         require_once($CFG->libdir.'/gradelib.php');
1704         if (!($feedback = data_submitted()) || !isset($feedback->userid) || !isset($feedback->offset)) {
1705             return true;      // No incoming data, nothing to validate
1706         }
1707         $userid = required_param('userid', PARAM_INT);
1708         $offset = required_param('offset', PARAM_INT);
1709         $gradinginfo = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($userid));
1710         $gradingdisabled = $gradinginfo->items[0]->grades[$userid]->locked || $gradinginfo->items[0]->grades[$userid]->overridden;
1711         if ($gradingdisabled) {
1712             return true;
1713         }
1714         $submissiondata = $this->display_submission($offset, $userid, false);
1715         $mform = $submissiondata->mform;
1716         $gradinginstance = $mform->use_advanced_grading();
1717         if (optional_param('cancel', false, PARAM_BOOL) || optional_param('next', false, PARAM_BOOL)) {
1718             // form was cancelled
1719             if ($gradinginstance) {
1720                 $gradinginstance->cancel();
1721             }
1722         } else if ($mform->is_submitted()) {
1723             // form was submitted (= a submit button other than 'cancel' or 'next' has been clicked)
1724             if (!$mform->is_validated()) {
1725                 return false;
1726             }
1727             // preprocess advanced grading here
1728             if ($gradinginstance) {
1729                 $data = $mform->get_data();
1730                 // create submission if it did not exist yet because we need submission->id for storing the grading instance
1731                 $submission = $this->get_submission($userid, true);
1732                 $_POST['xgrade'] = $gradinginstance->submit_and_get_grade($data->advancedgrading, $submission->id);
1733             }
1734         }
1735         return true;
1736     }
1738     /**
1739      *  Process teacher feedback submission
1740      *
1741      * This is called by submissions() when a grading even has taken place.
1742      * It gets its data from the submitted form.
1743      *
1744      * @global object
1745      * @global object
1746      * @global object
1747      * @return object|bool The updated submission object or false
1748      */
1749     function process_feedback($formdata=null) {
1750         global $CFG, $USER, $DB;
1751         require_once($CFG->libdir.'/gradelib.php');
1753         if (!$feedback = data_submitted() or !confirm_sesskey()) {      // No incoming data?
1754             return false;
1755         }
1757         ///For save and next, we need to know the userid to save, and the userid to go
1758         ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1759         ///as the userid to store
1760         if ((int)$feedback->saveuserid !== -1){
1761             $feedback->userid = $feedback->saveuserid;
1762         }
1764         if (!empty($feedback->cancel)) {          // User hit cancel button
1765             return false;
1766         }
1768         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);
1770         // store outcomes if needed
1771         $this->process_outcomes($feedback->userid);
1773         $submission = $this->get_submission($feedback->userid, true);  // Get or make one
1775         if (!($grading_info->items[0]->grades[$feedback->userid]->locked ||
1776             $grading_info->items[0]->grades[$feedback->userid]->overridden) ) {
1778             $submission->grade      = $feedback->xgrade;
1779             $submission->submissioncomment    = $feedback->submissioncomment_editor['text'];
1780             $submission->teacher    = $USER->id;
1781             $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1782             if (!$mailinfo) {
1783                 $submission->mailed = 1;       // treat as already mailed
1784             } else {
1785                 $submission->mailed = 0;       // Make sure mail goes out (again, even)
1786             }
1787             $submission->timemarked = time();
1789             unset($submission->data1);  // Don't need to update this.
1790             unset($submission->data2);  // Don't need to update this.
1792             if (empty($submission->timemodified)) {   // eg for offline assignments
1793                 // $submission->timemodified = time();
1794             }
1796             $DB->update_record('assignment_submissions', $submission);
1798             // triger grade event
1799             $this->update_grade($submission);
1801             add_to_log($this->course->id, 'assignment', 'update grades',
1802                        'submissions.php?id='.$this->cm->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
1803              if (!is_null($formdata)) {
1804                     if ($this->type == 'upload' || $this->type == 'uploadsingle') {
1805                         $mformdata = $formdata->mform->get_data();
1806                         $mformdata = file_postupdate_standard_filemanager($mformdata, 'files', $formdata->fileui_options, $this->context, 'mod_assignment', 'response', $submission->id);
1807                     }
1808              }
1809         }
1811         return $submission;
1813     }
1815     function process_outcomes($userid) {
1816         global $CFG, $USER;
1818         if (empty($CFG->enableoutcomes)) {
1819             return;
1820         }
1822         require_once($CFG->libdir.'/gradelib.php');
1824         if (!$formdata = data_submitted() or !confirm_sesskey()) {
1825             return;
1826         }
1828         $data = array();
1829         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
1831         if (!empty($grading_info->outcomes)) {
1832             foreach($grading_info->outcomes as $n=>$old) {
1833                 $name = 'outcome_'.$n;
1834                 if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
1835                     $data[$n] = $formdata->{$name}[$userid];
1836                 }
1837             }
1838         }
1839         if (count($data) > 0) {
1840             grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1841         }
1843     }
1845     /**
1846      * Load the submission object for a particular user
1847      *
1848      * @global object
1849      * @global object
1850      * @param int $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1851      * @param bool $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1852      * @param bool $teachermodified student submission set if false
1853      * @return object|bool The submission or false (if $createnew is false and there is no existing submission).
1854      */
1855     function get_submission($userid=0, $createnew=false, $teachermodified=false) {
1856         global $USER, $DB;
1858         if (empty($userid)) {
1859             $userid = $USER->id;
1860         }
1862         $submission = $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1864         if ($submission) {
1865             return $submission;
1866         } else if (!$createnew) {
1867             return false;
1868         }
1869         $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
1870         $DB->insert_record("assignment_submissions", $newsubmission);
1872         return $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1873     }
1875     /**
1876      * Check the given submission is complete. Preliminary rows are often created in the assignment_submissions
1877      * table before a submission actually takes place. This function checks to see if the given submission has actually
1878      * been submitted.
1879      *
1880      * @param  stdClass $submission The submission we want to check for completion
1881      * @return bool                 Indicates if the submission was found to be complete
1882      */
1883     public function is_submitted_with_required_data($submission) {
1884         return $submission->timemodified;
1885     }
1887     /**
1888      * Instantiates a new submission object for a given user
1889      *
1890      * Sets the assignment, userid and times, everything else is set to default values.
1891      *
1892      * @param int $userid The userid for which we want a submission object
1893      * @param bool $teachermodified student submission set if false
1894      * @return object The submission
1895      */
1896     function prepare_new_submission($userid, $teachermodified=false) {
1897         $submission = new stdClass();
1898         $submission->assignment   = $this->assignment->id;
1899         $submission->userid       = $userid;
1900         $submission->timecreated = time();
1901         // teachers should not be modifying modified date, except offline assignments
1902         if ($teachermodified) {
1903             $submission->timemodified = 0;
1904         } else {
1905             $submission->timemodified = $submission->timecreated;
1906         }
1907         $submission->numfiles     = 0;
1908         $submission->data1        = '';
1909         $submission->data2        = '';
1910         $submission->grade        = -1;
1911         $submission->submissioncomment      = '';
1912         $submission->format       = 0;
1913         $submission->teacher      = 0;
1914         $submission->timemarked   = 0;
1915         $submission->mailed       = 0;
1916         return $submission;
1917     }
1919     /**
1920      * Return all assignment submissions by ENROLLED students (even empty)
1921      *
1922      * @param string $sort optional field names for the ORDER BY in the sql query
1923      * @param string $dir optional specifying the sort direction, defaults to DESC
1924      * @return array The submission objects indexed by id
1925      */
1926     function get_submissions($sort='', $dir='DESC') {
1927         return assignment_get_all_submissions($this->assignment, $sort, $dir);
1928     }
1930     /**
1931      * Counts all complete (real) assignment submissions by enrolled students
1932      *
1933      * @param  int $groupid (optional) If nonzero then count is restricted to this group
1934      * @return int          The number of submissions
1935      */
1936     function count_real_submissions($groupid=0) {
1937         global $CFG;
1938         global $DB;
1940         // Grab the context assocated with our course module
1941         $context = context_module::instance($this->cm->id);
1943         // Get ids of users enrolled in the given course.
1944         list($enroledsql, $params) = get_enrolled_sql($context, 'mod/assignment:view', $groupid);
1945         $params['assignmentid'] = $this->cm->instance;
1947         // Get ids of users enrolled in the given course.
1948         return $DB->count_records_sql("SELECT COUNT('x')
1949                                          FROM {assignment_submissions} s
1950                                     LEFT JOIN {assignment} a ON a.id = s.assignment
1951                                    INNER JOIN ($enroledsql) u ON u.id = s.userid
1952                                         WHERE s.assignment = :assignmentid AND
1953                                               s.timemodified > 0", $params);
1954     }
1956     /**
1957      * Alerts teachers by email of new or changed assignments that need grading
1958      *
1959      * First checks whether the option to email teachers is set for this assignment.
1960      * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1961      * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1962      *
1963      * @global object
1964      * @global object
1965      * @param $submission object The submission that has changed
1966      * @return void
1967      */
1968     function email_teachers($submission) {
1969         global $CFG, $DB;
1971         if (empty($this->assignment->emailteachers)) {          // No need to do anything
1972             return;
1973         }
1975         $user = $DB->get_record('user', array('id'=>$submission->userid));
1977         if ($teachers = $this->get_graders($user)) {
1979             $strassignments = get_string('modulenameplural', 'assignment');
1980             $strassignment  = get_string('modulename', 'assignment');
1981             $strsubmitted  = get_string('submitted', 'assignment');
1983             foreach ($teachers as $teacher) {
1984                 $info = new stdClass();
1985                 $info->username = fullname($user, true);
1986                 $info->assignment = format_string($this->assignment->name,true);
1987                 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
1988                 $info->timeupdated = userdate($submission->timemodified, '%c', $teacher->timezone);
1990                 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1991                 $posttext = $this->email_teachers_text($info);
1992                 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
1994                 $eventdata = new stdClass();
1995                 $eventdata->modulename       = 'assignment';
1996                 $eventdata->userfrom         = $user;
1997                 $eventdata->userto           = $teacher;
1998                 $eventdata->subject          = $postsubject;
1999                 $eventdata->fullmessage      = $posttext;
2000                 $eventdata->fullmessageformat = FORMAT_PLAIN;
2001                 $eventdata->fullmessagehtml  = $posthtml;
2002                 $eventdata->smallmessage     = $postsubject;
2004                 $eventdata->name            = 'assignment_updates';
2005                 $eventdata->component       = 'mod_assignment';
2006                 $eventdata->notification    = 1;
2007                 $eventdata->contexturl      = $info->url;
2008                 $eventdata->contexturlname  = $info->assignment;
2010                 message_send($eventdata);
2011             }
2012         }
2013     }
2015     /**
2016      * Sends a file
2017      *
2018      * @param string $filearea
2019      * @param array $args
2020      * @param bool $forcedownload whether or not force download
2021      * @param array $options additional options affecting the file serving
2022      * @return bool
2023      */
2024     function send_file($filearea, $args, $forcedownload, array $options=array()) {
2025         debugging('plugin does not implement file sending', DEBUG_DEVELOPER);
2026         return false;
2027     }
2029     /**
2030      * Returns a list of teachers that should be grading given submission
2031      *
2032      * @param object $user
2033      * @return array
2034      */
2035     function get_graders($user) {
2036         global $DB;
2038         //potential graders
2039         list($enrolledsql, $params) = get_enrolled_sql($this->context, 'mod/assignment:grade', 0, true);
2040         $sql = "SELECT u.*
2041                   FROM {user} u
2042                   JOIN ($enrolledsql) je ON je.id = u.id";
2043         $potgraders = $DB->get_records_sql($sql, $params);
2045         $graders = array();
2046         if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) {   // Separate groups are being used
2047             if ($groups = groups_get_all_groups($this->course->id, $user->id)) {  // Try to find all groups
2048                 foreach ($groups as $group) {
2049                     foreach ($potgraders as $t) {
2050                         if ($t->id == $user->id) {
2051                             continue; // do not send self
2052                         }
2053                         if (groups_is_member($group->id, $t->id)) {
2054                             $graders[$t->id] = $t;
2055                         }
2056                     }
2057                 }
2058             } else {
2059                 // user not in group, try to find graders without group
2060                 foreach ($potgraders as $t) {
2061                     if ($t->id == $user->id) {
2062                         continue; // do not send self
2063                     }
2064                     if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
2065                         $graders[$t->id] = $t;
2066                     }
2067                 }
2068             }
2069         } else {
2070             foreach ($potgraders as $t) {
2071                 if ($t->id == $user->id) {
2072                     continue; // do not send self
2073                 }
2074                 $graders[$t->id] = $t;
2075             }
2076         }
2077         return $graders;
2078     }
2080     /**
2081      * Creates the text content for emails to teachers
2082      *
2083      * @param $info object The info used by the 'emailteachermail' language string
2084      * @return string
2085      */
2086     function email_teachers_text($info) {
2087         $posttext  = format_string($this->course->shortname, true, array('context' => $this->coursecontext)).' -> '.
2088                      $this->strassignments.' -> '.
2089                      format_string($this->assignment->name, true, array('context' => $this->context))."\n";
2090         $posttext .= '---------------------------------------------------------------------'."\n";
2091         $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
2092         $posttext .= "\n---------------------------------------------------------------------\n";
2093         return $posttext;
2094     }
2096      /**
2097      * Creates the html content for emails to teachers
2098      *
2099      * @param $info object The info used by the 'emailteachermailhtml' language string
2100      * @return string
2101      */
2102     function email_teachers_html($info) {
2103         global $CFG;
2104         $posthtml  = '<p><font face="sans-serif">'.
2105                      '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname, true, array('context' => $this->coursecontext)).'</a> ->'.
2106                      '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
2107                      '<a href="'.$CFG->wwwroot.'/mod/assignment/view.php?id='.$this->cm->id.'">'.format_string($this->assignment->name, true, array('context' => $this->context)).'</a></font></p>';
2108         $posthtml .= '<hr /><font face="sans-serif">';
2109         $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
2110         $posthtml .= '</font><hr />';
2111         return $posthtml;
2112     }
2114     /**
2115      * Produces a list of links to the files uploaded by a user
2116      *
2117      * @param $userid int optional id of the user. If 0 then $USER->id is used.
2118      * @param $return boolean optional defaults to false. If true the list is returned rather than printed
2119      * @return string optional
2120      */
2121     function print_user_files($userid=0, $return=false) {
2122         global $CFG, $USER, $OUTPUT;
2124         if (!$userid) {
2125             if (!isloggedin()) {
2126                 return '';
2127             }
2128             $userid = $USER->id;
2129         }
2131         $output = '';
2133         $submission = $this->get_submission($userid);
2134         if (!$submission) {
2135             return $output;
2136         }
2138         $fs = get_file_storage();
2139         $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false);
2140         if (!empty($files)) {
2141             require_once($CFG->dirroot . '/mod/assignment/locallib.php');
2142             if ($CFG->enableportfolios) {
2143                 require_once($CFG->libdir.'/portfoliolib.php');
2144                 $button = new portfolio_add_button();
2145             }
2146             foreach ($files as $file) {
2147                 $filename = $file->get_filename();
2148                 $mimetype = $file->get_mimetype();
2149                 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/mod_assignment/submission/'.$submission->id.'/'.$filename);
2150                 $output .= '<a href="'.$path.'" >'.$OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon')).s($filename).'</a>';
2151                 if ($CFG->enableportfolios && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
2152                     $button->set_callback_options('assignment_portfolio_caller',
2153                                                   array('id' => $this->cm->id, 'submissionid' => $submission->id, 'fileid' => $file->get_id()),
2154                                                   'mod_assignment');
2155                     $button->set_format_by_file($file);
2156                     $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
2157                 }
2159                 if ($CFG->enableplagiarism) {
2160                     require_once($CFG->libdir.'/plagiarismlib.php');
2161                     $output .= plagiarism_get_links(array('userid'=>$userid, 'file'=>$file, 'cmid'=>$this->cm->id, 'course'=>$this->course, 'assignment'=>$this->assignment));
2162                     $output .= '<br />';
2163                 }
2164             }
2165             if ($CFG->enableportfolios && count($files) > 1  && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
2166                 $button->set_callback_options('assignment_portfolio_caller',
2167                                               array('id' => $this->cm->id, 'submissionid' => $submission->id),
2168                                               'mod_assignment');
2169                 $output .= '<br />'  . $button->to_html(PORTFOLIO_ADD_TEXT_LINK);
2170             }
2171         }
2173         $output = '<div class="files">'.$output.'</div>';
2175         if ($return) {
2176             return $output;
2177         }
2178         echo $output;
2179     }
2181     /**
2182      * Count the files uploaded by a given user
2183      *
2184      * @param $itemid int The submission's id as the file's itemid.
2185      * @return int
2186      */
2187     function count_user_files($itemid) {
2188         $fs = get_file_storage();
2189         $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $itemid, "id", false);
2190         return count($files);
2191     }
2193     /**
2194      * Returns true if the student is allowed to submit
2195      *
2196      * Checks that the assignment has started and, if the option to prevent late
2197      * submissions is set, also checks that the assignment has not yet closed.
2198      * @return boolean
2199      */
2200     function isopen() {
2201         $time = time();
2202         if ($this->assignment->preventlate && $this->assignment->timedue) {
2203             return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
2204         } else {
2205             return ($this->assignment->timeavailable <= $time);
2206         }
2207     }
2210     /**
2211      * Return true if is set description is hidden till available date
2212      *
2213      * This is needed by calendar so that hidden descriptions do not
2214      * come up in upcoming events.
2215      *
2216      * Check that description is hidden till available date
2217      * By default return false
2218      * Assignments types should implement this method if needed
2219      * @return boolen
2220      */
2221     function description_is_hidden() {
2222         return false;
2223     }
2225     /**
2226      * Return an outline of the user's interaction with the assignment
2227      *
2228      * The default method prints the grade and timemodified
2229      * @param $grade object
2230      * @return object with properties ->info and ->time
2231      */
2232     function user_outline($grade) {
2234         $result = new stdClass();
2235         $result->info = get_string('grade').': '.$grade->str_long_grade;
2236         $result->time = $grade->dategraded;
2237         return $result;
2238     }
2240     /**
2241      * Print complete information about the user's interaction with the assignment
2242      *
2243      * @param $user object
2244      */
2245     function user_complete($user, $grade=null) {
2246         global $OUTPUT;
2248         if ($submission = $this->get_submission($user->id)) {
2250             $fs = get_file_storage();
2252             if ($files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false)) {
2253                 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
2254                 foreach ($files as $file) {
2255                     $countfiles .= "; ".$file->get_filename();
2256                 }
2257             }
2259             echo $OUTPUT->box_start();
2260             echo get_string("lastmodified").": ";
2261             echo userdate($submission->timemodified);
2262             echo $this->display_lateness($submission->timemodified);
2264             $this->print_user_files($user->id);
2266             echo '<br />';
2268             $this->view_feedback($submission);
2270             echo $OUTPUT->box_end();
2272         } else {
2273             if ($grade) {
2274                 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
2275                 if ($grade->str_feedback) {
2276                     echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
2277                 }
2278             }
2279             print_string("notsubmittedyet", "assignment");
2280         }
2281     }
2283     /**
2284      * Return a string indicating how late a submission is
2285      *
2286      * @param $timesubmitted int
2287      * @return string
2288      */
2289     function display_lateness($timesubmitted) {
2290         return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
2291     }
2293     /**
2294      * Empty method stub for all delete actions.
2295      */
2296     function delete() {
2297         //nothing by default
2298         redirect('view.php?id='.$this->cm->id);
2299     }
2301     /**
2302      * Empty custom feedback grading form.
2303      */
2304     function custom_feedbackform($submission, $return=false) {
2305         //nothing by default
2306         return '';
2307     }
2309     /**
2310      * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
2311      * for the course (see resource).
2312      *
2313      * Given a course_module object, this function returns any "extra" information that may be needed
2314      * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
2315      *
2316      * @param $coursemodule object The coursemodule object (record).
2317      * @return cached_cm_info Object used to customise appearance on course page
2318      */
2319     function get_coursemodule_info($coursemodule) {
2320         return null;
2321     }
2323     /**
2324      * Plugin cron method - do not use $this here, create new assignment instances if needed.
2325      * @return void
2326      */
2327     function cron() {
2328         //no plugin cron by default - override if needed
2329     }
2331     /**
2332      * Reset all submissions
2333      */
2334     function reset_userdata($data) {
2335         global $CFG, $DB;
2337         if (!$DB->count_records('assignment', array('course'=>$data->courseid, 'assignmenttype'=>$this->type))) {
2338             return array(); // no assignments of this type present
2339         }
2341         $componentstr = get_string('modulenameplural', 'assignment');
2342         $status = array();
2344         $typestr = get_string('type'.$this->type, 'assignment');
2345         // ugly hack to support pluggable assignment type titles...
2346         if($typestr === '[[type'.$this->type.']]'){
2347             $typestr = get_string('type'.$this->type, 'assignment_'.$this->type);
2348         }
2350         if (!empty($data->reset_assignment_submissions)) {
2351             $assignmentssql = "SELECT a.id
2352                                  FROM {assignment} a
2353                                 WHERE a.course=? AND a.assignmenttype=?";
2354             $params = array($data->courseid, $this->type);
2356             // now get rid of all submissions and responses
2357             $fs = get_file_storage();
2358             if ($assignments = $DB->get_records_sql($assignmentssql, $params)) {
2359                 foreach ($assignments as $assignmentid=>$unused) {
2360                     if (!$cm = get_coursemodule_from_instance('assignment', $assignmentid)) {
2361                         continue;
2362                     }
2363                     $context = context_module::instance($cm->id);
2364                     $fs->delete_area_files($context->id, 'mod_assignment', 'submission');
2365                     $fs->delete_area_files($context->id, 'mod_assignment', 'response');
2366                 }
2367             }
2369             $DB->delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)", $params);
2371             $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
2373             if (empty($data->reset_gradebook_grades)) {
2374                 // remove all grades from gradebook
2375                 assignment_reset_gradebook($data->courseid, $this->type);
2376             }
2377         }
2379         /// updating dates - shift may be negative too
2380         if ($data->timeshift) {
2381             shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
2382             $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
2383         }
2385         return $status;
2386     }
2389     function portfolio_exportable() {
2390         return false;
2391     }
2393     /**
2394      * base implementation for backing up subtype specific information
2395      * for one single module
2396      *
2397      * @param filehandle $bf file handle for xml file to write to
2398      * @param mixed $preferences the complete backup preference object
2399      *
2400      * @return boolean
2401      *
2402      * @static
2403      */
2404     static function backup_one_mod($bf, $preferences, $assignment) {
2405         return true;
2406     }
2408     /**
2409      * base implementation for backing up subtype specific information
2410      * for one single submission
2411      *
2412      * @param filehandle $bf file handle for xml file to write to
2413      * @param mixed $preferences the complete backup preference object
2414      * @param object $submission the assignment submission db record
2415      *
2416      * @return boolean
2417      *
2418      * @static
2419      */
2420     static function backup_one_submission($bf, $preferences, $assignment, $submission) {
2421         return true;
2422     }
2424     /**
2425      * base implementation for restoring subtype specific information
2426      * for one single module
2427      *
2428      * @param array  $info the array representing the xml
2429      * @param object $restore the restore preferences
2430      *
2431      * @return boolean
2432      *
2433      * @static
2434      */
2435     static function restore_one_mod($info, $restore, $assignment) {
2436         return true;
2437     }
2439     /**
2440      * base implementation for restoring subtype specific information
2441      * for one single submission
2442      *
2443      * @param object $submission the newly created submission
2444      * @param array  $info the array representing the xml
2445      * @param object $restore the restore preferences
2446      *
2447      * @return boolean
2448      *
2449      * @static
2450      */
2451     static function restore_one_submission($info, $restore, $assignment, $submission) {
2452         return true;
2453     }
2455 } ////// End of the assignment_base class
2458 class assignment_grading_form extends moodleform {
2459     /** @var stores the advaned grading instance (if used in grading) */
2460     private $advancegradinginstance;
2462     function definition() {
2463         global $OUTPUT;
2464         $mform =& $this->_form;
2466         if (isset($this->_customdata->advancedgradinginstance)) {
2467             $this->use_advanced_grading($this->_customdata->advancedgradinginstance);
2468         }
2470         $formattr = $mform->getAttributes();
2471         $formattr['id'] = 'submitform';
2472         $mform->setAttributes($formattr);
2473         // hidden params
2474         $mform->addElement('hidden', 'offset', ($this->_customdata->offset+1));
2475         $mform->setType('offset', PARAM_INT);
2476         $mform->addElement('hidden', 'userid', $this->_customdata->userid);
2477         $mform->setType('userid', PARAM_INT);
2478         $mform->addElement('hidden', 'nextid', $this->_customdata->nextid);
2479         $mform->setType('nextid', PARAM_INT);
2480         $mform->addElement('hidden', 'id', $this->_customdata->cm->id);
2481         $mform->setType('id', PARAM_INT);
2482         $mform->addElement('hidden', 'sesskey', sesskey());
2483         $mform->setType('sesskey', PARAM_ALPHANUM);
2484         $mform->addElement('hidden', 'mode', 'grade');
2485         $mform->setType('mode', PARAM_TEXT);
2486         $mform->addElement('hidden', 'menuindex', "0");
2487         $mform->setType('menuindex', PARAM_INT);
2488         $mform->addElement('hidden', 'saveuserid', "-1");
2489         $mform->setType('saveuserid', PARAM_INT);
2490         $mform->addElement('hidden', 'filter', "0");
2491         $mform->setType('filter', PARAM_INT);
2493         $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->user),
2494                                                 fullname($this->_customdata->user, true) . '<br/>' .
2495                                                 userdate($this->_customdata->submission->timemodified) .
2496                                                 $this->_customdata->lateness );
2498         $this->add_submission_content();
2499         $this->add_grades_section();
2501         $this->add_feedback_section();
2503         if ($this->_customdata->submission->timemarked) {
2504             $datestring = userdate($this->_customdata->submission->timemarked)."&nbsp; (".format_time(time() - $this->_customdata->submission->timemarked).")";
2505             $mform->addElement('header', 'Last Grade', get_string('lastgrade', 'assignment'));
2506             $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->teacher) ,
2507                                                     fullname($this->_customdata->teacher,true).
2508                                                     '<br/>'.$datestring);
2509         }
2510         // buttons
2511         $this->add_action_buttons();
2513     }
2515     /**
2516      * Gets or sets the instance for advanced grading
2517      *
2518      * @param gradingform_instance $gradinginstance
2519      */
2520     public function use_advanced_grading($gradinginstance = false) {
2521         if ($gradinginstance !== false) {
2522             $this->advancegradinginstance = $gradinginstance;
2523         }
2524         return $this->advancegradinginstance;
2525     }
2527     /**
2528      * Add the grades configuration section to the assignment configuration form
2529      */
2530     function add_grades_section() {
2531         global $CFG;
2532         $mform =& $this->_form;
2533         $attributes = array();
2534         if ($this->_customdata->gradingdisabled) {
2535             $attributes['disabled'] ='disabled';
2536         }
2538         $mform->addElement('header', 'Grades', get_string('grades', 'grades'));
2540         $grademenu = make_grades_menu($this->_customdata->assignment->grade);
2541         if ($gradinginstance = $this->use_advanced_grading()) {
2542             $gradinginstance->get_controller()->set_grade_range($grademenu);
2543             $gradingelement = $mform->addElement('grading', 'advancedgrading', get_string('grade').':', array('gradinginstance' => $gradinginstance));
2544             if ($this->_customdata->gradingdisabled) {
2545                 $gradingelement->freeze();
2546             } else {
2547                 $mform->addElement('hidden', 'advancedgradinginstanceid', $gradinginstance->get_id());
2548             }
2549         } else {
2550             // use simple direct grading
2551             $grademenu['-1'] = get_string('nograde');
2553             $mform->addElement('select', 'xgrade', get_string('grade').':', $grademenu, $attributes);
2554             $mform->setDefault('xgrade', $this->_customdata->submission->grade ); //@fixme some bug when element called 'grade' makes it break
2555             $mform->setType('xgrade', PARAM_INT);
2556         }
2558         if (!empty($this->_customdata->enableoutcomes)) {
2559             foreach($this->_customdata->grading_info->outcomes as $n=>$outcome) {
2560                 $options = make_grades_menu(-$outcome->scaleid);
2561                 if ($outcome->grades[$this->_customdata->submission->userid]->locked) {
2562                     $options[0] = get_string('nooutcome', 'grades');
2563                     $mform->addElement('static', 'outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->name.':',
2564                             $options[$outcome->grades[$this->_customdata->submission->userid]->grade]);
2565                 } else {
2566                     $options[''] = get_string('nooutcome', 'grades');
2567                     $attributes = array('id' => 'menuoutcome_'.$n );
2568                     $mform->addElement('select', 'outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->name.':', $options, $attributes );
2569                     $mform->setType('outcome_'.$n.'['.$this->_customdata->userid.']', PARAM_INT);
2570                     $mform->setDefault('outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->grades[$this->_customdata->submission->userid]->grade );
2571                 }
2572             }
2573         }
2574         $course_context = context_module::instance($this->_customdata->cm->id);
2575         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
2576             $grade = '<a href="'.$CFG->wwwroot.'/grade/report/grader/index.php?id='. $this->_customdata->courseid .'" >'.
2577                         $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade . '</a>';
2578         }else{
2579             $grade = $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade;
2580         }
2581         $mform->addElement('static', 'finalgrade', get_string('currentgrade', 'assignment').':' ,$grade);
2582         $mform->setType('finalgrade', PARAM_INT);
2583     }
2585     /**
2586      *
2587      * @global core_renderer $OUTPUT
2588      */
2589     function add_feedback_section() {
2590         global $OUTPUT;
2591         $mform =& $this->_form;
2592         $mform->addElement('header', 'Feed Back', get_string('feedback', 'grades'));
2594         if ($this->_customdata->gradingdisabled) {
2595             $mform->addElement('static', 'disabledfeedback', $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_feedback );
2596         } else {
2597             // visible elements
2599             $mform->addElement('editor', 'submissioncomment_editor', get_string('feedback', 'assignment').':', null, $this->get_editor_options() );
2600             $mform->setType('submissioncomment_editor', PARAM_RAW); // to be cleaned before display
2601             $mform->setDefault('submissioncomment_editor', $this->_customdata->submission->submissioncomment);
2602             //$mform->addRule('submissioncomment', get_string('required'), 'required', null, 'client');
2603             switch ($this->_customdata->assignment->assignmenttype) {
2604                 case 'upload' :
2605                 case 'uploadsingle' :
2606                     $mform->addElement('filemanager', 'files_filemanager', get_string('responsefiles', 'assignment'). ':', null, $this->_customdata->fileui_options);
2607                     break;
2608                 default :
2609                     break;
2610             }
2611             $mform->addElement('hidden', 'mailinfo_h', "0");
2612             $mform->setType('mailinfo_h', PARAM_INT);
2613             $mform->addElement('checkbox', 'mailinfo',get_string('enablenotification','assignment').
2614             $OUTPUT->help_icon('enablenotification', 'assignment') .':' );
2615             $mform->setType('mailinfo', PARAM_INT);
2616         }
2617     }
2619     function add_action_buttons($cancel = true, $submitlabel = NULL) {
2620         $mform =& $this->_form;
2621         //if there are more to be graded.
2622         if ($this->_customdata->nextid>0) {
2623             $buttonarray=array();
2624             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2625             //@todo: fix accessibility: javascript dependency not necessary
2626             $buttonarray[] = &$mform->createElement('submit', 'saveandnext', get_string('saveandnext'));
2627             $buttonarray[] = &$mform->createElement('submit', 'next', get_string('next'));
2628             $buttonarray[] = &$mform->createElement('cancel');
2629         } else {
2630             $buttonarray=array();
2631             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2632             $buttonarray[] = &$mform->createElement('cancel');
2633         }
2634         $mform->addGroup($buttonarray, 'grading_buttonar', '', array(' '), false);
2635         $mform->closeHeaderBefore('grading_buttonar');
2636         $mform->setType('grading_buttonar', PARAM_RAW);
2637     }
2639     function add_submission_content() {
2640         $mform =& $this->_form;
2641         $mform->addElement('header', 'Submission', get_string('submission', 'assignment'));
2642         $mform->addElement('static', '', '' , $this->_customdata->submission_content );
2643     }
2645     protected function get_editor_options() {
2646         $editoroptions = array();
2647         $editoroptions['component'] = 'mod_assignment';
2648         $editoroptions['filearea'] = 'feedback';
2649         $editoroptions['noclean'] = false;
2650         $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)
2651         $editoroptions['maxbytes'] = $this->_customdata->maxbytes;
2652         $editoroptions['context'] = $this->_customdata->context;
2653         return $editoroptions;
2654     }
2656     public function set_data($data) {
2657         $editoroptions = $this->get_editor_options();
2658         if (!isset($data->text)) {
2659             $data->text = '';
2660         }
2661         if (!isset($data->format)) {
2662             $data->textformat = FORMAT_HTML;
2663         } else {
2664             $data->textformat = $data->format;
2665         }
2667         if (!empty($this->_customdata->submission->id)) {
2668             $itemid = $this->_customdata->submission->id;
2669         } else {
2670             $itemid = null;
2671         }
2673         switch ($this->_customdata->assignment->assignmenttype) {
2674                 case 'upload' :
2675                 case 'uploadsingle' :
2676                     $data = file_prepare_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2677                     break;
2678                 default :
2679                     break;
2680         }
2682         $data = file_prepare_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2683         return parent::set_data($data);
2684     }
2686     public function get_data() {
2687         $data = parent::get_data();
2689         if (!empty($this->_customdata->submission->id)) {
2690             $itemid = $this->_customdata->submission->id;
2691         } else {
2692             $itemid = null; //TODO: this is wrong, itemid MUST be known when saving files!! (skodak)
2693         }
2695         if ($data) {
2696             $editoroptions = $this->get_editor_options();
2697             switch ($this->_customdata->assignment->assignmenttype) {
2698                 case 'upload' :
2699                 case 'uploadsingle' :
2700                     $data = file_postupdate_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2701                     break;
2702                 default :
2703                     break;
2704             }
2705             $data = file_postupdate_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2706         }
2708         if ($this->use_advanced_grading() && !isset($data->advancedgrading)) {
2709             $data->advancedgrading = null;
2710         }
2712         return $data;
2713     }
2716 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
2718 /**
2719  * Deletes an assignment instance
2720  *
2721  * This is done by calling the delete_instance() method of the assignment type class
2722  */
2723 function assignment_delete_instance($id){
2724     global $CFG, $DB;
2726     if (! $assignment = $DB->get_record('assignment', array('id'=>$id))) {
2727         return false;
2728     }
2730     // fall back to base class if plugin missing
2731     $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2732     if (file_exists($classfile)) {
2733         require_once($classfile);
2734         $assignmentclass = "assignment_$assignment->assignmenttype";
2736     } else {
2737         debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
2738         $assignmentclass = "assignment_base";
2739     }
2741     $ass = new $assignmentclass();
2742     return $ass->delete_instance($assignment);
2746 /**
2747  * Updates an assignment instance
2748  *
2749  * This is done by calling the update_instance() method of the assignment type class
2750  */
2751 function assignment_update_instance($assignment){
2752     global $CFG;
2754     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_PLUGIN);
2756     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2757     $assignmentclass = "assignment_$assignment->assignmenttype";
2758     $ass = new $assignmentclass();
2759     return $ass->update_instance($assignment);
2763 /**
2764  * Adds an assignment instance
2765  *
2766  * This is done by calling the add_instance() method of the assignment type class
2767  *
2768  * @param stdClass $assignment
2769  * @param mod_assignment_mod_form $mform
2770  * @return int intance id
2771  */
2772 function assignment_add_instance($assignment, $mform = null) {
2773     global $CFG;
2775     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_PLUGIN);
2777     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2778     $assignmentclass = "assignment_$assignment->assignmenttype";
2779     $ass = new $assignmentclass();
2780     return $ass->add_instance($assignment);
2784 /**
2785  * Returns an outline of a user interaction with an assignment
2786  *
2787  * This is done by calling the user_outline() method of the assignment type class
2788  */
2789 function assignment_user_outline($course, $user, $mod, $assignment) {
2790     global $CFG;
2792     require_once("$CFG->libdir/gradelib.php");
2793     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2794     $assignmentclass = "assignment_$assignment->assignmenttype";
2795     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2796     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2797     if (!empty($grades->items[0]->grades)) {
2798         return $ass->user_outline(reset($grades->items[0]->grades));
2799     } else {
2800         return null;
2801     }
2804 /**
2805  * Prints the complete info about a user's interaction with an assignment
2806  *
2807  * This is done by calling the user_complete() method of the assignment type class
2808  */
2809 function assignment_user_complete($course, $user, $mod, $assignment) {
2810     global $CFG;
2812     require_once("$CFG->libdir/gradelib.php");
2813     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2814     $assignmentclass = "assignment_$assignment->assignmenttype";
2815     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2816     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2817     if (empty($grades->items[0]->grades)) {
2818         $grade = false;
2819     } else {
2820         $grade = reset($grades->items[0]->grades);
2821     }
2822     return $ass->user_complete($user, $grade);
2825 /**
2826  * Function to be run periodically according to the moodle cron
2827  *
2828  * Finds all assignment notifications that have yet to be mailed out, and mails them
2829  */
2830 function assignment_cron () {
2831     global $CFG, $USER, $DB;
2833     /// first execute all crons in plugins
2834     if ($plugins = get_plugin_list('assignment')) {
2835         foreach ($plugins as $plugin=>$dir) {
2836             require_once("$dir/assignment.class.php");
2837             $assignmentclass = "assignment_$plugin";
2838             $ass = new $assignmentclass();
2839             $ass->cron();
2840         }
2841     }
2843     /// Notices older than 1 day will not be mailed.  This is to avoid the problem where
2844     /// cron has not been running for a long time, and then suddenly people are flooded
2845     /// with mail from the past few weeks or months
2847     $timenow   = time();
2848     $endtime   = $timenow - $CFG->maxeditingtime;
2849     $starttime = $endtime - 24 * 3600;   /// One day earlier
2851     if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2853         $realuser = clone($USER);
2855         foreach ($submissions as $key => $submission) {
2856             $DB->set_field("assignment_submissions", "mailed", "1", array("id"=>$submission->id));
2857         }
2859         $timenow = time();
2861         foreach ($submissions as $submission) {
2863             echo "Processing assignment submission $submission->id\n";
2865             if (! $user = $DB->get_record("user", array("id"=>$submission->userid))) {
2866                 echo "Could not find user $user->id\n";
2867                 continue;
2868             }
2870             if (! $course = $DB->get_record("course", array("id"=>$submission->course))) {
2871                 echo "Could not find course $submission->course\n";
2872                 continue;
2873             }
2875             /// Override the language and timezone of the "current" user, so that
2876             /// mail is customised for the receiver.
2877             cron_setup_user($user, $course);
2879             $coursecontext = context_course::instance($submission->course);
2880             $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
2881             if (!is_enrolled($coursecontext, $user->id)) {
2882                 echo fullname($user)." not an active participant in " . $courseshortname . "\n";
2883                 continue;
2884             }
2886             if (! $teacher = $DB->get_record("user", array("id"=>$submission->teacher))) {
2887                 echo "Could not find teacher $submission->teacher\n";
2888                 continue;
2889             }
2891             if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2892                 echo "Could not find course module for assignment id $submission->assignment\n";
2893                 continue;
2894             }
2896             if (! $mod->visible) {    /// Hold mail notification for hidden assignments until later
2897                 continue;
2898             }
2900             $strassignments = get_string("modulenameplural", "assignment");
2901             $strassignment  = get_string("modulename", "assignment");
2903             $assignmentinfo = new stdClass();
2904             $assignmentinfo->teacher = fullname($teacher);
2905             $assignmentinfo->assignment = format_string($submission->name,true);
2906             $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2908             $postsubject = "$courseshortname: $strassignments: ".format_string($submission->name,true);
2909             $posttext  = "$courseshortname -> $strassignments -> ".format_string($submission->name,true)."\n";
2910             $posttext .= "---------------------------------------------------------------------\n";
2911             $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2912             $posttext .= "---------------------------------------------------------------------\n";
2914             if ($user->mailformat == 1) {  // HTML
2915                 $posthtml = "<p><font face=\"sans-serif\">".
2916                 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$courseshortname</a> ->".
2917                 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2918                 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2919                 $posthtml .= "<hr /><font face=\"sans-serif\">";
2920                 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2921                 $posthtml .= "</font><hr />";
2922             } else {
2923                 $posthtml = "";
2924             }
2926             $eventdata = new stdClass();
2927             $eventdata->modulename       = 'assignment';
2928             $eventdata->userfrom         = $teacher;
2929             $eventdata->userto           = $user;
2930             $eventdata->subject          = $postsubject;
2931             $eventdata->fullmessage      = $posttext;
2932             $eventdata->fullmessageformat = FORMAT_PLAIN;
2933             $eventdata->fullmessagehtml  = $posthtml;
2934             $eventdata->smallmessage     = get_string('assignmentmailsmall', 'assignment', $assignmentinfo);
2936             $eventdata->name            = 'assignment_updates';
2937             $eventdata->component       = 'mod_assignment';
2938             $eventdata->notification    = 1;
2939             $eventdata->contexturl      = $assignmentinfo->url;
2940             $eventdata->contexturlname  = $assignmentinfo->assignment;
2942             message_send($eventdata);
2943         }
2945         cron_setup_user();
2946     }
2948     return true;
2951 /**
2952  * Return grade for given user or all users.
2953  *
2954  * @param stdClass $assignment An assignment instance
2955  * @param int $userid Optional user id, 0 means all users
2956  * @return array An array of grades, false if none
2957  */
2958 function assignment_get_user_grades($assignment, $userid=0) {
2959     global $CFG, $DB;
2961     if ($userid) {
2962         $user = "AND u.id = :userid";
2963         $params = array('userid'=>$userid);
2964     } else {
2965         $user = "";
2966     }
2967     $params['aid'] = $assignment->id;
2969     $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2970                    s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2971               FROM {user} u, {assignment_submissions} s
2972              WHERE u.id = s.userid AND s.assignment = :aid
2973                    $user";
2975     return $DB->get_records_sql($sql, $params);
2978 /**
2979  * Update activity grades
2980  *
2981  * @category grade
2982  * @param stdClass $assignment Assignment instance
2983  * @param int $userid specific user only, 0 means all
2984  * @param bool $nullifnone Not used
2985  */
2986 function assignment_update_grades($assignment, $userid=0, $nullifnone=true) {
2987     global $CFG, $DB;
2988     require_once($CFG->libdir.'/gradelib.php');
2990     if ($assignment->grade == 0) {
2991         assignment_grade_item_update($assignment);
2993     } else if ($grades = assignment_get_user_grades($assignment, $userid)) {
2994         foreach($grades as $k=>$v) {
2995             if ($v->rawgrade == -1) {
2996                 $grades[$k]->rawgrade = null;
2997             }
2998         }
2999         assignment_grade_item_update($assignment, $grades);
3001     } else {
3002         assignment_grade_item_update($assignment);
3003     }
3006 /**
3007  * Update all grades in gradebook.
3008  */
3009 function assignment_upgrade_grades() {
3010     global $DB;
3012     $sql = "SELECT COUNT('x')
3013               FROM {assignment} a, {course_modules} cm, {modules} m
3014              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
3015     $count = $DB->count_records_sql($sql);
3017     $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
3018               FROM {assignment} a, {course_modules} cm, {modules} m
3019              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
3020     $rs = $DB->get_recordset_sql($sql);
3021     if ($rs->valid()) {
3022         // too much debug output
3023         $pbar = new progress_bar('assignmentupgradegrades', 500, true);
3024         $i=0;
3025         foreach ($rs as $assignment) {
3026             $i++;
3027             upgrade_set_timeout(60*5); // set up timeout, may also abort execution
3028             assignment_update_grades($assignment);
3029             $pbar->update($i, $count, "Updating Assignment grades ($i/$count).");
3030         }
3031         upgrade_set_timeout(); // reset to default timeout
3032     }
3033     $rs->close();
3036 /**
3037  * Create grade item for given assignment
3038  *
3039  * @category grade
3040  * @param stdClass $assignment An assignment instance with extra cmidnumber property
3041  * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
3042  * @return int 0 if ok, error code otherwise
3043  */
3044 function assignment_grade_item_update($assignment, $grades=NULL) {
3045     global $CFG;
3046     require_once($CFG->libdir.'/gradelib.php');
3048     if (!isset($assignment->courseid)) {
3049         $assignment->courseid = $assignment->course;
3050     }
3052     $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
3054     if ($assignment->grade > 0) {
3055         $params['gradetype'] = GRADE_TYPE_VALUE;
3056         $params['grademax']  = $assignment->grade;
3057         $params['grademin']  = 0;
3059     } else if ($assignment->grade < 0) {
3060         $params['gradetype'] = GRADE_TYPE_SCALE;
3061         $params['scaleid']   = -$assignment->grade;
3063     } else {
3064         $params['gradetype'] = GRADE_TYPE_TEXT; // allow text comments only
3065     }
3067     if ($grades  === 'reset') {
3068         $params['reset'] = true;
3069         $grades = NULL;
3070     }
3072     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades, $params);
3075 /**
3076  * Delete grade item for given assignment
3077  *
3078  * @category grade
3079  * @param object $assignment object
3080  * @return object assignment
3081  */
3082 function assignment_grade_item_delete($assignment) {
3083     global $CFG;
3084     require_once($CFG->libdir.'/gradelib.php');
3086     if (!isset($assignment->courseid)) {
3087         $assignment->courseid = $assignment->course;
3088     }
3090     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
3094 /**
3095  * Serves assignment submissions and other files.
3096  *
3097  * @package  mod_assignment
3098  * @category files
3099  * @param stdClass $course course object
3100  * @param stdClass $cm course module object
3101  * @param stdClass $context context object
3102  * @param string $filearea file area
3103  * @param array $args extra arguments
3104  * @param bool $forcedownload whether or not force download
3105  * @param array $options additional options affecting the file serving
3106  * @return bool false if file not found, does not return if found - just send the file
3107  */
3108 function assignment_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
3109     global $CFG, $DB;
3111     if ($context->contextlevel != CONTEXT_MODULE) {
3112         return false;
3113     }
3115     require_login($course, false, $cm);
3117     if (!$assignment = $DB->get_record('assignment', array('id'=>$cm->instance))) {
3118         return false;
3119     }
3121     require_once($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
3122     $assignmentclass = 'assignment_'.$assignment->assignmenttype;
3123     $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm, $course);
3125     return $assignmentinstance->send_file($filearea, $args, $forcedownload, $options);
3127 /**
3128  * Checks if a scale is being used by an assignment
3129  *
3130  * This is used by the backup code to decide whether to back up a scale
3131  * @param $assignmentid int
3132  * @param $scaleid int
3133  * @return boolean True if the scale is used by the assignment
3134  */
3135 function assignment_scale_used($assignmentid, $scaleid) {
3136     global $DB;
3138     $return = false;
3140     $rec = $DB->get_record('assignment', array('id'=>$assignmentid,'grade'=>-$scaleid));
3142     if (!empty($rec) && !empty($scaleid)) {
3143         $return = true;
3144     }
3146     return $return;
3149 /**
3150  * Checks if scale is being used by any instance of assignment
3151  *
3152  * This is used to find out if scale used anywhere
3153  * @param $scaleid int
3154  * @return boolean True if the scale is used by any assignment
3155  */
3156 function assignment_scale_used_anywhere($scaleid) {
3157     global $DB;
3159     if ($scaleid and $DB->record_exists('assignment', array('grade'=>-$scaleid))) {
3160         return true;
3161     } else {
3162         return false;
3163     }
3166 /**
3167  * Make sure up-to-date events are created for all assignment instances
3168  *
3169  * This standard function will check all instances of this module
3170  * and make sure there are up-to-date events created for each of them.
3171  * If courseid = 0, then every assignment event in the site is checked, else
3172  * only assignment events belonging to the course specified are checked.
3173  * This function is used, in its new format, by restore_refresh_events()
3174  *
3175  * @param $courseid int optional If zero then all assignments for all courses are covered
3176  * @return boolean Always returns true
3177  */
3178 function assignment_refresh_events($courseid = 0) {
3179     global $DB;
3181     if ($courseid == 0) {
3182         if (! $assignments = $DB->get_records("assignment")) {
3183             return true;
3184         }
3185     } else {
3186         if (! $assignments = $DB->get_records("assignment", array("course"=>$courseid))) {
3187             return true;
3188         }
3189     }
3190     $moduleid = $DB->get_field('modules', 'id', array('name'=>'assignment'));
3192     foreach ($assignments as $assignment) {
3193         $cm = get_coursemodule_from_id('assignment', $assignment->id);
3194         $event = new stdClass();
3195         $event->name        = $assignment->name;
3196         $event->description = format_module_intro('assignment', $assignment, $cm->id);
3197         $event->timestart   = $assignment->timedue;
3199         if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
3200             update_event($event);
3202         } else {
3203             $event->courseid    = $assignment->course;
3204             $event->groupid     = 0;
3205             $event->userid      = 0;
3206             $event->modulename  = 'assignment';
3207             $event->instance    = $assignment->id;
3208             $event->eventtype   = 'due';
3209             $event->timeduration = 0;
3210             $event->visible     = $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$assignment->id));
3211             add_event($event);
3212         }
3214     }
3215     return true;
3218 /**
3219  * Print recent activity from all assignments in a given course
3220  *
3221  * This is used by the recent activity block
3222  */
3223 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
3224     global $CFG, $USER, $DB, $OUTPUT;
3226     // do not use log table if possible, it may be huge
3228     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
3229                                                      u.firstname, u.lastname, u.email, u.picture
3230                                                 FROM {assignment_submissions} asb
3231                                                      JOIN {assignment} a      ON a.id = asb.assignment
3232                                                      JOIN {course_modules} cm ON cm.instance = a.id
3233                                                      JOIN {modules} md        ON md.id = cm.module
3234                                                      JOIN {user} u            ON u.id = asb.userid
3235                                                WHERE asb.timemodified > ? AND
3236                                                      a.course = ? AND
3237                                                      md.name = 'assignment'
3238                                             ORDER BY asb.timemodified ASC", array($timestart, $course->id))) {
3239          return false;
3240     }
3242     $modinfo = get_fast_modinfo($course); // reference needed because we might load the groups
3243     $show    = array();
3244     $grader  = array();
3246     foreach($submissions as $submission) {
3247         if (!array_key_exists($submission->cmid, $modinfo->cms)) {
3248             continue;
3249         }
3250         $cm = $modinfo->cms[$submission->cmid];
3251         if (!$cm->uservisible) {
3252             continue;
3253         }
3254         if ($submission->userid == $USER->id) {
3255             $show[] = $submission;
3256             continue;
3257         }
3259         // the act of sumbitting of assignment may be considered private - only graders will see it if specified
3260         if (empty($CFG->assignment_showrecentsubmissions)) {
3261             if (!array_key_exists($cm->id, $grader)) {
3262                 $grader[$cm->id] = has_capability('moodle/grade:viewall', context_module::instance($cm->id));
3263             }
3264             if (!$grader[$cm->id]) {
3265                 continue;
3266             }
3267         }
3269         $groupmode = groups_get_activity_groupmode($cm, $course);
3271         if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', context_module::instance($cm->id))) {
3272             if (isguestuser()) {
3273                 // shortcut - guest user does not belong into any group
3274                 continue;
3275             }
3277             if (is_null($modinfo->groups)) {
3278                 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
3279             }
3281             // this will be slow - show only users that share group with me in this cm
3282             if (empty($modinfo->groups[$cm->id])) {
3283                 continue;
3284             }
3285             $usersgroups =  groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
3286             if (is_array($usersgroups)) {
3287                 $usersgroups = array_keys($usersgroups);
3288                 $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
3289                 if (empty($intersect)) {
3290                     continue;
3291                 }
3292             }
3293         }
3294         $show[] = $submission;
3295     }
3297     if (empty($show)) {
3298         return false;
3299     }
3301     echo $OUTPUT->heading(get_string('newsubmissions', 'assignment').':', 3);
3303     foreach ($show as $submission) {
3304         $cm = $modinfo->cms[$submission->cmid];
3305         $link = $CFG->wwwroot.'/mod/assignment/view.php?id='.$cm->id;
3306         print_recent_activity_note($submission->timemodified, $submission, $cm->name, $link, false, $viewfullnames);
3307     }
3309     return true;