MDL-30275 Assignment activity description not displayed on course page
[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 = get_context_instance(CONTEXT_MODULE, $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 = get_context_instance(CONTEXT_COURSE, $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 = get_context_instance(CONTEXT_MODULE,$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         $this->view_feedback();
170         $this->view_footer();
171     }
173     /**
174      * Display the header and top of a page
175      *
176      * (this doesn't change much for assignment types)
177      * This is used by the view() method to print the header of view.php but
178      * it can be used on other pages in which case the string to denote the
179      * page in the navigation trail should be passed as an argument
180      *
181      * @global object
182      * @param string $subpage Description of subpage to be used in navigation trail
183      */
184     function view_header($subpage='') {
185         global $CFG, $PAGE, $OUTPUT;
187         if ($subpage) {
188             $PAGE->navbar->add($subpage);
189         }
191         $PAGE->set_title($this->pagetitle);
192         $PAGE->set_heading($this->course->fullname);
194         echo $OUTPUT->header();
196         groups_print_activity_menu($this->cm, $CFG->wwwroot . '/mod/assignment/view.php?id=' . $this->cm->id);
198         echo '<div class="reportlink">'.$this->submittedlink().'</div>';
199         echo '<div class="clearer"></div>';
200     }
203     /**
204      * Display the assignment intro
205      *
206      * This will most likely be extended by assignment type plug-ins
207      * The default implementation prints the assignment description in a box
208      */
209     function view_intro() {
210         global $OUTPUT;
211         echo $OUTPUT->box_start('generalbox boxaligncenter', 'intro');
212         echo format_module_intro('assignment', $this->assignment, $this->cm->id);
213         echo $OUTPUT->box_end();
214         plagiarism_print_disclosure($this->cm->id);
215     }
217     /**
218      * Display the assignment dates
219      *
220      * Prints the assignment start and end dates in a box.
221      * This will be suitable for most assignment types
222      */
223     function view_dates() {
224         global $OUTPUT;
225         if (!$this->assignment->timeavailable && !$this->assignment->timedue) {
226             return;
227         }
229         echo $OUTPUT->box_start('generalbox boxaligncenter', 'dates');
230         echo '<table>';
231         if ($this->assignment->timeavailable) {
232             echo '<tr><td class="c0">'.get_string('availabledate','assignment').':</td>';
233             echo '    <td class="c1">'.userdate($this->assignment->timeavailable).'</td></tr>';
234         }
235         if ($this->assignment->timedue) {
236             echo '<tr><td class="c0">'.get_string('duedate','assignment').':</td>';
237             echo '    <td class="c1">'.userdate($this->assignment->timedue).'</td></tr>';
238         }
239         echo '</table>';
240         echo $OUTPUT->box_end();
241     }
244     /**
245      * Display the bottom and footer of a page
246      *
247      * This default method just prints the footer.
248      * This will be suitable for most assignment types
249      */
250     function view_footer() {
251         global $OUTPUT;
252         echo $OUTPUT->footer();
253     }
255     /**
256      * Display the feedback to the student
257      *
258      * This default method prints the teacher picture and name, date when marked,
259      * grade and teacher submissioncomment.
260      * If advanced grading is used the method render_grade from the
261      * advanced grading controller is called to display the grade.
262      *
263      * @global object
264      * @global object
265      * @global object
266      * @param object $submission The submission object or NULL in which case it will be loaded
267      */
268     function view_feedback($submission=NULL) {
269         global $USER, $CFG, $DB, $OUTPUT, $PAGE;
270         require_once($CFG->libdir.'/gradelib.php');
271         require_once("$CFG->dirroot/grade/grading/lib.php");
273         if (!$submission) { /// Get submission for this assignment
274             $userid = $USER->id;
275             $submission = $this->get_submission($userid);
276         } else {
277             $userid = $submission->userid;
278         }
279         // Check the user can submit
280         $canviewfeedback = ($userid == $USER->id && has_capability('mod/assignment:submit', $this->context, $USER->id, false));
281         // If not then check if the user still has the view cap and has a previous submission
282         $canviewfeedback = $canviewfeedback || (!empty($submission) && $submission->userid == $USER->id && has_capability('mod/assignment:view', $this->context));
283         // Or if user can grade (is a teacher or admin)
284         $canviewfeedback = $canviewfeedback || has_capability('mod/assignment:grade', $this->context);
286         if (!$canviewfeedback) {
287             // can not view or submit assignments -> no feedback
288             return;
289         }
291         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
292         $item = $grading_info->items[0];
293         $grade = $item->grades[$userid];
295         if ($grade->hidden or $grade->grade === false) { // hidden or error
296             return;
297         }
299         if ($grade->grade === null and empty($grade->str_feedback)) {   /// Nothing to show yet
300             return;
301         }
303         $graded_date = $grade->dategraded;
304         $graded_by   = $grade->usermodified;
306     /// We need the teacher info
307         if (!$teacher = $DB->get_record('user', array('id'=>$graded_by))) {
308             print_error('cannotfindteacher');
309         }
311     /// Print the feedback
312         echo $OUTPUT->heading(get_string('feedbackfromteacher', 'assignment', fullname($teacher)));
314         echo '<table cellspacing="0" class="feedback">';
316         echo '<tr>';
317         echo '<td class="left picture">';
318         if ($teacher) {
319             echo $OUTPUT->user_picture($teacher);
320         }
321         echo '</td>';
322         echo '<td class="topic">';
323         echo '<div class="from">';
324         if ($teacher) {
325             echo '<div class="fullname">'.fullname($teacher).'</div>';
326         }
327         echo '<div class="time">'.userdate($graded_date).'</div>';
328         echo '</div>';
329         echo '</td>';
330         echo '</tr>';
332         echo '<tr>';
333         echo '<td class="left side">&nbsp;</td>';
334         echo '<td class="content">';
335         $gradestr = '<div class="grade">'. get_string("grade").': '.$grade->str_long_grade. '</div>';
336         if (!empty($submission) && $controller = get_grading_manager($this->context, 'mod_assignment', 'submission')->get_active_controller()) {
337             $controller->set_grade_range(make_grades_menu($this->assignment->grade));
338             echo $controller->render_grade($PAGE, $submission->id, $item, $gradestr, has_capability('mod/assignment:grade', $this->context));
339         } else {
340             echo $gradestr;
341         }
342         echo '<div class="clearer"></div>';
344         echo '<div class="comment">';
345         echo $grade->str_feedback;
346         echo '</div>';
347         echo '</tr>';
349          if ($this->type == 'uploadsingle') { //@TODO: move to overload view_feedback method in the class or is uploadsingle merging into upload?
350             $responsefiles = $this->print_responsefiles($submission->userid, true);
351             if (!empty($responsefiles)) {
352                 echo '<tr>';
353                 echo '<td class="left side">&nbsp;</td>';
354                 echo '<td class="content">';
355                 echo $responsefiles;
356                 echo '</tr>';
357             }
358          }
360         echo '</table>';
361     }
363     /**
364      * Returns a link with info about the state of the assignment submissions
365      *
366      * This is used by view_header to put this link at the top right of the page.
367      * For teachers it gives the number of submitted assignments with a link
368      * For students it gives the time of their submission.
369      * This will be suitable for most assignment types.
370      *
371      * @global object
372      * @global object
373      * @param bool $allgroup print all groups info if user can access all groups, suitable for index.php
374      * @return string
375      */
376     function submittedlink($allgroups=false) {
377         global $USER;
378         global $CFG;
380         $submitted = '';
381         $urlbase = "{$CFG->wwwroot}/mod/assignment/";
383         $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
384         if (has_capability('mod/assignment:grade', $context)) {
385             if ($allgroups and has_capability('moodle/site:accessallgroups', $context)) {
386                 $group = 0;
387             } else {
388                 $group = groups_get_activity_group($this->cm);
389             }
390             if ($this->type == 'offline') {
391                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
392                              get_string('viewfeedback', 'assignment').'</a>';
393             } else if ($count = $this->count_real_submissions($group)) {
394                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
395                              get_string('viewsubmissions', 'assignment', $count).'</a>';
396             } else {
397                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
398                              get_string('noattempts', 'assignment').'</a>';
399             }
400         } else {
401             if (isloggedin()) {
402                 if ($submission = $this->get_submission($USER->id)) {
403                     if ($submission->timemodified) {
404                         if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
405                             $submitted = '<span class="early">'.userdate($submission->timemodified).'</span>';
406                         } else {
407                             $submitted = '<span class="late">'.userdate($submission->timemodified).'</span>';
408                         }
409                     }
410                 }
411             }
412         }
414         return $submitted;
415     }
418     /**
419      * @todo Document this function
420      */
421     function setup_elements(&$mform) {
423     }
425     /**
426      * Any preprocessing needed for the settings form for
427      * this assignment type
428      *
429      * @param array $default_values - array to fill in with the default values
430      *      in the form 'formelement' => 'value'
431      * @param object $form - the form that is to be displayed
432      * @return none
433      */
434     function form_data_preprocessing(&$default_values, $form) {
435     }
437     /**
438      * Any extra validation checks needed for the settings
439      * form for this assignment type
440      *
441      * See lib/formslib.php, 'validation' function for details
442      */
443     function form_validation($data, $files) {
444         return array();
445     }
447     /**
448      * Create a new assignment activity
449      *
450      * Given an object containing all the necessary data,
451      * (defined by the form in mod_form.php) this function
452      * will create a new instance and return the id number
453      * of the new instance.
454      * The due data is added to the calendar
455      * This is common to all assignment types.
456      *
457      * @global object
458      * @global object
459      * @param object $assignment The data from the form on mod_form.php
460      * @return int The id of the assignment
461      */
462     function add_instance($assignment) {
463         global $COURSE, $DB;
465         $assignment->timemodified = time();
466         $assignment->courseid = $assignment->course;
468         $returnid = $DB->insert_record("assignment", $assignment);
469         $assignment->id = $returnid;
471         if ($assignment->timedue) {
472             $event = new stdClass();
473             $event->name        = $assignment->name;
474             $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
475             $event->courseid    = $assignment->course;
476             $event->groupid     = 0;
477             $event->userid      = 0;
478             $event->modulename  = 'assignment';
479             $event->instance    = $returnid;
480             $event->eventtype   = 'due';
481             $event->timestart   = $assignment->timedue;
482             $event->timeduration = 0;
484             calendar_event::create($event);
485         }
487         assignment_grade_item_update($assignment);
489         return $returnid;
490     }
492     /**
493      * Deletes an assignment activity
494      *
495      * Deletes all database records, files and calendar events for this assignment.
496      *
497      * @global object
498      * @global object
499      * @param object $assignment The assignment to be deleted
500      * @return boolean False indicates error
501      */
502     function delete_instance($assignment) {
503         global $CFG, $DB;
505         $assignment->courseid = $assignment->course;
507         $result = true;
509         // now get rid of all files
510         $fs = get_file_storage();
511         if ($cm = get_coursemodule_from_instance('assignment', $assignment->id)) {
512             $context = get_context_instance(CONTEXT_MODULE, $cm->id);
513             $fs->delete_area_files($context->id);
514         }
516         if (! $DB->delete_records('assignment_submissions', array('assignment'=>$assignment->id))) {
517             $result = false;
518         }
520         if (! $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
521             $result = false;
522         }
524         if (! $DB->delete_records('assignment', array('id'=>$assignment->id))) {
525             $result = false;
526         }
527         $mod = $DB->get_field('modules','id',array('name'=>'assignment'));
529         assignment_grade_item_delete($assignment);
531         return $result;
532     }
534     /**
535      * Updates a new assignment activity
536      *
537      * Given an object containing all the necessary data,
538      * (defined by the form in mod_form.php) this function
539      * will update the assignment instance and return the id number
540      * The due date is updated in the calendar
541      * This is common to all assignment types.
542      *
543      * @global object
544      * @global object
545      * @param object $assignment The data from the form on mod_form.php
546      * @return bool success
547      */
548     function update_instance($assignment) {
549         global $COURSE, $DB;
551         $assignment->timemodified = time();
553         $assignment->id = $assignment->instance;
554         $assignment->courseid = $assignment->course;
556         $DB->update_record('assignment', $assignment);
558         if ($assignment->timedue) {
559             $event = new stdClass();
561             if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
563                 $event->name        = $assignment->name;
564                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
565                 $event->timestart   = $assignment->timedue;
567                 $calendarevent = calendar_event::load($event->id);
568                 $calendarevent->update($event);
569             } else {
570                 $event = new stdClass();
571                 $event->name        = $assignment->name;
572                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
573                 $event->courseid    = $assignment->course;
574                 $event->groupid     = 0;
575                 $event->userid      = 0;
576                 $event->modulename  = 'assignment';
577                 $event->instance    = $assignment->id;
578                 $event->eventtype   = 'due';
579                 $event->timestart   = $assignment->timedue;
580                 $event->timeduration = 0;
582                 calendar_event::create($event);
583             }
584         } else {
585             $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id));
586         }
588         // get existing grade item
589         assignment_grade_item_update($assignment);
591         return true;
592     }
594     /**
595      * Update grade item for this submission.
596      */
597     function update_grade($submission) {
598         assignment_update_grades($this->assignment, $submission->userid);
599     }
601     /**
602      * Top-level function for handling of submissions called by submissions.php
603      *
604      * This is for handling the teacher interaction with the grading interface
605      * This should be suitable for most assignment types.
606      *
607      * @global object
608      * @param string $mode Specifies the kind of teacher interaction taking place
609      */
610     function submissions($mode) {
611         ///The main switch is changed to facilitate
612         ///1) Batch fast grading
613         ///2) Skip to the next one on the popup
614         ///3) Save and Skip to the next one on the popup
616         //make user global so we can use the id
617         global $USER, $OUTPUT, $DB, $PAGE;
619         $mailinfo = optional_param('mailinfo', null, PARAM_BOOL);
621         if (optional_param('next', null, PARAM_BOOL)) {
622             $mode='next';
623         }
624         if (optional_param('saveandnext', null, PARAM_BOOL)) {
625             $mode='saveandnext';
626         }
628         if (is_null($mailinfo)) {
629             if (optional_param('sesskey', null, PARAM_BOOL)) {
630                 set_user_preference('assignment_mailinfo', $mailinfo);
631             } else {
632                 $mailinfo = get_user_preferences('assignment_mailinfo', 0);
633             }
634         } else {
635             set_user_preference('assignment_mailinfo', $mailinfo);
636         }
638         if (!($this->validate_and_preprocess_feedback())) {
639             // form was submitted ('Save' or 'Save and next' was pressed, but validation failed)
640             $this->display_submission();
641             return;
642         }
644         switch ($mode) {
645             case 'grade':                         // We are in a main window grading
646                 if ($submission = $this->process_feedback()) {
647                     $this->display_submissions(get_string('changessaved'));
648                 } else {
649                     $this->display_submissions();
650                 }
651                 break;
653             case 'single':                        // We are in a main window displaying one submission
654                 if ($submission = $this->process_feedback()) {
655                     $this->display_submissions(get_string('changessaved'));
656                 } else {
657                     $this->display_submission();
658                 }
659                 break;
661             case 'all':                          // Main window, display everything
662                 $this->display_submissions();
663                 break;
665             case 'fastgrade':
666                 ///do the fast grading stuff  - this process should work for all 3 subclasses
667                 $grading    = false;
668                 $commenting = false;
669                 $col        = false;
670                 if (isset($_POST['submissioncomment'])) {
671                     $col = 'submissioncomment';
672                     $commenting = true;
673                 }
674                 if (isset($_POST['menu'])) {
675                     $col = 'menu';
676                     $grading = true;
677                 }
678                 if (!$col) {
679                     //both submissioncomment and grade columns collapsed..
680                     $this->display_submissions();
681                     break;
682                 }
684                 foreach ($_POST[$col] as $id => $unusedvalue){
686                     $id = (int)$id; //clean parameter name
688                     $this->process_outcomes($id);
690                     if (!$submission = $this->get_submission($id)) {
691                         $submission = $this->prepare_new_submission($id);
692                         $newsubmission = true;
693                     } else {
694                         $newsubmission = false;
695                     }
696                     unset($submission->data1);  // Don't need to update this.
697                     unset($submission->data2);  // Don't need to update this.
699                     //for fast grade, we need to check if any changes take place
700                     $updatedb = false;
702                     if ($grading) {
703                         $grade = $_POST['menu'][$id];
704                         $updatedb = $updatedb || ($submission->grade != $grade);
705                         $submission->grade = $grade;
706                     } else {
707                         if (!$newsubmission) {
708                             unset($submission->grade);  // Don't need to update this.
709                         }
710                     }
711                     if ($commenting) {
712                         $commentvalue = trim($_POST['submissioncomment'][$id]);
713                         $updatedb = $updatedb || ($submission->submissioncomment != $commentvalue);
714                         $submission->submissioncomment = $commentvalue;
715                     } else {
716                         unset($submission->submissioncomment);  // Don't need to update this.
717                     }
719                     $submission->teacher    = $USER->id;
720                     if ($updatedb) {
721                         $submission->mailed = (int)(!$mailinfo);
722                     }
724                     $submission->timemarked = time();
726                     //if it is not an update, we don't change the last modified time etc.
727                     //this will also not write into database if no submissioncomment and grade is entered.
729                     if ($updatedb){
730                         if ($newsubmission) {
731                             if (!isset($submission->submissioncomment)) {
732                                 $submission->submissioncomment = '';
733                             }
734                             $sid = $DB->insert_record('assignment_submissions', $submission);
735                             $submission->id = $sid;
736                         } else {
737                             $DB->update_record('assignment_submissions', $submission);
738                         }
740                         // trigger grade event
741                         $this->update_grade($submission);
743                         //add to log only if updating
744                         add_to_log($this->course->id, 'assignment', 'update grades',
745                                    'submissions.php?id='.$this->cm->id.'&user='.$submission->userid,
746                                    $submission->userid, $this->cm->id);
747                     }
749                 }
751                 $message = $OUTPUT->notification(get_string('changessaved'), 'notifysuccess');
753                 $this->display_submissions($message);
754                 break;
757             case 'saveandnext':
758                 ///We are in pop up. save the current one and go to the next one.
759                 //first we save the current changes
760                 if ($submission = $this->process_feedback()) {
761                     //print_heading(get_string('changessaved'));
762                     //$extra_javascript = $this->update_main_listing($submission);
763                 }
765             case 'next':
766                 /// We are currently in pop up, but we want to skip to next one without saving.
767                 ///    This turns out to be similar to a single case
768                 /// The URL used is for the next submission.
769                 $offset = required_param('offset', PARAM_INT);
770                 $nextid = required_param('nextid', PARAM_INT);
771                 $id = required_param('id', PARAM_INT);
772                 $offset = (int)$offset+1;
773                 //$this->display_submission($offset+1 , $nextid);
774                 redirect('submissions.php?id='.$id.'&userid='. $nextid . '&mode=single&offset='.$offset);
775                 break;
777             case 'singlenosave':
778                 $this->display_submission();
779                 break;
781             default:
782                 echo "something seriously is wrong!!";
783                 break;
784         }
785     }
787     /**
788      * Checks if grading method allows quickgrade mode. At the moment it is hardcoded
789      * that advanced grading methods do not allow quickgrade.
790      *
791      * Assignment type plugins are not allowed to override this method
792      *
793      * @return boolean
794      */
795     public final function quickgrade_mode_allowed() {
796         global $CFG;
797         require_once("$CFG->dirroot/grade/grading/lib.php");
798         if ($controller = get_grading_manager($this->context, 'mod_assignment', 'submission')->get_active_controller()) {
799             return false;
800         }
801         return true;
802     }
804     /**
805      * Helper method updating the listing on the main script from popup using javascript
806      *
807      * @global object
808      * @global object
809      * @param $submission object The submission whose data is to be updated on the main page
810      */
811     function update_main_listing($submission) {
812         global $SESSION, $CFG, $OUTPUT;
814         $output = '';
816         $perpage = get_user_preferences('assignment_perpage', 10);
818         $quickgrade = get_user_preferences('assignment_quickgrade', 0) && $this->quickgrade_mode_allowed();
820         /// Run some Javascript to try and update the parent page
821         $output .= '<script type="text/javascript">'."\n<!--\n";
822         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['submissioncomment'])) {
823             if ($quickgrade){
824                 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid.'").value="'
825                 .trim($submission->submissioncomment).'";'."\n";
826              } else {
827                 $output.= 'opener.document.getElementById("com'.$submission->userid.
828                 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment)), 15)."\";\n";
829             }
830         }
832         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['grade'])) {
833             //echo optional_param('menuindex');
834             if ($quickgrade){
835                 $output.= 'opener.document.getElementById("menumenu'.$submission->userid.
836                 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT).'";'."\n";
837             } else {
838                 $output.= 'opener.document.getElementById("g'.$submission->userid.'").innerHTML="'.
839                 $this->display_grade($submission->grade)."\";\n";
840             }
841         }
842         //need to add student's assignments in there too.
843         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemodified']) &&
844             $submission->timemodified) {
845             $output.= 'opener.document.getElementById("ts'.$submission->userid.
846                  '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid)).userdate($submission->timemodified)."\";\n";
847         }
849         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemarked']) &&
850             $submission->timemarked) {
851             $output.= 'opener.document.getElementById("tt'.$submission->userid.
852                  '").innerHTML="'.userdate($submission->timemarked)."\";\n";
853         }
855         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['status'])) {
856             $output.= 'opener.document.getElementById("up'.$submission->userid.'").className="s1";';
857             $buttontext = get_string('update');
858             $url = new moodle_url('/mod/assignment/submissions.php', array(
859                     'id' => $this->cm->id,
860                     'userid' => $submission->userid,
861                     'mode' => 'single',
862                     'offset' => (optional_param('offset', '', PARAM_INT)-1)));
863             $button = $OUTPUT->action_link($url, $buttontext, new popup_action('click', $url, 'grade'.$submission->userid, array('height' => 450, 'width' => 700)), array('ttile'=>$buttontext));
865             $output .= 'opener.document.getElementById("up'.$submission->userid.'").innerHTML="'.addslashes_js($button).'";';
866         }
868         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $submission->userid);
870         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['finalgrade'])) {
871             $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid.
872             '").innerHTML="'.$grading_info->items[0]->grades[$submission->userid]->str_grade.'";'."\n";
873         }
875         if (!empty($CFG->enableoutcomes) and empty($SESSION->flextable['mod-assignment-submissions']->collapse['outcome'])) {
877             if (!empty($grading_info->outcomes)) {
878                 foreach($grading_info->outcomes as $n=>$outcome) {
879                     if ($outcome->grades[$submission->userid]->locked) {
880                         continue;
881                     }
883                     if ($quickgrade){
884                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.
885                         '").selectedIndex="'.$outcome->grades[$submission->userid]->grade.'";'."\n";
887                     } else {
888                         $options = make_grades_menu(-$outcome->scaleid);
889                         $options[0] = get_string('nooutcome', 'grades');
890                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.'").innerHTML="'.$options[$outcome->grades[$submission->userid]->grade]."\";\n";
891                     }
893                 }
894             }
895         }
897         $output .= "\n-->\n</script>";
898         return $output;
899     }
901     /**
902      *  Return a grade in user-friendly form, whether it's a scale or not
903      *
904      * @global object
905      * @param mixed $grade
906      * @return string User-friendly representation of grade
907      */
908     function display_grade($grade) {
909         global $DB;
911         static $scalegrades = array();   // Cache scales for each assignment - they might have different scales!!
913         if ($this->assignment->grade >= 0) {    // Normal number
914             if ($grade == -1) {
915                 return '-';
916             } else {
917                 return $grade.' / '.$this->assignment->grade;
918             }
920         } else {                                // Scale
921             if (empty($scalegrades[$this->assignment->id])) {
922                 if ($scale = $DB->get_record('scale', array('id'=>-($this->assignment->grade)))) {
923                     $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
924                 } else {
925                     return '-';
926                 }
927             }
928             if (isset($scalegrades[$this->assignment->id][$grade])) {
929                 return $scalegrades[$this->assignment->id][$grade];
930             }
931             return '-';
932         }
933     }
935     /**
936      *  Display a single submission, ready for grading on a popup window
937      *
938      * This default method prints the teacher info and submissioncomment box at the top and
939      * the student info and submission at the bottom.
940      * This method also fetches the necessary data in order to be able to
941      * provide a "Next submission" button.
942      * Calls preprocess_submission() to give assignment type plug-ins a chance
943      * to process submissions before they are graded
944      * This method gets its arguments from the page parameters userid and offset
945      *
946      * @global object
947      * @global object
948      * @param string $extra_javascript
949      */
950     function display_submission($offset=-1,$userid =-1, $display=true) {
951         global $CFG, $DB, $PAGE, $OUTPUT, $USER;
952         require_once($CFG->libdir.'/gradelib.php');
953         require_once($CFG->libdir.'/tablelib.php');
954         require_once("$CFG->dirroot/repository/lib.php");
955         require_once("$CFG->dirroot/grade/grading/lib.php");
956         if ($userid==-1) {
957             $userid = required_param('userid', PARAM_INT);
958         }
959         if ($offset==-1) {
960             $offset = required_param('offset', PARAM_INT);//offset for where to start looking for student.
961         }
962         $filter = optional_param('filter', 0, PARAM_INT);
964         if (!$user = $DB->get_record('user', array('id'=>$userid))) {
965             print_error('nousers');
966         }
968         if (!$submission = $this->get_submission($user->id)) {
969             $submission = $this->prepare_new_submission($userid);
970         }
971         if ($submission->timemodified > $submission->timemarked) {
972             $subtype = 'assignmentnew';
973         } else {
974             $subtype = 'assignmentold';
975         }
977         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
978         $gradingdisabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
980     /// construct SQL, using current offset to find the data of the next student
981         $course     = $this->course;
982         $assignment = $this->assignment;
983         $cm         = $this->cm;
984         $context    = get_context_instance(CONTEXT_MODULE, $cm->id);
986         //reset filter to all for offline assignment
987         if ($assignment->assignmenttype == 'offline' && $filter == self::FILTER_SUBMITTED) {
988             $filter = self::FILTER_ALL;
989         }
990         /// Get all ppl that can submit assignments
992         $currentgroup = groups_get_activity_group($cm);
993         $users = get_enrolled_users($context, 'mod/assignment:submit', $currentgroup, 'u.id');
994         if ($users) {
995             $users = array_keys($users);
996             // if groupmembersonly used, remove users who are not in any group
997             if (!empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
998                 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
999                     $users = array_intersect($users, array_keys($groupingusers));
1000                 }
1001             }
1002         }
1004         $nextid = 0;
1005         $where = '';
1006         if($filter == self::FILTER_SUBMITTED) {
1007             $where .= 's.timemodified > 0 AND ';
1008         } else if($filter == self::FILTER_REQUIRE_GRADING) {
1009             $where .= 's.timemarked < s.timemodified AND ';
1010         }
1012         if ($users) {
1013             $userfields = user_picture::fields('u', array('lastaccess'));
1014             $select = "SELECT $userfields,
1015                               s.id AS submissionid, s.grade, s.submissioncomment,
1016                               s.timemodified, s.timemarked,
1017                               CASE WHEN s.timemarked > 0 AND s.timemarked >= s.timemodified THEN 1
1018                                    ELSE 0 END AS status ";
1020             $sql = 'FROM {user} u '.
1021                    'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1022                    AND s.assignment = '.$this->assignment->id.' '.
1023                    'WHERE '.$where.'u.id IN ('.implode(',', $users).') ';
1025             if ($sort = flexible_table::get_sort_for_table('mod-assignment-submissions')) {
1026                 $sort = 'ORDER BY '.$sort.' ';
1027             }
1028             $auser = $DB->get_records_sql($select.$sql.$sort, null, $offset, 2);
1030             if (is_array($auser) && count($auser)>1) {
1031                 $nextuser = next($auser);
1032                 $nextid = $nextuser->id;
1033             }
1034         }
1036         if ($submission->teacher) {
1037             $teacher = $DB->get_record('user', array('id'=>$submission->teacher));
1038         } else {
1039             global $USER;
1040             $teacher = $USER;
1041         }
1043         $this->preprocess_submission($submission);
1045         $mformdata = new stdClass();
1046         $mformdata->context = $this->context;
1047         $mformdata->maxbytes = $this->course->maxbytes;
1048         $mformdata->courseid = $this->course->id;
1049         $mformdata->teacher = $teacher;
1050         $mformdata->assignment = $assignment;
1051         $mformdata->submission = $submission;
1052         $mformdata->lateness = $this->display_lateness($submission->timemodified);
1053         $mformdata->auser = $auser;
1054         $mformdata->user = $user;
1055         $mformdata->offset = $offset;
1056         $mformdata->userid = $userid;
1057         $mformdata->cm = $this->cm;
1058         $mformdata->grading_info = $grading_info;
1059         $mformdata->enableoutcomes = $CFG->enableoutcomes;
1060         $mformdata->grade = $this->assignment->grade;
1061         $mformdata->gradingdisabled = $gradingdisabled;
1062         $mformdata->nextid = $nextid;
1063         $mformdata->submissioncomment= $submission->submissioncomment;
1064         $mformdata->submissioncommentformat= FORMAT_HTML;
1065         $mformdata->submission_content= $this->print_user_files($user->id,true);
1066         $mformdata->filter = $filter;
1067         $mformdata->mailinfo = get_user_preferences('assignment_mailinfo', 0);
1068          if ($assignment->assignmenttype == 'upload') {
1069             $mformdata->fileui_options = array('subdirs'=>1, 'maxbytes'=>$assignment->maxbytes, 'maxfiles'=>$assignment->var1, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL);
1070         } elseif ($assignment->assignmenttype == 'uploadsingle') {
1071             $mformdata->fileui_options = array('subdirs'=>0, 'maxbytes'=>$CFG->userquota, 'maxfiles'=>1, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL);
1072         }
1073         $advancedgradingwarning = false;
1074         $gradingmanager = get_grading_manager($this->context, 'mod_assignment', 'submission');
1075         if ($gradingmethod = $gradingmanager->get_active_method()) {
1076             $controller = $gradingmanager->get_controller($gradingmethod);
1077             if ($controller->is_form_available()) {
1078                 $itemid = null;
1079                 if (!empty($submission->id)) {
1080                     $itemid = $submission->id;
1081                 }
1082                 if ($gradingdisabled && $itemid) {
1083                     $mformdata->advancedgradinginstance = $controller->get_current_instance($USER->id, $itemid);
1084                 } else if (!$gradingdisabled) {
1085                     $instanceid = optional_param('advancedgradinginstanceid', 0, PARAM_INT);
1086                     $mformdata->advancedgradinginstance = $controller->get_or_create_instance($instanceid, $USER->id, $itemid);
1087                 }
1088             } else {
1089                 $advancedgradingwarning = $controller->form_unavailable_notification();
1090             }
1091         }
1093         $submitform = new mod_assignment_grading_form( null, $mformdata );
1095          if (!$display) {
1096             $ret_data = new stdClass();
1097             $ret_data->mform = $submitform;
1098             if (isset($mformdata->fileui_options)) {
1099                 $ret_data->fileui_options = $mformdata->fileui_options;
1100             }
1101             return $ret_data;
1102         }
1104         if ($submitform->is_cancelled()) {
1105             redirect('submissions.php?id='.$this->cm->id);
1106         }
1108         $submitform->set_data($mformdata);
1110         $PAGE->set_title($this->course->fullname . ': ' .get_string('feedback', 'assignment').' - '.fullname($user, true));
1111         $PAGE->set_heading($this->course->fullname);
1112         $PAGE->navbar->add(get_string('submissions', 'assignment'), new moodle_url('/mod/assignment/submissions.php', array('id'=>$cm->id)));
1113         $PAGE->navbar->add(fullname($user, true));
1115         echo $OUTPUT->header();
1116         echo $OUTPUT->heading(get_string('feedback', 'assignment').': '.fullname($user, true));
1118         // display mform here...
1119         if ($advancedgradingwarning) {
1120             echo $OUTPUT->notification($advancedgradingwarning, 'error');
1121         }
1122         $submitform->display();
1124         $customfeedback = $this->custom_feedbackform($submission, true);
1125         if (!empty($customfeedback)) {
1126             echo $customfeedback;
1127         }
1129         echo $OUTPUT->footer();
1130     }
1132     /**
1133      *  Preprocess submission before grading
1134      *
1135      * Called by display_submission()
1136      * The default type does nothing here.
1137      *
1138      * @param object $submission The submission object
1139      */
1140     function preprocess_submission(&$submission) {
1141     }
1143     /**
1144      *  Display all the submissions ready for grading
1145      *
1146      * @global object
1147      * @global object
1148      * @global object
1149      * @global object
1150      * @param string $message
1151      * @return bool|void
1152      */
1153     function display_submissions($message='') {
1154         global $CFG, $DB, $USER, $DB, $OUTPUT, $PAGE;
1155         require_once($CFG->libdir.'/gradelib.php');
1157         /* first we check to see if the form has just been submitted
1158          * to request user_preference updates
1159          */
1161        $filters = array(self::FILTER_ALL             => get_string('all'),
1162                         self::FILTER_REQUIRE_GRADING => get_string('requiregrading', 'assignment'));
1164         $updatepref = optional_param('updatepref', 0, PARAM_BOOL);
1165         if ($updatepref) {
1166             $perpage = optional_param('perpage', 10, PARAM_INT);
1167             $perpage = ($perpage <= 0) ? 10 : $perpage ;
1168             $filter = optional_param('filter', 0, PARAM_INT);
1169             set_user_preference('assignment_perpage', $perpage);
1170             set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
1171             set_user_preference('assignment_filter', $filter);
1172         }
1174         /* next we get perpage and quickgrade (allow quick grade) params
1175          * from database
1176          */
1177         $perpage    = get_user_preferences('assignment_perpage', 10);
1178         $quickgrade = get_user_preferences('assignment_quickgrade', 0) && $this->quickgrade_mode_allowed();
1179         $filter = get_user_preferences('assignment_filter', 0);
1180         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);
1182         if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
1183             $uses_outcomes = true;
1184         } else {
1185             $uses_outcomes = false;
1186         }
1188         $page    = optional_param('page', 0, PARAM_INT);
1189         $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
1191     /// Some shortcuts to make the code read better
1193         $course     = $this->course;
1194         $assignment = $this->assignment;
1195         $cm         = $this->cm;
1196         $hassubmission = false;
1198         // reset filter to all for offline assignment only.
1199         if ($assignment->assignmenttype == 'offline') {
1200             if ($filter == self::FILTER_SUBMITTED) {
1201                 $filter = self::FILTER_ALL;
1202             }
1203         } else {
1204             $filters[self::FILTER_SUBMITTED] = get_string('submitted', 'assignment');
1205         }
1207         $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
1208         add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->cm->id, $this->assignment->id, $this->cm->id);
1210         $PAGE->set_title(format_string($this->assignment->name,true));
1211         $PAGE->set_heading($this->course->fullname);
1212         echo $OUTPUT->header();
1214         echo '<div class="usersubmissions">';
1216         //hook to allow plagiarism plugins to update status/print links.
1217         plagiarism_update_status($this->course, $this->cm);
1219         $course_context = get_context_instance(CONTEXT_COURSE, $course->id);
1220         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
1221             echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">'
1222                 . get_string('seeallcoursegrades', 'grades') . '</a></div>';
1223         }
1225         if (!empty($message)) {
1226             echo $message;   // display messages here if any
1227         }
1229         $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1231     /// Check to see if groups are being used in this assignment
1233         /// find out current groups mode
1234         $groupmode = groups_get_activity_groupmode($cm);
1235         $currentgroup = groups_get_activity_group($cm, true);
1236         groups_print_activity_menu($cm, $CFG->wwwroot . '/mod/assignment/submissions.php?id=' . $this->cm->id);
1238         /// Print quickgrade form around the table
1239         if ($quickgrade) {
1240             $formattrs = array();
1241             $formattrs['action'] = new moodle_url('/mod/assignment/submissions.php');
1242             $formattrs['id'] = 'fastg';
1243             $formattrs['method'] = 'post';
1245             echo html_writer::start_tag('form', $formattrs);
1246             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'id',      'value'=> $this->cm->id));
1247             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'mode',    'value'=> 'fastgrade'));
1248             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'page',    'value'=> $page));
1249             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=> sesskey()));
1250         }
1252         /// Get all ppl that are allowed to submit assignments
1253         list($esql, $params) = get_enrolled_sql($context, 'mod/assignment:submit', $currentgroup);
1255         if ($filter == self::FILTER_ALL) {
1256             $sql = "SELECT u.id FROM {user} u ".
1257                    "LEFT JOIN ($esql) eu ON eu.id=u.id ".
1258                    "WHERE u.deleted = 0 AND eu.id=u.id ";
1259         } else {
1260             $wherefilter = ' AND s.assignment = '. $this->assignment->id;
1261             $assignmentsubmission = "LEFT JOIN {assignment_submissions} s ON (u.id = s.userid) ";
1262             if($filter == self::FILTER_SUBMITTED) {
1263                 $wherefilter .= ' AND s.timemodified > 0 ';
1264             } else if($filter == self::FILTER_REQUIRE_GRADING && $assignment->assignmenttype != 'offline') {
1265                 $wherefilter .= ' AND s.timemarked < s.timemodified ';
1266             } else { // require grading for offline assignment
1267                 $assignmentsubmission = "";
1268                 $wherefilter = "";
1269             }
1271             $sql = "SELECT u.id FROM {user} u ".
1272                    "LEFT JOIN ($esql) eu ON eu.id=u.id ".
1273                    $assignmentsubmission.
1274                    "WHERE u.deleted = 0 AND eu.id=u.id ".
1275                    $wherefilter;
1276         }
1278         $users = $DB->get_records_sql($sql, $params);
1279         if (!empty($users)) {
1280             if($assignment->assignmenttype == 'offline' && $filter == self::FILTER_REQUIRE_GRADING) {
1281                 //remove users who has submitted their assignment
1282                 foreach ($this->get_submissions() as $submission) {
1283                     if (array_key_exists($submission->userid, $users)) {
1284                         unset($users[$submission->userid]);
1285                     }
1286                 }
1287             }
1288             $users = array_keys($users);
1289         }
1291         // if groupmembersonly used, remove users who are not in any group
1292         if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
1293             if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1294                 $users = array_intersect($users, array_keys($groupingusers));
1295             }
1296         }
1298         $extrafields = get_extra_user_fields($context);
1299         $tablecolumns = array_merge(array('picture', 'fullname'), $extrafields,
1300                 array('grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade'));
1301         if ($uses_outcomes) {
1302             $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
1303         }
1305         $extrafieldnames = array();
1306         foreach ($extrafields as $field) {
1307             $extrafieldnames[] = get_user_field_name($field);
1308         }
1309         $tableheaders = array_merge(
1310                 array('', get_string('fullnameuser')),
1311                 $extrafieldnames,
1312                 array(
1313                     get_string('grade'),
1314                     get_string('comment', 'assignment'),
1315                     get_string('lastmodified').' ('.get_string('submission', 'assignment').')',
1316                     get_string('lastmodified').' ('.get_string('grade').')',
1317                     get_string('status'),
1318                     get_string('finalgrade', 'grades'),
1319                 ));
1320         if ($uses_outcomes) {
1321             $tableheaders[] = get_string('outcome', 'grades');
1322         }
1324         require_once($CFG->libdir.'/tablelib.php');
1325         $table = new flexible_table('mod-assignment-submissions');
1327         $table->define_columns($tablecolumns);
1328         $table->define_headers($tableheaders);
1329         $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;currentgroup='.$currentgroup);
1331         $table->sortable(true, 'lastname');//sorted by lastname by default
1332         $table->collapsible(true);
1333         $table->initialbars(true);
1335         $table->column_suppress('picture');
1336         $table->column_suppress('fullname');
1338         $table->column_class('picture', 'picture');
1339         $table->column_class('fullname', 'fullname');
1340         foreach ($extrafields as $field) {
1341             $table->column_class($field, $field);
1342         }
1343         $table->column_class('grade', 'grade');
1344         $table->column_class('submissioncomment', 'comment');
1345         $table->column_class('timemodified', 'timemodified');
1346         $table->column_class('timemarked', 'timemarked');
1347         $table->column_class('status', 'status');
1348         $table->column_class('finalgrade', 'finalgrade');
1349         if ($uses_outcomes) {
1350             $table->column_class('outcome', 'outcome');
1351         }
1353         $table->set_attribute('cellspacing', '0');
1354         $table->set_attribute('id', 'attempts');
1355         $table->set_attribute('class', 'submissions');
1356         $table->set_attribute('width', '100%');
1358         $table->no_sorting('finalgrade');
1359         $table->no_sorting('outcome');
1361         // Start working -- this is necessary as soon as the niceties are over
1362         $table->setup();
1364         /// Construct the SQL
1365         list($where, $params) = $table->get_sql_where();
1366         if ($where) {
1367             $where .= ' AND ';
1368         }
1370         if ($filter == self::FILTER_SUBMITTED) {
1371            $where .= 's.timemodified > 0 AND ';
1372         } else if($filter == self::FILTER_REQUIRE_GRADING) {
1373             $where = '';
1374             if ($assignment->assignmenttype != 'offline') {
1375                $where .= 's.timemarked < s.timemodified AND ';
1376             }
1377         }
1379         if ($sort = $table->get_sql_sort()) {
1380             $sort = ' ORDER BY '.$sort;
1381         }
1383         $ufields = user_picture::fields('u', $extrafields);
1384         if (!empty($users)) {
1385             $select = "SELECT $ufields,
1386                               s.id AS submissionid, s.grade, s.submissioncomment,
1387                               s.timemodified, s.timemarked,
1388                               CASE WHEN s.timemarked > 0 AND s.timemarked >= s.timemodified THEN 1
1389                                    ELSE 0 END AS status ";
1391             $sql = 'FROM {user} u '.
1392                    'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1393                     AND s.assignment = '.$this->assignment->id.' '.
1394                    'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1396             $ausers = $DB->get_records_sql($select.$sql.$sort, $params, $table->get_page_start(), $table->get_page_size());
1398             $table->pagesize($perpage, count($users));
1400             ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1401             $offset = $page * $perpage;
1402             $strupdate = get_string('update');
1403             $strgrade  = get_string('grade');
1404             $grademenu = make_grades_menu($this->assignment->grade);
1406             if ($ausers !== false) {
1407                 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
1408                 $endposition = $offset + $perpage;
1409                 $currentposition = 0;
1410                 foreach ($ausers as $auser) {
1411                     if ($currentposition == $offset && $offset < $endposition) {
1412                         $final_grade = $grading_info->items[0]->grades[$auser->id];
1413                         $grademax = $grading_info->items[0]->grademax;
1414                         $final_grade->formatted_grade = round($final_grade->grade,2) .' / ' . round($grademax,2);
1415                         $locked_overridden = 'locked';
1416                         if ($final_grade->overridden) {
1417                             $locked_overridden = 'overridden';
1418                         }
1420                         // TODO add here code if advanced grading grade must be reviewed => $auser->status=0
1422                         $picture = $OUTPUT->user_picture($auser);
1424                         if (empty($auser->submissionid)) {
1425                             $auser->grade = -1; //no submission yet
1426                         }
1428                         if (!empty($auser->submissionid)) {
1429                             $hassubmission = true;
1430                         ///Prints student answer and student modified date
1431                         ///attach file or print link to student answer, depending on the type of the assignment.
1432                         ///Refer to print_student_answer in inherited classes.
1433                             if ($auser->timemodified > 0) {
1434                                 $studentmodified = '<div id="ts'.$auser->id.'">'.$this->print_student_answer($auser->id)
1435                                                  . userdate($auser->timemodified).'</div>';
1436                             } else {
1437                                 $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1438                             }
1439                         ///Print grade, dropdown or text
1440                             if ($auser->timemarked > 0) {
1441                                 $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
1443                                 if ($final_grade->locked or $final_grade->overridden) {
1444                                     $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1445                                 } else if ($quickgrade) {
1446                                     $attributes = array();
1447                                     $attributes['tabindex'] = $tabindex++;
1448                                     $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1449                                     $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
1450                                 } else {
1451                                     $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1452                                 }
1454                             } else {
1455                                 $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1456                                 if ($final_grade->locked or $final_grade->overridden) {
1457                                     $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1458                                 } else if ($quickgrade) {
1459                                     $attributes = array();
1460                                     $attributes['tabindex'] = $tabindex++;
1461                                     $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1462                                     $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1463                                 } else {
1464                                     $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1465                                 }
1466                             }
1467                         ///Print Comment
1468                             if ($final_grade->locked or $final_grade->overridden) {
1469                                 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';
1471                             } else if ($quickgrade) {
1472                                 $comment = '<div id="com'.$auser->id.'">'
1473                                          . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1474                                          . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1475                             } else {
1476                                 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
1477                             }
1478                         } else {
1479                             $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1480                             $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1481                             $status          = '<div id="st'.$auser->id.'">&nbsp;</div>';
1483                             if ($final_grade->locked or $final_grade->overridden) {
1484                                 $grade = '<div id="g'.$auser->id.'">'.$final_grade->formatted_grade . '</div>';
1485                                 $hassubmission = true;
1486                             } else if ($quickgrade) {   // allow editing
1487                                 $attributes = array();
1488                                 $attributes['tabindex'] = $tabindex++;
1489                                 $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1490                                 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1491                                 $hassubmission = true;
1492                             } else {
1493                                 $grade = '<div id="g'.$auser->id.'">-</div>';
1494                             }
1496                             if ($final_grade->locked or $final_grade->overridden) {
1497                                 $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
1498                             } else if ($quickgrade) {
1499                                 $comment = '<div id="com'.$auser->id.'">'
1500                                          . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1501                                          . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1502                             } else {
1503                                 $comment = '<div id="com'.$auser->id.'">&nbsp;</div>';
1504                             }
1505                         }
1507                         if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
1508                             $auser->status = 0;
1509                         } else {
1510                             $auser->status = 1;
1511                         }
1513                         $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
1515                         ///No more buttons, we use popups ;-).
1516                         $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1517                                    . '&amp;userid='.$auser->id.'&amp;mode=single'.'&amp;filter='.$filter.'&amp;offset='.$offset++;
1519                         $button = $OUTPUT->action_link($popup_url, $buttontext);
1521                         $status  = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
1523                         $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';
1525                         $outcomes = '';
1527                         if ($uses_outcomes) {
1529                             foreach($grading_info->outcomes as $n=>$outcome) {
1530                                 $outcomes .= '<div class="outcome"><label>'.$outcome->name.'</label>';
1531                                 $options = make_grades_menu(-$outcome->scaleid);
1533                                 if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
1534                                     $options[0] = get_string('nooutcome', 'grades');
1535                                     $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
1536                                 } else {
1537                                     $attributes = array();
1538                                     $attributes['tabindex'] = $tabindex++;
1539                                     $attributes['id'] = 'outcome_'.$n.'_'.$auser->id;
1540                                     $outcomes .= ' '.html_writer::select($options, 'outcome_'.$n.'['.$auser->id.']', $outcome->grades[$auser->id]->grade, array(0=>get_string('nooutcome', 'grades')), $attributes);
1541                                 }
1542                                 $outcomes .= '</div>';
1543                             }
1544                         }
1546                         $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>';
1547                         $extradata = array();
1548                         foreach ($extrafields as $field) {
1549                             $extradata[] = $auser->{$field};
1550                         }
1551                         $row = array_merge(array($picture, $userlink), $extradata,
1552                                 array($grade, $comment, $studentmodified, $teachermodified,
1553                                 $status, $finalgrade));
1554                         if ($uses_outcomes) {
1555                             $row[] = $outcomes;
1556                         }
1557                         $table->add_data($row);
1558                     }
1559                     $currentposition++;
1560                 }
1561                 if ($hassubmission && ($this->assignment->assignmenttype=='upload' || $this->assignment->assignmenttype=='online' || $this->assignment->assignmenttype=='uploadsingle')) { //TODO: this is an ugly hack, where is the plugin spirit? (skodak)
1562                     echo html_writer::start_tag('div', array('class' => 'mod-assignment-download-link'));
1563                     echo html_writer::link(new moodle_url('/mod/assignment/submissions.php', array('id' => $this->cm->id, 'download' => 'zip')), get_string('downloadall', 'assignment'));
1564                     echo html_writer::end_tag('div');
1565                 }
1566                 $table->print_html();  /// Print the whole table
1567             } else {
1568                 if ($filter == self::FILTER_SUBMITTED) {
1569                     echo html_writer::tag('div', get_string('nosubmisson', 'assignment'), array('class'=>'nosubmisson'));
1570                 } else if ($filter == self::FILTER_REQUIRE_GRADING) {
1571                     echo html_writer::tag('div', get_string('norequiregrading', 'assignment'), array('class'=>'norequiregrading'));
1572                 }
1573             }
1574         }
1576         /// Print quickgrade form around the table
1577         if ($quickgrade && $table->started_output && !empty($users)){
1578             $mailinfopref = false;
1579             if (get_user_preferences('assignment_mailinfo', 1)) {
1580                 $mailinfopref = true;
1581             }
1582             $emailnotification =  html_writer::checkbox('mailinfo', 1, $mailinfopref, get_string('enablenotification','assignment'));
1584             $emailnotification .= $OUTPUT->help_icon('enablenotification', 'assignment');
1585             echo html_writer::tag('div', $emailnotification, array('class'=>'emailnotification'));
1587             $savefeedback = html_writer::empty_tag('input', array('type'=>'submit', 'name'=>'fastg', 'value'=>get_string('saveallfeedback', 'assignment')));
1588             echo html_writer::tag('div', $savefeedback, array('class'=>'fastgbutton'));
1590             echo html_writer::end_tag('form');
1591         } else if ($quickgrade) {
1592             echo html_writer::end_tag('form');
1593         }
1595         echo '</div>';
1596         /// End of fast grading form
1598         /// Mini form for setting user preference
1600         $formaction = new moodle_url('/mod/assignment/submissions.php', array('id'=>$this->cm->id));
1601         $mform = new MoodleQuickForm('optionspref', 'post', $formaction, '', array('class'=>'optionspref'));
1603         $mform->addElement('hidden', 'updatepref');
1604         $mform->setDefault('updatepref', 1);
1605         $mform->addElement('header', 'qgprefs', get_string('optionalsettings', 'assignment'));
1606         $mform->addElement('select', 'filter', get_string('show'),  $filters);
1608         $mform->setDefault('filter', $filter);
1610         $mform->addElement('text', 'perpage', get_string('pagesize', 'assignment'), array('size'=>1));
1611         $mform->setDefault('perpage', $perpage);
1613         if ($this->quickgrade_mode_allowed()) {
1614             $mform->addElement('checkbox', 'quickgrade', get_string('quickgrade','assignment'));
1615             $mform->setDefault('quickgrade', $quickgrade);
1616             $mform->addHelpButton('quickgrade', 'quickgrade', 'assignment');
1617         }
1619         $mform->addElement('submit', 'savepreferences', get_string('savepreferences'));
1621         $mform->display();
1623         echo $OUTPUT->footer();
1624     }
1626     /**
1627      * If the form was cancelled ('Cancel' or 'Next' was pressed), call cancel method
1628      * from advanced grading (if applicable) and returns true
1629      * If the form was submitted, validates it and returns false if validation did not pass.
1630      * If validation passes, preprocess advanced grading (if applicable) and returns true.
1631      *
1632      * Note to the developers: This is NOT the correct way to implement advanced grading
1633      * in grading form. The assignment grading was written long time ago and unfortunately
1634      * does not fully use the mforms. Usually function is_validated() is called to
1635      * validate the form and get_data() is called to get the data from the form.
1636      *
1637      * Here we have to push the calculated grade to $_POST['xgrade'] because further processing
1638      * of the form gets the data not from form->get_data(), but from $_POST (using statement
1639      * like  $feedback = data_submitted() )
1640      */
1641     protected function validate_and_preprocess_feedback() {
1642         global $USER, $CFG;
1643         require_once($CFG->libdir.'/gradelib.php');
1644         if (!($feedback = data_submitted()) || !isset($feedback->userid) || !isset($feedback->offset)) {
1645             return true;      // No incoming data, nothing to validate
1646         }
1647         $userid = required_param('userid', PARAM_INT);
1648         $offset = required_param('offset', PARAM_INT);
1649         $gradinginfo = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($userid));
1650         $gradingdisabled = $gradinginfo->items[0]->grades[$userid]->locked || $gradinginfo->items[0]->grades[$userid]->overridden;
1651         if ($gradingdisabled) {
1652             return true;
1653         }
1654         $submissiondata = $this->display_submission($offset, $userid, false);
1655         $mform = $submissiondata->mform;
1656         $gradinginstance = $mform->use_advanced_grading();
1657         if (optional_param('cancel', false, PARAM_BOOL) || optional_param('next', false, PARAM_BOOL)) {
1658             // form was cancelled
1659             if ($gradinginstance) {
1660                 $gradinginstance->cancel();
1661             }
1662         } else if ($mform->is_submitted()) {
1663             // form was submitted (= a submit button other than 'cancel' or 'next' has been clicked)
1664             if (!$mform->is_validated()) {
1665                 return false;
1666             }
1667             // preprocess advanced grading here
1668             if ($gradinginstance) {
1669                 $data = $mform->get_data();
1670                 // create submission if it did not exist yet because we need submission->id for storing the grading instance
1671                 $submission = $this->get_submission($userid, true);
1672                 $_POST['xgrade'] = $gradinginstance->submit_and_get_grade($data->advancedgrading, $submission->id);
1673             }
1674         }
1675         return true;
1676     }
1678     /**
1679      *  Process teacher feedback submission
1680      *
1681      * This is called by submissions() when a grading even has taken place.
1682      * It gets its data from the submitted form.
1683      *
1684      * @global object
1685      * @global object
1686      * @global object
1687      * @return object|bool The updated submission object or false
1688      */
1689     function process_feedback($formdata=null) {
1690         global $CFG, $USER, $DB;
1691         require_once($CFG->libdir.'/gradelib.php');
1693         if (!$feedback = data_submitted() or !confirm_sesskey()) {      // No incoming data?
1694             return false;
1695         }
1697         ///For save and next, we need to know the userid to save, and the userid to go
1698         ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1699         ///as the userid to store
1700         if ((int)$feedback->saveuserid !== -1){
1701             $feedback->userid = $feedback->saveuserid;
1702         }
1704         if (!empty($feedback->cancel)) {          // User hit cancel button
1705             return false;
1706         }
1708         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);
1710         // store outcomes if needed
1711         $this->process_outcomes($feedback->userid);
1713         $submission = $this->get_submission($feedback->userid, true);  // Get or make one
1715         if (!($grading_info->items[0]->grades[$feedback->userid]->locked ||
1716             $grading_info->items[0]->grades[$feedback->userid]->overridden) ) {
1718             $submission->grade      = $feedback->xgrade;
1719             $submission->submissioncomment    = $feedback->submissioncomment_editor['text'];
1720             $submission->teacher    = $USER->id;
1721             $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1722             if (!$mailinfo) {
1723                 $submission->mailed = 1;       // treat as already mailed
1724             } else {
1725                 $submission->mailed = 0;       // Make sure mail goes out (again, even)
1726             }
1727             $submission->timemarked = time();
1729             unset($submission->data1);  // Don't need to update this.
1730             unset($submission->data2);  // Don't need to update this.
1732             if (empty($submission->timemodified)) {   // eg for offline assignments
1733                 // $submission->timemodified = time();
1734             }
1736             $DB->update_record('assignment_submissions', $submission);
1738             // triger grade event
1739             $this->update_grade($submission);
1741             add_to_log($this->course->id, 'assignment', 'update grades',
1742                        'submissions.php?id='.$this->cm->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
1743              if (!is_null($formdata)) {
1744                     if ($this->type == 'upload' || $this->type == 'uploadsingle') {
1745                         $mformdata = $formdata->mform->get_data();
1746                         $mformdata = file_postupdate_standard_filemanager($mformdata, 'files', $formdata->fileui_options, $this->context, 'mod_assignment', 'response', $submission->id);
1747                     }
1748              }
1749         }
1751         return $submission;
1753     }
1755     function process_outcomes($userid) {
1756         global $CFG, $USER;
1758         if (empty($CFG->enableoutcomes)) {
1759             return;
1760         }
1762         require_once($CFG->libdir.'/gradelib.php');
1764         if (!$formdata = data_submitted() or !confirm_sesskey()) {
1765             return;
1766         }
1768         $data = array();
1769         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
1771         if (!empty($grading_info->outcomes)) {
1772             foreach($grading_info->outcomes as $n=>$old) {
1773                 $name = 'outcome_'.$n;
1774                 if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
1775                     $data[$n] = $formdata->{$name}[$userid];
1776                 }
1777             }
1778         }
1779         if (count($data) > 0) {
1780             grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1781         }
1783     }
1785     /**
1786      * Load the submission object for a particular user
1787      *
1788      * @global object
1789      * @global object
1790      * @param $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1791      * @param $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1792      * @param bool $teachermodified student submission set if false
1793      * @return object The submission
1794      */
1795     function get_submission($userid=0, $createnew=false, $teachermodified=false) {
1796         global $USER, $DB;
1798         if (empty($userid)) {
1799             $userid = $USER->id;
1800         }
1802         $submission = $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1804         if ($submission || !$createnew) {
1805             return $submission;
1806         }
1807         $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
1808         $DB->insert_record("assignment_submissions", $newsubmission);
1810         return $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1811     }
1813     /**
1814      * Instantiates a new submission object for a given user
1815      *
1816      * Sets the assignment, userid and times, everything else is set to default values.
1817      *
1818      * @param int $userid The userid for which we want a submission object
1819      * @param bool $teachermodified student submission set if false
1820      * @return object The submission
1821      */
1822     function prepare_new_submission($userid, $teachermodified=false) {
1823         $submission = new stdClass();
1824         $submission->assignment   = $this->assignment->id;
1825         $submission->userid       = $userid;
1826         $submission->timecreated = time();
1827         // teachers should not be modifying modified date, except offline assignments
1828         if ($teachermodified) {
1829             $submission->timemodified = 0;
1830         } else {
1831             $submission->timemodified = $submission->timecreated;
1832         }
1833         $submission->numfiles     = 0;
1834         $submission->data1        = '';
1835         $submission->data2        = '';
1836         $submission->grade        = -1;
1837         $submission->submissioncomment      = '';
1838         $submission->format       = 0;
1839         $submission->teacher      = 0;
1840         $submission->timemarked   = 0;
1841         $submission->mailed       = 0;
1842         return $submission;
1843     }
1845     /**
1846      * Return all assignment submissions by ENROLLED students (even empty)
1847      *
1848      * @param string $sort optional field names for the ORDER BY in the sql query
1849      * @param string $dir optional specifying the sort direction, defaults to DESC
1850      * @return array The submission objects indexed by id
1851      */
1852     function get_submissions($sort='', $dir='DESC') {
1853         return assignment_get_all_submissions($this->assignment, $sort, $dir);
1854     }
1856     /**
1857      * Counts all real assignment submissions by ENROLLED students (not empty ones)
1858      *
1859      * @param int $groupid optional If nonzero then count is restricted to this group
1860      * @return int The number of submissions
1861      */
1862     function count_real_submissions($groupid=0) {
1863         return assignment_count_real_submissions($this->cm, $groupid);
1864     }
1866     /**
1867      * Alerts teachers by email of new or changed assignments that need grading
1868      *
1869      * First checks whether the option to email teachers is set for this assignment.
1870      * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1871      * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1872      *
1873      * @global object
1874      * @global object
1875      * @param $submission object The submission that has changed
1876      * @return void
1877      */
1878     function email_teachers($submission) {
1879         global $CFG, $DB;
1881         if (empty($this->assignment->emailteachers)) {          // No need to do anything
1882             return;
1883         }
1885         $user = $DB->get_record('user', array('id'=>$submission->userid));
1887         if ($teachers = $this->get_graders($user)) {
1889             $strassignments = get_string('modulenameplural', 'assignment');
1890             $strassignment  = get_string('modulename', 'assignment');
1891             $strsubmitted  = get_string('submitted', 'assignment');
1893             foreach ($teachers as $teacher) {
1894                 $info = new stdClass();
1895                 $info->username = fullname($user, true);
1896                 $info->assignment = format_string($this->assignment->name,true);
1897                 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
1898                 $info->timeupdated = userdate($submission->timemodified, '%c', $teacher->timezone);
1900                 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1901                 $posttext = $this->email_teachers_text($info);
1902                 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
1904                 $eventdata = new stdClass();
1905                 $eventdata->modulename       = 'assignment';
1906                 $eventdata->userfrom         = $user;
1907                 $eventdata->userto           = $teacher;
1908                 $eventdata->subject          = $postsubject;
1909                 $eventdata->fullmessage      = $posttext;
1910                 $eventdata->fullmessageformat = FORMAT_PLAIN;
1911                 $eventdata->fullmessagehtml  = $posthtml;
1912                 $eventdata->smallmessage     = $postsubject;
1914                 $eventdata->name            = 'assignment_updates';
1915                 $eventdata->component       = 'mod_assignment';
1916                 $eventdata->notification    = 1;
1917                 $eventdata->contexturl      = $info->url;
1918                 $eventdata->contexturlname  = $info->assignment;
1920                 message_send($eventdata);
1921             }
1922         }
1923     }
1925     /**
1926      * @param string $filearea
1927      * @param array $args
1928      * @return bool
1929      */
1930     function send_file($filearea, $args) {
1931         debugging('plugin does not implement file sending', DEBUG_DEVELOPER);
1932         return false;
1933     }
1935     /**
1936      * Returns a list of teachers that should be grading given submission
1937      *
1938      * @param object $user
1939      * @return array
1940      */
1941     function get_graders($user) {
1942         //potential graders
1943         $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false);
1945         $graders = array();
1946         if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) {   // Separate groups are being used
1947             if ($groups = groups_get_all_groups($this->course->id, $user->id)) {  // Try to find all groups
1948                 foreach ($groups as $group) {
1949                     foreach ($potgraders as $t) {
1950                         if ($t->id == $user->id) {
1951                             continue; // do not send self
1952                         }
1953                         if (groups_is_member($group->id, $t->id)) {
1954                             $graders[$t->id] = $t;
1955                         }
1956                     }
1957                 }
1958             } else {
1959                 // user not in group, try to find graders without group
1960                 foreach ($potgraders as $t) {
1961                     if ($t->id == $user->id) {
1962                         continue; // do not send self
1963                     }
1964                     if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
1965                         $graders[$t->id] = $t;
1966                     }
1967                 }
1968             }
1969         } else {
1970             foreach ($potgraders as $t) {
1971                 if ($t->id == $user->id) {
1972                     continue; // do not send self
1973                 }
1974                 $graders[$t->id] = $t;
1975             }
1976         }
1977         return $graders;
1978     }
1980     /**
1981      * Creates the text content for emails to teachers
1982      *
1983      * @param $info object The info used by the 'emailteachermail' language string
1984      * @return string
1985      */
1986     function email_teachers_text($info) {
1987         $posttext  = format_string($this->course->shortname, true, array('context' => $this->coursecontext)).' -> '.
1988                      $this->strassignments.' -> '.
1989                      format_string($this->assignment->name, true, array('context' => $this->context))."\n";
1990         $posttext .= '---------------------------------------------------------------------'."\n";
1991         $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
1992         $posttext .= "\n---------------------------------------------------------------------\n";
1993         return $posttext;
1994     }
1996      /**
1997      * Creates the html content for emails to teachers
1998      *
1999      * @param $info object The info used by the 'emailteachermailhtml' language string
2000      * @return string
2001      */
2002     function email_teachers_html($info) {
2003         global $CFG;
2004         $posthtml  = '<p><font face="sans-serif">'.
2005                      '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname, true, array('context' => $this->coursecontext)).'</a> ->'.
2006                      '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
2007                      '<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>';
2008         $posthtml .= '<hr /><font face="sans-serif">';
2009         $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
2010         $posthtml .= '</font><hr />';
2011         return $posthtml;
2012     }
2014     /**
2015      * Produces a list of links to the files uploaded by a user
2016      *
2017      * @param $userid int optional id of the user. If 0 then $USER->id is used.
2018      * @param $return boolean optional defaults to false. If true the list is returned rather than printed
2019      * @return string optional
2020      */
2021     function print_user_files($userid=0, $return=false) {
2022         global $CFG, $USER, $OUTPUT;
2024         if (!$userid) {
2025             if (!isloggedin()) {
2026                 return '';
2027             }
2028             $userid = $USER->id;
2029         }
2031         $output = '';
2033         $submission = $this->get_submission($userid);
2034         if (!$submission) {
2035             return $output;
2036         }
2038         $fs = get_file_storage();
2039         $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false);
2040         if (!empty($files)) {
2041             require_once($CFG->dirroot . '/mod/assignment/locallib.php');
2042             if ($CFG->enableportfolios) {
2043                 require_once($CFG->libdir.'/portfoliolib.php');
2044                 $button = new portfolio_add_button();
2045             }
2046             foreach ($files as $file) {
2047                 $filename = $file->get_filename();
2048                 $mimetype = $file->get_mimetype();
2049                 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/mod_assignment/submission/'.$submission->id.'/'.$filename);
2050                 $output .= '<a href="'.$path.'" ><img src="'.$OUTPUT->pix_url(file_mimetype_icon($mimetype)).'" class="icon" alt="'.$mimetype.'" />'.s($filename).'</a>';
2051                 if ($CFG->enableportfolios && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
2052                     $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id, 'submissionid' => $submission->id, 'fileid' => $file->get_id()), '/mod/assignment/locallib.php');
2053                     $button->set_format_by_file($file);
2054                     $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
2055                 }
2057                 if ($CFG->enableplagiarism) {
2058                     require_once($CFG->libdir.'/plagiarismlib.php');
2059                     $output .= plagiarism_get_links(array('userid'=>$userid, 'file'=>$file, 'cmid'=>$this->cm->id, 'course'=>$this->course, 'assignment'=>$this->assignment));
2060                     $output .= '<br />';
2061                 }
2062             }
2063             if ($CFG->enableportfolios && count($files) > 1  && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
2064                 $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id, 'submissionid' => $submission->id), '/mod/assignment/locallib.php');
2065                 $output .= '<br />'  . $button->to_html(PORTFOLIO_ADD_TEXT_LINK);
2066             }
2067         }
2069         $output = '<div class="files">'.$output.'</div>';
2071         if ($return) {
2072             return $output;
2073         }
2074         echo $output;
2075     }
2077     /**
2078      * Count the files uploaded by a given user
2079      *
2080      * @param $itemid int The submission's id as the file's itemid.
2081      * @return int
2082      */
2083     function count_user_files($itemid) {
2084         $fs = get_file_storage();
2085         $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $itemid, "id", false);
2086         return count($files);
2087     }
2089     /**
2090      * Returns true if the student is allowed to submit
2091      *
2092      * Checks that the assignment has started and, if the option to prevent late
2093      * submissions is set, also checks that the assignment has not yet closed.
2094      * @return boolean
2095      */
2096     function isopen() {
2097         $time = time();
2098         if ($this->assignment->preventlate && $this->assignment->timedue) {
2099             return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
2100         } else {
2101             return ($this->assignment->timeavailable <= $time);
2102         }
2103     }
2106     /**
2107      * Return true if is set description is hidden till available date
2108      *
2109      * This is needed by calendar so that hidden descriptions do not
2110      * come up in upcoming events.
2111      *
2112      * Check that description is hidden till available date
2113      * By default return false
2114      * Assignments types should implement this method if needed
2115      * @return boolen
2116      */
2117     function description_is_hidden() {
2118         return false;
2119     }
2121     /**
2122      * Return an outline of the user's interaction with the assignment
2123      *
2124      * The default method prints the grade and timemodified
2125      * @param $grade object
2126      * @return object with properties ->info and ->time
2127      */
2128     function user_outline($grade) {
2130         $result = new stdClass();
2131         $result->info = get_string('grade').': '.$grade->str_long_grade;
2132         $result->time = $grade->dategraded;
2133         return $result;
2134     }
2136     /**
2137      * Print complete information about the user's interaction with the assignment
2138      *
2139      * @param $user object
2140      */
2141     function user_complete($user, $grade=null) {
2142         global $OUTPUT;
2144         if ($submission = $this->get_submission($user->id)) {
2146             $fs = get_file_storage();
2148             if ($files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false)) {
2149                 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
2150                 foreach ($files as $file) {
2151                     $countfiles .= "; ".$file->get_filename();
2152                 }
2153             }
2155             echo $OUTPUT->box_start();
2156             echo get_string("lastmodified").": ";
2157             echo userdate($submission->timemodified);
2158             echo $this->display_lateness($submission->timemodified);
2160             $this->print_user_files($user->id);
2162             echo '<br />';
2164             $this->view_feedback($submission);
2166             echo $OUTPUT->box_end();
2168         } else {
2169             if ($grade) {
2170                 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
2171                 if ($grade->str_feedback) {
2172                     echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
2173                 }
2174             }
2175             print_string("notsubmittedyet", "assignment");
2176         }
2177     }
2179     /**
2180      * Return a string indicating how late a submission is
2181      *
2182      * @param $timesubmitted int
2183      * @return string
2184      */
2185     function display_lateness($timesubmitted) {
2186         return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
2187     }
2189     /**
2190      * Empty method stub for all delete actions.
2191      */
2192     function delete() {
2193         //nothing by default
2194         redirect('view.php?id='.$this->cm->id);
2195     }
2197     /**
2198      * Empty custom feedback grading form.
2199      */
2200     function custom_feedbackform($submission, $return=false) {
2201         //nothing by default
2202         return '';
2203     }
2205     /**
2206      * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
2207      * for the course (see resource).
2208      *
2209      * Given a course_module object, this function returns any "extra" information that may be needed
2210      * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
2211      *
2212      * @param $coursemodule object The coursemodule object (record).
2213      * @return cached_cm_info Object used to customise appearance on course page
2214      */
2215     function get_coursemodule_info($coursemodule) {
2216         return null;
2217     }
2219     /**
2220      * Plugin cron method - do not use $this here, create new assignment instances if needed.
2221      * @return void
2222      */
2223     function cron() {
2224         //no plugin cron by default - override if needed
2225     }
2227     /**
2228      * Reset all submissions
2229      */
2230     function reset_userdata($data) {
2231         global $CFG, $DB;
2233         if (!$DB->count_records('assignment', array('course'=>$data->courseid, 'assignmenttype'=>$this->type))) {
2234             return array(); // no assignments of this type present
2235         }
2237         $componentstr = get_string('modulenameplural', 'assignment');
2238         $status = array();
2240         $typestr = get_string('type'.$this->type, 'assignment');
2241         // ugly hack to support pluggable assignment type titles...
2242         if($typestr === '[[type'.$this->type.']]'){
2243             $typestr = get_string('type'.$this->type, 'assignment_'.$this->type);
2244         }
2246         if (!empty($data->reset_assignment_submissions)) {
2247             $assignmentssql = "SELECT a.id
2248                                  FROM {assignment} a
2249                                 WHERE a.course=? AND a.assignmenttype=?";
2250             $params = array($data->courseid, $this->type);
2252             // now get rid of all submissions and responses
2253             $fs = get_file_storage();
2254             if ($assignments = $DB->get_records_sql($assignmentssql, $params)) {
2255                 foreach ($assignments as $assignmentid=>$unused) {
2256                     if (!$cm = get_coursemodule_from_instance('assignment', $assignmentid)) {
2257                         continue;
2258                     }
2259                     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2260                     $fs->delete_area_files($context->id, 'mod_assignment', 'submission');
2261                     $fs->delete_area_files($context->id, 'mod_assignment', 'response');
2262                 }
2263             }
2265             $DB->delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)", $params);
2267             $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
2269             if (empty($data->reset_gradebook_grades)) {
2270                 // remove all grades from gradebook
2271                 assignment_reset_gradebook($data->courseid, $this->type);
2272             }
2273         }
2275         /// updating dates - shift may be negative too
2276         if ($data->timeshift) {
2277             shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
2278             $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
2279         }
2281         return $status;
2282     }
2285     function portfolio_exportable() {
2286         return false;
2287     }
2289     /**
2290      * base implementation for backing up subtype specific information
2291      * for one single module
2292      *
2293      * @param filehandle $bf file handle for xml file to write to
2294      * @param mixed $preferences the complete backup preference object
2295      *
2296      * @return boolean
2297      *
2298      * @static
2299      */
2300     static function backup_one_mod($bf, $preferences, $assignment) {
2301         return true;
2302     }
2304     /**
2305      * base implementation for backing up subtype specific information
2306      * for one single submission
2307      *
2308      * @param filehandle $bf file handle for xml file to write to
2309      * @param mixed $preferences the complete backup preference object
2310      * @param object $submission the assignment submission db record
2311      *
2312      * @return boolean
2313      *
2314      * @static
2315      */
2316     static function backup_one_submission($bf, $preferences, $assignment, $submission) {
2317         return true;
2318     }
2320     /**
2321      * base implementation for restoring subtype specific information
2322      * for one single module
2323      *
2324      * @param array  $info the array representing the xml
2325      * @param object $restore the restore preferences
2326      *
2327      * @return boolean
2328      *
2329      * @static
2330      */
2331     static function restore_one_mod($info, $restore, $assignment) {
2332         return true;
2333     }
2335     /**
2336      * base implementation for restoring subtype specific information
2337      * for one single submission
2338      *
2339      * @param object $submission the newly created submission
2340      * @param array  $info the array representing the xml
2341      * @param object $restore the restore preferences
2342      *
2343      * @return boolean
2344      *
2345      * @static
2346      */
2347     static function restore_one_submission($info, $restore, $assignment, $submission) {
2348         return true;
2349     }
2351 } ////// End of the assignment_base class
2354 class mod_assignment_grading_form extends moodleform {
2355     /** @var stores the advaned grading instance (if used in grading) */
2356     private $advancegradinginstance;
2358     function definition() {
2359         global $OUTPUT;
2360         $mform =& $this->_form;
2362         if (isset($this->_customdata->advancedgradinginstance)) {
2363             $this->use_advanced_grading($this->_customdata->advancedgradinginstance);
2364         }
2366         $formattr = $mform->getAttributes();
2367         $formattr['id'] = 'submitform';
2368         $mform->setAttributes($formattr);
2369         // hidden params
2370         $mform->addElement('hidden', 'offset', ($this->_customdata->offset+1));
2371         $mform->setType('offset', PARAM_INT);
2372         $mform->addElement('hidden', 'userid', $this->_customdata->userid);
2373         $mform->setType('userid', PARAM_INT);
2374         $mform->addElement('hidden', 'nextid', $this->_customdata->nextid);
2375         $mform->setType('nextid', PARAM_INT);
2376         $mform->addElement('hidden', 'id', $this->_customdata->cm->id);
2377         $mform->setType('id', PARAM_INT);
2378         $mform->addElement('hidden', 'sesskey', sesskey());
2379         $mform->setType('sesskey', PARAM_ALPHANUM);
2380         $mform->addElement('hidden', 'mode', 'grade');
2381         $mform->setType('mode', PARAM_TEXT);
2382         $mform->addElement('hidden', 'menuindex', "0");
2383         $mform->setType('menuindex', PARAM_INT);
2384         $mform->addElement('hidden', 'saveuserid', "-1");
2385         $mform->setType('saveuserid', PARAM_INT);
2386         $mform->addElement('hidden', 'filter', "0");
2387         $mform->setType('filter', PARAM_INT);
2389         $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->user),
2390                                                 fullname($this->_customdata->user, true) . '<br/>' .
2391                                                 userdate($this->_customdata->submission->timemodified) .
2392                                                 $this->_customdata->lateness );
2394         $this->add_submission_content();
2395         $this->add_grades_section();
2397         $this->add_feedback_section();
2399         if ($this->_customdata->submission->timemarked) {
2400             $datestring = userdate($this->_customdata->submission->timemarked)."&nbsp; (".format_time(time() - $this->_customdata->submission->timemarked).")";
2401             $mform->addElement('header', 'Last Grade', get_string('lastgrade', 'assignment'));
2402             $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->teacher) ,
2403                                                     fullname($this->_customdata->teacher,true).
2404                                                     '<br/>'.$datestring);
2405         }
2406         // buttons
2407         $this->add_action_buttons();
2409     }
2411     /**
2412      * Gets or sets the instance for advanced grading
2413      *
2414      * @param gradingform_instance $gradinginstance
2415      */
2416     public function use_advanced_grading($gradinginstance = false) {
2417         if ($gradinginstance !== false) {
2418             $this->advancegradinginstance = $gradinginstance;
2419         }
2420         return $this->advancegradinginstance;
2421     }
2423     function add_grades_section() {
2424         global $CFG;
2425         $mform =& $this->_form;
2426         $attributes = array();
2427         if ($this->_customdata->gradingdisabled) {
2428             $attributes['disabled'] ='disabled';
2429         }
2431         $mform->addElement('header', 'Grades', get_string('grades', 'grades'));
2433         $grademenu = make_grades_menu($this->_customdata->assignment->grade);
2434         if ($gradinginstance = $this->use_advanced_grading()) {
2435             $gradinginstance->get_controller()->set_grade_range($grademenu);
2436             $gradingelement = $mform->addElement('grading', 'advancedgrading', get_string('grade').':', array('gradinginstance' => $gradinginstance));
2437             if ($this->_customdata->gradingdisabled) {
2438                 $gradingelement->freeze();
2439             } else {
2440                 $mform->addElement('hidden', 'advancedgradinginstanceid', $gradinginstance->get_id());
2441             }
2442         } else {
2443             // use simple direct grading
2444             $grademenu['-1'] = get_string('nograde');
2446             $mform->addElement('select', 'xgrade', get_string('grade').':', $grademenu, $attributes);
2447             $mform->setDefault('xgrade', $this->_customdata->submission->grade ); //@fixme some bug when element called 'grade' makes it break
2448             $mform->setType('xgrade', PARAM_INT);
2449         }
2451         if (!empty($this->_customdata->enableoutcomes)) {
2452             foreach($this->_customdata->grading_info->outcomes as $n=>$outcome) {
2453                 $options = make_grades_menu(-$outcome->scaleid);
2454                 if ($outcome->grades[$this->_customdata->submission->userid]->locked) {
2455                     $options[0] = get_string('nooutcome', 'grades');
2456                     $mform->addElement('static', 'outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->name.':',
2457                             $options[$outcome->grades[$this->_customdata->submission->userid]->grade]);
2458                 } else {
2459                     $options[''] = get_string('nooutcome', 'grades');
2460                     $attributes = array('id' => 'menuoutcome_'.$n );
2461                     $mform->addElement('select', 'outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->name.':', $options, $attributes );
2462                     $mform->setType('outcome_'.$n.'['.$this->_customdata->userid.']', PARAM_INT);
2463                     $mform->setDefault('outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->grades[$this->_customdata->submission->userid]->grade );
2464                 }
2465             }
2466         }
2467         $course_context = get_context_instance(CONTEXT_MODULE , $this->_customdata->cm->id);
2468         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
2469             $grade = '<a href="'.$CFG->wwwroot.'/grade/report/grader/index.php?id='. $this->_customdata->courseid .'" >'.
2470                         $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade . '</a>';
2471         }else{
2472             $grade = $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade;
2473         }
2474         $mform->addElement('static', 'finalgrade', get_string('currentgrade', 'assignment').':' ,$grade);
2475         $mform->setType('finalgrade', PARAM_INT);
2476     }
2478     /**
2479      *
2480      * @global core_renderer $OUTPUT
2481      */
2482     function add_feedback_section() {
2483         global $OUTPUT;
2484         $mform =& $this->_form;
2485         $mform->addElement('header', 'Feed Back', get_string('feedback', 'grades'));
2487         if ($this->_customdata->gradingdisabled) {
2488             $mform->addElement('static', 'disabledfeedback', $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_feedback );
2489         } else {
2490             // visible elements
2492             $mform->addElement('editor', 'submissioncomment_editor', get_string('feedback', 'assignment').':', null, $this->get_editor_options() );
2493             $mform->setType('submissioncomment_editor', PARAM_RAW); // to be cleaned before display
2494             $mform->setDefault('submissioncomment_editor', $this->_customdata->submission->submissioncomment);
2495             //$mform->addRule('submissioncomment', get_string('required'), 'required', null, 'client');
2496             switch ($this->_customdata->assignment->assignmenttype) {
2497                 case 'upload' :
2498                 case 'uploadsingle' :
2499                     $mform->addElement('filemanager', 'files_filemanager', get_string('responsefiles', 'assignment'). ':', null, $this->_customdata->fileui_options);
2500                     break;
2501                 default :
2502                     break;
2503             }
2504             $mform->addElement('hidden', 'mailinfo_h', "0");
2505             $mform->setType('mailinfo_h', PARAM_INT);
2506             $mform->addElement('checkbox', 'mailinfo',get_string('enablenotification','assignment').
2507             $OUTPUT->help_icon('enablenotification', 'assignment') .':' );
2508             $mform->setType('mailinfo', PARAM_INT);
2509         }
2510     }
2512     function add_action_buttons() {
2513         $mform =& $this->_form;
2514         //if there are more to be graded.
2515         if ($this->_customdata->nextid>0) {
2516             $buttonarray=array();
2517             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2518             //@todo: fix accessibility: javascript dependency not necessary
2519             $buttonarray[] = &$mform->createElement('submit', 'saveandnext', get_string('saveandnext'));
2520             $buttonarray[] = &$mform->createElement('submit', 'next', get_string('next'));
2521             $buttonarray[] = &$mform->createElement('cancel');
2522         } else {
2523             $buttonarray=array();
2524             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2525             $buttonarray[] = &$mform->createElement('cancel');
2526         }
2527         $mform->addGroup($buttonarray, 'grading_buttonar', '', array(' '), false);
2528         $mform->closeHeaderBefore('grading_buttonar');
2529         $mform->setType('grading_buttonar', PARAM_RAW);
2530     }
2532     function add_submission_content() {
2533         $mform =& $this->_form;
2534         $mform->addElement('header', 'Submission', get_string('submission', 'assignment'));
2535         $mform->addElement('static', '', '' , $this->_customdata->submission_content );
2536     }
2538     protected function get_editor_options() {
2539         $editoroptions = array();
2540         $editoroptions['component'] = 'mod_assignment';
2541         $editoroptions['filearea'] = 'feedback';
2542         $editoroptions['noclean'] = false;
2543         $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)
2544         $editoroptions['maxbytes'] = $this->_customdata->maxbytes;
2545         $editoroptions['context'] = $this->_customdata->context;
2546         return $editoroptions;
2547     }
2549     public function set_data($data) {
2550         $editoroptions = $this->get_editor_options();
2551         if (!isset($data->text)) {
2552             $data->text = '';
2553         }
2554         if (!isset($data->format)) {
2555             $data->textformat = FORMAT_HTML;
2556         } else {
2557             $data->textformat = $data->format;
2558         }
2560         if (!empty($this->_customdata->submission->id)) {
2561             $itemid = $this->_customdata->submission->id;
2562         } else {
2563             $itemid = null;
2564         }
2566         switch ($this->_customdata->assignment->assignmenttype) {
2567                 case 'upload' :
2568                 case 'uploadsingle' :
2569                     $data = file_prepare_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2570                     break;
2571                 default :
2572                     break;
2573         }
2575         $data = file_prepare_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2576         return parent::set_data($data);
2577     }
2579     public function get_data() {
2580         $data = parent::get_data();
2582         if (!empty($this->_customdata->submission->id)) {
2583             $itemid = $this->_customdata->submission->id;
2584         } else {
2585             $itemid = null; //TODO: this is wrong, itemid MUST be known when saving files!! (skodak)
2586         }
2588         if ($data) {
2589             $editoroptions = $this->get_editor_options();
2590             switch ($this->_customdata->assignment->assignmenttype) {
2591                 case 'upload' :
2592                 case 'uploadsingle' :
2593                     $data = file_postupdate_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2594                     break;
2595                 default :
2596                     break;
2597             }
2598             $data = file_postupdate_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2599         }
2601         if ($this->use_advanced_grading() && !isset($data->advancedgrading)) {
2602             $data->advancedgrading = null;
2603         }
2605         return $data;
2606     }
2609 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
2611 /**
2612  * Deletes an assignment instance
2613  *
2614  * This is done by calling the delete_instance() method of the assignment type class
2615  */
2616 function assignment_delete_instance($id){
2617     global $CFG, $DB;
2619     if (! $assignment = $DB->get_record('assignment', array('id'=>$id))) {
2620         return false;
2621     }
2623     // fall back to base class if plugin missing
2624     $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2625     if (file_exists($classfile)) {
2626         require_once($classfile);
2627         $assignmentclass = "assignment_$assignment->assignmenttype";
2629     } else {
2630         debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
2631         $assignmentclass = "assignment_base";
2632     }
2634     $ass = new $assignmentclass();
2635     return $ass->delete_instance($assignment);
2639 /**
2640  * Updates an assignment instance
2641  *
2642  * This is done by calling the update_instance() method of the assignment type class
2643  */
2644 function assignment_update_instance($assignment){
2645     global $CFG;
2647     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_PLUGIN);
2649     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2650     $assignmentclass = "assignment_$assignment->assignmenttype";
2651     $ass = new $assignmentclass();
2652     return $ass->update_instance($assignment);
2656 /**
2657  * Adds an assignment instance
2658  *
2659  * This is done by calling the add_instance() method of the assignment type class
2660  */
2661 function assignment_add_instance($assignment) {
2662     global $CFG;
2664     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_PLUGIN);
2666     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2667     $assignmentclass = "assignment_$assignment->assignmenttype";
2668     $ass = new $assignmentclass();
2669     return $ass->add_instance($assignment);
2673 /**
2674  * Returns an outline of a user interaction with an assignment
2675  *
2676  * This is done by calling the user_outline() method of the assignment type class
2677  */
2678 function assignment_user_outline($course, $user, $mod, $assignment) {
2679     global $CFG;
2681     require_once("$CFG->libdir/gradelib.php");
2682     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2683     $assignmentclass = "assignment_$assignment->assignmenttype";
2684     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2685     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2686     if (!empty($grades->items[0]->grades)) {
2687         return $ass->user_outline(reset($grades->items[0]->grades));
2688     } else {
2689         return null;
2690     }
2693 /**
2694  * Prints the complete info about a user's interaction with an assignment
2695  *
2696  * This is done by calling the user_complete() method of the assignment type class
2697  */
2698 function assignment_user_complete($course, $user, $mod, $assignment) {
2699     global $CFG;
2701     require_once("$CFG->libdir/gradelib.php");
2702     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2703     $assignmentclass = "assignment_$assignment->assignmenttype";
2704     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2705     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2706     if (empty($grades->items[0]->grades)) {
2707         $grade = false;
2708     } else {
2709         $grade = reset($grades->items[0]->grades);
2710     }
2711     return $ass->user_complete($user, $grade);
2714 /**
2715  * Function to be run periodically according to the moodle cron
2716  *
2717  * Finds all assignment notifications that have yet to be mailed out, and mails them
2718  */
2719 function assignment_cron () {
2720     global $CFG, $USER, $DB;
2722     /// first execute all crons in plugins
2723     if ($plugins = get_plugin_list('assignment')) {
2724         foreach ($plugins as $plugin=>$dir) {
2725             require_once("$dir/assignment.class.php");
2726             $assignmentclass = "assignment_$plugin";
2727             $ass = new $assignmentclass();
2728             $ass->cron();
2729         }
2730     }
2732     /// Notices older than 1 day will not be mailed.  This is to avoid the problem where
2733     /// cron has not been running for a long time, and then suddenly people are flooded
2734     /// with mail from the past few weeks or months
2736     $timenow   = time();
2737     $endtime   = $timenow - $CFG->maxeditingtime;
2738     $starttime = $endtime - 24 * 3600;   /// One day earlier
2740     if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2742         $realuser = clone($USER);
2744         foreach ($submissions as $key => $submission) {
2745             $DB->set_field("assignment_submissions", "mailed", "1", array("id"=>$submission->id));
2746         }
2748         $timenow = time();
2750         foreach ($submissions as $submission) {
2752             echo "Processing assignment submission $submission->id\n";
2754             if (! $user = $DB->get_record("user", array("id"=>$submission->userid))) {
2755                 echo "Could not find user $user->id\n";
2756                 continue;
2757             }
2759             if (! $course = $DB->get_record("course", array("id"=>$submission->course))) {
2760                 echo "Could not find course $submission->course\n";
2761                 continue;
2762             }
2764             /// Override the language and timezone of the "current" user, so that
2765             /// mail is customised for the receiver.
2766             cron_setup_user($user, $course);
2768             $coursecontext = get_context_instance(CONTEXT_COURSE, $submission->course);
2769             $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
2770             if (!is_enrolled($coursecontext, $user->id)) {
2771                 echo fullname($user)." not an active participant in " . $courseshortname . "\n";
2772                 continue;
2773             }
2775             if (! $teacher = $DB->get_record("user", array("id"=>$submission->teacher))) {
2776                 echo "Could not find teacher $submission->teacher\n";
2777                 continue;
2778             }
2780             if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2781                 echo "Could not find course module for assignment id $submission->assignment\n";
2782                 continue;
2783             }
2785             if (! $mod->visible) {    /// Hold mail notification for hidden assignments until later
2786                 continue;
2787             }
2789             $strassignments = get_string("modulenameplural", "assignment");
2790             $strassignment  = get_string("modulename", "assignment");
2792             $assignmentinfo = new stdClass();
2793             $assignmentinfo->teacher = fullname($teacher);
2794             $assignmentinfo->assignment = format_string($submission->name,true);
2795             $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2797             $postsubject = "$courseshortname: $strassignments: ".format_string($submission->name,true);
2798             $posttext  = "$courseshortname -> $strassignments -> ".format_string($submission->name,true)."\n";
2799             $posttext .= "---------------------------------------------------------------------\n";
2800             $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2801             $posttext .= "---------------------------------------------------------------------\n";
2803             if ($user->mailformat == 1) {  // HTML
2804                 $posthtml = "<p><font face=\"sans-serif\">".
2805                 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$courseshortname</a> ->".
2806                 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2807                 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2808                 $posthtml .= "<hr /><font face=\"sans-serif\">";
2809                 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2810                 $posthtml .= "</font><hr />";
2811             } else {
2812                 $posthtml = "";
2813             }
2815             $eventdata = new stdClass();
2816             $eventdata->modulename       = 'assignment';
2817             $eventdata->userfrom         = $teacher;
2818             $eventdata->userto           = $user;
2819             $eventdata->subject          = $postsubject;
2820             $eventdata->fullmessage      = $posttext;
2821             $eventdata->fullmessageformat = FORMAT_PLAIN;
2822             $eventdata->fullmessagehtml  = $posthtml;
2823             $eventdata->smallmessage     = get_string('assignmentmailsmall', 'assignment', $assignmentinfo);
2825             $eventdata->name            = 'assignment_updates';
2826             $eventdata->component       = 'mod_assignment';
2827             $eventdata->notification    = 1;
2828             $eventdata->contexturl      = $assignmentinfo->url;
2829             $eventdata->contexturlname  = $assignmentinfo->assignment;
2831             message_send($eventdata);
2832         }
2834         cron_setup_user();
2835     }
2837     return true;
2840 /**
2841  * Return grade for given user or all users.
2842  *
2843  * @param int $assignmentid id of assignment
2844  * @param int $userid optional user id, 0 means all users
2845  * @return array array of grades, false if none
2846  */
2847 function assignment_get_user_grades($assignment, $userid=0) {
2848     global $CFG, $DB;
2850     if ($userid) {
2851         $user = "AND u.id = :userid";
2852         $params = array('userid'=>$userid);
2853     } else {
2854         $user = "";
2855     }
2856     $params['aid'] = $assignment->id;
2858     $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2859                    s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2860               FROM {user} u, {assignment_submissions} s
2861              WHERE u.id = s.userid AND s.assignment = :aid
2862                    $user";
2864     return $DB->get_records_sql($sql, $params);
2867 /**
2868  * Update activity grades
2869  *
2870  * @param object $assignment
2871  * @param int $userid specific user only, 0 means all
2872  */
2873 function assignment_update_grades($assignment, $userid=0, $nullifnone=true) {
2874     global $CFG, $DB;
2875     require_once($CFG->libdir.'/gradelib.php');
2877     if ($assignment->grade == 0) {
2878         assignment_grade_item_update($assignment);
2880     } else if ($grades = assignment_get_user_grades($assignment, $userid)) {
2881         foreach($grades as $k=>$v) {
2882             if ($v->rawgrade == -1) {
2883                 $grades[$k]->rawgrade = null;
2884             }
2885         }
2886         assignment_grade_item_update($assignment, $grades);
2888     } else {
2889         assignment_grade_item_update($assignment);
2890     }
2893 /**
2894  * Update all grades in gradebook.
2895  */
2896 function assignment_upgrade_grades() {
2897     global $DB;
2899     $sql = "SELECT COUNT('x')
2900               FROM {assignment} a, {course_modules} cm, {modules} m
2901              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2902     $count = $DB->count_records_sql($sql);
2904     $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
2905               FROM {assignment} a, {course_modules} cm, {modules} m
2906              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2907     $rs = $DB->get_recordset_sql($sql);
2908     if ($rs->valid()) {
2909         // too much debug output
2910         $pbar = new progress_bar('assignmentupgradegrades', 500, true);
2911         $i=0;
2912         foreach ($rs as $assignment) {
2913             $i++;
2914             upgrade_set_timeout(60*5); // set up timeout, may also abort execution
2915             assignment_update_grades($assignment);
2916             $pbar->update($i, $count, "Updating Assignment grades ($i/$count).");
2917         }
2918         upgrade_set_timeout(); // reset to default timeout
2919     }
2920     $rs->close();
2923 /**
2924  * Create grade item for given assignment
2925  *
2926  * @param object $assignment object with extra cmidnumber
2927  * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
2928  * @return int 0 if ok, error code otherwise
2929  */
2930 function assignment_grade_item_update($assignment, $grades=NULL) {
2931     global $CFG;
2932     require_once($CFG->libdir.'/gradelib.php');
2934     if (!isset($assignment->courseid)) {
2935         $assignment->courseid = $assignment->course;
2936     }
2938     $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
2940     if ($assignment->grade > 0) {
2941         $params['gradetype'] = GRADE_TYPE_VALUE;
2942         $params['grademax']  = $assignment->grade;
2943         $params['grademin']  = 0;
2945     } else if ($assignment->grade < 0) {
2946         $params['gradetype'] = GRADE_TYPE_SCALE;
2947         $params['scaleid']   = -$assignment->grade;
2949     } else {
2950         $params['gradetype'] = GRADE_TYPE_TEXT; // allow text comments only
2951     }
2953     if ($grades  === 'reset') {
2954         $params['reset'] = true;
2955         $grades = NULL;
2956     }
2958     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades, $params);
2961 /**
2962  * Delete grade item for given assignment
2963  *
2964  * @param object $assignment object
2965  * @return object assignment
2966  */
2967 function assignment_grade_item_delete($assignment) {
2968     global $CFG;
2969     require_once($CFG->libdir.'/gradelib.php');
2971     if (!isset($assignment->courseid)) {
2972         $assignment->courseid = $assignment->course;
2973     }
2975     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
2978 /**
2979  * Returns the users with data in one assignment (students and teachers)
2980  *
2981  * @todo: deprecated - to be deleted in 2.2
2982  *
2983  * @param $assignmentid int
2984  * @return array of user objects
2985  */
2986 function assignment_get_participants($assignmentid) {
2987     global $CFG, $DB;
2989     //Get students
2990     $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2991                                         FROM {user} u,
2992                                              {assignment_submissions} a
2993                                        WHERE a.assignment = ? and
2994                                              u.id = a.userid", array($assignmentid));
2995     //Get teachers
2996     $teachers = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2997                                         FROM {user} u,
2998                                              {assignment_submissions} a
2999                                        WHERE a.assignment = ? and
3000                                              u.id = a.teacher", array($assignmentid));
3002     //Add teachers to students
3003     if ($teachers) {
3004         foreach ($teachers as $teacher) {
3005             $students[$teacher->id] = $teacher;
3006         }
3007     }
3008     //Return students array (it contains an array of unique users)
3009     return ($students);
3012 /**
3013  * Serves assignment submissions and other files.
3014  *
3015  * @param object $course
3016  * @param object $cm
3017  * @param object $context
3018  * @param string $filearea
3019  * @param array $args
3020  * @param bool $forcedownload
3021  * @return bool false if file not found, does not return if found - just send the file
3022  */
3023 function assignment_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) {
3024     global $CFG, $DB;
3026     if ($context->contextlevel != CONTEXT_MODULE) {
3027         return false;
3028     }
3030     require_login($course, false, $cm);
3032     if (!$assignment = $DB->get_record('assignment', array('id'=>$cm->instance))) {
3033         return false;
3034     }
3036     require_once($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
3037     $assignmentclass = 'assignment_'.$assignment->assignmenttype;
3038     $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm, $course);
3040     return $assignmentinstance->send_file($filearea, $args);
3042 /**
3043  * Checks if a scale is being used by an assignment
3044  *
3045  * This is used by the backup code to decide whether to back up a scale
3046  * @param $assignmentid int
3047  * @param $scaleid int
3048  * @return boolean True if the scale is used by the assignment
3049  */
3050 function assignment_scale_used($assignmentid, $scaleid) {
3051     global $DB;
3053     $return = false;
3055     $rec = $DB->get_record('assignment', array('id'=>$assignmentid,'grade'=>-$scaleid));
3057     if (!empty($rec) && !empty($scaleid)) {
3058         $return = true;
3059     }
3061     return $return;
3064 /**
3065  * Checks if scale is being used by any instance of assignment
3066  *
3067  * This is used to find out if scale used anywhere
3068  * @param $scaleid int
3069  * @return boolean True if the scale is used by any assignment
3070  */
3071 function assignment_scale_used_anywhere($scaleid) {
3072     global $DB;
3074     if ($scaleid and $DB->record_exists('assignment', array('grade'=>-$scaleid))) {
3075         return true;
3076     } else {
3077         return false;
3078     }
3081 /**
3082  * Make sure up-to-date events are created for all assignment instances
3083  *
3084  * This standard function will check all instances of this module
3085  * and make sure there are up-to-date events created for each of them.
3086  * If courseid = 0, then every assignment event in the site is checked, else
3087  * only assignment events belonging to the course specified are checked.
3088  * This function is used, in its new format, by restore_refresh_events()
3089  *
3090  * @param $courseid int optional If zero then all assignments for all courses are covered
3091  * @return boolean Always returns true
3092  */
3093 function assignment_refresh_events($courseid = 0) {
3094     global $DB;
3096     if ($courseid == 0) {
3097         if (! $assignments = $DB->get_records("assignment")) {
3098             return true;
3099         }
3100     } else {
3101         if (! $assignments = $DB->get_records("assignment", array("course"=>$courseid))) {
3102             return true;
3103         }
3104     }
3105     $moduleid = $DB->get_field('modules', 'id', array('name'=>'assignment'));
3107     foreach ($assignments as $assignment) {
3108         $cm = get_coursemodule_from_id('assignment', $assignment->id);
3109         $event = new stdClass();
3110         $event->name        = $assignment->name;
3111         $event->description = format_module_intro('assignment', $assignment, $cm->id);
3112         $event->timestart   = $assignment->timedue;
3114         if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
3115             update_event($event);
3117         } else {
3118             $event->courseid    = $assignment->course;
3119             $event->groupid     = 0;
3120             $event->userid      = 0;
3121             $event->modulename  = 'assignment';
3122             $event->instance    = $assignment->id;
3123             $event->eventtype   = 'due';
3124             $event->timeduration = 0;
3125             $event->visible     = $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$assignment->id));
3126             add_event($event);
3127         }
3129     }
3130     return true;
3133 /**
3134  * Print recent activity from all assignments in a given course
3135  *
3136  * This is used by the recent activity block
3137  */
3138 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
3139     global $CFG, $USER, $DB, $OUTPUT;
3141     // do not use log table if possible, it may be huge
3143     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
3144                                                      u.firstname, u.lastname, u.email, u.picture
3145                                                 FROM {assignment_submissions} asb
3146                                                      JOIN {assignment} a      ON a.id = asb.assignment
3147                                                      JOIN {course_modules} cm ON cm.instance = a.id
3148                                                      JOIN {modules} md        ON md.id = cm.module
3149                                                      JOIN {user} u            ON u.id = asb.userid
3150                                                WHERE asb.timemodified > ? AND
3151                                                      a.course = ? AND
3152                                                      md.name = 'assignment'
3153                                             ORDER BY asb.timemodified ASC", array($timestart, $course->id))) {
3154          return false;
3155     }
3157     $modinfo =& get_fast_modinfo($course); // reference needed because we might load the groups
3158     $show    = array();
3159     $grader  = array();
3161     foreach($submissions as $submission) {
3162         if (!array_key_exists($submission->cmid, $modinfo->cms)) {
3163             continue;
3164         }
3165         $cm = $modinfo->cms[$submission->cmid];
3166         if (!$cm->uservisible) {
3167             continue;
3168         }
3169         if ($submission->userid == $USER->id) {
3170             $show[] = $submission;
3171             continue;
3172         }
3174         // the act of sumbitting of assignment may be considered private - only graders will see it if specified
3175         if (empty($CFG->assignment_showrecentsubmissions)) {
3176             if (!array_key_exists($cm->id, $grader)) {
3177                 $grader[$cm->id] = has_capability('moodle/grade:viewall', get_context_instance(CONTEXT_MODULE, $cm->id));
3178             }
3179             if (!$grader[$cm->id]) {
3180                 continue;
3181             }
3182         }
3184         $groupmode = groups_get_activity_groupmode($cm, $course);
3186         if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
3187             if (isguestuser()) {
3188                 // shortcut - guest user does not belong into any group
3189                 continue;
3190             }
3192             if (is_null($modinfo->groups)) {
3193                 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
3194             }
3196             // this will be slow - show only users that share group with me in this cm
3197             if (empty($modinfo->groups[$cm->id])) {
3198                 continue;
3199             }
3200             $usersgroups =  groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
3201             if (is_array($usersgroups)) {
3202                 $usersgroups = array_keys($usersgroups);
3203                 $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
3204                 if (empty($intersect)) {
3205                     continue;
3206                 }
3207             }
3208         }
3209         $show[] = $submission;
3210     }
3212     if (empty($show)) {
3213         return false;
3214     }
3216     echo $OUTPUT->heading(get_string('newsubmissions', 'assignment').':', 3);
3218     foreach ($show as $submission) {
3219         $cm = $modinfo->cms[$submission->cmid];
3220         $link = $CFG->wwwroot.'/mod/assignment/view.php?id='.$cm->id;
3221         print_recent_activity_note($submission->timemodified, $submission, $cm->name, $link, false, $viewfullnames);
3222     }
3224     return true;
3228 /**
3229  * Returns all assignments since a given time in specified forum.
3230  */
3231 function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0)  {
3232     global $CFG, $COURSE, $USER, $DB;
3234     if ($COURSE->id == $courseid) {
3235         $course = $COURSE;
3236     } else {
3237         $course = $DB->get_record('course', array('id'=>$courseid));
3238     }
3240     $modinfo =& get_fast_modinfo($course);
3242     $cm = $modinfo->cms[$cmid];
3244     $params = array();
3245     if ($userid) {
3246         $userselect = "AND u.id = :userid";
3247         $params['userid'] = $userid;
3248     } else {
3249         $userselect = "";
3250     }
3252     if ($groupid) {
3253         $groupselect = "AND gm.groupid = :groupid";
3254         $groupjoin   = "JOIN {groups_members} gm ON  gm.userid=u.id";
3255         $params['groupid'] = $groupid;
3256     } else {
3257         $groupselect = "";
3258         $groupjoin   = "";
3259     }
3261     $params['cminstance'] = $cm->instance;
3262     $params['timestart'] = $timestart;
3264     $userfields = user_picture::fields('u', null, 'userid');
3266     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified,
3267                                                      $userfields
3268                                                 FROM {assignment_submissions} asb
3269                                                 JOIN {assignment} a      ON a.id = asb.assignment
3270                                                 JOIN {user} u            ON u.id = asb.userid
3271                                           $groupjoin
3272                                                WHERE asb.timemodified > :timestart AND a.id = :cminstance
3273                                                      $userselect $groupselect
3274                                             ORDER BY asb.timemodified ASC", $params)) {
3275          return;
3276     }
3278     $groupmode       = groups_get_activity_groupmode($cm, $course);
3279     $cm_context      = get_context_instance(CONTEXT_MODULE, $cm->id);
3280     $grader          = has_capability('moodle/grade:viewall', $cm_context);
3281     $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
3282     $viewfullnames   = has_capability('moodle/site:viewfullnames', $cm_context);
3284     if (is_null($modinfo->groups)) {
3285         $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
3286     }
3288     $show = array();
3290     foreach($submissions as $submission) {
3291         if ($submission->userid == $USER->id) {
3292             $show[] = $submission;
3293             continue;
3294         }
3295         // the act of submitting of assignment may be considered private - only graders will see it if specified
3296         if (empty($CFG->assignment_showrecentsubmissions)) {
3297             if (!$grader) {
3298                 continue;
3299             }
3300         }
3302         if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
3303             if (isguestuser()) {
3304                 // shortcut - guest user does not belong into any group
3305                 continue;
3306             }
3308             // this will be slow - show only users that share group with me in this cm
3309             if (empty($modinfo->groups[$cm->id])) {
3310                 continue;
3311             }
3312             $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
3313             if (is_array($usersgroups)) {
3314                 $usersgroups = array_keys($usersgroups);
3315                 $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
3316                 if (empty($intersect)) {
3317                     continue;
3318                 }
3319             }
3320         }
3321         $show[] = $submission;