Merge branch 'MDL-31919-master-2' of git://git.luns.net.uk/moodle
[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         echo 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 the submission has been completed
404                     if ($this->is_submitted_with_required_data($submission)) {
405                         if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
406                             $submitted = '<span class="early">'.userdate($submission->timemodified).'</span>';
407                         } else {
408                             $submitted = '<span class="late">'.userdate($submission->timemodified).'</span>';
409                         }
410                     }
411                 }
412             }
413         }
415         return $submitted;
416     }
419     /**
420      * @todo Document this function
421      */
422     function setup_elements(&$mform) {
424     }
426     /**
427      * Any preprocessing needed for the settings form for
428      * this assignment type
429      *
430      * @param array $default_values - array to fill in with the default values
431      *      in the form 'formelement' => 'value'
432      * @param object $form - the form that is to be displayed
433      * @return none
434      */
435     function form_data_preprocessing(&$default_values, $form) {
436     }
438     /**
439      * Any extra validation checks needed for the settings
440      * form for this assignment type
441      *
442      * See lib/formslib.php, 'validation' function for details
443      */
444     function form_validation($data, $files) {
445         return array();
446     }
448     /**
449      * Create a new assignment activity
450      *
451      * Given an object containing all the necessary data,
452      * (defined by the form in mod_form.php) this function
453      * will create a new instance and return the id number
454      * of the new instance.
455      * The due data is added to the calendar
456      * This is common to all assignment types.
457      *
458      * @global object
459      * @global object
460      * @param object $assignment The data from the form on mod_form.php
461      * @return int The id of the assignment
462      */
463     function add_instance($assignment) {
464         global $COURSE, $DB;
466         $assignment->timemodified = time();
467         $assignment->courseid = $assignment->course;
469         $returnid = $DB->insert_record("assignment", $assignment);
470         $assignment->id = $returnid;
472         if ($assignment->timedue) {
473             $event = new stdClass();
474             $event->name        = $assignment->name;
475             $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
476             $event->courseid    = $assignment->course;
477             $event->groupid     = 0;
478             $event->userid      = 0;
479             $event->modulename  = 'assignment';
480             $event->instance    = $returnid;
481             $event->eventtype   = 'due';
482             $event->timestart   = $assignment->timedue;
483             $event->timeduration = 0;
485             calendar_event::create($event);
486         }
488         assignment_grade_item_update($assignment);
490         return $returnid;
491     }
493     /**
494      * Deletes an assignment activity
495      *
496      * Deletes all database records, files and calendar events for this assignment.
497      *
498      * @global object
499      * @global object
500      * @param object $assignment The assignment to be deleted
501      * @return boolean False indicates error
502      */
503     function delete_instance($assignment) {
504         global $CFG, $DB;
506         $assignment->courseid = $assignment->course;
508         $result = true;
510         // now get rid of all files
511         $fs = get_file_storage();
512         if ($cm = get_coursemodule_from_instance('assignment', $assignment->id)) {
513             $context = get_context_instance(CONTEXT_MODULE, $cm->id);
514             $fs->delete_area_files($context->id);
515         }
517         if (! $DB->delete_records('assignment_submissions', array('assignment'=>$assignment->id))) {
518             $result = false;
519         }
521         if (! $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
522             $result = false;
523         }
525         if (! $DB->delete_records('assignment', array('id'=>$assignment->id))) {
526             $result = false;
527         }
528         $mod = $DB->get_field('modules','id',array('name'=>'assignment'));
530         assignment_grade_item_delete($assignment);
532         return $result;
533     }
535     /**
536      * Updates a new assignment activity
537      *
538      * Given an object containing all the necessary data,
539      * (defined by the form in mod_form.php) this function
540      * will update the assignment instance and return the id number
541      * The due date is updated in the calendar
542      * This is common to all assignment types.
543      *
544      * @global object
545      * @global object
546      * @param object $assignment The data from the form on mod_form.php
547      * @return bool success
548      */
549     function update_instance($assignment) {
550         global $COURSE, $DB;
552         $assignment->timemodified = time();
554         $assignment->id = $assignment->instance;
555         $assignment->courseid = $assignment->course;
557         $DB->update_record('assignment', $assignment);
559         if ($assignment->timedue) {
560             $event = new stdClass();
562             if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
564                 $event->name        = $assignment->name;
565                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
566                 $event->timestart   = $assignment->timedue;
568                 $calendarevent = calendar_event::load($event->id);
569                 $calendarevent->update($event);
570             } else {
571                 $event = new stdClass();
572                 $event->name        = $assignment->name;
573                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
574                 $event->courseid    = $assignment->course;
575                 $event->groupid     = 0;
576                 $event->userid      = 0;
577                 $event->modulename  = 'assignment';
578                 $event->instance    = $assignment->id;
579                 $event->eventtype   = 'due';
580                 $event->timestart   = $assignment->timedue;
581                 $event->timeduration = 0;
583                 calendar_event::create($event);
584             }
585         } else {
586             $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id));
587         }
589         // get existing grade item
590         assignment_grade_item_update($assignment);
592         return true;
593     }
595     /**
596      * Update grade item for this submission.
597      *
598      * @param stdClass $submission The submission instance
599      */
600     function update_grade($submission) {
601         assignment_update_grades($this->assignment, $submission->userid);
602     }
604     /**
605      * Top-level function for handling of submissions called by submissions.php
606      *
607      * This is for handling the teacher interaction with the grading interface
608      * This should be suitable for most assignment types.
609      *
610      * @global object
611      * @param string $mode Specifies the kind of teacher interaction taking place
612      */
613     function submissions($mode) {
614         ///The main switch is changed to facilitate
615         ///1) Batch fast grading
616         ///2) Skip to the next one on the popup
617         ///3) Save and Skip to the next one on the popup
619         //make user global so we can use the id
620         global $USER, $OUTPUT, $DB, $PAGE;
622         $mailinfo = optional_param('mailinfo', null, PARAM_BOOL);
624         if (optional_param('next', null, PARAM_BOOL)) {
625             $mode='next';
626         }
627         if (optional_param('saveandnext', null, PARAM_BOOL)) {
628             $mode='saveandnext';
629         }
631         if (is_null($mailinfo)) {
632             if (optional_param('sesskey', null, PARAM_BOOL)) {
633                 set_user_preference('assignment_mailinfo', 0);
634             } else {
635                 $mailinfo = get_user_preferences('assignment_mailinfo', 0);
636             }
637         } else {
638             set_user_preference('assignment_mailinfo', $mailinfo);
639         }
641         if (!($this->validate_and_preprocess_feedback())) {
642             // form was submitted ('Save' or 'Save and next' was pressed, but validation failed)
643             $this->display_submission();
644             return;
645         }
647         switch ($mode) {
648             case 'grade':                         // We are in a main window grading
649                 if ($submission = $this->process_feedback()) {
650                     $this->display_submissions(get_string('changessaved'));
651                 } else {
652                     $this->display_submissions();
653                 }
654                 break;
656             case 'single':                        // We are in a main window displaying one submission
657                 if ($submission = $this->process_feedback()) {
658                     $this->display_submissions(get_string('changessaved'));
659                 } else {
660                     $this->display_submission();
661                 }
662                 break;
664             case 'all':                          // Main window, display everything
665                 $this->display_submissions();
666                 break;
668             case 'fastgrade':
669                 ///do the fast grading stuff  - this process should work for all 3 subclasses
670                 $grading    = false;
671                 $commenting = false;
672                 $col        = false;
673                 if (isset($_POST['submissioncomment'])) {
674                     $col = 'submissioncomment';
675                     $commenting = true;
676                 }
677                 if (isset($_POST['menu'])) {
678                     $col = 'menu';
679                     $grading = true;
680                 }
681                 if (!$col) {
682                     //both submissioncomment and grade columns collapsed..
683                     $this->display_submissions();
684                     break;
685                 }
687                 foreach ($_POST[$col] as $id => $unusedvalue){
689                     $id = (int)$id; //clean parameter name
691                     $this->process_outcomes($id);
693                     if (!$submission = $this->get_submission($id)) {
694                         $submission = $this->prepare_new_submission($id);
695                         $newsubmission = true;
696                     } else {
697                         $newsubmission = false;
698                     }
699                     unset($submission->data1);  // Don't need to update this.
700                     unset($submission->data2);  // Don't need to update this.
702                     //for fast grade, we need to check if any changes take place
703                     $updatedb = false;
705                     if ($grading) {
706                         $grade = $_POST['menu'][$id];
707                         $updatedb = $updatedb || ($submission->grade != $grade);
708                         $submission->grade = $grade;
709                     } else {
710                         if (!$newsubmission) {
711                             unset($submission->grade);  // Don't need to update this.
712                         }
713                     }
714                     if ($commenting) {
715                         $commentvalue = trim($_POST['submissioncomment'][$id]);
716                         $updatedb = $updatedb || ($submission->submissioncomment != $commentvalue);
717                         $submission->submissioncomment = $commentvalue;
718                     } else {
719                         unset($submission->submissioncomment);  // Don't need to update this.
720                     }
722                     $submission->teacher    = $USER->id;
723                     if ($updatedb) {
724                         $submission->mailed = (int)(!$mailinfo);
725                     }
727                     $submission->timemarked = time();
729                     //if it is not an update, we don't change the last modified time etc.
730                     //this will also not write into database if no submissioncomment and grade is entered.
732                     if ($updatedb){
733                         if ($newsubmission) {
734                             if (!isset($submission->submissioncomment)) {
735                                 $submission->submissioncomment = '';
736                             }
737                             $sid = $DB->insert_record('assignment_submissions', $submission);
738                             $submission->id = $sid;
739                         } else {
740                             $DB->update_record('assignment_submissions', $submission);
741                         }
743                         // trigger grade event
744                         $this->update_grade($submission);
746                         //add to log only if updating
747                         add_to_log($this->course->id, 'assignment', 'update grades',
748                                    'submissions.php?id='.$this->cm->id.'&user='.$submission->userid,
749                                    $submission->userid, $this->cm->id);
750                     }
752                 }
754                 $message = $OUTPUT->notification(get_string('changessaved'), 'notifysuccess');
756                 $this->display_submissions($message);
757                 break;
760             case 'saveandnext':
761                 ///We are in pop up. save the current one and go to the next one.
762                 //first we save the current changes
763                 if ($submission = $this->process_feedback()) {
764                     //print_heading(get_string('changessaved'));
765                     //$extra_javascript = $this->update_main_listing($submission);
766                 }
768             case 'next':
769                 /// We are currently in pop up, but we want to skip to next one without saving.
770                 ///    This turns out to be similar to a single case
771                 /// The URL used is for the next submission.
772                 $offset = required_param('offset', PARAM_INT);
773                 $nextid = required_param('nextid', PARAM_INT);
774                 $id = required_param('id', PARAM_INT);
775                 $filter = optional_param('filter', self::FILTER_ALL, PARAM_INT);
777                 if ($mode == 'next' || $filter !== self::FILTER_REQUIRE_GRADING) {
778                     $offset = (int)$offset+1;
779                 }
780                 $redirect = new moodle_url('submissions.php',
781                         array('id' => $id, 'offset' => $offset, 'userid' => $nextid,
782                         'mode' => 'single', 'filter' => $filter));
784                 redirect($redirect);
785                 break;
787             case 'singlenosave':
788                 $this->display_submission();
789                 break;
791             default:
792                 echo "something seriously is wrong!!";
793                 break;
794         }
795     }
797     /**
798      * Checks if grading method allows quickgrade mode. At the moment it is hardcoded
799      * that advanced grading methods do not allow quickgrade.
800      *
801      * Assignment type plugins are not allowed to override this method
802      *
803      * @return boolean
804      */
805     public final function quickgrade_mode_allowed() {
806         global $CFG;
807         require_once("$CFG->dirroot/grade/grading/lib.php");
808         if ($controller = get_grading_manager($this->context, 'mod_assignment', 'submission')->get_active_controller()) {
809             return false;
810         }
811         return true;
812     }
814     /**
815      * Helper method updating the listing on the main script from popup using javascript
816      *
817      * @global object
818      * @global object
819      * @param $submission object The submission whose data is to be updated on the main page
820      */
821     function update_main_listing($submission) {
822         global $SESSION, $CFG, $OUTPUT;
824         $output = '';
826         $perpage = get_user_preferences('assignment_perpage', 10);
828         $quickgrade = get_user_preferences('assignment_quickgrade', 0) && $this->quickgrade_mode_allowed();
830         /// Run some Javascript to try and update the parent page
831         $output .= '<script type="text/javascript">'."\n<!--\n";
832         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['submissioncomment'])) {
833             if ($quickgrade){
834                 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid.'").value="'
835                 .trim($submission->submissioncomment).'";'."\n";
836              } else {
837                 $output.= 'opener.document.getElementById("com'.$submission->userid.
838                 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment)), 15)."\";\n";
839             }
840         }
842         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['grade'])) {
843             //echo optional_param('menuindex');
844             if ($quickgrade){
845                 $output.= 'opener.document.getElementById("menumenu'.$submission->userid.
846                 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT).'";'."\n";
847             } else {
848                 $output.= 'opener.document.getElementById("g'.$submission->userid.'").innerHTML="'.
849                 $this->display_grade($submission->grade)."\";\n";
850             }
851         }
852         //need to add student's assignments in there too.
853         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemodified']) &&
854             $submission->timemodified) {
855             $output.= 'opener.document.getElementById("ts'.$submission->userid.
856                  '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid)).userdate($submission->timemodified)."\";\n";
857         }
859         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemarked']) &&
860             $submission->timemarked) {
861             $output.= 'opener.document.getElementById("tt'.$submission->userid.
862                  '").innerHTML="'.userdate($submission->timemarked)."\";\n";
863         }
865         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['status'])) {
866             $output.= 'opener.document.getElementById("up'.$submission->userid.'").className="s1";';
867             $buttontext = get_string('update');
868             $url = new moodle_url('/mod/assignment/submissions.php', array(
869                     'id' => $this->cm->id,
870                     'userid' => $submission->userid,
871                     'mode' => 'single',
872                     'offset' => (optional_param('offset', '', PARAM_INT)-1)));
873             $button = $OUTPUT->action_link($url, $buttontext, new popup_action('click', $url, 'grade'.$submission->userid, array('height' => 450, 'width' => 700)), array('ttile'=>$buttontext));
875             $output .= 'opener.document.getElementById("up'.$submission->userid.'").innerHTML="'.addslashes_js($button).'";';
876         }
878         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $submission->userid);
880         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['finalgrade'])) {
881             $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid.
882             '").innerHTML="'.$grading_info->items[0]->grades[$submission->userid]->str_grade.'";'."\n";
883         }
885         if (!empty($CFG->enableoutcomes) and empty($SESSION->flextable['mod-assignment-submissions']->collapse['outcome'])) {
887             if (!empty($grading_info->outcomes)) {
888                 foreach($grading_info->outcomes as $n=>$outcome) {
889                     if ($outcome->grades[$submission->userid]->locked) {
890                         continue;
891                     }
893                     if ($quickgrade){
894                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.
895                         '").selectedIndex="'.$outcome->grades[$submission->userid]->grade.'";'."\n";
897                     } else {
898                         $options = make_grades_menu(-$outcome->scaleid);
899                         $options[0] = get_string('nooutcome', 'grades');
900                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.'").innerHTML="'.$options[$outcome->grades[$submission->userid]->grade]."\";\n";
901                     }
903                 }
904             }
905         }
907         $output .= "\n-->\n</script>";
908         return $output;
909     }
911     /**
912      *  Return a grade in user-friendly form, whether it's a scale or not
913      *
914      * @global object
915      * @param mixed $grade
916      * @return string User-friendly representation of grade
917      */
918     function display_grade($grade) {
919         global $DB;
921         static $scalegrades = array();   // Cache scales for each assignment - they might have different scales!!
923         if ($this->assignment->grade >= 0) {    // Normal number
924             if ($grade == -1) {
925                 return '-';
926             } else {
927                 return $grade.' / '.$this->assignment->grade;
928             }
930         } else {                                // Scale
931             if (empty($scalegrades[$this->assignment->id])) {
932                 if ($scale = $DB->get_record('scale', array('id'=>-($this->assignment->grade)))) {
933                     $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
934                 } else {
935                     return '-';
936                 }
937             }
938             if (isset($scalegrades[$this->assignment->id][$grade])) {
939                 return $scalegrades[$this->assignment->id][$grade];
940             }
941             return '-';
942         }
943     }
945     /**
946      *  Display a single submission, ready for grading on a popup window
947      *
948      * This default method prints the teacher info and submissioncomment box at the top and
949      * the student info and submission at the bottom.
950      * This method also fetches the necessary data in order to be able to
951      * provide a "Next submission" button.
952      * Calls preprocess_submission() to give assignment type plug-ins a chance
953      * to process submissions before they are graded
954      * This method gets its arguments from the page parameters userid and offset
955      *
956      * @global object
957      * @global object
958      * @param string $extra_javascript
959      */
960     function display_submission($offset=-1,$userid =-1, $display=true) {
961         global $CFG, $DB, $PAGE, $OUTPUT, $USER;
962         require_once($CFG->libdir.'/gradelib.php');
963         require_once($CFG->libdir.'/tablelib.php');
964         require_once("$CFG->dirroot/repository/lib.php");
965         require_once("$CFG->dirroot/grade/grading/lib.php");
966         if ($userid==-1) {
967             $userid = required_param('userid', PARAM_INT);
968         }
969         if ($offset==-1) {
970             $offset = required_param('offset', PARAM_INT);//offset for where to start looking for student.
971         }
972         $filter = optional_param('filter', 0, PARAM_INT);
974         if (!$user = $DB->get_record('user', array('id'=>$userid))) {
975             print_error('nousers');
976         }
978         if (!$submission = $this->get_submission($user->id)) {
979             $submission = $this->prepare_new_submission($userid);
980         }
981         if ($submission->timemodified > $submission->timemarked) {
982             $subtype = 'assignmentnew';
983         } else {
984             $subtype = 'assignmentold';
985         }
987         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
988         $gradingdisabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
990     /// construct SQL, using current offset to find the data of the next student
991         $course     = $this->course;
992         $assignment = $this->assignment;
993         $cm         = $this->cm;
994         $context    = get_context_instance(CONTEXT_MODULE, $cm->id);
996         //reset filter to all for offline assignment
997         if ($assignment->assignmenttype == 'offline' && $filter == self::FILTER_SUBMITTED) {
998             $filter = self::FILTER_ALL;
999         }
1000         /// Get all ppl that can submit assignments
1002         $currentgroup = groups_get_activity_group($cm);
1003         $users = get_enrolled_users($context, 'mod/assignment:submit', $currentgroup, 'u.id');
1004         if ($users) {
1005             $users = array_keys($users);
1006             // if groupmembersonly used, remove users who are not in any group
1007             if (!empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
1008                 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1009                     $users = array_intersect($users, array_keys($groupingusers));
1010                 }
1011             }
1012         }
1014         $nextid = 0;
1015         $where = '';
1016         if($filter == self::FILTER_SUBMITTED) {
1017             $where .= 's.timemodified > 0 AND ';
1018         } else if($filter == self::FILTER_REQUIRE_GRADING) {
1019             $where .= 's.timemarked < s.timemodified AND ';
1020         }
1022         if ($users) {
1023             $userfields = user_picture::fields('u', array('lastaccess'));
1024             $select = "SELECT $userfields,
1025                               s.id AS submissionid, s.grade, s.submissioncomment,
1026                               s.timemodified, s.timemarked,
1027                               CASE WHEN s.timemarked > 0 AND s.timemarked >= s.timemodified THEN 1
1028                                    ELSE 0 END AS status ";
1030             $sql = 'FROM {user} u '.
1031                    'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1032                    AND s.assignment = '.$this->assignment->id.' '.
1033                    'WHERE '.$where.'u.id IN ('.implode(',', $users).') ';
1035             if ($sort = flexible_table::get_sort_for_table('mod-assignment-submissions')) {
1036                 $sort = 'ORDER BY '.$sort.' ';
1037             }
1038             $auser = $DB->get_records_sql($select.$sql.$sort, null, $offset, 2);
1040             if (is_array($auser) && count($auser)>1) {
1041                 $nextuser = next($auser);
1042                 $nextid = $nextuser->id;
1043             }
1044         }
1046         if ($submission->teacher) {
1047             $teacher = $DB->get_record('user', array('id'=>$submission->teacher));
1048         } else {
1049             global $USER;
1050             $teacher = $USER;
1051         }
1053         $this->preprocess_submission($submission);
1055         $mformdata = new stdClass();
1056         $mformdata->context = $this->context;
1057         $mformdata->maxbytes = $this->course->maxbytes;
1058         $mformdata->courseid = $this->course->id;
1059         $mformdata->teacher = $teacher;
1060         $mformdata->assignment = $assignment;
1061         $mformdata->submission = $submission;
1062         $mformdata->lateness = $this->display_lateness($submission->timemodified);
1063         $mformdata->auser = $auser;
1064         $mformdata->user = $user;
1065         $mformdata->offset = $offset;
1066         $mformdata->userid = $userid;
1067         $mformdata->cm = $this->cm;
1068         $mformdata->grading_info = $grading_info;
1069         $mformdata->enableoutcomes = $CFG->enableoutcomes;
1070         $mformdata->grade = $this->assignment->grade;
1071         $mformdata->gradingdisabled = $gradingdisabled;
1072         $mformdata->nextid = $nextid;
1073         $mformdata->submissioncomment= $submission->submissioncomment;
1074         $mformdata->submissioncommentformat= FORMAT_HTML;
1075         $mformdata->submission_content= $this->print_user_files($user->id,true);
1076         $mformdata->filter = $filter;
1077         $mformdata->mailinfo = get_user_preferences('assignment_mailinfo', 0);
1078          if ($assignment->assignmenttype == 'upload') {
1079             $mformdata->fileui_options = array('subdirs'=>1, 'maxbytes'=>$assignment->maxbytes, 'maxfiles'=>$assignment->var1, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL);
1080         } elseif ($assignment->assignmenttype == 'uploadsingle') {
1081             $mformdata->fileui_options = array('subdirs'=>0, 'maxbytes'=>$CFG->userquota, 'maxfiles'=>1, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL);
1082         }
1083         $advancedgradingwarning = false;
1084         $gradingmanager = get_grading_manager($this->context, 'mod_assignment', 'submission');
1085         if ($gradingmethod = $gradingmanager->get_active_method()) {
1086             $controller = $gradingmanager->get_controller($gradingmethod);
1087             if ($controller->is_form_available()) {
1088                 $itemid = null;
1089                 if (!empty($submission->id)) {
1090                     $itemid = $submission->id;
1091                 }
1092                 if ($gradingdisabled && $itemid) {
1093                     $mformdata->advancedgradinginstance = $controller->get_current_instance($USER->id, $itemid);
1094                 } else if (!$gradingdisabled) {
1095                     $instanceid = optional_param('advancedgradinginstanceid', 0, PARAM_INT);
1096                     $mformdata->advancedgradinginstance = $controller->get_or_create_instance($instanceid, $USER->id, $itemid);
1097                 }
1098             } else {
1099                 $advancedgradingwarning = $controller->form_unavailable_notification();
1100             }
1101         }
1103         $submitform = new mod_assignment_grading_form( null, $mformdata );
1105          if (!$display) {
1106             $ret_data = new stdClass();
1107             $ret_data->mform = $submitform;
1108             if (isset($mformdata->fileui_options)) {
1109                 $ret_data->fileui_options = $mformdata->fileui_options;
1110             }
1111             return $ret_data;
1112         }
1114         if ($submitform->is_cancelled()) {
1115             redirect('submissions.php?id='.$this->cm->id);
1116         }
1118         $submitform->set_data($mformdata);
1120         $PAGE->set_title($this->course->fullname . ': ' .get_string('feedback', 'assignment').' - '.fullname($user, true));
1121         $PAGE->set_heading($this->course->fullname);
1122         $PAGE->navbar->add(get_string('submissions', 'assignment'), new moodle_url('/mod/assignment/submissions.php', array('id'=>$cm->id)));
1123         $PAGE->navbar->add(fullname($user, true));
1125         echo $OUTPUT->header();
1126         echo $OUTPUT->heading(get_string('feedback', 'assignment').': '.fullname($user, true));
1128         // display mform here...
1129         if ($advancedgradingwarning) {
1130             echo $OUTPUT->notification($advancedgradingwarning, 'error');
1131         }
1132         $submitform->display();
1134         $customfeedback = $this->custom_feedbackform($submission, true);
1135         if (!empty($customfeedback)) {
1136             echo $customfeedback;
1137         }
1139         echo $OUTPUT->footer();
1140     }
1142     /**
1143      *  Preprocess submission before grading
1144      *
1145      * Called by display_submission()
1146      * The default type does nothing here.
1147      *
1148      * @param object $submission The submission object
1149      */
1150     function preprocess_submission(&$submission) {
1151     }
1153     /**
1154      *  Display all the submissions ready for grading
1155      *
1156      * @global object
1157      * @global object
1158      * @global object
1159      * @global object
1160      * @param string $message
1161      * @return bool|void
1162      */
1163     function display_submissions($message='') {
1164         global $CFG, $DB, $USER, $DB, $OUTPUT, $PAGE;
1165         require_once($CFG->libdir.'/gradelib.php');
1167         /* first we check to see if the form has just been submitted
1168          * to request user_preference updates
1169          */
1171        $filters = array(self::FILTER_ALL             => get_string('all'),
1172                         self::FILTER_REQUIRE_GRADING => get_string('requiregrading', 'assignment'));
1174         $updatepref = optional_param('updatepref', 0, PARAM_BOOL);
1175         if ($updatepref) {
1176             $perpage = optional_param('perpage', 10, PARAM_INT);
1177             $perpage = ($perpage <= 0) ? 10 : $perpage ;
1178             $filter = optional_param('filter', 0, PARAM_INT);
1179             set_user_preference('assignment_perpage', $perpage);
1180             set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
1181             set_user_preference('assignment_filter', $filter);
1182         }
1184         /* next we get perpage and quickgrade (allow quick grade) params
1185          * from database
1186          */
1187         $perpage    = get_user_preferences('assignment_perpage', 10);
1188         $quickgrade = get_user_preferences('assignment_quickgrade', 0) && $this->quickgrade_mode_allowed();
1189         $filter = get_user_preferences('assignment_filter', 0);
1190         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);
1192         if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
1193             $uses_outcomes = true;
1194         } else {
1195             $uses_outcomes = false;
1196         }
1198         $page    = optional_param('page', 0, PARAM_INT);
1199         $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
1201     /// Some shortcuts to make the code read better
1203         $course     = $this->course;
1204         $assignment = $this->assignment;
1205         $cm         = $this->cm;
1206         $hassubmission = false;
1208         // reset filter to all for offline assignment only.
1209         if ($assignment->assignmenttype == 'offline') {
1210             if ($filter == self::FILTER_SUBMITTED) {
1211                 $filter = self::FILTER_ALL;
1212             }
1213         } else {
1214             $filters[self::FILTER_SUBMITTED] = get_string('submitted', 'assignment');
1215         }
1217         $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
1218         add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->cm->id, $this->assignment->id, $this->cm->id);
1220         $PAGE->set_title(format_string($this->assignment->name,true));
1221         $PAGE->set_heading($this->course->fullname);
1222         echo $OUTPUT->header();
1224         echo '<div class="usersubmissions">';
1226         //hook to allow plagiarism plugins to update status/print links.
1227         echo plagiarism_update_status($this->course, $this->cm);
1229         $course_context = get_context_instance(CONTEXT_COURSE, $course->id);
1230         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
1231             echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">'
1232                 . get_string('seeallcoursegrades', 'grades') . '</a></div>';
1233         }
1235         if (!empty($message)) {
1236             echo $message;   // display messages here if any
1237         }
1239         $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1241     /// Check to see if groups are being used in this assignment
1243         /// find out current groups mode
1244         $groupmode = groups_get_activity_groupmode($cm);
1245         $currentgroup = groups_get_activity_group($cm, true);
1246         groups_print_activity_menu($cm, $CFG->wwwroot . '/mod/assignment/submissions.php?id=' . $this->cm->id);
1248         /// Print quickgrade form around the table
1249         if ($quickgrade) {
1250             $formattrs = array();
1251             $formattrs['action'] = new moodle_url('/mod/assignment/submissions.php');
1252             $formattrs['id'] = 'fastg';
1253             $formattrs['method'] = 'post';
1255             echo html_writer::start_tag('form', $formattrs);
1256             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'id',      'value'=> $this->cm->id));
1257             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'mode',    'value'=> 'fastgrade'));
1258             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'page',    'value'=> $page));
1259             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=> sesskey()));
1260         }
1262         /// Get all ppl that are allowed to submit assignments
1263         list($esql, $params) = get_enrolled_sql($context, 'mod/assignment:submit', $currentgroup);
1265         if ($filter == self::FILTER_ALL) {
1266             $sql = "SELECT u.id FROM {user} u ".
1267                    "LEFT JOIN ($esql) eu ON eu.id=u.id ".
1268                    "WHERE u.deleted = 0 AND eu.id=u.id ";
1269         } else {
1270             $wherefilter = ' AND s.assignment = '. $this->assignment->id;
1271             $assignmentsubmission = "LEFT JOIN {assignment_submissions} s ON (u.id = s.userid) ";
1272             if($filter == self::FILTER_SUBMITTED) {
1273                 $wherefilter .= ' AND s.timemodified > 0 ';
1274             } else if($filter == self::FILTER_REQUIRE_GRADING && $assignment->assignmenttype != 'offline') {
1275                 $wherefilter .= ' AND s.timemarked < s.timemodified ';
1276             } else { // require grading for offline assignment
1277                 $assignmentsubmission = "";
1278                 $wherefilter = "";
1279             }
1281             $sql = "SELECT u.id FROM {user} u ".
1282                    "LEFT JOIN ($esql) eu ON eu.id=u.id ".
1283                    $assignmentsubmission.
1284                    "WHERE u.deleted = 0 AND eu.id=u.id ".
1285                    $wherefilter;
1286         }
1288         $users = $DB->get_records_sql($sql, $params);
1289         if (!empty($users)) {
1290             if($assignment->assignmenttype == 'offline' && $filter == self::FILTER_REQUIRE_GRADING) {
1291                 //remove users who has submitted their assignment
1292                 foreach ($this->get_submissions() as $submission) {
1293                     if (array_key_exists($submission->userid, $users)) {
1294                         unset($users[$submission->userid]);
1295                     }
1296                 }
1297             }
1298             $users = array_keys($users);
1299         }
1301         // if groupmembersonly used, remove users who are not in any group
1302         if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
1303             if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1304                 $users = array_intersect($users, array_keys($groupingusers));
1305             }
1306         }
1308         $extrafields = get_extra_user_fields($context);
1309         $tablecolumns = array_merge(array('picture', 'fullname'), $extrafields,
1310                 array('grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade'));
1311         if ($uses_outcomes) {
1312             $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
1313         }
1315         $extrafieldnames = array();
1316         foreach ($extrafields as $field) {
1317             $extrafieldnames[] = get_user_field_name($field);
1318         }
1319         $tableheaders = array_merge(
1320                 array('', get_string('fullnameuser')),
1321                 $extrafieldnames,
1322                 array(
1323                     get_string('grade'),
1324                     get_string('comment', 'assignment'),
1325                     get_string('lastmodified').' ('.get_string('submission', 'assignment').')',
1326                     get_string('lastmodified').' ('.get_string('grade').')',
1327                     get_string('status'),
1328                     get_string('finalgrade', 'grades'),
1329                 ));
1330         if ($uses_outcomes) {
1331             $tableheaders[] = get_string('outcome', 'grades');
1332         }
1334         require_once($CFG->libdir.'/tablelib.php');
1335         $table = new flexible_table('mod-assignment-submissions');
1337         $table->define_columns($tablecolumns);
1338         $table->define_headers($tableheaders);
1339         $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;currentgroup='.$currentgroup);
1341         $table->sortable(true, 'lastname');//sorted by lastname by default
1342         $table->collapsible(true);
1343         $table->initialbars(true);
1345         $table->column_suppress('picture');
1346         $table->column_suppress('fullname');
1348         $table->column_class('picture', 'picture');
1349         $table->column_class('fullname', 'fullname');
1350         foreach ($extrafields as $field) {
1351             $table->column_class($field, $field);
1352         }
1353         $table->column_class('grade', 'grade');
1354         $table->column_class('submissioncomment', 'comment');
1355         $table->column_class('timemodified', 'timemodified');
1356         $table->column_class('timemarked', 'timemarked');
1357         $table->column_class('status', 'status');
1358         $table->column_class('finalgrade', 'finalgrade');
1359         if ($uses_outcomes) {
1360             $table->column_class('outcome', 'outcome');
1361         }
1363         $table->set_attribute('cellspacing', '0');
1364         $table->set_attribute('id', 'attempts');
1365         $table->set_attribute('class', 'submissions');
1366         $table->set_attribute('width', '100%');
1368         $table->no_sorting('finalgrade');
1369         $table->no_sorting('outcome');
1371         // Start working -- this is necessary as soon as the niceties are over
1372         $table->setup();
1374         /// Construct the SQL
1375         list($where, $params) = $table->get_sql_where();
1376         if ($where) {
1377             $where .= ' AND ';
1378         }
1380         if ($filter == self::FILTER_SUBMITTED) {
1381            $where .= 's.timemodified > 0 AND ';
1382         } else if($filter == self::FILTER_REQUIRE_GRADING) {
1383             $where = '';
1384             if ($assignment->assignmenttype != 'offline') {
1385                $where .= 's.timemarked < s.timemodified AND ';
1386             }
1387         }
1389         if ($sort = $table->get_sql_sort()) {
1390             $sort = ' ORDER BY '.$sort;
1391         }
1393         $ufields = user_picture::fields('u', $extrafields);
1394         if (!empty($users)) {
1395             $select = "SELECT $ufields,
1396                               s.id AS submissionid, s.grade, s.submissioncomment,
1397                               s.timemodified, s.timemarked,
1398                               CASE WHEN s.timemarked > 0 AND s.timemarked >= s.timemodified THEN 1
1399                                    ELSE 0 END AS status ";
1401             $sql = 'FROM {user} u '.
1402                    'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1403                     AND s.assignment = '.$this->assignment->id.' '.
1404                    'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1406             $ausers = $DB->get_records_sql($select.$sql.$sort, $params, $table->get_page_start(), $table->get_page_size());
1408             $table->pagesize($perpage, count($users));
1410             ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1411             $offset = $page * $perpage;
1412             $strupdate = get_string('update');
1413             $strgrade  = get_string('grade');
1414             $grademenu = make_grades_menu($this->assignment->grade);
1416             if ($ausers !== false) {
1417                 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
1418                 $endposition = $offset + $perpage;
1419                 $currentposition = 0;
1420                 foreach ($ausers as $auser) {
1421                     if ($currentposition == $offset && $offset < $endposition) {
1422                         $rowclass = null;
1423                         $final_grade = $grading_info->items[0]->grades[$auser->id];
1424                         $grademax = $grading_info->items[0]->grademax;
1425                         $final_grade->formatted_grade = round($final_grade->grade,2) .' / ' . round($grademax,2);
1426                         $locked_overridden = 'locked';
1427                         if ($final_grade->overridden) {
1428                             $locked_overridden = 'overridden';
1429                         }
1431                         // TODO add here code if advanced grading grade must be reviewed => $auser->status=0
1433                         $picture = $OUTPUT->user_picture($auser);
1435                         if (empty($auser->submissionid)) {
1436                             $auser->grade = -1; //no submission yet
1437                         }
1439                         if (!empty($auser->submissionid)) {
1440                             $hassubmission = true;
1441                         ///Prints student answer and student modified date
1442                         ///attach file or print link to student answer, depending on the type of the assignment.
1443                         ///Refer to print_student_answer in inherited classes.
1444                             if ($auser->timemodified > 0) {
1445                                 $studentmodifiedcontent = $this->print_student_answer($auser->id)
1446                                         . userdate($auser->timemodified);
1447                                 if ($assignment->timedue && $auser->timemodified > $assignment->timedue) {
1448                                     $studentmodifiedcontent .= assignment_display_lateness($auser->timemodified, $assignment->timedue);
1449                                     $rowclass = 'late';
1450                                 }
1451                             } else {
1452                                 $studentmodifiedcontent = '&nbsp;';
1453                             }
1454                             $studentmodified = html_writer::tag('div', $studentmodifiedcontent, array('id' => 'ts' . $auser->id));
1455                         ///Print grade, dropdown or text
1456                             if ($auser->timemarked > 0) {
1457                                 $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
1459                                 if ($final_grade->locked or $final_grade->overridden) {
1460                                     $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1461                                 } else if ($quickgrade) {
1462                                     $attributes = array();
1463                                     $attributes['tabindex'] = $tabindex++;
1464                                     $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1465                                     $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
1466                                 } else {
1467                                     $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1468                                 }
1470                             } else {
1471                                 $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1472                                 if ($final_grade->locked or $final_grade->overridden) {
1473                                     $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1474                                 } else if ($quickgrade) {
1475                                     $attributes = array();
1476                                     $attributes['tabindex'] = $tabindex++;
1477                                     $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1478                                     $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1479                                 } else {
1480                                     $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1481                                 }
1482                             }
1483                         ///Print Comment
1484                             if ($final_grade->locked or $final_grade->overridden) {
1485                                 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';
1487                             } else if ($quickgrade) {
1488                                 $comment = '<div id="com'.$auser->id.'">'
1489                                          . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1490                                          . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1491                             } else {
1492                                 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
1493                             }
1494                         } else {
1495                             $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1496                             $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1497                             $status          = '<div id="st'.$auser->id.'">&nbsp;</div>';
1499                             if ($final_grade->locked or $final_grade->overridden) {
1500                                 $grade = '<div id="g'.$auser->id.'">'.$final_grade->formatted_grade . '</div>';
1501                                 $hassubmission = true;
1502                             } else if ($quickgrade) {   // allow editing
1503                                 $attributes = array();
1504                                 $attributes['tabindex'] = $tabindex++;
1505                                 $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1506                                 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1507                                 $hassubmission = true;
1508                             } else {
1509                                 $grade = '<div id="g'.$auser->id.'">-</div>';
1510                             }
1512                             if ($final_grade->locked or $final_grade->overridden) {
1513                                 $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
1514                             } else if ($quickgrade) {
1515                                 $comment = '<div id="com'.$auser->id.'">'
1516                                          . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1517                                          . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1518                             } else {
1519                                 $comment = '<div id="com'.$auser->id.'">&nbsp;</div>';
1520                             }
1521                         }
1523                         if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
1524                             $auser->status = 0;
1525                         } else {
1526                             $auser->status = 1;
1527                         }
1529                         $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
1531                         ///No more buttons, we use popups ;-).
1532                         $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1533                                    . '&amp;userid='.$auser->id.'&amp;mode=single'.'&amp;filter='.$filter.'&amp;offset='.$offset++;
1535                         $button = $OUTPUT->action_link($popup_url, $buttontext);
1537                         $status  = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
1539                         $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';
1541                         $outcomes = '';
1543                         if ($uses_outcomes) {
1545                             foreach($grading_info->outcomes as $n=>$outcome) {
1546                                 $outcomes .= '<div class="outcome"><label>'.$outcome->name.'</label>';
1547                                 $options = make_grades_menu(-$outcome->scaleid);
1549                                 if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
1550                                     $options[0] = get_string('nooutcome', 'grades');
1551                                     $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
1552                                 } else {
1553                                     $attributes = array();
1554                                     $attributes['tabindex'] = $tabindex++;
1555                                     $attributes['id'] = 'outcome_'.$n.'_'.$auser->id;
1556                                     $outcomes .= ' '.html_writer::select($options, 'outcome_'.$n.'['.$auser->id.']', $outcome->grades[$auser->id]->grade, array(0=>get_string('nooutcome', 'grades')), $attributes);
1557                                 }
1558                                 $outcomes .= '</div>';
1559                             }
1560                         }
1562                         $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>';
1563                         $extradata = array();
1564                         foreach ($extrafields as $field) {
1565                             $extradata[] = $auser->{$field};
1566                         }
1567                         $row = array_merge(array($picture, $userlink), $extradata,
1568                                 array($grade, $comment, $studentmodified, $teachermodified,
1569                                 $status, $finalgrade));
1570                         if ($uses_outcomes) {
1571                             $row[] = $outcomes;
1572                         }
1573                         $table->add_data($row, $rowclass);
1574                     }
1575                     $currentposition++;
1576                 }
1577                 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)
1578                     echo html_writer::start_tag('div', array('class' => 'mod-assignment-download-link'));
1579                     echo html_writer::link(new moodle_url('/mod/assignment/submissions.php', array('id' => $this->cm->id, 'download' => 'zip')), get_string('downloadall', 'assignment'));
1580                     echo html_writer::end_tag('div');
1581                 }
1582                 $table->print_html();  /// Print the whole table
1583             } else {
1584                 if ($filter == self::FILTER_SUBMITTED) {
1585                     echo html_writer::tag('div', get_string('nosubmisson', 'assignment'), array('class'=>'nosubmisson'));
1586                 } else if ($filter == self::FILTER_REQUIRE_GRADING) {
1587                     echo html_writer::tag('div', get_string('norequiregrading', 'assignment'), array('class'=>'norequiregrading'));
1588                 }
1589             }
1590         }
1592         /// Print quickgrade form around the table
1593         if ($quickgrade && $table->started_output && !empty($users)){
1594             $mailinfopref = false;
1595             if (get_user_preferences('assignment_mailinfo', 1)) {
1596                 $mailinfopref = true;
1597             }
1598             $emailnotification =  html_writer::checkbox('mailinfo', 1, $mailinfopref, get_string('enablenotification','assignment'));
1600             $emailnotification .= $OUTPUT->help_icon('enablenotification', 'assignment');
1601             echo html_writer::tag('div', $emailnotification, array('class'=>'emailnotification'));
1603             $savefeedback = html_writer::empty_tag('input', array('type'=>'submit', 'name'=>'fastg', 'value'=>get_string('saveallfeedback', 'assignment')));
1604             echo html_writer::tag('div', $savefeedback, array('class'=>'fastgbutton'));
1606             echo html_writer::end_tag('form');
1607         } else if ($quickgrade) {
1608             echo html_writer::end_tag('form');
1609         }
1611         echo '</div>';
1612         /// End of fast grading form
1614         /// Mini form for setting user preference
1616         $formaction = new moodle_url('/mod/assignment/submissions.php', array('id'=>$this->cm->id));
1617         $mform = new MoodleQuickForm('optionspref', 'post', $formaction, '', array('class'=>'optionspref'));
1619         $mform->addElement('hidden', 'updatepref');
1620         $mform->setDefault('updatepref', 1);
1621         $mform->addElement('header', 'qgprefs', get_string('optionalsettings', 'assignment'));
1622         $mform->addElement('select', 'filter', get_string('show'),  $filters);
1624         $mform->setDefault('filter', $filter);
1626         $mform->addElement('text', 'perpage', get_string('pagesize', 'assignment'), array('size'=>1));
1627         $mform->setDefault('perpage', $perpage);
1629         if ($this->quickgrade_mode_allowed()) {
1630             $mform->addElement('checkbox', 'quickgrade', get_string('quickgrade','assignment'));
1631             $mform->setDefault('quickgrade', $quickgrade);
1632             $mform->addHelpButton('quickgrade', 'quickgrade', 'assignment');
1633         }
1635         $mform->addElement('submit', 'savepreferences', get_string('savepreferences'));
1637         $mform->display();
1639         echo $OUTPUT->footer();
1640     }
1642     /**
1643      * If the form was cancelled ('Cancel' or 'Next' was pressed), call cancel method
1644      * from advanced grading (if applicable) and returns true
1645      * If the form was submitted, validates it and returns false if validation did not pass.
1646      * If validation passes, preprocess advanced grading (if applicable) and returns true.
1647      *
1648      * Note to the developers: This is NOT the correct way to implement advanced grading
1649      * in grading form. The assignment grading was written long time ago and unfortunately
1650      * does not fully use the mforms. Usually function is_validated() is called to
1651      * validate the form and get_data() is called to get the data from the form.
1652      *
1653      * Here we have to push the calculated grade to $_POST['xgrade'] because further processing
1654      * of the form gets the data not from form->get_data(), but from $_POST (using statement
1655      * like  $feedback = data_submitted() )
1656      */
1657     protected function validate_and_preprocess_feedback() {
1658         global $USER, $CFG;
1659         require_once($CFG->libdir.'/gradelib.php');
1660         if (!($feedback = data_submitted()) || !isset($feedback->userid) || !isset($feedback->offset)) {
1661             return true;      // No incoming data, nothing to validate
1662         }
1663         $userid = required_param('userid', PARAM_INT);
1664         $offset = required_param('offset', PARAM_INT);
1665         $gradinginfo = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($userid));
1666         $gradingdisabled = $gradinginfo->items[0]->grades[$userid]->locked || $gradinginfo->items[0]->grades[$userid]->overridden;
1667         if ($gradingdisabled) {
1668             return true;
1669         }
1670         $submissiondata = $this->display_submission($offset, $userid, false);
1671         $mform = $submissiondata->mform;
1672         $gradinginstance = $mform->use_advanced_grading();
1673         if (optional_param('cancel', false, PARAM_BOOL) || optional_param('next', false, PARAM_BOOL)) {
1674             // form was cancelled
1675             if ($gradinginstance) {
1676                 $gradinginstance->cancel();
1677             }
1678         } else if ($mform->is_submitted()) {
1679             // form was submitted (= a submit button other than 'cancel' or 'next' has been clicked)
1680             if (!$mform->is_validated()) {
1681                 return false;
1682             }
1683             // preprocess advanced grading here
1684             if ($gradinginstance) {
1685                 $data = $mform->get_data();
1686                 // create submission if it did not exist yet because we need submission->id for storing the grading instance
1687                 $submission = $this->get_submission($userid, true);
1688                 $_POST['xgrade'] = $gradinginstance->submit_and_get_grade($data->advancedgrading, $submission->id);
1689             }
1690         }
1691         return true;
1692     }
1694     /**
1695      *  Process teacher feedback submission
1696      *
1697      * This is called by submissions() when a grading even has taken place.
1698      * It gets its data from the submitted form.
1699      *
1700      * @global object
1701      * @global object
1702      * @global object
1703      * @return object|bool The updated submission object or false
1704      */
1705     function process_feedback($formdata=null) {
1706         global $CFG, $USER, $DB;
1707         require_once($CFG->libdir.'/gradelib.php');
1709         if (!$feedback = data_submitted() or !confirm_sesskey()) {      // No incoming data?
1710             return false;
1711         }
1713         ///For save and next, we need to know the userid to save, and the userid to go
1714         ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1715         ///as the userid to store
1716         if ((int)$feedback->saveuserid !== -1){
1717             $feedback->userid = $feedback->saveuserid;
1718         }
1720         if (!empty($feedback->cancel)) {          // User hit cancel button
1721             return false;
1722         }
1724         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);
1726         // store outcomes if needed
1727         $this->process_outcomes($feedback->userid);
1729         $submission = $this->get_submission($feedback->userid, true);  // Get or make one
1731         if (!($grading_info->items[0]->grades[$feedback->userid]->locked ||
1732             $grading_info->items[0]->grades[$feedback->userid]->overridden) ) {
1734             $submission->grade      = $feedback->xgrade;
1735             $submission->submissioncomment    = $feedback->submissioncomment_editor['text'];
1736             $submission->teacher    = $USER->id;
1737             $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1738             if (!$mailinfo) {
1739                 $submission->mailed = 1;       // treat as already mailed
1740             } else {
1741                 $submission->mailed = 0;       // Make sure mail goes out (again, even)
1742             }
1743             $submission->timemarked = time();
1745             unset($submission->data1);  // Don't need to update this.
1746             unset($submission->data2);  // Don't need to update this.
1748             if (empty($submission->timemodified)) {   // eg for offline assignments
1749                 // $submission->timemodified = time();
1750             }
1752             $DB->update_record('assignment_submissions', $submission);
1754             // triger grade event
1755             $this->update_grade($submission);
1757             add_to_log($this->course->id, 'assignment', 'update grades',
1758                        'submissions.php?id='.$this->cm->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
1759              if (!is_null($formdata)) {
1760                     if ($this->type == 'upload' || $this->type == 'uploadsingle') {
1761                         $mformdata = $formdata->mform->get_data();
1762                         $mformdata = file_postupdate_standard_filemanager($mformdata, 'files', $formdata->fileui_options, $this->context, 'mod_assignment', 'response', $submission->id);
1763                     }
1764              }
1765         }
1767         return $submission;
1769     }
1771     function process_outcomes($userid) {
1772         global $CFG, $USER;
1774         if (empty($CFG->enableoutcomes)) {
1775             return;
1776         }
1778         require_once($CFG->libdir.'/gradelib.php');
1780         if (!$formdata = data_submitted() or !confirm_sesskey()) {
1781             return;
1782         }
1784         $data = array();
1785         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
1787         if (!empty($grading_info->outcomes)) {
1788             foreach($grading_info->outcomes as $n=>$old) {
1789                 $name = 'outcome_'.$n;
1790                 if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
1791                     $data[$n] = $formdata->{$name}[$userid];
1792                 }
1793             }
1794         }
1795         if (count($data) > 0) {
1796             grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1797         }
1799     }
1801     /**
1802      * Load the submission object for a particular user
1803      *
1804      * @global object
1805      * @global object
1806      * @param $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1807      * @param $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1808      * @param bool $teachermodified student submission set if false
1809      * @return object The submission
1810      */
1811     function get_submission($userid=0, $createnew=false, $teachermodified=false) {
1812         global $USER, $DB;
1814         if (empty($userid)) {
1815             $userid = $USER->id;
1816         }
1818         $submission = $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1820         if ($submission || !$createnew) {
1821             return $submission;
1822         }
1823         $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
1824         $DB->insert_record("assignment_submissions", $newsubmission);
1826         return $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1827     }
1829     /**
1830      * Check the given submission is complete. Preliminary rows are often created in the assignment_submissions
1831      * table before a submission actually takes place. This function checks to see if the given submission has actually
1832      * been submitted.
1833      *
1834      * @param  stdClass $submission The submission we want to check for completion
1835      * @return bool                 Indicates if the submission was found to be complete
1836      */
1837     public function is_submitted_with_required_data($submission) {
1838         return $submission->timemodified;
1839     }
1841     /**
1842      * Instantiates a new submission object for a given user
1843      *
1844      * Sets the assignment, userid and times, everything else is set to default values.
1845      *
1846      * @param int $userid The userid for which we want a submission object
1847      * @param bool $teachermodified student submission set if false
1848      * @return object The submission
1849      */
1850     function prepare_new_submission($userid, $teachermodified=false) {
1851         $submission = new stdClass();
1852         $submission->assignment   = $this->assignment->id;
1853         $submission->userid       = $userid;
1854         $submission->timecreated = time();
1855         // teachers should not be modifying modified date, except offline assignments
1856         if ($teachermodified) {
1857             $submission->timemodified = 0;
1858         } else {
1859             $submission->timemodified = $submission->timecreated;
1860         }
1861         $submission->numfiles     = 0;
1862         $submission->data1        = '';
1863         $submission->data2        = '';
1864         $submission->grade        = -1;
1865         $submission->submissioncomment      = '';
1866         $submission->format       = 0;
1867         $submission->teacher      = 0;
1868         $submission->timemarked   = 0;
1869         $submission->mailed       = 0;
1870         return $submission;
1871     }
1873     /**
1874      * Return all assignment submissions by ENROLLED students (even empty)
1875      *
1876      * @param string $sort optional field names for the ORDER BY in the sql query
1877      * @param string $dir optional specifying the sort direction, defaults to DESC
1878      * @return array The submission objects indexed by id
1879      */
1880     function get_submissions($sort='', $dir='DESC') {
1881         return assignment_get_all_submissions($this->assignment, $sort, $dir);
1882     }
1884     /**
1885      * Counts all complete (real) assignment submissions by enrolled students
1886      *
1887      * @param  int $groupid (optional) If nonzero then count is restricted to this group
1888      * @return int          The number of submissions
1889      */
1890     function count_real_submissions($groupid=0) {
1891         global $CFG;
1892         global $DB;
1894         // Grab the context assocated with our course module
1895         $context = get_context_instance(CONTEXT_MODULE, $this->cm->id);
1897         // Get ids of users enrolled in the given course.
1898         list($enroledsql, $params) = get_enrolled_sql($context, 'mod/assignment:view', $groupid);
1899         $params['assignmentid'] = $this->cm->instance;
1901         // Get ids of users enrolled in the given course.
1902         return $DB->count_records_sql("SELECT COUNT('x')
1903                                          FROM {assignment_submissions} s
1904                                     LEFT JOIN {assignment} a ON a.id = s.assignment
1905                                    INNER JOIN ($enroledsql) u ON u.id = s.userid
1906                                         WHERE s.assignment = :assignmentid AND
1907                                               s.timemodified > 0", $params);
1908     }
1910     /**
1911      * Alerts teachers by email of new or changed assignments that need grading
1912      *
1913      * First checks whether the option to email teachers is set for this assignment.
1914      * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1915      * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1916      *
1917      * @global object
1918      * @global object
1919      * @param $submission object The submission that has changed
1920      * @return void
1921      */
1922     function email_teachers($submission) {
1923         global $CFG, $DB;
1925         if (empty($this->assignment->emailteachers)) {          // No need to do anything
1926             return;
1927         }
1929         $user = $DB->get_record('user', array('id'=>$submission->userid));
1931         if ($teachers = $this->get_graders($user)) {
1933             $strassignments = get_string('modulenameplural', 'assignment');
1934             $strassignment  = get_string('modulename', 'assignment');
1935             $strsubmitted  = get_string('submitted', 'assignment');
1937             foreach ($teachers as $teacher) {
1938                 $info = new stdClass();
1939                 $info->username = fullname($user, true);
1940                 $info->assignment = format_string($this->assignment->name,true);
1941                 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
1942                 $info->timeupdated = userdate($submission->timemodified, '%c', $teacher->timezone);
1944                 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1945                 $posttext = $this->email_teachers_text($info);
1946                 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
1948                 $eventdata = new stdClass();
1949                 $eventdata->modulename       = 'assignment';
1950                 $eventdata->userfrom         = $user;
1951                 $eventdata->userto           = $teacher;
1952                 $eventdata->subject          = $postsubject;
1953                 $eventdata->fullmessage      = $posttext;
1954                 $eventdata->fullmessageformat = FORMAT_PLAIN;
1955                 $eventdata->fullmessagehtml  = $posthtml;
1956                 $eventdata->smallmessage     = $postsubject;
1958                 $eventdata->name            = 'assignment_updates';
1959                 $eventdata->component       = 'mod_assignment';
1960                 $eventdata->notification    = 1;
1961                 $eventdata->contexturl      = $info->url;
1962                 $eventdata->contexturlname  = $info->assignment;
1964                 message_send($eventdata);
1965             }
1966         }
1967     }
1969     /**
1970      * @param string $filearea
1971      * @param array $args
1972      * @return bool
1973      */
1974     function send_file($filearea, $args) {
1975         debugging('plugin does not implement file sending', DEBUG_DEVELOPER);
1976         return false;
1977     }
1979     /**
1980      * Returns a list of teachers that should be grading given submission
1981      *
1982      * @param object $user
1983      * @return array
1984      */
1985     function get_graders($user) {
1986         //potential graders
1987         $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false);
1989         $graders = array();
1990         if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) {   // Separate groups are being used
1991             if ($groups = groups_get_all_groups($this->course->id, $user->id)) {  // Try to find all groups
1992                 foreach ($groups as $group) {
1993                     foreach ($potgraders as $t) {
1994                         if ($t->id == $user->id) {
1995                             continue; // do not send self
1996                         }
1997                         if (groups_is_member($group->id, $t->id)) {
1998                             $graders[$t->id] = $t;
1999                         }
2000                     }
2001                 }
2002             } else {
2003                 // user not in group, try to find graders without group
2004                 foreach ($potgraders as $t) {
2005                     if ($t->id == $user->id) {
2006                         continue; // do not send self
2007                     }
2008                     if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
2009                         $graders[$t->id] = $t;
2010                     }
2011                 }
2012             }
2013         } else {
2014             foreach ($potgraders as $t) {
2015                 if ($t->id == $user->id) {
2016                     continue; // do not send self
2017                 }
2018                 $graders[$t->id] = $t;
2019             }
2020         }
2021         return $graders;
2022     }
2024     /**
2025      * Creates the text content for emails to teachers
2026      *
2027      * @param $info object The info used by the 'emailteachermail' language string
2028      * @return string
2029      */
2030     function email_teachers_text($info) {
2031         $posttext  = format_string($this->course->shortname, true, array('context' => $this->coursecontext)).' -> '.
2032                      $this->strassignments.' -> '.
2033                      format_string($this->assignment->name, true, array('context' => $this->context))."\n";
2034         $posttext .= '---------------------------------------------------------------------'."\n";
2035         $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
2036         $posttext .= "\n---------------------------------------------------------------------\n";
2037         return $posttext;
2038     }
2040      /**
2041      * Creates the html content for emails to teachers
2042      *
2043      * @param $info object The info used by the 'emailteachermailhtml' language string
2044      * @return string
2045      */
2046     function email_teachers_html($info) {
2047         global $CFG;
2048         $posthtml  = '<p><font face="sans-serif">'.
2049                      '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname, true, array('context' => $this->coursecontext)).'</a> ->'.
2050                      '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
2051                      '<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>';
2052         $posthtml .= '<hr /><font face="sans-serif">';
2053         $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
2054         $posthtml .= '</font><hr />';
2055         return $posthtml;
2056     }
2058     /**
2059      * Produces a list of links to the files uploaded by a user
2060      *
2061      * @param $userid int optional id of the user. If 0 then $USER->id is used.
2062      * @param $return boolean optional defaults to false. If true the list is returned rather than printed
2063      * @return string optional
2064      */
2065     function print_user_files($userid=0, $return=false) {
2066         global $CFG, $USER, $OUTPUT;
2068         if (!$userid) {
2069             if (!isloggedin()) {
2070                 return '';
2071             }
2072             $userid = $USER->id;
2073         }
2075         $output = '';
2077         $submission = $this->get_submission($userid);
2078         if (!$submission) {
2079             return $output;
2080         }
2082         $fs = get_file_storage();
2083         $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false);
2084         if (!empty($files)) {
2085             require_once($CFG->dirroot . '/mod/assignment/locallib.php');
2086             if ($CFG->enableportfolios) {
2087                 require_once($CFG->libdir.'/portfoliolib.php');
2088                 $button = new portfolio_add_button();
2089             }
2090             foreach ($files as $file) {
2091                 $filename = $file->get_filename();
2092                 $mimetype = $file->get_mimetype();
2093                 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/mod_assignment/submission/'.$submission->id.'/'.$filename);
2094                 $output .= '<a href="'.$path.'" ><img src="'.$OUTPUT->pix_url(file_mimetype_icon($mimetype)).'" class="icon" alt="'.$mimetype.'" />'.s($filename).'</a>';
2095                 if ($CFG->enableportfolios && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
2096                     $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id, 'submissionid' => $submission->id, 'fileid' => $file->get_id()), '/mod/assignment/locallib.php');
2097                     $button->set_format_by_file($file);
2098                     $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
2099                 }
2101                 if ($CFG->enableplagiarism) {
2102                     require_once($CFG->libdir.'/plagiarismlib.php');
2103                     $output .= plagiarism_get_links(array('userid'=>$userid, 'file'=>$file, 'cmid'=>$this->cm->id, 'course'=>$this->course, 'assignment'=>$this->assignment));
2104                     $output .= '<br />';
2105                 }
2106             }
2107             if ($CFG->enableportfolios && count($files) > 1  && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
2108                 $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id, 'submissionid' => $submission->id), '/mod/assignment/locallib.php');
2109                 $output .= '<br />'  . $button->to_html(PORTFOLIO_ADD_TEXT_LINK);
2110             }
2111         }
2113         $output = '<div class="files">'.$output.'</div>';
2115         if ($return) {
2116             return $output;
2117         }
2118         echo $output;
2119     }
2121     /**
2122      * Count the files uploaded by a given user
2123      *
2124      * @param $itemid int The submission's id as the file's itemid.
2125      * @return int
2126      */
2127     function count_user_files($itemid) {
2128         $fs = get_file_storage();
2129         $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $itemid, "id", false);
2130         return count($files);
2131     }
2133     /**
2134      * Returns true if the student is allowed to submit
2135      *
2136      * Checks that the assignment has started and, if the option to prevent late
2137      * submissions is set, also checks that the assignment has not yet closed.
2138      * @return boolean
2139      */
2140     function isopen() {
2141         $time = time();
2142         if ($this->assignment->preventlate && $this->assignment->timedue) {
2143             return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
2144         } else {
2145             return ($this->assignment->timeavailable <= $time);
2146         }
2147     }
2150     /**
2151      * Return true if is set description is hidden till available date
2152      *
2153      * This is needed by calendar so that hidden descriptions do not
2154      * come up in upcoming events.
2155      *
2156      * Check that description is hidden till available date
2157      * By default return false
2158      * Assignments types should implement this method if needed
2159      * @return boolen
2160      */
2161     function description_is_hidden() {
2162         return false;
2163     }
2165     /**
2166      * Return an outline of the user's interaction with the assignment
2167      *
2168      * The default method prints the grade and timemodified
2169      * @param $grade object
2170      * @return object with properties ->info and ->time
2171      */
2172     function user_outline($grade) {
2174         $result = new stdClass();
2175         $result->info = get_string('grade').': '.$grade->str_long_grade;
2176         $result->time = $grade->dategraded;
2177         return $result;
2178     }
2180     /**
2181      * Print complete information about the user's interaction with the assignment
2182      *
2183      * @param $user object
2184      */
2185     function user_complete($user, $grade=null) {
2186         global $OUTPUT;
2188         if ($submission = $this->get_submission($user->id)) {
2190             $fs = get_file_storage();
2192             if ($files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false)) {
2193                 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
2194                 foreach ($files as $file) {
2195                     $countfiles .= "; ".$file->get_filename();
2196                 }
2197             }
2199             echo $OUTPUT->box_start();
2200             echo get_string("lastmodified").": ";
2201             echo userdate($submission->timemodified);
2202             echo $this->display_lateness($submission->timemodified);
2204             $this->print_user_files($user->id);
2206             echo '<br />';
2208             $this->view_feedback($submission);
2210             echo $OUTPUT->box_end();
2212         } else {
2213             if ($grade) {
2214                 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
2215                 if ($grade->str_feedback) {
2216                     echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
2217                 }
2218             }
2219             print_string("notsubmittedyet", "assignment");
2220         }
2221     }
2223     /**
2224      * Return a string indicating how late a submission is
2225      *
2226      * @param $timesubmitted int
2227      * @return string
2228      */
2229     function display_lateness($timesubmitted) {
2230         return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
2231     }
2233     /**
2234      * Empty method stub for all delete actions.
2235      */
2236     function delete() {
2237         //nothing by default
2238         redirect('view.php?id='.$this->cm->id);
2239     }
2241     /**
2242      * Empty custom feedback grading form.
2243      */
2244     function custom_feedbackform($submission, $return=false) {
2245         //nothing by default
2246         return '';
2247     }
2249     /**
2250      * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
2251      * for the course (see resource).
2252      *
2253      * Given a course_module object, this function returns any "extra" information that may be needed
2254      * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
2255      *
2256      * @param $coursemodule object The coursemodule object (record).
2257      * @return cached_cm_info Object used to customise appearance on course page
2258      */
2259     function get_coursemodule_info($coursemodule) {
2260         return null;
2261     }
2263     /**
2264      * Plugin cron method - do not use $this here, create new assignment instances if needed.
2265      * @return void
2266      */
2267     function cron() {
2268         //no plugin cron by default - override if needed
2269     }
2271     /**
2272      * Reset all submissions
2273      */
2274     function reset_userdata($data) {
2275         global $CFG, $DB;
2277         if (!$DB->count_records('assignment', array('course'=>$data->courseid, 'assignmenttype'=>$this->type))) {
2278             return array(); // no assignments of this type present
2279         }
2281         $componentstr = get_string('modulenameplural', 'assignment');
2282         $status = array();
2284         $typestr = get_string('type'.$this->type, 'assignment');
2285         // ugly hack to support pluggable assignment type titles...
2286         if($typestr === '[[type'.$this->type.']]'){
2287             $typestr = get_string('type'.$this->type, 'assignment_'.$this->type);
2288         }
2290         if (!empty($data->reset_assignment_submissions)) {
2291             $assignmentssql = "SELECT a.id
2292                                  FROM {assignment} a
2293                                 WHERE a.course=? AND a.assignmenttype=?";
2294             $params = array($data->courseid, $this->type);
2296             // now get rid of all submissions and responses
2297             $fs = get_file_storage();
2298             if ($assignments = $DB->get_records_sql($assignmentssql, $params)) {
2299                 foreach ($assignments as $assignmentid=>$unused) {
2300                     if (!$cm = get_coursemodule_from_instance('assignment', $assignmentid)) {
2301                         continue;
2302                     }
2303                     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2304                     $fs->delete_area_files($context->id, 'mod_assignment', 'submission');
2305                     $fs->delete_area_files($context->id, 'mod_assignment', 'response');
2306                 }
2307             }
2309             $DB->delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)", $params);
2311             $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
2313             if (empty($data->reset_gradebook_grades)) {
2314                 // remove all grades from gradebook
2315                 assignment_reset_gradebook($data->courseid, $this->type);
2316             }
2317         }
2319         /// updating dates - shift may be negative too
2320         if ($data->timeshift) {
2321             shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
2322             $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
2323         }
2325         return $status;
2326     }
2329     function portfolio_exportable() {
2330         return false;
2331     }
2333     /**
2334      * base implementation for backing up subtype specific information
2335      * for one single module
2336      *
2337      * @param filehandle $bf file handle for xml file to write to
2338      * @param mixed $preferences the complete backup preference object
2339      *
2340      * @return boolean
2341      *
2342      * @static
2343      */
2344     static function backup_one_mod($bf, $preferences, $assignment) {
2345         return true;
2346     }
2348     /**
2349      * base implementation for backing up subtype specific information
2350      * for one single submission
2351      *
2352      * @param filehandle $bf file handle for xml file to write to
2353      * @param mixed $preferences the complete backup preference object
2354      * @param object $submission the assignment submission db record
2355      *
2356      * @return boolean
2357      *
2358      * @static
2359      */
2360     static function backup_one_submission($bf, $preferences, $assignment, $submission) {
2361         return true;
2362     }
2364     /**
2365      * base implementation for restoring subtype specific information
2366      * for one single module
2367      *
2368      * @param array  $info the array representing the xml
2369      * @param object $restore the restore preferences
2370      *
2371      * @return boolean
2372      *
2373      * @static
2374      */
2375     static function restore_one_mod($info, $restore, $assignment) {
2376         return true;
2377     }
2379     /**
2380      * base implementation for restoring subtype specific information
2381      * for one single submission
2382      *
2383      * @param object $submission the newly created submission
2384      * @param array  $info the array representing the xml
2385      * @param object $restore the restore preferences
2386      *
2387      * @return boolean
2388      *
2389      * @static
2390      */
2391     static function restore_one_submission($info, $restore, $assignment, $submission) {
2392         return true;
2393     }
2395 } ////// End of the assignment_base class
2398 class mod_assignment_grading_form extends moodleform {
2399     /** @var stores the advaned grading instance (if used in grading) */
2400     private $advancegradinginstance;
2402     function definition() {
2403         global $OUTPUT;
2404         $mform =& $this->_form;
2406         if (isset($this->_customdata->advancedgradinginstance)) {
2407             $this->use_advanced_grading($this->_customdata->advancedgradinginstance);
2408         }
2410         $formattr = $mform->getAttributes();
2411         $formattr['id'] = 'submitform';
2412         $mform->setAttributes($formattr);
2413         // hidden params
2414         $mform->addElement('hidden', 'offset', ($this->_customdata->offset+1));
2415         $mform->setType('offset', PARAM_INT);
2416         $mform->addElement('hidden', 'userid', $this->_customdata->userid);
2417         $mform->setType('userid', PARAM_INT);
2418         $mform->addElement('hidden', 'nextid', $this->_customdata->nextid);
2419         $mform->setType('nextid', PARAM_INT);
2420         $mform->addElement('hidden', 'id', $this->_customdata->cm->id);
2421         $mform->setType('id', PARAM_INT);
2422         $mform->addElement('hidden', 'sesskey', sesskey());
2423         $mform->setType('sesskey', PARAM_ALPHANUM);
2424         $mform->addElement('hidden', 'mode', 'grade');
2425         $mform->setType('mode', PARAM_TEXT);
2426         $mform->addElement('hidden', 'menuindex', "0");
2427         $mform->setType('menuindex', PARAM_INT);
2428         $mform->addElement('hidden', 'saveuserid', "-1");
2429         $mform->setType('saveuserid', PARAM_INT);
2430         $mform->addElement('hidden', 'filter', "0");
2431         $mform->setType('filter', PARAM_INT);
2433         $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->user),
2434                                                 fullname($this->_customdata->user, true) . '<br/>' .
2435                                                 userdate($this->_customdata->submission->timemodified) .
2436                                                 $this->_customdata->lateness );
2438         $this->add_submission_content();
2439         $this->add_grades_section();
2441         $this->add_feedback_section();
2443         if ($this->_customdata->submission->timemarked) {
2444             $datestring = userdate($this->_customdata->submission->timemarked)."&nbsp; (".format_time(time() - $this->_customdata->submission->timemarked).")";
2445             $mform->addElement('header', 'Last Grade', get_string('lastgrade', 'assignment'));
2446             $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->teacher) ,
2447                                                     fullname($this->_customdata->teacher,true).
2448                                                     '<br/>'.$datestring);
2449         }
2450         // buttons
2451         $this->add_action_buttons();
2453     }
2455     /**
2456      * Gets or sets the instance for advanced grading
2457      *
2458      * @param gradingform_instance $gradinginstance
2459      */
2460     public function use_advanced_grading($gradinginstance = false) {
2461         if ($gradinginstance !== false) {
2462             $this->advancegradinginstance = $gradinginstance;
2463         }
2464         return $this->advancegradinginstance;
2465     }
2467     /**
2468      * Add the grades configuration section to the assignment configuration form
2469      */
2470     function add_grades_section() {
2471         global $CFG;
2472         $mform =& $this->_form;
2473         $attributes = array();
2474         if ($this->_customdata->gradingdisabled) {
2475             $attributes['disabled'] ='disabled';
2476         }
2478         $mform->addElement('header', 'Grades', get_string('grades', 'grades'));
2480         $grademenu = make_grades_menu($this->_customdata->assignment->grade);
2481         if ($gradinginstance = $this->use_advanced_grading()) {
2482             $gradinginstance->get_controller()->set_grade_range($grademenu);
2483             $gradingelement = $mform->addElement('grading', 'advancedgrading', get_string('grade').':', array('gradinginstance' => $gradinginstance));
2484             if ($this->_customdata->gradingdisabled) {
2485                 $gradingelement->freeze();
2486             } else {
2487                 $mform->addElement('hidden', 'advancedgradinginstanceid', $gradinginstance->get_id());
2488             }
2489         } else {
2490             // use simple direct grading
2491             $grademenu['-1'] = get_string('nograde');
2493             $mform->addElement('select', 'xgrade', get_string('grade').':', $grademenu, $attributes);
2494             $mform->setDefault('xgrade', $this->_customdata->submission->grade ); //@fixme some bug when element called 'grade' makes it break
2495             $mform->setType('xgrade', PARAM_INT);
2496         }
2498         if (!empty($this->_customdata->enableoutcomes)) {
2499             foreach($this->_customdata->grading_info->outcomes as $n=>$outcome) {
2500                 $options = make_grades_menu(-$outcome->scaleid);
2501                 if ($outcome->grades[$this->_customdata->submission->userid]->locked) {
2502                     $options[0] = get_string('nooutcome', 'grades');
2503                     $mform->addElement('static', 'outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->name.':',
2504                             $options[$outcome->grades[$this->_customdata->submission->userid]->grade]);
2505                 } else {
2506                     $options[''] = get_string('nooutcome', 'grades');
2507                     $attributes = array('id' => 'menuoutcome_'.$n );
2508                     $mform->addElement('select', 'outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->name.':', $options, $attributes );
2509                     $mform->setType('outcome_'.$n.'['.$this->_customdata->userid.']', PARAM_INT);
2510                     $mform->setDefault('outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->grades[$this->_customdata->submission->userid]->grade );
2511                 }
2512             }
2513         }
2514         $course_context = get_context_instance(CONTEXT_MODULE , $this->_customdata->cm->id);
2515         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
2516             $grade = '<a href="'.$CFG->wwwroot.'/grade/report/grader/index.php?id='. $this->_customdata->courseid .'" >'.
2517                         $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade . '</a>';
2518         }else{
2519             $grade = $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade;
2520         }
2521         $mform->addElement('static', 'finalgrade', get_string('currentgrade', 'assignment').':' ,$grade);
2522         $mform->setType('finalgrade', PARAM_INT);
2523     }
2525     /**
2526      *
2527      * @global core_renderer $OUTPUT
2528      */
2529     function add_feedback_section() {
2530         global $OUTPUT;
2531         $mform =& $this->_form;
2532         $mform->addElement('header', 'Feed Back', get_string('feedback', 'grades'));
2534         if ($this->_customdata->gradingdisabled) {
2535             $mform->addElement('static', 'disabledfeedback', $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_feedback );
2536         } else {
2537             // visible elements
2539             $mform->addElement('editor', 'submissioncomment_editor', get_string('feedback', 'assignment').':', null, $this->get_editor_options() );
2540             $mform->setType('submissioncomment_editor', PARAM_RAW); // to be cleaned before display
2541             $mform->setDefault('submissioncomment_editor', $this->_customdata->submission->submissioncomment);
2542             //$mform->addRule('submissioncomment', get_string('required'), 'required', null, 'client');
2543             switch ($this->_customdata->assignment->assignmenttype) {
2544                 case 'upload' :
2545                 case 'uploadsingle' :
2546                     $mform->addElement('filemanager', 'files_filemanager', get_string('responsefiles', 'assignment'). ':', null, $this->_customdata->fileui_options);
2547                     break;
2548                 default :
2549                     break;
2550             }
2551             $mform->addElement('hidden', 'mailinfo_h', "0");
2552             $mform->setType('mailinfo_h', PARAM_INT);
2553             $mform->addElement('checkbox', 'mailinfo',get_string('enablenotification','assignment').
2554             $OUTPUT->help_icon('enablenotification', 'assignment') .':' );
2555             $mform->setType('mailinfo', PARAM_INT);
2556         }
2557     }
2559     function add_action_buttons() {
2560         $mform =& $this->_form;
2561         //if there are more to be graded.
2562         if ($this->_customdata->nextid>0) {
2563             $buttonarray=array();
2564             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2565             //@todo: fix accessibility: javascript dependency not necessary
2566             $buttonarray[] = &$mform->createElement('submit', 'saveandnext', get_string('saveandnext'));
2567             $buttonarray[] = &$mform->createElement('submit', 'next', get_string('next'));
2568             $buttonarray[] = &$mform->createElement('cancel');
2569         } else {
2570             $buttonarray=array();
2571             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2572             $buttonarray[] = &$mform->createElement('cancel');
2573         }
2574         $mform->addGroup($buttonarray, 'grading_buttonar', '', array(' '), false);
2575         $mform->closeHeaderBefore('grading_buttonar');
2576         $mform->setType('grading_buttonar', PARAM_RAW);
2577     }
2579     function add_submission_content() {
2580         $mform =& $this->_form;
2581         $mform->addElement('header', 'Submission', get_string('submission', 'assignment'));
2582         $mform->addElement('static', '', '' , $this->_customdata->submission_content );
2583     }
2585     protected function get_editor_options() {
2586         $editoroptions = array();
2587         $editoroptions['component'] = 'mod_assignment';
2588         $editoroptions['filearea'] = 'feedback';
2589         $editoroptions['noclean'] = false;
2590         $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)
2591         $editoroptions['maxbytes'] = $this->_customdata->maxbytes;
2592         $editoroptions['context'] = $this->_customdata->context;
2593         return $editoroptions;
2594     }
2596     public function set_data($data) {
2597         $editoroptions = $this->get_editor_options();
2598         if (!isset($data->text)) {
2599             $data->text = '';
2600         }
2601         if (!isset($data->format)) {
2602             $data->textformat = FORMAT_HTML;
2603         } else {
2604             $data->textformat = $data->format;
2605         }
2607         if (!empty($this->_customdata->submission->id)) {
2608             $itemid = $this->_customdata->submission->id;
2609         } else {
2610             $itemid = null;
2611         }
2613         switch ($this->_customdata->assignment->assignmenttype) {
2614                 case 'upload' :
2615                 case 'uploadsingle' :
2616                     $data = file_prepare_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2617                     break;
2618                 default :
2619                     break;
2620         }
2622         $data = file_prepare_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2623         return parent::set_data($data);
2624     }
2626     public function get_data() {
2627         $data = parent::get_data();
2629         if (!empty($this->_customdata->submission->id)) {
2630             $itemid = $this->_customdata->submission->id;
2631         } else {
2632             $itemid = null; //TODO: this is wrong, itemid MUST be known when saving files!! (skodak)
2633         }
2635         if ($data) {
2636             $editoroptions = $this->get_editor_options();
2637             switch ($this->_customdata->assignment->assignmenttype) {
2638                 case 'upload' :
2639                 case 'uploadsingle' :
2640                     $data = file_postupdate_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2641                     break;
2642                 default :
2643                     break;
2644             }
2645             $data = file_postupdate_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2646         }
2648         if ($this->use_advanced_grading() && !isset($data->advancedgrading)) {
2649             $data->advancedgrading = null;
2650         }
2652         return $data;
2653     }
2656 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
2658 /**
2659  * Deletes an assignment instance
2660  *
2661  * This is done by calling the delete_instance() method of the assignment type class
2662  */
2663 function assignment_delete_instance($id){
2664     global $CFG, $DB;
2666     if (! $assignment = $DB->get_record('assignment', array('id'=>$id))) {
2667         return false;
2668     }
2670     // fall back to base class if plugin missing
2671     $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2672     if (file_exists($classfile)) {
2673         require_once($classfile);
2674         $assignmentclass = "assignment_$assignment->assignmenttype";
2676     } else {
2677         debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
2678         $assignmentclass = "assignment_base";
2679     }
2681     $ass = new $assignmentclass();
2682     return $ass->delete_instance($assignment);
2686 /**
2687  * Updates an assignment instance
2688  *
2689  * This is done by calling the update_instance() method of the assignment type class
2690  */
2691 function assignment_update_instance($assignment){
2692     global $CFG;
2694     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_PLUGIN);
2696     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2697     $assignmentclass = "assignment_$assignment->assignmenttype";
2698     $ass = new $assignmentclass();
2699     return $ass->update_instance($assignment);
2703 /**
2704  * Adds an assignment instance
2705  *
2706  * This is done by calling the add_instance() method of the assignment type class
2707  */
2708 function assignment_add_instance($assignment) {
2709     global $CFG;
2711     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_PLUGIN);
2713     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2714     $assignmentclass = "assignment_$assignment->assignmenttype";
2715     $ass = new $assignmentclass();
2716     return $ass->add_instance($assignment);
2720 /**
2721  * Returns an outline of a user interaction with an assignment
2722  *
2723  * This is done by calling the user_outline() method of the assignment type class
2724  */
2725 function assignment_user_outline($course, $user, $mod, $assignment) {
2726     global $CFG;
2728     require_once("$CFG->libdir/gradelib.php");
2729     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2730     $assignmentclass = "assignment_$assignment->assignmenttype";
2731     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2732     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2733     if (!empty($grades->items[0]->grades)) {
2734         return $ass->user_outline(reset($grades->items[0]->grades));
2735     } else {
2736         return null;
2737     }
2740 /**
2741  * Prints the complete info about a user's interaction with an assignment
2742  *
2743  * This is done by calling the user_complete() method of the assignment type class
2744  */
2745 function assignment_user_complete($course, $user, $mod, $assignment) {
2746     global $CFG;
2748     require_once("$CFG->libdir/gradelib.php");
2749     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2750     $assignmentclass = "assignment_$assignment->assignmenttype";
2751     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2752     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2753     if (empty($grades->items[0]->grades)) {
2754         $grade = false;
2755     } else {
2756         $grade = reset($grades->items[0]->grades);
2757     }
2758     return $ass->user_complete($user, $grade);
2761 /**
2762  * Function to be run periodically according to the moodle cron
2763  *
2764  * Finds all assignment notifications that have yet to be mailed out, and mails them
2765  */
2766 function assignment_cron () {
2767     global $CFG, $USER, $DB;
2769     /// first execute all crons in plugins
2770     if ($plugins = get_plugin_list('assignment')) {
2771         foreach ($plugins as $plugin=>$dir) {
2772             require_once("$dir/assignment.class.php");
2773             $assignmentclass = "assignment_$plugin";
2774             $ass = new $assignmentclass();
2775             $ass->cron();
2776         }
2777     }
2779     /// Notices older than 1 day will not be mailed.  This is to avoid the problem where
2780     /// cron has not been running for a long time, and then suddenly people are flooded
2781     /// with mail from the past few weeks or months
2783     $timenow   = time();
2784     $endtime   = $timenow - $CFG->maxeditingtime;
2785     $starttime = $endtime - 24 * 3600;   /// One day earlier
2787     if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2789         $realuser = clone($USER);
2791         foreach ($submissions as $key => $submission) {
2792             $DB->set_field("assignment_submissions", "mailed", "1", array("id"=>$submission->id));
2793         }
2795         $timenow = time();
2797         foreach ($submissions as $submission) {
2799             echo "Processing assignment submission $submission->id\n";
2801             if (! $user = $DB->get_record("user", array("id"=>$submission->userid))) {
2802                 echo "Could not find user $user->id\n";
2803                 continue;
2804             }
2806             if (! $course = $DB->get_record("course", array("id"=>$submission->course))) {
2807                 echo "Could not find course $submission->course\n";
2808                 continue;
2809             }
2811             /// Override the language and timezone of the "current" user, so that
2812             /// mail is customised for the receiver.
2813             cron_setup_user($user, $course);
2815             $coursecontext = get_context_instance(CONTEXT_COURSE, $submission->course);
2816             $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
2817             if (!is_enrolled($coursecontext, $user->id)) {
2818                 echo fullname($user)." not an active participant in " . $courseshortname . "\n";
2819                 continue;
2820             }
2822             if (! $teacher = $DB->get_record("user", array("id"=>$submission->teacher))) {
2823                 echo "Could not find teacher $submission->teacher\n";
2824                 continue;
2825             }
2827             if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2828                 echo "Could not find course module for assignment id $submission->assignment\n";
2829                 continue;
2830             }
2832             if (! $mod->visible) {    /// Hold mail notification for hidden assignments until later
2833                 continue;
2834             }
2836             $strassignments = get_string("modulenameplural", "assignment");
2837             $strassignment  = get_string("modulename", "assignment");
2839             $assignmentinfo = new stdClass();
2840             $assignmentinfo->teacher = fullname($teacher);
2841             $assignmentinfo->assignment = format_string($submission->name,true);
2842             $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2844             $postsubject = "$courseshortname: $strassignments: ".format_string($submission->name,true);
2845             $posttext  = "$courseshortname -> $strassignments -> ".format_string($submission->name,true)."\n";
2846             $posttext .= "---------------------------------------------------------------------\n";
2847             $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2848             $posttext .= "---------------------------------------------------------------------\n";
2850             if ($user->mailformat == 1) {  // HTML
2851                 $posthtml = "<p><font face=\"sans-serif\">".
2852                 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$courseshortname</a> ->".
2853                 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2854                 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2855                 $posthtml .= "<hr /><font face=\"sans-serif\">";
2856                 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2857                 $posthtml .= "</font><hr />";
2858             } else {
2859                 $posthtml = "";
2860             }
2862             $eventdata = new stdClass();
2863             $eventdata->modulename       = 'assignment';
2864             $eventdata->userfrom         = $teacher;
2865             $eventdata->userto           = $user;
2866             $eventdata->subject          = $postsubject;
2867             $eventdata->fullmessage      = $posttext;
2868             $eventdata->fullmessageformat = FORMAT_PLAIN;
2869             $eventdata->fullmessagehtml  = $posthtml;
2870             $eventdata->smallmessage     = get_string('assignmentmailsmall', 'assignment', $assignmentinfo);
2872             $eventdata->name            = 'assignment_updates';
2873             $eventdata->component       = 'mod_assignment';
2874             $eventdata->notification    = 1;
2875             $eventdata->contexturl      = $assignmentinfo->url;
2876             $eventdata->contexturlname  = $assignmentinfo->assignment;
2878             message_send($eventdata);
2879         }
2881         cron_setup_user();
2882     }
2884     return true;
2887 /**
2888  * Return grade for given user or all users.
2889  *
2890  * @param stdClass $assignment An assignment instance
2891  * @param int $userid Optional user id, 0 means all users
2892  * @return array An array of grades, false if none
2893  */
2894 function assignment_get_user_grades($assignment, $userid=0) {
2895     global $CFG, $DB;
2897     if ($userid) {
2898         $user = "AND u.id = :userid";
2899         $params = array('userid'=>$userid);
2900     } else {
2901         $user = "";
2902     }
2903     $params['aid'] = $assignment->id;
2905     $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2906                    s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2907               FROM {user} u, {assignment_submissions} s
2908              WHERE u.id = s.userid AND s.assignment = :aid
2909                    $user";
2911     return $DB->get_records_sql($sql, $params);
2914 /**
2915  * Update activity grades
2916  *
2917  * @category grade
2918  * @param stdClass $assignment Assignment instance
2919  * @param int $userid specific user only, 0 means all
2920  * @param bool $nullifnone Not used
2921  */
2922 function assignment_update_grades($assignment, $userid=0, $nullifnone=true) {
2923     global $CFG, $DB;
2924     require_once($CFG->libdir.'/gradelib.php');
2926     if ($assignment->grade == 0) {
2927         assignment_grade_item_update($assignment);
2929     } else if ($grades = assignment_get_user_grades($assignment, $userid)) {
2930         foreach($grades as $k=>$v) {
2931             if ($v->rawgrade == -1) {
2932                 $grades[$k]->rawgrade = null;
2933             }
2934         }
2935         assignment_grade_item_update($assignment, $grades);
2937     } else {
2938         assignment_grade_item_update($assignment);
2939     }
2942 /**
2943  * Update all grades in gradebook.
2944  */
2945 function assignment_upgrade_grades() {
2946     global $DB;
2948     $sql = "SELECT COUNT('x')
2949               FROM {assignment} a, {course_modules} cm, {modules} m
2950              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2951     $count = $DB->count_records_sql($sql);
2953     $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
2954               FROM {assignment} a, {course_modules} cm, {modules} m
2955              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2956     $rs = $DB->get_recordset_sql($sql);
2957     if ($rs->valid()) {
2958         // too much debug output
2959         $pbar = new progress_bar('assignmentupgradegrades', 500, true);
2960         $i=0;
2961         foreach ($rs as $assignment) {
2962             $i++;
2963             upgrade_set_timeout(60*5); // set up timeout, may also abort execution
2964             assignment_update_grades($assignment);
2965             $pbar->update($i, $count, "Updating Assignment grades ($i/$count).");
2966         }
2967         upgrade_set_timeout(); // reset to default timeout
2968     }
2969     $rs->close();
2972 /**
2973  * Create grade item for given assignment
2974  *
2975  * @category grade
2976  * @param stdClass $assignment An assignment instance with extra cmidnumber property
2977  * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
2978  * @return int 0 if ok, error code otherwise
2979  */
2980 function assignment_grade_item_update($assignment, $grades=NULL) {
2981     global $CFG;
2982     require_once($CFG->libdir.'/gradelib.php');
2984     if (!isset($assignment->courseid)) {
2985         $assignment->courseid = $assignment->course;
2986     }
2988     $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
2990     if ($assignment->grade > 0) {
2991         $params['gradetype'] = GRADE_TYPE_VALUE;
2992         $params['grademax']  = $assignment->grade;
2993         $params['grademin']  = 0;
2995     } else if ($assignment->grade < 0) {
2996         $params['gradetype'] = GRADE_TYPE_SCALE;
2997         $params['scaleid']   = -$assignment->grade;
2999     } else {
3000         $params['gradetype'] = GRADE_TYPE_TEXT; // allow text comments only
3001     }
3003     if ($grades  === 'reset') {
3004         $params['reset'] = true;
3005         $grades = NULL;
3006     }
3008     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades, $params);
3011 /**
3012  * Delete grade item for given assignment
3013  *
3014  * @category grade
3015  * @param object $assignment object
3016  * @return object assignment
3017  */
3018 function assignment_grade_item_delete($assignment) {
3019     global $CFG;
3020     require_once($CFG->libdir.'/gradelib.php');
3022     if (!isset($assignment->courseid)) {
3023         $assignment->courseid = $assignment->course;
3024     }
3026     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
3029 /**
3030  * Returns the users with data in one assignment (students and teachers)
3031  *
3032  * @todo: deprecated - to be deleted in 2.2
3033  *
3034  * @param $assignmentid int
3035  * @return array of user objects
3036  */
3037 function assignment_get_participants($assignmentid) {
3038     global $CFG, $DB;
3040     //Get students
3041     $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
3042                                         FROM {user} u,
3043                                              {assignment_submissions} a
3044                                        WHERE a.assignment = ? and
3045                                              u.id = a.userid", array($assignmentid));
3046     //Get teachers
3047     $teachers = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
3048                                         FROM {user} u,
3049                                              {assignment_submissions} a
3050                                        WHERE a.assignment = ? and
3051                                              u.id = a.teacher", array($assignmentid));
3053     //Add teachers to students
3054     if ($teachers) {
3055         foreach ($teachers as $teacher) {
3056             $students[$teacher->id] = $teacher;
3057         }
3058     }
3059     //Return students array (it contains an array of unique users)
3060     return ($students);
3063 /**
3064  * Serves assignment submissions and other files.
3065  *
3066  * @package  mod_assignment
3067  * @category files
3068  * @param stdClass $course course object
3069  * @param stdClass $cm course module object
3070  * @param stdClass $context context object
3071  * @param string $filearea file area
3072  * @param array $args extra arguments
3073  * @param bool $forcedownload whether or not force download
3074  * @return bool false if file not found, does not return if found - just send the file
3075  */
3076 function assignment_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) {
3077     global $CFG, $DB;
3079     if ($context->contextlevel != CONTEXT_MODULE) {
3080         return false;
3081     }
3083     require_login($course, false, $cm);
3085     if (!$assignment = $DB->get_record('assignment', array('id'=>$cm->instance))) {
3086         return false;
3087     }
3089     require_once($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
3090     $assignmentclass = 'assignment_'.$assignment->assignmenttype;
3091     $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm, $course);
3093     return $assignmentinstance->send_file($filearea, $args);
3095 /**
3096  * Checks if a scale is being used by an assignment
3097  *
3098  * This is used by the backup code to decide whether to back up a scale
3099  * @param $assignmentid int
3100  * @param $scaleid int
3101  * @return boolean True if the scale is used by the assignment
3102  */
3103 function assignment_scale_used($assignmentid, $scaleid) {
3104     global $DB;
3106     $return = false;
3108     $rec = $DB->get_record('assignment', array('id'=>$assignmentid,'grade'=>-$scaleid));
3110     if (!empty($rec) && !empty($scaleid)) {
3111         $return = true;
3112     }
3114     return $return;
3117 /**
3118  * Checks if scale is being used by any instance of assignment
3119  *
3120  * This is used to find out if scale used anywhere
3121  * @param $scaleid int
3122  * @return boolean True if the scale is used by any assignment
3123  */
3124 function assignment_scale_used_anywhere($scaleid) {
3125     global $DB;
3127     if ($scaleid and $DB->record_exists('assignment', array('grade'=>-$scaleid))) {
3128         return true;
3129     } else {
3130         return false;
3131     }
3134 /**
3135  * Make sure up-to-date events are created for all assignment instances
3136  *
3137  * This standard function will check all instances of this module
3138  * and make sure there are up-to-date events created for each of them.
3139  * If courseid = 0, then every assignment event in the site is checked, else
3140  * only assignment events belonging to the course specified are checked.
3141  * This function is used, in its new format, by restore_refresh_events()
3142  *
3143  * @param $courseid int optional If zero then all assignments for all courses are covered
3144  * @return boolean Always returns true
3145  */
3146 function assignment_refresh_events($courseid = 0) {
3147     global $DB;
3149     if ($courseid == 0) {
3150         if (! $assignments = $DB->get_records("assignment")) {
3151             return true;
3152         }
3153     } else {
3154         if (! $assignments = $DB->get_records("assignment", array("course"=>$courseid))) {
3155             return true;
3156         }
3157     }
3158     $moduleid = $DB->get_field('modules', 'id', array('name'=>'assignment'));
3160     foreach ($assignments as $assignment) {
3161         $cm = get_coursemodule_from_id('assignment', $assignment->id);
3162         $event = new stdClass();
3163         $event->name        = $assignment->name;
3164         $event->description = format_module_intro('assignment', $assignment, $cm->id);
3165         $event->timestart   = $assignment->timedue;
3167         if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
3168             update_event($event);
3170         } else {
3171             $event->courseid    = $assignment->course;
3172             $event->groupid     = 0;
3173             $event->userid      = 0;
3174             $event->modulename  = 'assignment';
3175             $event->instance    = $assignment->id;
3176             $event->eventtype   = 'due';
3177             $event->timeduration = 0;
3178             $event->visible     = $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$assignment->id));
3179             add_event($event);
3180         }
3182     }
3183     return true;
3186 /**
3187  * Print recent activity from all assignments in a given course
3188  *
3189  * This is used by the recent activity block
3190  */
3191 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
3192     global $CFG, $USER, $DB, $OUTPUT;
3194     // do not use log table if possible, it may be huge
3196     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
3197                                                      u.firstname, u.lastname, u.email, u.picture
3198                                                 FROM {assignment_submissions} asb
3199                                                      JOIN {assignment} a      ON a.id = asb.assignment
3200                                                      JOIN {course_modules} cm ON cm.instance = a.id
3201                                                      JOIN {modules} md        ON md.id = cm.module
3202                                                      JOIN {user} u            ON u.id = asb.userid
3203                                                WHERE asb.timemodified > ? AND
3204                                                      a.course = ? AND
3205                                                      md.name = 'assignment'
3206                                             ORDER BY asb.timemodified ASC", array($timestart, $course->id))) {
3207          return false;
3208     }
3210     $modinfo =& get_fast_modinfo($course); // reference needed because we might load the groups
3211     $show    = array();
3212     $grader  = array();
3214     foreach($submissions as $submission) {
3215         if (!array_key_exists($submission->cmid, $modinfo->cms)) {
3216             continue;
3217         }
3218         $cm = $modinfo->cms[$submission->cmid];
3219         if (!$cm->uservisible) {
3220             continue;
3221         }
3222         if ($submission->userid == $USER->id) {
3223             $show[] = $submission;
3224             continue;
3225         }
3227         // the act of sumbitting of assignment may be considered private - only graders will see it if specified
3228         if (empty($CFG->assignment_showrecentsubmissions)) {
3229             if (!array_key_exists($cm->id, $grader)) {
3230                 $grader[$cm->id] = has_capability('moodle/grade:viewall', get_context_instance(CONTEXT_MODULE, $cm->id));
3231             }
3232             if (!$grader[$cm->id]) {
3233                 continue;
3234             }
3235         }
3237         $groupmode = groups_get_activity_groupmode($cm, $course);
3239         if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
3240             if (isguestuser()) {
3241                 // shortcut - guest user does not belong into any group
3242                 continue;
3243             }
3245             if (is_null($modinfo->groups)) {
3246                 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
3247             }
3249             // this will be slow - show only users that share group with me in this cm
3250             if (empty($modinfo->groups[$cm->id])) {
3251                 continue;
3252             }
3253             $usersgroups =  groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
3254             if (is_array($usersgroups)) {
3255                 $usersgroups = array_keys($usersgroups);
3256                 $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
3257                 if (empty($intersect)) {
3258                     continue;
3259                 }
3260             }
3261         }
3262         $show[] = $submission;
3263     }
3265     if (empty($show)) {
3266         return false;
3267     }
3269     echo $OUTPUT->heading(get_string('newsubmissions', 'assignment').':', 3);
3271     foreach ($show as $submission) {
3272         $cm = $modinfo->cms[$submission->cmid];
3273         $link = $CFG->wwwroot.'/mod/assignment/view.php?id='.$cm->id;
3274         print_recent_activity_note($submission->timemodified, $submission, $cm->name, $link, false, $viewfullnames);
3275     }
3277     return true;
3281 /**
3282  * Returns all assignments since a given time in specified forum.
3283  */
3284 function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0)  {
3285     global $CFG, $COURSE, $USER, $DB;
3287     if ($COURSE->id == $courseid) {
3288         $course = $COURSE;
3289     } else {
3290         $course = $DB->get_record('course', array('id'=>$courseid));
3291     }
3293     $modinfo =& get_fast_modinfo($course);
3295     $cm = $modinfo->cms[$cmid];
3297     $params = array();
3298     if ($userid) {
3299         $userselect = "AND u.id = :userid";
3300         $params['userid'] = $userid;
3301     } else {
3302         $userselect = "";
3303     }
3305     if ($groupid) {
3306         $groupselect = "AND gm.groupid = :groupid";
3307         $groupjoin   = "JOIN {groups_members} gm ON  gm.userid=u.id";
3308         $params['groupid'] = $groupid;
3309     } else {
3310         $groupselect = "";
3311         $groupjoin   = "";
3312     }
3314     $params['cminstance'] = $cm->instance;
3315     $params['timestart'] = $timestart;
3317     $userfields = user_picture::fields('u', null, 'userid');
3319     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified,
3320                                                      $userfields
3321     &n