Merge remote branch 'origin/master' into rubric
[moodle.git] / mod / assignment / lib.php
1 <?PHP
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
18 /**
19  * assignment_base is the base class for assignment types
20  *
21  * This class provides all the functionality for an assignment
22  *
23  * @package   mod-assignment
24  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
25  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26  */
28 /** Include eventslib.php */
29 require_once($CFG->libdir.'/eventslib.php');
30 /** Include formslib.php */
31 require_once($CFG->libdir.'/formslib.php');
32 /** Include calendar/lib.php */
33 require_once($CFG->dirroot.'/calendar/lib.php');
35 /** ASSIGNMENT_COUNT_WORDS = 1 */
36 define('ASSIGNMENT_COUNT_WORDS', 1);
37 /** ASSIGNMENT_COUNT_LETTERS = 2 */
38 define('ASSIGNMENT_COUNT_LETTERS', 2);
40 /**
41  * Standard base class for all assignment submodules (assignment types).
42  *
43  * @package   mod-assignment
44  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
45  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
46  */
47 class assignment_base {
49     const FILTER_ALL             = 0;
50     const FILTER_SUBMITTED       = 1;
51     const FILTER_REQUIRE_GRADING = 2;
53     /** @var object */
54     var $cm;
55     /** @var object */
56     var $course;
57     /** @var stdClass */
58     var $coursecontext;
59     /** @var object */
60     var $assignment;
61     /** @var string */
62     var $strassignment;
63     /** @var string */
64     var $strassignments;
65     /** @var string */
66     var $strsubmissions;
67     /** @var string */
68     var $strlastmodified;
69     /** @var string */
70     var $pagetitle;
71     /** @var bool */
72     var $usehtmleditor;
73     /**
74      * @todo document this var
75      */
76     var $defaultformat;
77     /**
78      * @todo document this var
79      */
80     var $context;
81     /** @var string */
82     var $type;
84     /**
85      * Constructor for the base assignment class
86      *
87      * Constructor for the base assignment class.
88      * If cmid is set create the cm, course, assignment objects.
89      * If the assignment is hidden and the user is not a teacher then
90      * this prints a page header and notice.
91      *
92      * @global object
93      * @global object
94      * @param int $cmid the current course module id - not set for new assignments
95      * @param object $assignment usually null, but if we have it we pass it to save db access
96      * @param object $cm usually null, but if we have it we pass it to save db access
97      * @param object $course usually null, but if we have it we pass it to save db access
98      */
99     function assignment_base($cmid='staticonly', $assignment=NULL, $cm=NULL, $course=NULL) {
100         global $COURSE, $DB;
102         if ($cmid == 'staticonly') {
103             //use static functions only!
104             return;
105         }
107         global $CFG;
109         if ($cm) {
110             $this->cm = $cm;
111         } else if (! $this->cm = get_coursemodule_from_id('assignment', $cmid)) {
112             print_error('invalidcoursemodule');
113         }
115         $this->context = get_context_instance(CONTEXT_MODULE, $this->cm->id);
117         if ($course) {
118             $this->course = $course;
119         } else if ($this->cm->course == $COURSE->id) {
120             $this->course = $COURSE;
121         } else if (! $this->course = $DB->get_record('course', array('id'=>$this->cm->course))) {
122             print_error('invalidid', 'assignment');
123         }
124         $this->coursecontext = get_context_instance(CONTEXT_COURSE, $this->course->id);
125         $courseshortname = format_text($this->course->shortname, true, array('context' => $this->coursecontext));
127         if ($assignment) {
128             $this->assignment = $assignment;
129         } else if (! $this->assignment = $DB->get_record('assignment', array('id'=>$this->cm->instance))) {
130             print_error('invalidid', 'assignment');
131         }
133         $this->assignment->cmidnumber = $this->cm->idnumber; // compatibility with modedit assignment obj
134         $this->assignment->courseid   = $this->course->id; // compatibility with modedit assignment obj
136         $this->strassignment = get_string('modulename', 'assignment');
137         $this->strassignments = get_string('modulenameplural', 'assignment');
138         $this->strsubmissions = get_string('submissions', 'assignment');
139         $this->strlastmodified = get_string('lastmodified');
140         $this->pagetitle = strip_tags($courseshortname.': '.$this->strassignment.': '.format_string($this->assignment->name, true, array('context' => $this->context)));
142         // visibility handled by require_login() with $cm parameter
143         // get current group only when really needed
145     /// Set up things for a HTML editor if it's needed
146         $this->defaultformat = editors_get_preferred_format();
147     }
149     /**
150      * Display the assignment, used by view.php
151      *
152      * This in turn calls the methods producing individual parts of the page
153      */
154     function view() {
156         $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
157         require_capability('mod/assignment:view', $context);
159         add_to_log($this->course->id, "assignment", "view", "view.php?id={$this->cm->id}",
160                    $this->assignment->id, $this->cm->id);
162         $this->view_header();
164         $this->view_intro();
166         $this->view_dates();
168         $this->view_feedback();
170         $this->view_footer();
171     }
173     /**
174      * Display the header and top of a page
175      *
176      * (this doesn't change much for assignment types)
177      * This is used by the view() method to print the header of view.php but
178      * it can be used on other pages in which case the string to denote the
179      * page in the navigation trail should be passed as an argument
180      *
181      * @global object
182      * @param string $subpage Description of subpage to be used in navigation trail
183      */
184     function view_header($subpage='') {
185         global $CFG, $PAGE, $OUTPUT;
187         if ($subpage) {
188             $PAGE->navbar->add($subpage);
189         }
191         $PAGE->set_title($this->pagetitle);
192         $PAGE->set_heading($this->course->fullname);
194         echo $OUTPUT->header();
196         groups_print_activity_menu($this->cm, $CFG->wwwroot . '/mod/assignment/view.php?id=' . $this->cm->id);
198         echo '<div class="reportlink">'.$this->submittedlink().'</div>';
199         echo '<div class="clearer"></div>';
200     }
203     /**
204      * Display the assignment intro
205      *
206      * This will most likely be extended by assignment type plug-ins
207      * The default implementation prints the assignment description in a box
208      */
209     function view_intro() {
210         global $OUTPUT;
211         echo $OUTPUT->box_start('generalbox boxaligncenter', 'intro');
212         echo format_module_intro('assignment', $this->assignment, $this->cm->id);
213         echo $OUTPUT->box_end();
214         plagiarism_print_disclosure($this->cm->id);
215     }
217     /**
218      * Display the assignment dates
219      *
220      * Prints the assignment start and end dates in a box.
221      * This will be suitable for most assignment types
222      */
223     function view_dates() {
224         global $OUTPUT;
225         if (!$this->assignment->timeavailable && !$this->assignment->timedue) {
226             return;
227         }
229         echo $OUTPUT->box_start('generalbox boxaligncenter', 'dates');
230         echo '<table>';
231         if ($this->assignment->timeavailable) {
232             echo '<tr><td class="c0">'.get_string('availabledate','assignment').':</td>';
233             echo '    <td class="c1">'.userdate($this->assignment->timeavailable).'</td></tr>';
234         }
235         if ($this->assignment->timedue) {
236             echo '<tr><td class="c0">'.get_string('duedate','assignment').':</td>';
237             echo '    <td class="c1">'.userdate($this->assignment->timedue).'</td></tr>';
238         }
239         echo '</table>';
240         echo $OUTPUT->box_end();
241     }
244     /**
245      * Display the bottom and footer of a page
246      *
247      * This default method just prints the footer.
248      * This will be suitable for most assignment types
249      */
250     function view_footer() {
251         global $OUTPUT;
252         echo $OUTPUT->footer();
253     }
255     /**
256      * Display the feedback to the student
257      *
258      * This default method prints the teacher picture and name, date when marked,
259      * grade and teacher submissioncomment.
260      *
261      * @global object
262      * @global object
263      * @global object
264      * @param object $submission The submission object or NULL in which case it will be loaded
265      */
266     function view_feedback($submission=NULL) {
267         global $USER, $CFG, $DB, $OUTPUT, $PAGE;
268         require_once($CFG->libdir.'/gradelib.php');
269         require_once("$CFG->dirroot/grade/grading/lib.php");
271         if (!is_enrolled($this->context, $USER, 'mod/assignment:view')) {
272             // can not submit assignments -> no feedback
273             return;
274         }
276         if (!$submission) { /// Get submission for this assignment
277             $submission = $this->get_submission($USER->id);
278         }
279         // Check the user can submit
280         $cansubmit = 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         $cansubmit = $cansubmit || (!empty($submission) && has_capability('mod/assignment:view', $this->context, $USER->id, false));
284         if (!$cansubmit) {
285             // can not submit assignments -> no feedback
286             return;
287         }
289         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $USER->id);
290         $item = $grading_info->items[0];
291         $grade = $item->grades[$USER->id];
293         if ($grade->hidden or $grade->grade === false) { // hidden or error
294             return;
295         }
297         if ($grade->grade === null and empty($grade->str_feedback)) {   /// Nothing to show yet
298             return;
299         }
301         $graded_date = $grade->dategraded;
302         $graded_by   = $grade->usermodified;
304     /// We need the teacher info
305         if (!$teacher = $DB->get_record('user', array('id'=>$graded_by))) {
306             print_error('cannotfindteacher');
307         }
309     /// Print the feedback
310         echo $OUTPUT->heading(get_string('feedbackfromteacher', 'assignment', fullname($teacher)));
312         echo '<table cellspacing="0" class="feedback">';
314         echo '<tr>';
315         echo '<td class="left picture">';
316         if ($teacher) {
317             echo $OUTPUT->user_picture($teacher);
318         }
319         echo '</td>';
320         echo '<td class="topic">';
321         echo '<div class="from">';
322         if ($teacher) {
323             echo '<div class="fullname">'.fullname($teacher).'</div>';
324         }
325         echo '<div class="time">'.userdate($graded_date).'</div>';
326         echo '</div>';
327         echo '</td>';
328         echo '</tr>';
330         echo '<tr>';
331         echo '<td class="left side">&nbsp;</td>';
332         echo '<td class="content">';
333         $grade_str = '<div class="grade">'. get_string("grade").': '.$grade->str_long_grade. '</div>';
334         if (!empty($submission) && $controller = get_grading_manager($this->context, 'mod_assignment', 'submission')->get_active_controller()) {
335             $controller->set_grade_range(make_grades_menu($this->assignment->grade));
336             echo $controller->render_grade($PAGE, $submission->id, $item, $grade_str);
337         } else {
338             echo $grade_str;
339         }
340         echo '<div class="clearer"></div>';
342         echo '<div class="comment">';
343         echo $grade->str_feedback;
344         echo '</div>';
345         echo '</tr>';
347          if ($this->type == 'uploadsingle') { //@TODO: move to overload view_feedback method in the class or is uploadsingle merging into upload?
348             $responsefiles = $this->print_responsefiles($submission->userid, true);
349             if (!empty($responsefiles)) {
350                 echo '<tr>';
351                 echo '<td class="left side">&nbsp;</td>';
352                 echo '<td class="content">';
353                 echo $responsefiles;
354                 echo '</tr>';
355             }
356          }
358         echo '</table>';
359     }
361     /**
362      * Returns a link with info about the state of the assignment submissions
363      *
364      * This is used by view_header to put this link at the top right of the page.
365      * For teachers it gives the number of submitted assignments with a link
366      * For students it gives the time of their submission.
367      * This will be suitable for most assignment types.
368      *
369      * @global object
370      * @global object
371      * @param bool $allgroup print all groups info if user can access all groups, suitable for index.php
372      * @return string
373      */
374     function submittedlink($allgroups=false) {
375         global $USER;
376         global $CFG;
378         $submitted = '';
379         $urlbase = "{$CFG->wwwroot}/mod/assignment/";
381         $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
382         if (has_capability('mod/assignment:grade', $context)) {
383             if ($allgroups and has_capability('moodle/site:accessallgroups', $context)) {
384                 $group = 0;
385             } else {
386                 $group = groups_get_activity_group($this->cm);
387             }
388             if ($this->type == 'offline') {
389                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
390                              get_string('viewfeedback', 'assignment').'</a>';
391             } else if ($count = $this->count_real_submissions($group)) {
392                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
393                              get_string('viewsubmissions', 'assignment', $count).'</a>';
394             } else {
395                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
396                              get_string('noattempts', 'assignment').'</a>';
397             }
398         } else {
399             if (isloggedin()) {
400                 if ($submission = $this->get_submission($USER->id)) {
401                     if ($submission->timemodified) {
402                         if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
403                             $submitted = '<span class="early">'.userdate($submission->timemodified).'</span>';
404                         } else {
405                             $submitted = '<span class="late">'.userdate($submission->timemodified).'</span>';
406                         }
407                     }
408                 }
409             }
410         }
412         return $submitted;
413     }
416     /**
417      * @todo Document this function
418      */
419     function setup_elements(&$mform) {
421     }
423     /**
424      * Any preprocessing needed for the settings form for
425      * this assignment type
426      *
427      * @param array $default_values - array to fill in with the default values
428      *      in the form 'formelement' => 'value'
429      * @param object $form - the form that is to be displayed
430      * @return none
431      */
432     function form_data_preprocessing(&$default_values, $form) {
433     }
435     /**
436      * Any extra validation checks needed for the settings
437      * form for this assignment type
438      *
439      * See lib/formslib.php, 'validation' function for details
440      */
441     function form_validation($data, $files) {
442         return array();
443     }
445     /**
446      * Create a new assignment activity
447      *
448      * Given an object containing all the necessary data,
449      * (defined by the form in mod_form.php) this function
450      * will create a new instance and return the id number
451      * of the new instance.
452      * The due data is added to the calendar
453      * This is common to all assignment types.
454      *
455      * @global object
456      * @global object
457      * @param object $assignment The data from the form on mod_form.php
458      * @return int The id of the assignment
459      */
460     function add_instance($assignment) {
461         global $COURSE, $DB;
463         $assignment->timemodified = time();
464         $assignment->courseid = $assignment->course;
466         $returnid = $DB->insert_record("assignment", $assignment);
467         $assignment->id = $returnid;
469         if ($assignment->timedue) {
470             $event = new stdClass();
471             $event->name        = $assignment->name;
472             $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
473             $event->courseid    = $assignment->course;
474             $event->groupid     = 0;
475             $event->userid      = 0;
476             $event->modulename  = 'assignment';
477             $event->instance    = $returnid;
478             $event->eventtype   = 'due';
479             $event->timestart   = $assignment->timedue;
480             $event->timeduration = 0;
482             calendar_event::create($event);
483         }
485         assignment_grade_item_update($assignment);
487         return $returnid;
488     }
490     /**
491      * Deletes an assignment activity
492      *
493      * Deletes all database records, files and calendar events for this assignment.
494      *
495      * @global object
496      * @global object
497      * @param object $assignment The assignment to be deleted
498      * @return boolean False indicates error
499      */
500     function delete_instance($assignment) {
501         global $CFG, $DB;
503         $assignment->courseid = $assignment->course;
505         $result = true;
507         // now get rid of all files
508         $fs = get_file_storage();
509         if ($cm = get_coursemodule_from_instance('assignment', $assignment->id)) {
510             $context = get_context_instance(CONTEXT_MODULE, $cm->id);
511             $fs->delete_area_files($context->id);
512         }
514         if (! $DB->delete_records('assignment_submissions', array('assignment'=>$assignment->id))) {
515             $result = false;
516         }
518         if (! $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
519             $result = false;
520         }
522         if (! $DB->delete_records('assignment', array('id'=>$assignment->id))) {
523             $result = false;
524         }
525         $mod = $DB->get_field('modules','id',array('name'=>'assignment'));
527         assignment_grade_item_delete($assignment);
529         return $result;
530     }
532     /**
533      * Updates a new assignment activity
534      *
535      * Given an object containing all the necessary data,
536      * (defined by the form in mod_form.php) this function
537      * will update the assignment instance and return the id number
538      * The due date is updated in the calendar
539      * This is common to all assignment types.
540      *
541      * @global object
542      * @global object
543      * @param object $assignment The data from the form on mod_form.php
544      * @return bool success
545      */
546     function update_instance($assignment) {
547         global $COURSE, $DB;
549         $assignment->timemodified = time();
551         $assignment->id = $assignment->instance;
552         $assignment->courseid = $assignment->course;
554         $DB->update_record('assignment', $assignment);
556         if ($assignment->timedue) {
557             $event = new stdClass();
559             if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
561                 $event->name        = $assignment->name;
562                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
563                 $event->timestart   = $assignment->timedue;
565                 $calendarevent = calendar_event::load($event->id);
566                 $calendarevent->update($event);
567             } else {
568                 $event = new stdClass();
569                 $event->name        = $assignment->name;
570                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
571                 $event->courseid    = $assignment->course;
572                 $event->groupid     = 0;
573                 $event->userid      = 0;
574                 $event->modulename  = 'assignment';
575                 $event->instance    = $assignment->id;
576                 $event->eventtype   = 'due';
577                 $event->timestart   = $assignment->timedue;
578                 $event->timeduration = 0;
580                 calendar_event::create($event);
581             }
582         } else {
583             $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id));
584         }
586         // get existing grade item
587         assignment_grade_item_update($assignment);
589         return true;
590     }
592     /**
593      * Update grade item for this submission.
594      */
595     function update_grade($submission) {
596         assignment_update_grades($this->assignment, $submission->userid);
597     }
599     /**
600      * Top-level function for handling of submissions called by submissions.php
601      *
602      * This is for handling the teacher interaction with the grading interface
603      * This should be suitable for most assignment types.
604      *
605      * @global object
606      * @param string $mode Specifies the kind of teacher interaction taking place
607      */
608     function submissions($mode) {
609         ///The main switch is changed to facilitate
610         ///1) Batch fast grading
611         ///2) Skip to the next one on the popup
612         ///3) Save and Skip to the next one on the popup
614         //make user global so we can use the id
615         global $USER, $OUTPUT, $DB, $PAGE;
616         $mailinfo = optional_param('mailinfo', null, PARAM_BOOL);
618         if (optional_param('next', null, PARAM_BOOL)) {
619             $mode='next';
620         }
621         if (optional_param('saveandnext', null, PARAM_BOOL)) {
622             $mode='saveandnext';
623         }
625         if (is_null($mailinfo)) {
626             if (optional_param('sesskey', null, PARAM_BOOL)) {
627                 set_user_preference('assignment_mailinfo', $mailinfo);
628             } else {
629                 $mailinfo = get_user_preferences('assignment_mailinfo', 0);
630             }
631         } else {
632             set_user_preference('assignment_mailinfo', $mailinfo);
633         }
635         if (!($this->validate_and_preprocess_feedback())) {
636             // form was submitted ('Save' or 'Save and next' was pressed, but validation failed)
637             $this->display_submission();
638             return;
639         }
641         switch ($mode) {
642             case 'grade':                         // We are in a main window grading
643                 if ($submission = $this->process_feedback()) {
644                     $this->display_submissions(get_string('changessaved'));
645                 } else {
646                     $this->display_submissions();
647                 }
648                 break;
650             case 'single':                        // We are in a main window displaying one submission
651                 if ($submission = $this->process_feedback()) {
652                     $this->display_submissions(get_string('changessaved'));
653                 } else {
654                     $this->display_submission();
655                 }
656                 break;
658             case 'all':                          // Main window, display everything
659                 $this->display_submissions();
660                 break;
662             case 'fastgrade':
663                 ///do the fast grading stuff  - this process should work for all 3 subclasses
664                 $grading    = false;
665                 $commenting = false;
666                 $col        = false;
667                 if (isset($_POST['submissioncomment'])) {
668                     $col = 'submissioncomment';
669                     $commenting = true;
670                 }
671                 if (isset($_POST['menu'])) {
672                     $col = 'menu';
673                     $grading = true;
674                 }
675                 if (!$col) {
676                     //both submissioncomment and grade columns collapsed..
677                     $this->display_submissions();
678                     break;
679                 }
681                 foreach ($_POST[$col] as $id => $unusedvalue){
683                     $id = (int)$id; //clean parameter name
685                     $this->process_outcomes($id);
687                     if (!$submission = $this->get_submission($id)) {
688                         $submission = $this->prepare_new_submission($id);
689                         $newsubmission = true;
690                     } else {
691                         $newsubmission = false;
692                     }
693                     unset($submission->data1);  // Don't need to update this.
694                     unset($submission->data2);  // Don't need to update this.
696                     //for fast grade, we need to check if any changes take place
697                     $updatedb = false;
699                     if ($grading) {
700                         $grade = $_POST['menu'][$id];
701                         $updatedb = $updatedb || ($submission->grade != $grade);
702                         $submission->grade = $grade;
703                     } else {
704                         if (!$newsubmission) {
705                             unset($submission->grade);  // Don't need to update this.
706                         }
707                     }
708                     if ($commenting) {
709                         $commentvalue = trim($_POST['submissioncomment'][$id]);
710                         $updatedb = $updatedb || ($submission->submissioncomment != $commentvalue);
711                         $submission->submissioncomment = $commentvalue;
712                     } else {
713                         unset($submission->submissioncomment);  // Don't need to update this.
714                     }
716                     $submission->teacher    = $USER->id;
717                     if ($updatedb) {
718                         $submission->mailed = (int)(!$mailinfo);
719                     }
721                     $submission->timemarked = time();
723                     //if it is not an update, we don't change the last modified time etc.
724                     //this will also not write into database if no submissioncomment and grade is entered.
726                     if ($updatedb){
727                         if ($newsubmission) {
728                             if (!isset($submission->submissioncomment)) {
729                                 $submission->submissioncomment = '';
730                             }
731                             $sid = $DB->insert_record('assignment_submissions', $submission);
732                             $submission->id = $sid;
733                         } else {
734                             $DB->update_record('assignment_submissions', $submission);
735                         }
737                         // trigger grade event
738                         $this->update_grade($submission);
740                         //add to log only if updating
741                         add_to_log($this->course->id, 'assignment', 'update grades',
742                                    'submissions.php?id='.$this->cm->id.'&user='.$submission->userid,
743                                    $submission->userid, $this->cm->id);
744                     }
746                 }
748                 $message = $OUTPUT->notification(get_string('changessaved'), 'notifysuccess');
750                 $this->display_submissions($message);
751                 break;
754             case 'saveandnext':
755                 ///We are in pop up. save the current one and go to the next one.
756                 //first we save the current changes
757                 if ($submission = $this->process_feedback()) {
758                     //print_heading(get_string('changessaved'));
759                     //$extra_javascript = $this->update_main_listing($submission);
760                 }
762             case 'next':
763                 /// We are currently in pop up, but we want to skip to next one without saving.
764                 ///    This turns out to be similar to a single case
765                 /// The URL used is for the next submission.
766                 $offset = required_param('offset', PARAM_INT);
767                 $nextid = required_param('nextid', PARAM_INT);
768                 $id = required_param('id', PARAM_INT);
769                 $offset = (int)$offset+1;
770                 //$this->display_submission($offset+1 , $nextid);
771                 redirect('submissions.php?id='.$id.'&userid='. $nextid . '&mode=single&offset='.$offset);
772                 break;
774             case 'singlenosave':
775                 $this->display_submission();
776                 break;
778             default:
779                 echo "something seriously is wrong!!";
780                 break;
781         }
782     }
784     /**
785      * Checks if grading method allows quickgrade mode. At the moment it is hardcoded
786      * that advanced grading methods do not allow quickgrade.
787      *
788      * Assignment type plugins are not allowed to override this method
789      *
790      * @return boolean
791      */
792     public final function quickgrade_mode_allowed() {
793         global $CFG;
794         require_once("$CFG->dirroot/grade/grading/lib.php");
795         if ($controller = get_grading_manager($this->context, 'mod_assignment', 'submission')->get_active_controller()) {
796             return false;
797         }
798         return true;
799     }
801     /**
802      * Helper method updating the listing on the main script from popup using javascript
803      *
804      * @global object
805      * @global object
806      * @param $submission object The submission whose data is to be updated on the main page
807      */
808     function update_main_listing($submission) {
809         global $SESSION, $CFG, $OUTPUT;
811         $output = '';
813         $perpage = get_user_preferences('assignment_perpage', 10);
815         $quickgrade = get_user_preferences('assignment_quickgrade', 0) && $this->quickgrade_mode_allowed();
817         /// Run some Javascript to try and update the parent page
818         $output .= '<script type="text/javascript">'."\n<!--\n";
819         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['submissioncomment'])) {
820             if ($quickgrade){
821                 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid.'").value="'
822                 .trim($submission->submissioncomment).'";'."\n";
823              } else {
824                 $output.= 'opener.document.getElementById("com'.$submission->userid.
825                 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment)), 15)."\";\n";
826             }
827         }
829         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['grade'])) {
830             //echo optional_param('menuindex');
831             if ($quickgrade){
832                 $output.= 'opener.document.getElementById("menumenu'.$submission->userid.
833                 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT).'";'."\n";
834             } else {
835                 $output.= 'opener.document.getElementById("g'.$submission->userid.'").innerHTML="'.
836                 $this->display_grade($submission->grade)."\";\n";
837             }
838         }
839         //need to add student's assignments in there too.
840         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemodified']) &&
841             $submission->timemodified) {
842             $output.= 'opener.document.getElementById("ts'.$submission->userid.
843                  '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid)).userdate($submission->timemodified)."\";\n";
844         }
846         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemarked']) &&
847             $submission->timemarked) {
848             $output.= 'opener.document.getElementById("tt'.$submission->userid.
849                  '").innerHTML="'.userdate($submission->timemarked)."\";\n";
850         }
852         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['status'])) {
853             $output.= 'opener.document.getElementById("up'.$submission->userid.'").className="s1";';
854             $buttontext = get_string('update');
855             $url = new moodle_url('/mod/assignment/submissions.php', array(
856                     'id' => $this->cm->id,
857                     'userid' => $submission->userid,
858                     'mode' => 'single',
859                     'offset' => (optional_param('offset', '', PARAM_INT)-1)));
860             $button = $OUTPUT->action_link($url, $buttontext, new popup_action('click', $url, 'grade'.$submission->userid, array('height' => 450, 'width' => 700)), array('ttile'=>$buttontext));
862             $output .= 'opener.document.getElementById("up'.$submission->userid.'").innerHTML="'.addslashes_js($button).'";';
863         }
865         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $submission->userid);
867         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['finalgrade'])) {
868             $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid.
869             '").innerHTML="'.$grading_info->items[0]->grades[$submission->userid]->str_grade.'";'."\n";
870         }
872         if (!empty($CFG->enableoutcomes) and empty($SESSION->flextable['mod-assignment-submissions']->collapse['outcome'])) {
874             if (!empty($grading_info->outcomes)) {
875                 foreach($grading_info->outcomes as $n=>$outcome) {
876                     if ($outcome->grades[$submission->userid]->locked) {
877                         continue;
878                     }
880                     if ($quickgrade){
881                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.
882                         '").selectedIndex="'.$outcome->grades[$submission->userid]->grade.'";'."\n";
884                     } else {
885                         $options = make_grades_menu(-$outcome->scaleid);
886                         $options[0] = get_string('nooutcome', 'grades');
887                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.'").innerHTML="'.$options[$outcome->grades[$submission->userid]->grade]."\";\n";
888                     }
890                 }
891             }
892         }
894         $output .= "\n-->\n</script>";
895         return $output;
896     }
898     /**
899      *  Return a grade in user-friendly form, whether it's a scale or not
900      *
901      * @global object
902      * @param mixed $grade
903      * @return string User-friendly representation of grade
904      */
905     function display_grade($grade) {
906         global $DB;
908         static $scalegrades = array();   // Cache scales for each assignment - they might have different scales!!
910         if ($this->assignment->grade >= 0) {    // Normal number
911             if ($grade == -1) {
912                 return '-';
913             } else {
914                 return $grade.' / '.$this->assignment->grade;
915             }
917         } else {                                // Scale
918             if (empty($scalegrades[$this->assignment->id])) {
919                 if ($scale = $DB->get_record('scale', array('id'=>-($this->assignment->grade)))) {
920                     $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
921                 } else {
922                     return '-';
923                 }
924             }
925             if (isset($scalegrades[$this->assignment->id][$grade])) {
926                 return $scalegrades[$this->assignment->id][$grade];
927             }
928             return '-';
929         }
930     }
932     /**
933      *  Display a single submission, ready for grading on a popup window
934      *
935      * This default method prints the teacher info and submissioncomment box at the top and
936      * the student info and submission at the bottom.
937      * This method also fetches the necessary data in order to be able to
938      * provide a "Next submission" button.
939      * Calls preprocess_submission() to give assignment type plug-ins a chance
940      * to process submissions before they are graded
941      * This method gets its arguments from the page parameters userid and offset
942      *
943      * @global object
944      * @global object
945      * @param string $extra_javascript
946      */
947     function display_submission($offset=-1,$userid =-1, $display=true) {
948         global $CFG, $DB, $PAGE, $OUTPUT, $USER;
949         require_once($CFG->libdir.'/gradelib.php');
950         require_once($CFG->libdir.'/tablelib.php');
951         require_once("$CFG->dirroot/repository/lib.php");
952         require_once("$CFG->dirroot/grade/grading/lib.php");
953         if ($userid==-1) {
954             $userid = required_param('userid', PARAM_INT);
955         }
956         if ($offset==-1) {
957             $offset = required_param('offset', PARAM_INT);//offset for where to start looking for student.
958         }
959         $filter = optional_param('filter', 0, PARAM_INT);
961         if (!$user = $DB->get_record('user', array('id'=>$userid))) {
962             print_error('nousers');
963         }
965         if (!$submission = $this->get_submission($user->id)) {
966             $submission = $this->prepare_new_submission($userid);
967         }
968         if ($submission->timemodified > $submission->timemarked) {
969             $subtype = 'assignmentnew';
970         } else {
971             $subtype = 'assignmentold';
972         }
974         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
975         $gradingdisabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
977     /// construct SQL, using current offset to find the data of the next student
978         $course     = $this->course;
979         $assignment = $this->assignment;
980         $cm         = $this->cm;
981         $context    = get_context_instance(CONTEXT_MODULE, $cm->id);
983         //reset filter to all for offline assignment
984         if ($assignment->assignmenttype == 'offline' && $filter == self::FILTER_SUBMITTED) {
985             $filter = self::FILTER_ALL;
986         }
987         /// Get all ppl that can submit assignments
989         $currentgroup = groups_get_activity_group($cm);
990         $users = get_enrolled_users($context, 'mod/assignment:view', $currentgroup, 'u.id');
991         if ($users) {
992             $users = array_keys($users);
993             // if groupmembersonly used, remove users who are not in any group
994             if (!empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
995                 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
996                     $users = array_intersect($users, array_keys($groupingusers));
997                 }
998             }
999         }
1001         $nextid = 0;
1002         $where = '';
1003         if($filter == self::FILTER_SUBMITTED) {
1004             $where .= 's.timemodified > 0 AND ';
1005         } else if($filter == self::FILTER_REQUIRE_GRADING) {
1006             $where .= 's.timemarked < s.timemodified AND ';
1007         }
1009         if ($users) {
1010             $userfields = user_picture::fields('u', array('lastaccess'));
1011             $select = "SELECT $userfields,
1012                               s.id AS submissionid, s.grade, s.submissioncomment,
1013                               s.timemodified, s.timemarked ";
1014             $sql = 'FROM {user} u '.
1015                    'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1016                    AND s.assignment = '.$this->assignment->id.' '.
1017                    'WHERE '.$where.'u.id IN ('.implode(',', $users).') ';
1019             if ($sort = flexible_table::get_sort_for_table('mod-assignment-submissions')) {
1020                 $sort = 'ORDER BY '.$sort.' ';
1021             }
1022             $auser = $DB->get_records_sql($select.$sql.$sort, null, $offset, 2);
1024             if (is_array($auser) && count($auser)>1) {
1025                 $nextuser = next($auser);
1026             /// Calculate user status
1027                 $nextuser->status = ($nextuser->timemarked > 0) && ($nextuser->timemarked >= $nextuser->timemodified);
1028                 $nextid = $nextuser->id;
1029             }
1030         }
1032         if ($submission->teacher) {
1033             $teacher = $DB->get_record('user', array('id'=>$submission->teacher));
1034         } else {
1035             global $USER;
1036             $teacher = $USER;
1037         }
1039         $this->preprocess_submission($submission);
1041         $mformdata = new stdClass();
1042         $mformdata->context = $this->context;
1043         $mformdata->maxbytes = $this->course->maxbytes;
1044         $mformdata->courseid = $this->course->id;
1045         $mformdata->teacher = $teacher;
1046         $mformdata->assignment = $assignment;
1047         $mformdata->submission = $submission;
1048         $mformdata->lateness = $this->display_lateness($submission->timemodified);
1049         $mformdata->auser = $auser;
1050         $mformdata->user = $user;
1051         $mformdata->offset = $offset;
1052         $mformdata->userid = $userid;
1053         $mformdata->cm = $this->cm;
1054         $mformdata->grading_info = $grading_info;
1055         $mformdata->enableoutcomes = $CFG->enableoutcomes;
1056         $mformdata->grade = $this->assignment->grade;
1057         $mformdata->gradingdisabled = $gradingdisabled;
1058         $mformdata->nextid = $nextid;
1059         $mformdata->submissioncomment= $submission->submissioncomment;
1060         $mformdata->submissioncommentformat= FORMAT_HTML;
1061         $mformdata->submission_content= $this->print_user_files($user->id,true);
1062         $mformdata->filter = $filter;
1063         $mformdata->mailinfo = get_user_preferences('assignment_mailinfo', 0);
1064          if ($assignment->assignmenttype == 'upload') {
1065             $mformdata->fileui_options = array('subdirs'=>1, 'maxbytes'=>$assignment->maxbytes, 'maxfiles'=>$assignment->var1, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL);
1066         } elseif ($assignment->assignmenttype == 'uploadsingle') {
1067             $mformdata->fileui_options = array('subdirs'=>0, 'maxbytes'=>$CFG->userquota, 'maxfiles'=>1, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL);
1068         }
1069         if ($controller = get_grading_manager($this->context, 'mod_assignment', 'submission')->get_active_controller()) {
1070             $itemid = null;
1071             if (!empty($submission->id)) {
1072                 $itemid = $submission->id;
1073             }
1074             $mformdata->advancedgradinginstance = $controller->create_instance($USER->id, $itemid);
1075         }
1077         $submitform = new mod_assignment_grading_form( null, $mformdata );
1079          if (!$display) {
1080             $ret_data = new stdClass();
1081             $ret_data->mform = $submitform;
1082             if (isset($mformdata->fileui_options)) {
1083                 $ret_data->fileui_options = $mformdata->fileui_options;
1084             }
1085             return $ret_data;
1086         }
1088         if ($submitform->is_cancelled()) {
1089             redirect('submissions.php?id='.$this->cm->id);
1090         }
1092         $submitform->set_data($mformdata);
1094         $PAGE->set_title($this->course->fullname . ': ' .get_string('feedback', 'assignment').' - '.fullname($user, true));
1095         $PAGE->set_heading($this->course->fullname);
1096         $PAGE->navbar->add(get_string('submissions', 'assignment'), new moodle_url('/mod/assignment/submissions.php', array('id'=>$cm->id)));
1097         $PAGE->navbar->add(fullname($user, true));
1099         echo $OUTPUT->header();
1100         echo $OUTPUT->heading(get_string('feedback', 'assignment').': '.fullname($user, true));
1102         // display mform here...
1103         $submitform->display();
1105         $customfeedback = $this->custom_feedbackform($submission, true);
1106         if (!empty($customfeedback)) {
1107             echo $customfeedback;
1108         }
1110         echo $OUTPUT->footer();
1111     }
1113     /**
1114      *  Preprocess submission before grading
1115      *
1116      * Called by display_submission()
1117      * The default type does nothing here.
1118      *
1119      * @param object $submission The submission object
1120      */
1121     function preprocess_submission(&$submission) {
1122     }
1124     /**
1125      *  Display all the submissions ready for grading
1126      *
1127      * @global object
1128      * @global object
1129      * @global object
1130      * @global object
1131      * @param string $message
1132      * @return bool|void
1133      */
1134     function display_submissions($message='') {
1135         global $CFG, $DB, $USER, $DB, $OUTPUT, $PAGE;
1136         require_once($CFG->libdir.'/gradelib.php');
1138         /* first we check to see if the form has just been submitted
1139          * to request user_preference updates
1140          */
1142        $filters = array(self::FILTER_ALL             => get_string('all'),
1143                         self::FILTER_REQUIRE_GRADING => get_string('requiregrading', 'assignment'));
1145         $updatepref = optional_param('updatepref', 0, PARAM_BOOL);
1146         if ($updatepref) {
1147             $perpage = optional_param('perpage', 10, PARAM_INT);
1148             $perpage = ($perpage <= 0) ? 10 : $perpage ;
1149             $filter = optional_param('filter', 0, PARAM_INT);
1150             set_user_preference('assignment_perpage', $perpage);
1151             set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
1152             set_user_preference('assignment_filter', $filter);
1153         }
1155         /* next we get perpage and quickgrade (allow quick grade) params
1156          * from database
1157          */
1158         $perpage    = get_user_preferences('assignment_perpage', 10);
1159         $quickgrade = get_user_preferences('assignment_quickgrade', 0) && $this->quickgrade_mode_allowed();
1160         $filter = get_user_preferences('assignment_filter', 0);
1161         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);
1163         if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
1164             $uses_outcomes = true;
1165         } else {
1166             $uses_outcomes = false;
1167         }
1169         $page    = optional_param('page', 0, PARAM_INT);
1170         $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
1172     /// Some shortcuts to make the code read better
1174         $course     = $this->course;
1175         $assignment = $this->assignment;
1176         $cm         = $this->cm;
1177         $hassubmission = false;
1179         // reset filter to all for offline assignment only.
1180         if ($assignment->assignmenttype == 'offline') {
1181             if ($filter == self::FILTER_SUBMITTED) {
1182                 $filter = self::FILTER_ALL;
1183             }
1184         } else {
1185             $filters[self::FILTER_SUBMITTED] = get_string('submitted', 'assignment');
1186         }
1188         $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
1189         add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->cm->id, $this->assignment->id, $this->cm->id);
1191         $PAGE->set_title(format_string($this->assignment->name,true));
1192         $PAGE->set_heading($this->course->fullname);
1193         echo $OUTPUT->header();
1195         echo '<div class="usersubmissions">';
1197         //hook to allow plagiarism plugins to update status/print links.
1198         plagiarism_update_status($this->course, $this->cm);
1200         $course_context = get_context_instance(CONTEXT_COURSE, $course->id);
1201         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
1202             echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">'
1203                 . get_string('seeallcoursegrades', 'grades') . '</a></div>';
1204         }
1206         if (!empty($message)) {
1207             echo $message;   // display messages here if any
1208         }
1210         $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1212     /// Check to see if groups are being used in this assignment
1214         /// find out current groups mode
1215         $groupmode = groups_get_activity_groupmode($cm);
1216         $currentgroup = groups_get_activity_group($cm, true);
1217         groups_print_activity_menu($cm, $CFG->wwwroot . '/mod/assignment/submissions.php?id=' . $this->cm->id);
1219         /// Print quickgrade form around the table
1220         if ($quickgrade) {
1221             $formattrs = array();
1222             $formattrs['action'] = new moodle_url('/mod/assignment/submissions.php');
1223             $formattrs['id'] = 'fastg';
1224             $formattrs['method'] = 'post';
1226             echo html_writer::start_tag('form', $formattrs);
1227             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'id',      'value'=> $this->cm->id));
1228             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'mode',    'value'=> 'fastgrade'));
1229             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'page',    'value'=> $page));
1230             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=> sesskey()));
1231         }
1233         /// Get all ppl that are allowed to submit assignments
1234         list($esql, $params) = get_enrolled_sql($context, 'mod/assignment:submit', $currentgroup);
1236         if ($filter == self::FILTER_ALL) {
1237             $sql = "SELECT u.id FROM {user} u ".
1238                    "LEFT JOIN ($esql) eu ON eu.id=u.id ".
1239                    "WHERE u.deleted = 0 AND eu.id=u.id ";
1240         } else {
1241             $wherefilter = ' AND s.assignment = '. $this->assignment->id;
1242             $assignmentsubmission = "LEFT JOIN {assignment_submissions} s ON (u.id = s.userid) ";
1243             if($filter == self::FILTER_SUBMITTED) {
1244                 $wherefilter .= ' AND s.timemodified > 0 ';
1245             } else if($filter == self::FILTER_REQUIRE_GRADING && $assignment->assignmenttype != 'offline') {
1246                 $wherefilter .= ' AND s.timemarked < s.timemodified ';
1247             } else { // require grading for offline assignment
1248                 $assignmentsubmission = "";
1249                 $wherefilter = "";
1250             }
1252             $sql = "SELECT u.id FROM {user} u ".
1253                    "LEFT JOIN ($esql) eu ON eu.id=u.id ".
1254                    $assignmentsubmission.
1255                    "WHERE u.deleted = 0 AND eu.id=u.id ".
1256                    $wherefilter;
1257         }
1259         $users = $DB->get_records_sql($sql, $params);
1260         if (!empty($users)) {
1261             if($assignment->assignmenttype == 'offline' && $filter == self::FILTER_REQUIRE_GRADING) {
1262                 //remove users who has submitted their assignment
1263                 foreach ($this->get_submissions() as $submission) {
1264                     if (array_key_exists($submission->userid, $users)) {
1265                         unset($users[$submission->userid]);
1266                     }
1267                 }
1268             }
1269             $users = array_keys($users);
1270         }
1272         // if groupmembersonly used, remove users who are not in any group
1273         if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
1274             if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1275                 $users = array_intersect($users, array_keys($groupingusers));
1276             }
1277         }
1279         $tablecolumns = array('picture', 'fullname', 'grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade');
1280         if ($uses_outcomes) {
1281             $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
1282         }
1284         $tableheaders = array('',
1285                               get_string('fullnameuser'),
1286                               get_string('grade'),
1287                               get_string('comment', 'assignment'),
1288                               get_string('lastmodified').' ('.get_string('submission', 'assignment').')',
1289                               get_string('lastmodified').' ('.get_string('grade').')',
1290                               get_string('status'),
1291                               get_string('finalgrade', 'grades'));
1292         if ($uses_outcomes) {
1293             $tableheaders[] = get_string('outcome', 'grades');
1294         }
1296         require_once($CFG->libdir.'/tablelib.php');
1297         $table = new flexible_table('mod-assignment-submissions');
1299         $table->define_columns($tablecolumns);
1300         $table->define_headers($tableheaders);
1301         $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;currentgroup='.$currentgroup);
1303         $table->sortable(true, 'lastname');//sorted by lastname by default
1304         $table->collapsible(true);
1305         $table->initialbars(true);
1307         $table->column_suppress('picture');
1308         $table->column_suppress('fullname');
1310         $table->column_class('picture', 'picture');
1311         $table->column_class('fullname', 'fullname');
1312         $table->column_class('grade', 'grade');
1313         $table->column_class('submissioncomment', 'comment');
1314         $table->column_class('timemodified', 'timemodified');
1315         $table->column_class('timemarked', 'timemarked');
1316         $table->column_class('status', 'status');
1317         $table->column_class('finalgrade', 'finalgrade');
1318         if ($uses_outcomes) {
1319             $table->column_class('outcome', 'outcome');
1320         }
1322         $table->set_attribute('cellspacing', '0');
1323         $table->set_attribute('id', 'attempts');
1324         $table->set_attribute('class', 'submissions');
1325         $table->set_attribute('width', '100%');
1327         $table->no_sorting('finalgrade');
1328         $table->no_sorting('outcome');
1330         // Start working -- this is necessary as soon as the niceties are over
1331         $table->setup();
1333         /// Construct the SQL
1334         list($where, $params) = $table->get_sql_where();
1335         if ($where) {
1336             $where .= ' AND ';
1337         }
1339         if ($filter == self::FILTER_SUBMITTED) {
1340            $where .= 's.timemodified > 0 AND ';
1341         } else if($filter == self::FILTER_REQUIRE_GRADING) {
1342             $where = '';
1343             if ($assignment->assignmenttype != 'offline') {
1344                $where .= 's.timemarked < s.timemodified AND ';
1345             }
1346         }
1348         if ($sort = $table->get_sql_sort()) {
1349             $sort = ' ORDER BY '.$sort;
1350         }
1352         $ufields = user_picture::fields('u');
1353         if (!empty($users)) {
1354             $select = "SELECT $ufields,
1355                               s.id AS submissionid, s.grade, s.submissioncomment,
1356                               s.timemodified, s.timemarked ";
1357             $sql = 'FROM {user} u '.
1358                    'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1359                     AND s.assignment = '.$this->assignment->id.' '.
1360                    'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1362             $ausers = $DB->get_records_sql($select.$sql.$sort, $params, $table->get_page_start(), $table->get_page_size());
1364             $table->pagesize($perpage, count($users));
1366             ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1367             $offset = $page * $perpage;
1368             $strupdate = get_string('update');
1369             $strgrade  = get_string('grade');
1370             $grademenu = make_grades_menu($this->assignment->grade);
1372             if ($ausers !== false) {
1373                 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
1374                 $endposition = $offset + $perpage;
1375                 $currentposition = 0;
1376                 foreach ($ausers as $auser) {
1377                     if ($currentposition == $offset && $offset < $endposition) {
1378                         $final_grade = $grading_info->items[0]->grades[$auser->id];
1379                         $grademax = $grading_info->items[0]->grademax;
1380                         $final_grade->formatted_grade = round($final_grade->grade,2) .' / ' . round($grademax,2);
1381                         $locked_overridden = 'locked';
1382                         if ($final_grade->overridden) {
1383                             $locked_overridden = 'overridden';
1384                         }
1386                     /// Calculate user status
1387                         $auser->status = ($auser->timemarked > 0) && ($auser->timemarked >= $auser->timemodified);
1388                         // TODO add here code if advanced grading grade must be reviewed => $auser->status=0
1389                         $picture = $OUTPUT->user_picture($auser);
1391                         if (empty($auser->submissionid)) {
1392                             $auser->grade = -1; //no submission yet
1393                         }
1395                         if (!empty($auser->submissionid)) {
1396                             $hassubmission = true;
1397                         ///Prints student answer and student modified date
1398                         ///attach file or print link to student answer, depending on the type of the assignment.
1399                         ///Refer to print_student_answer in inherited classes.
1400                             if ($auser->timemodified > 0) {
1401                                 $studentmodified = '<div id="ts'.$auser->id.'">'.$this->print_student_answer($auser->id)
1402                                                  . userdate($auser->timemodified).'</div>';
1403                             } else {
1404                                 $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1405                             }
1406                         ///Print grade, dropdown or text
1407                             if ($auser->timemarked > 0) {
1408                                 $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
1410                                 if ($final_grade->locked or $final_grade->overridden) {
1411                                     $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1412                                 } else if ($quickgrade) {
1413                                     $attributes = array();
1414                                     $attributes['tabindex'] = $tabindex++;
1415                                     $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1416                                     $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
1417                                 } else {
1418                                     $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1419                                 }
1421                             } else {
1422                                 $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1423                                 if ($final_grade->locked or $final_grade->overridden) {
1424                                     $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1425                                 } else if ($quickgrade) {
1426                                     $attributes = array();
1427                                     $attributes['tabindex'] = $tabindex++;
1428                                     $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1429                                     $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1430                                 } else {
1431                                     $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1432                                 }
1433                             }
1434                         ///Print Comment
1435                             if ($final_grade->locked or $final_grade->overridden) {
1436                                 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';
1438                             } else if ($quickgrade) {
1439                                 $comment = '<div id="com'.$auser->id.'">'
1440                                          . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1441                                          . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1442                             } else {
1443                                 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
1444                             }
1445                         } else {
1446                             $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1447                             $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1448                             $status          = '<div id="st'.$auser->id.'">&nbsp;</div>';
1450                             if ($final_grade->locked or $final_grade->overridden) {
1451                                 $grade = '<div id="g'.$auser->id.'">'.$final_grade->formatted_grade . '</div>';
1452                                 $hassubmission = true;
1453                             } else if ($quickgrade) {   // allow editing
1454                                 $attributes = array();
1455                                 $attributes['tabindex'] = $tabindex++;
1456                                 $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1457                                 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1458                                 $hassubmission = true;
1459                             } else {
1460                                 $grade = '<div id="g'.$auser->id.'">-</div>';
1461                             }
1463                             if ($final_grade->locked or $final_grade->overridden) {
1464                                 $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
1465                             } else if ($quickgrade) {
1466                                 $comment = '<div id="com'.$auser->id.'">'
1467                                          . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1468                                          . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1469                             } else {
1470                                 $comment = '<div id="com'.$auser->id.'">&nbsp;</div>';
1471                             }
1472                         }
1474                         if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
1475                             $auser->status = 0;
1476                         } else {
1477                             $auser->status = 1;
1478                         }
1480                         $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
1482                         ///No more buttons, we use popups ;-).
1483                         $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1484                                    . '&amp;userid='.$auser->id.'&amp;mode=single'.'&amp;filter='.$filter.'&amp;offset='.$offset++;
1486                         $button = $OUTPUT->action_link($popup_url, $buttontext);
1488                         $status  = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
1490                         $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';
1492                         $outcomes = '';
1494                         if ($uses_outcomes) {
1496                             foreach($grading_info->outcomes as $n=>$outcome) {
1497                                 $outcomes .= '<div class="outcome"><label>'.$outcome->name.'</label>';
1498                                 $options = make_grades_menu(-$outcome->scaleid);
1500                                 if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
1501                                     $options[0] = get_string('nooutcome', 'grades');
1502                                     $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
1503                                 } else {
1504                                     $attributes = array();
1505                                     $attributes['tabindex'] = $tabindex++;
1506                                     $attributes['id'] = 'outcome_'.$n.'_'.$auser->id;
1507                                     $outcomes .= ' '.html_writer::select($options, 'outcome_'.$n.'['.$auser->id.']', $outcome->grades[$auser->id]->grade, array(0=>get_string('nooutcome', 'grades')), $attributes);
1508                                 }
1509                                 $outcomes .= '</div>';
1510                             }
1511                         }
1513                         $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>';
1514                         $row = array($picture, $userlink, $grade, $comment, $studentmodified, $teachermodified, $status, $finalgrade);
1515                         if ($uses_outcomes) {
1516                             $row[] = $outcomes;
1517                         }
1518                         $table->add_data($row);
1519                     }
1520                     $currentposition++;
1521                 }
1522                 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)
1523                     echo html_writer::start_tag('div', array('class' => 'mod-assignment-download-link'));
1524                     echo html_writer::link(new moodle_url('/mod/assignment/submissions.php', array('id' => $this->cm->id, 'download' => 'zip')), get_string('downloadall', 'assignment'));
1525                     echo html_writer::end_tag('div');
1526                 }
1527                 $table->print_html();  /// Print the whole table
1528             } else {
1529                 if ($filter == self::FILTER_SUBMITTED) {
1530                     echo html_writer::tag('div', get_string('nosubmisson', 'assignment'), array('class'=>'nosubmisson'));
1531                 } else if ($filter == self::FILTER_REQUIRE_GRADING) {
1532                     echo html_writer::tag('div', get_string('norequiregrading', 'assignment'), array('class'=>'norequiregrading'));
1533                 }
1534             }
1535         }
1537         /// Print quickgrade form around the table
1538         if ($quickgrade && $table->started_output && !empty($users)){
1539             $mailinfopref = false;
1540             if (get_user_preferences('assignment_mailinfo', 1)) {
1541                 $mailinfopref = true;
1542             }
1543             $emailnotification =  html_writer::checkbox('mailinfo', 1, $mailinfopref, get_string('enablenotification','assignment'));
1545             $emailnotification .= $OUTPUT->help_icon('enablenotification', 'assignment');
1546             echo html_writer::tag('div', $emailnotification, array('class'=>'emailnotification'));
1548             $savefeedback = html_writer::empty_tag('input', array('type'=>'submit', 'name'=>'fastg', 'value'=>get_string('saveallfeedback', 'assignment')));
1549             echo html_writer::tag('div', $savefeedback, array('class'=>'fastgbutton'));
1551             echo html_writer::end_tag('form');
1552         } else if ($quickgrade) {
1553             echo html_writer::end_tag('form');
1554         }
1556         echo '</div>';
1557         /// End of fast grading form
1559         /// Mini form for setting user preference
1561         $formaction = new moodle_url('/mod/assignment/submissions.php', array('id'=>$this->cm->id));
1562         $mform = new MoodleQuickForm('optionspref', 'post', $formaction, '', array('class'=>'optionspref'));
1564         $mform->addElement('hidden', 'updatepref');
1565         $mform->setDefault('updatepref', 1);
1566         $mform->addElement('header', 'qgprefs', get_string('optionalsettings', 'assignment'));
1567         $mform->addElement('select', 'filter', get_string('show'),  $filters);
1569         $mform->setDefault('filter', $filter);
1571         $mform->addElement('text', 'perpage', get_string('pagesize', 'assignment'), array('size'=>1));
1572         $mform->setDefault('perpage', $perpage);
1574         if ($this->quickgrade_mode_allowed()) {
1575             $mform->addElement('checkbox', 'quickgrade', get_string('quickgrade','assignment'));
1576             $mform->setDefault('quickgrade', $quickgrade);
1577             $mform->addHelpButton('quickgrade', 'quickgrade', 'assignment');
1578         }
1580         $mform->addElement('submit', 'savepreferences', get_string('savepreferences'));
1582         $mform->display();
1584         echo $OUTPUT->footer();
1585     }
1587     /**
1588      * If the form was cancelled ('Cancel' or 'Next' was pressed), call cancel method
1589      * from advanced grading (if applicable) and returns true
1590      * If the form was submitted, validates it and returns false if validation did not pass.
1591      * If validation passes, preprocess advanced grading (if applicable) and returns true.
1592      */
1593     function validate_and_preprocess_feedback() {
1594         global $USER;
1595         if (!($feedback = data_submitted()) || !isset($feedback->userid) || !isset($feedback->offset)) {
1596             return true;      // No incoming data, nothing to validate
1597         }
1598         $userid = required_param('userid', PARAM_INT);
1599         $offset = required_param('offset', PARAM_INT);
1600         $submissiondata = $this->display_submission($offset, $userid, false);
1601         $mform = $submissiondata->mform;
1602         $gradinginstance = $mform->use_advanced_grading();
1603         if (optional_param('cancel', false, PARAM_BOOL) || optional_param('next', false, PARAM_BOOL)) {
1604             // form was cancelled
1605             if ($gradinginstance) {
1606                 $gradinginstance->cancel();
1607             }
1608         } else if ($mform->is_submitted()) {
1609             // form was submitted (= a submit button other than 'cancel' or 'next' has been clicked)
1610             if (!$mform->is_validated()) {
1611                 return false;
1612             }
1613             // preprocess advanced grading here
1614             if ($gradinginstance) {
1615                 $data = $mform->get_data();
1616                 // create submission if it did not exist yet because we need submission->id for storing the grading instance
1617                 $submission = $this->get_submission($userid, true);
1618                 $_POST['xgrade'] = $gradinginstance->submit_and_get_grade($data->advancedgrading, $submission->id);
1619             }
1620         }
1621         return true;
1622     }
1624     /**
1625      *  Process teacher feedback submission
1626      *
1627      * This is called by submissions() when a grading even has taken place.
1628      * It gets its data from the submitted form.
1629      *
1630      * @global object
1631      * @global object
1632      * @global object
1633      * @return object|bool The updated submission object or false
1634      */
1635     function process_feedback($formdata=null) {
1636         global $CFG, $USER, $DB;
1637         require_once($CFG->libdir.'/gradelib.php');
1639         if (!$feedback = data_submitted() or !confirm_sesskey()) {      // No incoming data?
1640             return false;
1641         }
1643         ///For save and next, we need to know the userid to save, and the userid to go
1644         ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1645         ///as the userid to store
1646         if ((int)$feedback->saveuserid !== -1){
1647             $feedback->userid = $feedback->saveuserid;
1648         }
1650         if (!empty($feedback->cancel)) {          // User hit cancel button
1651             return false;
1652         }
1654         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);
1656         // store outcomes if needed
1657         $this->process_outcomes($feedback->userid);
1659         $submission = $this->get_submission($feedback->userid, true);  // Get or make one
1661         if (!($grading_info->items[0]->grades[$feedback->userid]->locked ||
1662             $grading_info->items[0]->grades[$feedback->userid]->overridden) ) {
1664             $submission->grade      = $feedback->xgrade;
1665             $submission->submissioncomment    = $feedback->submissioncomment_editor['text'];
1666             $submission->teacher    = $USER->id;
1667             $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1668             if (!$mailinfo) {
1669                 $submission->mailed = 1;       // treat as already mailed
1670             } else {
1671                 $submission->mailed = 0;       // Make sure mail goes out (again, even)
1672             }
1673             $submission->timemarked = time();
1675             unset($submission->data1);  // Don't need to update this.
1676             unset($submission->data2);  // Don't need to update this.
1678             if (empty($submission->timemodified)) {   // eg for offline assignments
1679                 // $submission->timemodified = time();
1680             }
1682             $DB->update_record('assignment_submissions', $submission);
1684             // triger grade event
1685             $this->update_grade($submission);
1687             add_to_log($this->course->id, 'assignment', 'update grades',
1688                        'submissions.php?id='.$this->cm->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
1689              if (!is_null($formdata)) {
1690                     if ($this->type == 'upload' || $this->type == 'uploadsingle') {
1691                         $mformdata = $formdata->mform->get_data();
1692                         $mformdata = file_postupdate_standard_filemanager($mformdata, 'files', $formdata->fileui_options, $this->context, 'mod_assignment', 'response', $submission->id);
1693                     }
1694              }
1695         }
1697         return $submission;
1699     }
1701     function process_outcomes($userid) {
1702         global $CFG, $USER;
1704         if (empty($CFG->enableoutcomes)) {
1705             return;
1706         }
1708         require_once($CFG->libdir.'/gradelib.php');
1710         if (!$formdata = data_submitted() or !confirm_sesskey()) {
1711             return;
1712         }
1714         $data = array();
1715         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
1717         if (!empty($grading_info->outcomes)) {
1718             foreach($grading_info->outcomes as $n=>$old) {
1719                 $name = 'outcome_'.$n;
1720                 if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
1721                     $data[$n] = $formdata->{$name}[$userid];
1722                 }
1723             }
1724         }
1725         if (count($data) > 0) {
1726             grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1727         }
1729     }
1731     /**
1732      * Load the submission object for a particular user
1733      *
1734      * @global object
1735      * @global object
1736      * @param $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1737      * @param $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1738      * @param bool $teachermodified student submission set if false
1739      * @return object The submission
1740      */
1741     function get_submission($userid=0, $createnew=false, $teachermodified=false) {
1742         global $USER, $DB;
1744         if (empty($userid)) {
1745             $userid = $USER->id;
1746         }
1748         $submission = $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1750         if ($submission || !$createnew) {
1751             return $submission;
1752         }
1753         $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
1754         $DB->insert_record("assignment_submissions", $newsubmission);
1756         return $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1757     }
1759     /**
1760      * Instantiates a new submission object for a given user
1761      *
1762      * Sets the assignment, userid and times, everything else is set to default values.
1763      *
1764      * @param int $userid The userid for which we want a submission object
1765      * @param bool $teachermodified student submission set if false
1766      * @return object The submission
1767      */
1768     function prepare_new_submission($userid, $teachermodified=false) {
1769         $submission = new stdClass();
1770         $submission->assignment   = $this->assignment->id;
1771         $submission->userid       = $userid;
1772         $submission->timecreated = time();
1773         // teachers should not be modifying modified date, except offline assignments
1774         if ($teachermodified) {
1775             $submission->timemodified = 0;
1776         } else {
1777             $submission->timemodified = $submission->timecreated;
1778         }
1779         $submission->numfiles     = 0;
1780         $submission->data1        = '';
1781         $submission->data2        = '';
1782         $submission->grade        = -1;
1783         $submission->submissioncomment      = '';
1784         $submission->format       = 0;
1785         $submission->teacher      = 0;
1786         $submission->timemarked   = 0;
1787         $submission->mailed       = 0;
1788         return $submission;
1789     }
1791     /**
1792      * Return all assignment submissions by ENROLLED students (even empty)
1793      *
1794      * @param string $sort optional field names for the ORDER BY in the sql query
1795      * @param string $dir optional specifying the sort direction, defaults to DESC
1796      * @return array The submission objects indexed by id
1797      */
1798     function get_submissions($sort='', $dir='DESC') {
1799         return assignment_get_all_submissions($this->assignment, $sort, $dir);
1800     }
1802     /**
1803      * Counts all real assignment submissions by ENROLLED students (not empty ones)
1804      *
1805      * @param int $groupid optional If nonzero then count is restricted to this group
1806      * @return int The number of submissions
1807      */
1808     function count_real_submissions($groupid=0) {
1809         return assignment_count_real_submissions($this->cm, $groupid);
1810     }
1812     /**
1813      * Alerts teachers by email of new or changed assignments that need grading
1814      *
1815      * First checks whether the option to email teachers is set for this assignment.
1816      * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1817      * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1818      *
1819      * @global object
1820      * @global object
1821      * @param $submission object The submission that has changed
1822      * @return void
1823      */
1824     function email_teachers($submission) {
1825         global $CFG, $DB;
1827         if (empty($this->assignment->emailteachers)) {          // No need to do anything
1828             return;
1829         }
1831         $user = $DB->get_record('user', array('id'=>$submission->userid));
1833         if ($teachers = $this->get_graders($user)) {
1835             $strassignments = get_string('modulenameplural', 'assignment');
1836             $strassignment  = get_string('modulename', 'assignment');
1837             $strsubmitted  = get_string('submitted', 'assignment');
1839             foreach ($teachers as $teacher) {
1840                 $info = new stdClass();
1841                 $info->username = fullname($user, true);
1842                 $info->assignment = format_string($this->assignment->name,true);
1843                 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
1844                 $info->timeupdated = strftime('%c',$submission->timemodified);
1846                 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1847                 $posttext = $this->email_teachers_text($info);
1848                 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
1850                 $eventdata = new stdClass();
1851                 $eventdata->modulename       = 'assignment';
1852                 $eventdata->userfrom         = $user;
1853                 $eventdata->userto           = $teacher;
1854                 $eventdata->subject          = $postsubject;
1855                 $eventdata->fullmessage      = $posttext;
1856                 $eventdata->fullmessageformat = FORMAT_PLAIN;
1857                 $eventdata->fullmessagehtml  = $posthtml;
1858                 $eventdata->smallmessage     = $postsubject;
1860                 $eventdata->name            = 'assignment_updates';
1861                 $eventdata->component       = 'mod_assignment';
1862                 $eventdata->notification    = 1;
1863                 $eventdata->contexturl      = $info->url;
1864                 $eventdata->contexturlname  = $info->assignment;
1866                 message_send($eventdata);
1867             }
1868         }
1869     }
1871     /**
1872      * @param string $filearea
1873      * @param array $args
1874      * @return bool
1875      */
1876     function send_file($filearea, $args) {
1877         debugging('plugin does not implement file sending', DEBUG_DEVELOPER);
1878         return false;
1879     }
1881     /**
1882      * Returns a list of teachers that should be grading given submission
1883      *
1884      * @param object $user
1885      * @return array
1886      */
1887     function get_graders($user) {
1888         //potential graders
1889         $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false);
1891         $graders = array();
1892         if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) {   // Separate groups are being used
1893             if ($groups = groups_get_all_groups($this->course->id, $user->id)) {  // Try to find all groups
1894                 foreach ($groups as $group) {
1895                     foreach ($potgraders as $t) {
1896                         if ($t->id == $user->id) {
1897                             continue; // do not send self
1898                         }
1899                         if (groups_is_member($group->id, $t->id)) {
1900                             $graders[$t->id] = $t;
1901                         }
1902                     }
1903                 }
1904             } else {
1905                 // user not in group, try to find graders without group
1906                 foreach ($potgraders as $t) {
1907                     if ($t->id == $user->id) {
1908                         continue; // do not send self
1909                     }
1910                     if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
1911                         $graders[$t->id] = $t;
1912                     }
1913                 }
1914             }
1915         } else {
1916             foreach ($potgraders as $t) {
1917                 if ($t->id == $user->id) {
1918                     continue; // do not send self
1919                 }
1920                 $graders[$t->id] = $t;
1921             }
1922         }
1923         return $graders;
1924     }
1926     /**
1927      * Creates the text content for emails to teachers
1928      *
1929      * @param $info object The info used by the 'emailteachermail' language string
1930      * @return string
1931      */
1932     function email_teachers_text($info) {
1933         $posttext  = format_string($this->course->shortname, true, array('context' => $this->coursecontext)).' -> '.
1934                      $this->strassignments.' -> '.
1935                      format_string($this->assignment->name, true, array('context' => $this->context))."\n";
1936         $posttext .= '---------------------------------------------------------------------'."\n";
1937         $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
1938         $posttext .= "\n---------------------------------------------------------------------\n";
1939         return $posttext;
1940     }
1942      /**
1943      * Creates the html content for emails to teachers
1944      *
1945      * @param $info object The info used by the 'emailteachermailhtml' language string
1946      * @return string
1947      */
1948     function email_teachers_html($info) {
1949         global $CFG;
1950         $posthtml  = '<p><font face="sans-serif">'.
1951                      '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname, true, array('context' => $this->coursecontext)).'</a> ->'.
1952                      '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
1953                      '<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>';
1954         $posthtml .= '<hr /><font face="sans-serif">';
1955         $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
1956         $posthtml .= '</font><hr />';
1957         return $posthtml;
1958     }
1960     /**
1961      * Produces a list of links to the files uploaded by a user
1962      *
1963      * @param $userid int optional id of the user. If 0 then $USER->id is used.
1964      * @param $return boolean optional defaults to false. If true the list is returned rather than printed
1965      * @return string optional
1966      */
1967     function print_user_files($userid=0, $return=false) {
1968         global $CFG, $USER, $OUTPUT;
1970         if (!$userid) {
1971             if (!isloggedin()) {
1972                 return '';
1973             }
1974             $userid = $USER->id;
1975         }
1977         $output = '';
1979         $submission = $this->get_submission($userid);
1980         if (!$submission) {
1981             return $output;
1982         }
1984         $fs = get_file_storage();
1985         $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false);
1986         if (!empty($files)) {
1987             require_once($CFG->dirroot . '/mod/assignment/locallib.php');
1988             if ($CFG->enableportfolios) {
1989                 require_once($CFG->libdir.'/portfoliolib.php');
1990                 $button = new portfolio_add_button();
1991             }
1992             foreach ($files as $file) {
1993                 $filename = $file->get_filename();
1994                 $mimetype = $file->get_mimetype();
1995                 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/mod_assignment/submission/'.$submission->id.'/'.$filename);
1996                 $output .= '<a href="'.$path.'" ><img src="'.$OUTPUT->pix_url(file_mimetype_icon($mimetype)).'" class="icon" alt="'.$mimetype.'" />'.s($filename).'</a>';
1997                 if ($CFG->enableportfolios && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1998                     $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id, 'submissionid' => $submission->id, 'fileid' => $file->get_id()), '/mod/assignment/locallib.php');
1999                     $button->set_format_by_file($file);
2000                     $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
2001                 }
2003                 if ($CFG->enableplagiarism) {
2004                     require_once($CFG->libdir.'/plagiarismlib.php');
2005                     $output .= plagiarism_get_links(array('userid'=>$userid, 'file'=>$file, 'cmid'=>$this->cm->id, 'course'=>$this->course, 'assignment'=>$this->assignment));
2006                     $output .= '<br />';
2007                 }
2008             }
2009             if ($CFG->enableportfolios && count($files) > 1  && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
2010                 $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id, 'submissionid' => $submission->id), '/mod/assignment/locallib.php');
2011                 $output .= '<br />'  . $button->to_html(PORTFOLIO_ADD_TEXT_LINK);
2012             }
2013         }
2015         $output = '<div class="files">'.$output.'</div>';
2017         if ($return) {
2018             return $output;
2019         }
2020         echo $output;
2021     }
2023     /**
2024      * Count the files uploaded by a given user
2025      *
2026      * @param $itemid int The submission's id as the file's itemid.
2027      * @return int
2028      */
2029     function count_user_files($itemid) {
2030         $fs = get_file_storage();
2031         $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $itemid, "id", false);
2032         return count($files);
2033     }
2035     /**
2036      * Returns true if the student is allowed to submit
2037      *
2038      * Checks that the assignment has started and, if the option to prevent late
2039      * submissions is set, also checks that the assignment has not yet closed.
2040      * @return boolean
2041      */
2042     function isopen() {
2043         $time = time();
2044         if ($this->assignment->preventlate && $this->assignment->timedue) {
2045             return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
2046         } else {
2047             return ($this->assignment->timeavailable <= $time);
2048         }
2049     }
2052     /**
2053      * Return true if is set description is hidden till available date
2054      *
2055      * This is needed by calendar so that hidden descriptions do not
2056      * come up in upcoming events.
2057      *
2058      * Check that description is hidden till available date
2059      * By default return false
2060      * Assignments types should implement this method if needed
2061      * @return boolen
2062      */
2063     function description_is_hidden() {
2064         return false;
2065     }
2067     /**
2068      * Return an outline of the user's interaction with the assignment
2069      *
2070      * The default method prints the grade and timemodified
2071      * @param $grade object
2072      * @return object with properties ->info and ->time
2073      */
2074     function user_outline($grade) {
2076         $result = new stdClass();
2077         $result->info = get_string('grade').': '.$grade->str_long_grade;
2078         $result->time = $grade->dategraded;
2079         return $result;
2080     }
2082     /**
2083      * Print complete information about the user's interaction with the assignment
2084      *
2085      * @param $user object
2086      */
2087     function user_complete($user, $grade=null) {
2088         global $OUTPUT;
2089         if ($grade) {
2090             echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
2091             if ($grade->str_feedback) {
2092                 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
2093             }
2094         }
2096         if ($submission = $this->get_submission($user->id)) {
2098             $fs = get_file_storage();
2100             if ($files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false)) {
2101                 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
2102                 foreach ($files as $file) {
2103                     $countfiles .= "; ".$file->get_filename();
2104                 }
2105             }
2107             echo $OUTPUT->box_start();
2108             echo get_string("lastmodified").": ";
2109             echo userdate($submission->timemodified);
2110             echo $this->display_lateness($submission->timemodified);
2112             $this->print_user_files($user->id);
2114             echo '<br />';
2116             $this->view_feedback($submission);
2118             echo $OUTPUT->box_end();
2120         } else {
2121             print_string("notsubmittedyet", "assignment");
2122         }
2123     }
2125     /**
2126      * Return a string indicating how late a submission is
2127      *
2128      * @param $timesubmitted int
2129      * @return string
2130      */
2131     function display_lateness($timesubmitted) {
2132         return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
2133     }
2135     /**
2136      * Empty method stub for all delete actions.
2137      */
2138     function delete() {
2139         //nothing by default
2140         redirect('view.php?id='.$this->cm->id);
2141     }
2143     /**
2144      * Empty custom feedback grading form.
2145      */
2146     function custom_feedbackform($submission, $return=false) {
2147         //nothing by default
2148         return '';
2149     }
2151     /**
2152      * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
2153      * for the course (see resource).
2154      *
2155      * Given a course_module object, this function returns any "extra" information that may be needed
2156      * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
2157      *
2158      * @param $coursemodule object The coursemodule object (record).
2159      * @return cached_cm_info Object used to customise appearance on course page
2160      */
2161     function get_coursemodule_info($coursemodule) {
2162         return null;
2163     }
2165     /**
2166      * Plugin cron method - do not use $this here, create new assignment instances if needed.
2167      * @return void
2168      */
2169     function cron() {
2170         //no plugin cron by default - override if needed
2171     }
2173     /**
2174      * Reset all submissions
2175      */
2176     function reset_userdata($data) {
2177         global $CFG, $DB;
2179         if (!$DB->count_records('assignment', array('course'=>$data->courseid, 'assignmenttype'=>$this->type))) {
2180             return array(); // no assignments of this type present
2181         }
2183         $componentstr = get_string('modulenameplural', 'assignment');
2184         $status = array();
2186         $typestr = get_string('type'.$this->type, 'assignment');
2187         // ugly hack to support pluggable assignment type titles...
2188         if($typestr === '[[type'.$this->type.']]'){
2189             $typestr = get_string('type'.$this->type, 'assignment_'.$this->type);
2190         }
2192         if (!empty($data->reset_assignment_submissions)) {
2193             $assignmentssql = "SELECT a.id
2194                                  FROM {assignment} a
2195                                 WHERE a.course=? AND a.assignmenttype=?";
2196             $params = array($data->courseid, $this->type);
2198             // now get rid of all submissions and responses
2199             $fs = get_file_storage();
2200             if ($assignments = $DB->get_records_sql($assignmentssql, $params)) {
2201                 foreach ($assignments as $assignmentid=>$unused) {
2202                     if (!$cm = get_coursemodule_from_instance('assignment', $assignmentid)) {
2203                         continue;
2204                     }
2205                     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2206                     $fs->delete_area_files($context->id, 'mod_assignment', 'submission');
2207                     $fs->delete_area_files($context->id, 'mod_assignment', 'response');
2208                 }
2209             }
2211             $DB->delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)", $params);
2213             $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
2215             if (empty($data->reset_gradebook_grades)) {
2216                 // remove all grades from gradebook
2217                 assignment_reset_gradebook($data->courseid, $this->type);
2218             }
2219         }
2221         /// updating dates - shift may be negative too
2222         if ($data->timeshift) {
2223             shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
2224             $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
2225         }
2227         return $status;
2228     }
2231     function portfolio_exportable() {
2232         return false;
2233     }
2235     /**
2236      * base implementation for backing up subtype specific information
2237      * for one single module
2238      *
2239      * @param filehandle $bf file handle for xml file to write to
2240      * @param mixed $preferences the complete backup preference object
2241      *
2242      * @return boolean
2243      *
2244      * @static
2245      */
2246     static function backup_one_mod($bf, $preferences, $assignment) {
2247         return true;
2248     }
2250     /**
2251      * base implementation for backing up subtype specific information
2252      * for one single submission
2253      *
2254      * @param filehandle $bf file handle for xml file to write to
2255      * @param mixed $preferences the complete backup preference object
2256      * @param object $submission the assignment submission db record
2257      *
2258      * @return boolean
2259      *
2260      * @static
2261      */
2262     static function backup_one_submission($bf, $preferences, $assignment, $submission) {
2263         return true;
2264     }
2266     /**
2267      * base implementation for restoring subtype specific information
2268      * for one single module
2269      *
2270      * @param array  $info the array representing the xml
2271      * @param object $restore the restore preferences
2272      *
2273      * @return boolean
2274      *
2275      * @static
2276      */
2277     static function restore_one_mod($info, $restore, $assignment) {
2278         return true;
2279     }
2281     /**
2282      * base implementation for restoring subtype specific information
2283      * for one single submission
2284      *
2285      * @param object $submission the newly created submission
2286      * @param array  $info the array representing the xml
2287      * @param object $restore the restore preferences
2288      *
2289      * @return boolean
2290      *
2291      * @static
2292      */
2293     static function restore_one_submission($info, $restore, $assignment, $submission) {
2294         return true;
2295     }
2297 } ////// End of the assignment_base class
2300 class mod_assignment_grading_form extends moodleform {
2302     function definition() {
2303         global $OUTPUT;
2304         $mform =& $this->_form;
2306         if (isset($this->_customdata->advancedgradinginstance)) {
2307             $this->use_advanced_grading($this->_customdata->advancedgradinginstance);
2308         }
2310         $formattr = $mform->getAttributes();
2311         $formattr['id'] = 'submitform';
2312         $mform->setAttributes($formattr);
2313         // hidden params
2314         $mform->addElement('hidden', 'offset', ($this->_customdata->offset+1));
2315         $mform->setType('offset', PARAM_INT);
2316         $mform->addElement('hidden', 'userid', $this->_customdata->userid);
2317         $mform->setType('userid', PARAM_INT);
2318         $mform->addElement('hidden', 'nextid', $this->_customdata->nextid);
2319         $mform->setType('nextid', PARAM_INT);
2320         $mform->addElement('hidden', 'id', $this->_customdata->cm->id);
2321         $mform->setType('id', PARAM_INT);
2322         $mform->addElement('hidden', 'sesskey', sesskey());
2323         $mform->setType('sesskey', PARAM_ALPHANUM);
2324         $mform->addElement('hidden', 'mode', 'grade');
2325         $mform->setType('mode', PARAM_TEXT);
2326         $mform->addElement('hidden', 'menuindex', "0");
2327         $mform->setType('menuindex', PARAM_INT);
2328         $mform->addElement('hidden', 'saveuserid', "-1");
2329         $mform->setType('saveuserid', PARAM_INT);
2330         $mform->addElement('hidden', 'filter', "0");
2331         $mform->setType('filter', PARAM_INT);
2333         $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->user),
2334                                                 fullname($this->_customdata->user, true) . '<br/>' .
2335                                                 userdate($this->_customdata->submission->timemodified) .
2336                                                 $this->_customdata->lateness );
2338         $this->add_submission_content();
2339         $this->add_grades_section();
2341         $this->add_feedback_section();
2343         if ($this->_customdata->submission->timemarked) {
2344             $datestring = userdate($this->_customdata->submission->timemarked)."&nbsp; (".format_time(time() - $this->_customdata->submission->timemarked).")";
2345             $mform->addElement('header', 'Last Grade', get_string('lastgrade', 'assignment'));
2346             $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->teacher) ,
2347                                                     fullname($this->_customdata->teacher,true).
2348                                                     '<br/>'.$datestring);
2349         }
2350         // buttons
2351         $this->add_action_buttons();
2353     }
2355     private $advancegradinginstance;
2356     /**
2357      * Gets or sets the instance for advanced grading
2358      *
2359      * @param gradingform_instance $gradinginstance
2360      */
2361     public function use_advanced_grading($gradinginstance = false) {
2362         if ($gradinginstance !== false) {
2363             $this->advancegradinginstance = $gradinginstance;
2364         }
2365         return $this->advancegradinginstance;
2366     }
2368     function add_grades_section() {
2369         global $CFG;
2370         $mform =& $this->_form;
2371         $attributes = array();
2372         if ($this->_customdata->gradingdisabled) {
2373             $attributes['disabled'] ='disabled';
2374         }
2376         $mform->addElement('header', 'Grades', get_string('grades', 'grades'));
2378         $grademenu = make_grades_menu($this->_customdata->assignment->grade);
2379         if ($gradinginstance = $this->use_advanced_grading()) {
2380             $gradinginstance->get_controller()->set_grade_range($grademenu);
2381             $mform->addElement('grading', 'advancedgrading', get_string('grade').':', array('gradinginstance' => $gradinginstance));
2382         } else {
2383             // use simple direct grading
2384             $grademenu['-1'] = get_string('nograde');
2386             $mform->addElement('select', 'xgrade', get_string('grade').':', $grademenu, $attributes);
2387             $mform->setDefault('xgrade', $this->_customdata->submission->grade ); //@fixme some bug when element called 'grade' makes it break
2388             $mform->setType('xgrade', PARAM_INT);
2389         }
2391         if (!empty($this->_customdata->enableoutcomes)) {
2392             foreach($this->_customdata->grading_info->outcomes as $n=>$outcome) {
2393                 $options = make_grades_menu(-$outcome->scaleid);
2394                 if ($outcome->grades[$this->_customdata->submission->userid]->locked) {
2395                     $options[0] = get_string('nooutcome', 'grades');
2396                     echo $options[$outcome->grades[$this->_customdata->submission->userid]->grade];
2397                 } else {
2398                     $options[''] = get_string('nooutcome', 'grades');
2399                     $attributes = array('id' => 'menuoutcome_'.$n );
2400                     $mform->addElement('select', 'outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->name.':', $options, $attributes );
2401                     $mform->setType('outcome_'.$n.'['.$this->_customdata->userid.']', PARAM_INT);
2402                     $mform->setDefault('outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->grades[$this->_customdata->submission->userid]->grade );
2403                 }
2404             }
2405         }
2406         $course_context = get_context_instance(CONTEXT_MODULE , $this->_customdata->cm->id);
2407         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
2408             $grade = '<a href="'.$CFG->wwwroot.'/grade/report/grader/index.php?id='. $this->_customdata->courseid .'" >'.
2409                         $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade . '</a>';
2410         }else{
2411             $grade = $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade;
2412         }
2413         $mform->addElement('static', 'finalgrade', get_string('currentgrade', 'assignment').':' ,$grade);
2414         $mform->setType('finalgrade', PARAM_INT);
2415     }
2417     /**
2418      *
2419      * @global core_renderer $OUTPUT
2420      */
2421     function add_feedback_section() {
2422         global $OUTPUT;
2423         $mform =& $this->_form;
2424         $mform->addElement('header', 'Feed Back', get_string('feedback', 'grades'));
2426         if ($this->_customdata->gradingdisabled) {
2427             $mform->addElement('static', 'disabledfeedback', $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_feedback );
2428         } else {
2429             // visible elements
2431             $mform->addElement('editor', 'submissioncomment_editor', get_string('feedback', 'assignment').':', null, $this->get_editor_options() );
2432             $mform->setType('submissioncomment_editor', PARAM_RAW); // to be cleaned before display
2433             $mform->setDefault('submissioncomment_editor', $this->_customdata->submission->submissioncomment);
2434             //$mform->addRule('submissioncomment', get_string('required'), 'required', null, 'client');
2435             switch ($this->_customdata->assignment->assignmenttype) {
2436                 case 'upload' :
2437                 case 'uploadsingle' :
2438                     $mform->addElement('filemanager', 'files_filemanager', get_string('responsefiles', 'assignment'). ':', null, $this->_customdata->fileui_options);
2439                     break;
2440                 default :
2441                     break;
2442             }
2443             $mform->addElement('hidden', 'mailinfo_h', "0");
2444             $mform->setType('mailinfo_h', PARAM_INT);
2445             $mform->addElement('checkbox', 'mailinfo',get_string('enablenotification','assignment').
2446             $OUTPUT->help_icon('enablenotification', 'assignment') .':' );
2447             $mform->setType('mailinfo', PARAM_INT);
2448         }
2449     }
2451     function add_action_buttons() {
2452         $mform =& $this->_form;
2453         //if there are more to be graded.
2454         if ($this->_customdata->nextid>0) {
2455             $buttonarray=array();
2456             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2457             //@todo: fix accessibility: javascript dependency not necessary
2458             $buttonarray[] = &$mform->createElement('submit', 'saveandnext', get_string('saveandnext'));
2459             $buttonarray[] = &$mform->createElement('submit', 'next', get_string('next'));
2460             $buttonarray[] = &$mform->createElement('cancel');
2461         } else {
2462             $buttonarray=array();
2463             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2464             $buttonarray[] = &$mform->createElement('cancel');
2465         }
2466         $mform->addGroup($buttonarray, 'grading_buttonar', '', array(' '), false);
2467         $mform->closeHeaderBefore('grading_buttonar');
2468         $mform->setType('grading_buttonar', PARAM_RAW);
2469     }
2471     function add_submission_content() {
2472         $mform =& $this->_form;
2473         $mform->addElement('header', 'Submission', get_string('submission', 'assignment'));
2474         $mform->addElement('static', '', '' , $this->_customdata->submission_content );
2475     }
2477     protected function get_editor_options() {
2478         $editoroptions = array();
2479         $editoroptions['component'] = 'mod_assignment';
2480         $editoroptions['filearea'] = 'feedback';
2481         $editoroptions['noclean'] = false;
2482         $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)
2483         $editoroptions['maxbytes'] = $this->_customdata->maxbytes;
2484         $editoroptions['context'] = $this->_customdata->context;
2485         return $editoroptions;
2486     }
2488     public function set_data($data) {
2489         $editoroptions = $this->get_editor_options();
2490         if (!isset($data->text)) {
2491             $data->text = '';
2492         }
2493         if (!isset($data->format)) {
2494             $data->textformat = FORMAT_HTML;
2495         } else {
2496             $data->textformat = $data->format;
2497         }
2499         if (!empty($this->_customdata->submission->id)) {
2500             $itemid = $this->_customdata->submission->id;
2501         } else {
2502             $itemid = null;
2503         }
2505         switch ($this->_customdata->assignment->assignmenttype) {
2506                 case 'upload' :
2507                 case 'uploadsingle' :
2508                     $data = file_prepare_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2509                     break;
2510                 default :
2511                     break;
2512         }
2514         $data = file_prepare_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2515         return parent::set_data($data);
2516     }
2518     public function get_data() {
2519         $data = parent::get_data();
2521         if (!empty($this->_customdata->submission->id)) {
2522             $itemid = $this->_customdata->submission->id;
2523         } else {
2524             $itemid = null; //TODO: this is wrong, itemid MUST be known when saving files!! (skodak)
2525         }
2527         if ($data) {
2528             $editoroptions = $this->get_editor_options();
2529             switch ($this->_customdata->assignment->assignmenttype) {
2530                 case 'upload' :
2531                 case 'uploadsingle' :
2532                     $data = file_postupdate_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2533                     break;
2534                 default :
2535                     break;
2536             }
2537             $data = file_postupdate_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2538         }
2540         if ($this->use_advanced_grading() && !isset($data->advancedgrading)) {
2541             $data->advancedgrading = null;
2542         }
2544         return $data;
2545     }
2548 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
2550 /**
2551  * Deletes an assignment instance
2552  *
2553  * This is done by calling the delete_instance() method of the assignment type class
2554  */
2555 function assignment_delete_instance($id){
2556     global $CFG, $DB;
2558     if (! $assignment = $DB->get_record('assignment', array('id'=>$id))) {
2559         return false;
2560     }
2562     // fall back to base class if plugin missing
2563     $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2564     if (file_exists($classfile)) {
2565         require_once($classfile);
2566         $assignmentclass = "assignment_$assignment->assignmenttype";
2568     } else {
2569         debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
2570         $assignmentclass = "assignment_base";
2571     }
2573     $ass = new $assignmentclass();
2574     return $ass->delete_instance($assignment);
2578 /**
2579  * Updates an assignment instance
2580  *
2581  * This is done by calling the update_instance() method of the assignment type class
2582  */
2583 function assignment_update_instance($assignment){
2584     global $CFG;
2586     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_PLUGIN);
2588     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2589     $assignmentclass = "assignment_$assignment->assignmenttype";
2590     $ass = new $assignmentclass();
2591     return $ass->update_instance($assignment);
2595 /**
2596  * Adds an assignment instance
2597  *
2598  * This is done by calling the add_instance() method of the assignment type class
2599  */
2600 function assignment_add_instance($assignment) {
2601     global $CFG;
2603     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_PLUGIN);
2605     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2606     $assignmentclass = "assignment_$assignment->assignmenttype";
2607     $ass = new $assignmentclass();
2608     return $ass->add_instance($assignment);
2612 /**
2613  * Returns an outline of a user interaction with an assignment
2614  *
2615  * This is done by calling the user_outline() method of the assignment type class
2616  */
2617 function assignment_user_outline($course, $user, $mod, $assignment) {
2618     global $CFG;
2620     require_once("$CFG->libdir/gradelib.php");
2621     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2622     $assignmentclass = "assignment_$assignment->assignmenttype";
2623     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2624     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2625     if (!empty($grades->items[0]->grades)) {
2626         return $ass->user_outline(reset($grades->items[0]->grades));
2627     } else {
2628         return null;
2629     }
2632 /**
2633  * Prints the complete info about a user's interaction with an assignment
2634  *
2635  * This is done by calling the user_complete() method of the assignment type class
2636  */
2637 function assignment_user_complete($course, $user, $mod, $assignment) {
2638     global $CFG;
2640     require_once("$CFG->libdir/gradelib.php");
2641     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2642     $assignmentclass = "assignment_$assignment->assignmenttype";
2643     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2644     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2645     if (empty($grades->items[0]->grades)) {
2646         $grade = false;
2647     } else {
2648         $grade = reset($grades->items[0]->grades);
2649     }
2650     return $ass->user_complete($user, $grade);
2653 /**
2654  * Function to be run periodically according to the moodle cron
2655  *
2656  * Finds all assignment notifications that have yet to be mailed out, and mails them
2657  */
2658 function assignment_cron () {
2659     global $CFG, $USER, $DB;
2661     /// first execute all crons in plugins
2662     if ($plugins = get_plugin_list('assignment')) {
2663         foreach ($plugins as $plugin=>$dir) {
2664             require_once("$dir/assignment.class.php");
2665             $assignmentclass = "assignment_$plugin";
2666             $ass = new $assignmentclass();
2667             $ass->cron();
2668         }
2669     }
2671     /// Notices older than 1 day will not be mailed.  This is to avoid the problem where
2672     /// cron has not been running for a long time, and then suddenly people are flooded
2673     /// with mail from the past few weeks or months
2675     $timenow   = time();
2676     $endtime   = $timenow - $CFG->maxeditingtime;
2677     $starttime = $endtime - 24 * 3600;   /// One day earlier
2679     if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2681         $realuser = clone($USER);
2683         foreach ($submissions as $key => $submission) {
2684             $DB->set_field("assignment_submissions", "mailed", "1", array("id"=>$submission->id));
2685         }
2687         $timenow = time();
2689         foreach ($submissions as $submission) {
2691             echo "Processing assignment submission $submission->id\n";
2693             if (! $user = $DB->get_record("user", array("id"=>$submission->userid))) {
2694                 echo "Could not find user $user->id\n";
2695                 continue;
2696             }
2698             if (! $course = $DB->get_record("course", array("id"=>$submission->course))) {
2699                 echo "Could not find course $submission->course\n";
2700                 continue;
2701             }
2703             /// Override the language and timezone of the "current" user, so that
2704             /// mail is customised for the receiver.
2705             cron_setup_user($user, $course);
2707             $coursecontext = get_context_instance(CONTEXT_COURSE, $submission->course);
2708             $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
2709             if (!is_enrolled($coursecontext, $user->id)) {
2710                 echo fullname($user)." not an active participant in " . $courseshortname . "\n";
2711                 continue;
2712             }
2714             if (! $teacher = $DB->get_record("user", array("id"=>$submission->teacher))) {
2715                 echo "Could not find teacher $submission->teacher\n";
2716                 continue;
2717             }
2719             if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2720                 echo "Could not find course module for assignment id $submission->assignment\n";
2721                 continue;
2722             }
2724             if (! $mod->visible) {    /// Hold mail notification for hidden assignments until later
2725                 continue;
2726             }
2728             $strassignments = get_string("modulenameplural", "assignment");
2729             $strassignment  = get_string("modulename", "assignment");
2731             $assignmentinfo = new stdClass();
2732             $assignmentinfo->teacher = fullname($teacher);
2733             $assignmentinfo->assignment = format_string($submission->name,true);
2734             $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2736             $postsubject = "$courseshortname: $strassignments: ".format_string($submission->name,true);
2737             $posttext  = "$courseshortname -> $strassignments -> ".format_string($submission->name,true)."\n";
2738             $posttext .= "---------------------------------------------------------------------\n";
2739             $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2740             $posttext .= "---------------------------------------------------------------------\n";
2742             if ($user->mailformat == 1) {  // HTML
2743                 $posthtml = "<p><font face=\"sans-serif\">".
2744                 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$courseshortname</a> ->".
2745                 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2746                 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2747                 $posthtml .= "<hr /><font face=\"sans-serif\">";
2748                 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2749                 $posthtml .= "</font><hr />";
2750             } else {
2751                 $posthtml = "";
2752             }
2754             $eventdata = new stdClass();
2755             $eventdata->modulename       = 'assignment';
2756             $eventdata->userfrom         = $teacher;
2757             $eventdata->userto           = $user;
2758             $eventdata->subject          = $postsubject;
2759             $eventdata->fullmessage      = $posttext;
2760             $eventdata->fullmessageformat = FORMAT_PLAIN;
2761             $eventdata->fullmessagehtml  = $posthtml;
2762             $eventdata->smallmessage     = get_string('assignmentmailsmall', 'assignment', $assignmentinfo);
2764             $eventdata->name            = 'assignment_updates';
2765             $eventdata->component       = 'mod_assignment';
2766             $eventdata->notification    = 1;
2767             $eventdata->contexturl      = $assignmentinfo->url;
2768             $eventdata->contexturlname  = $assignmentinfo->assignment;
2770             message_send($eventdata);
2771         }
2773         cron_setup_user();
2774     }
2776     return true;
2779 /**
2780  * Return grade for given user or all users.
2781  *
2782  * @param int $assignmentid id of assignment
2783  * @param int $userid optional user id, 0 means all users
2784  * @return array array of grades, false if none
2785  */
2786 function assignment_get_user_grades($assignment, $userid=0) {
2787     global $CFG, $DB;
2789     if ($userid) {
2790         $user = "AND u.id = :userid";
2791         $params = array('userid'=>$userid);
2792     } else {
2793         $user = "";
2794     }
2795     $params['aid'] = $assignment->id;
2797     $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2798                    s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2799               FROM {user} u, {assignment_submissions} s
2800              WHERE u.id = s.userid AND s.assignment = :aid
2801                    $user";
2803     return $DB->get_records_sql($sql, $params);
2806 /**
2807  * Update activity grades
2808  *
2809  * @param object $assignment
2810  * @param int $userid specific user only, 0 means all
2811  */
2812 function assignment_update_grades($assignment, $userid=0, $nullifnone=true) {
2813     global $CFG, $DB;
2814     require_once($CFG->libdir.'/gradelib.php');
2816     if ($assignment->grade == 0) {
2817         assignment_grade_item_update($assignment);
2819     } else if ($grades = assignment_get_user_grades($assignment, $userid)) {
2820         foreach($grades as $k=>$v) {
2821             if ($v->rawgrade == -1) {
2822                 $grades[$k]->rawgrade = null;
2823             }
2824         }
2825         assignment_grade_item_update($assignment, $grades);
2827     } else {
2828         assignment_grade_item_update($assignment);
2829     }
2832 /**
2833  * Update all grades in gradebook.
2834  */
2835 function assignment_upgrade_grades() {
2836     global $DB;
2838     $sql = "SELECT COUNT('x')
2839               FROM {assignment} a, {course_modules} cm, {modules} m
2840              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2841     $count = $DB->count_records_sql($sql);
2843     $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
2844               FROM {assignment} a, {course_modules} cm, {modules} m
2845              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2846     $rs = $DB->get_recordset_sql($sql);
2847     if ($rs->valid()) {
2848         // too much debug output
2849         $pbar = new progress_bar('assignmentupgradegrades', 500, true);
2850         $i=0;
2851         foreach ($rs as $assignment) {
2852             $i++;
2853             upgrade_set_timeout(60*5); // set up timeout, may also abort execution
2854             assignment_update_grades($assignment);
2855             $pbar->update($i, $count, "Updating Assignment grades ($i/$count).");
2856         }
2857         upgrade_set_timeout(); // reset to default timeout
2858     }
2859     $rs->close();
2862 /**
2863  * Create grade item for given assignment
2864  *
2865  * @param object $assignment object with extra cmidnumber
2866  * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
2867  * @return int 0 if ok, error code otherwise
2868  */
2869 function assignment_grade_item_update($assignment, $grades=NULL) {
2870     global $CFG;
2871     require_once($CFG->libdir.'/gradelib.php');
2873     if (!isset($assignment->courseid)) {
2874         $assignment->courseid = $assignment->course;
2875     }
2877     $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
2879     if ($assignment->grade > 0) {
2880         $params['gradetype'] = GRADE_TYPE_VALUE;
2881         $params['grademax']  = $assignment->grade;
2882         $params['grademin']  = 0;
2884     } else if ($assignment->grade < 0) {
2885         $params['gradetype'] = GRADE_TYPE_SCALE;
2886         $params['scaleid']   = -$assignment->grade;
2888     } else {
2889         $params['gradetype'] = GRADE_TYPE_TEXT; // allow text comments only
2890     }
2892     if ($grades  === 'reset') {
2893         $params['reset'] = true;
2894         $grades = NULL;
2895     }
2897     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades, $params);
2900 /**
2901  * Delete grade item for given assignment
2902  *
2903  * @param object $assignment object
2904  * @return object assignment
2905  */
2906 function assignment_grade_item_delete($assignment) {
2907     global $CFG;
2908     require_once($CFG->libdir.'/gradelib.php');
2910     if (!isset($assignment->courseid)) {
2911         $assignment->courseid = $assignment->course;
2912     }
2914     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
2917 /**
2918  * Returns the users with data in one assignment (students and teachers)
2919  *
2920  * @todo: deprecated - to be deleted in 2.2
2921  *
2922  * @param $assignmentid int
2923  * @return array of user objects
2924  */
2925 function assignment_get_participants($assignmentid) {
2926     global $CFG, $DB;
2928     //Get students
2929     $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2930                                         FROM {user} u,
2931                                              {assignment_submissions} a
2932                                        WHERE a.assignment = ? and
2933                                              u.id = a.userid", array($assignmentid));
2934     //Get teachers
2935     $teachers = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2936                                         FROM {user} u,
2937                                              {assignment_submissions} a
2938                                        WHERE a.assignment = ? and
2939                                              u.id = a.teacher", array($assignmentid));
2941     //Add teachers to students
2942     if ($teachers) {
2943         foreach ($teachers as $teacher) {
2944             $students[$teacher->id] = $teacher;
2945         }
2946     }
2947     //Return students array (it contains an array of unique users)
2948     return ($students);
2951 /**
2952  * Serves assignment submissions and other files.
2953  *
2954  * @param object $course
2955  * @param object $cm
2956  * @param object $context
2957  * @param string $filearea
2958  * @param array $args
2959  * @param bool $forcedownload
2960  * @return bool false if file not found, does not return if found - just send the file
2961  */
2962 function assignment_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) {
2963     global $CFG, $DB;
2965     if ($context->contextlevel != CONTEXT_MODULE) {
2966         return false;
2967     }
2969     require_login($course, false, $cm);
2971     if (!$assignment = $DB->get_record('assignment', array('id'=>$cm->instance))) {
2972         return false;
2973     }
2975     require_once($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
2976     $assignmentclass = 'assignment_'.$assignment->assignmenttype;
2977     $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm, $course);
2979     return $assignmentinstance->send_file($filearea, $args);
2981 /**
2982  * Checks if a scale is being used by an assignment
2983  *
2984  * This is used by the backup code to decide whether to back up a scale
2985  * @param $assignmentid int
2986  * @param $scaleid int
2987  * @return boolean True if the scale is used by the assignment
2988  */
2989 function assignment_scale_used($assignmentid, $scaleid) {
2990     global $DB;
2992     $return = false;
2994     $rec = $DB->get_record('assignment', array('id'=>$assignmentid,'grade'=>-$scaleid));
2996     if (!empty($rec) && !empty($scaleid)) {
2997         $return = true;
2998     }
3000     return $return;
3003 /**
3004  * Checks if scale is being used by any instance of assignment
3005  *
3006  * This is used to find out if scale used anywhere
3007  * @param $scaleid int
3008  * @return boolean True if the scale is used by any assignment
3009  */
3010 function assignment_scale_used_anywhere($scaleid) {
3011     global $DB;
3013     if ($scaleid and $DB->record_exists('assignment', array('grade'=>-$scaleid))) {
3014         return true;
3015     } else {
3016         return false;
3017     }
3020 /**
3021  * Make sure up-to-date events are created for all assignment instances
3022  *
3023  * This standard function will check all instances of this module
3024  * and make sure there are up-to-date events created for each of them.
3025  * If courseid = 0, then every assignment event in the site is checked, else
3026  * only assignment events belonging to the course specified are checked.
3027  * This function is used, in its new format, by restore_refresh_events()
3028  *
3029  * @param $courseid int optional If zero then all assignments for all courses are covered
3030  * @return boolean Always returns true
3031  */
3032 function assignment_refresh_events($courseid = 0) {
3033     global $DB;
3035     if ($courseid == 0) {
3036         if (! $assignments = $DB->get_records("assignment")) {
3037             return true;
3038         }
3039     } else {
3040         if (! $assignments = $DB->get_records("assignment", array("course"=>$courseid))) {
3041             return true;
3042         }
3043     }
3044     $moduleid = $DB->get_field('modules', 'id', array('name'=>'assignment'));
3046     foreach ($assignments as $assignment) {
3047         $cm = get_coursemodule_from_id('assignment', $assignment->id);
3048         $event = new stdClass();
3049         $event->name        = $assignment->name;
3050         $event->description = format_module_intro('assignment', $assignment, $cm->id);
3051         $event->timestart   = $assignment->timedue;
3053         if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
3054             update_event($event);
3056         } else {
3057             $event->courseid    = $assignment->course;
3058             $event->groupid     = 0;
3059             $event->userid      = 0;
3060             $event->modulename  = 'assignment';
3061             $event->instance    = $assignment->id;
3062             $event->eventtype   = 'due';
3063             $event->timeduration = 0;
3064             $event->visible     = $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$assignment->id));
3065             add_event($event);
3066         }
3068     }
3069     return true;
3072 /**
3073  * Print recent activity from all assignments in a given course
3074  *
3075  * This is used by the recent activity block
3076  */
3077 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
3078     global $CFG, $USER, $DB, $OUTPUT;
3080     // do not use log table if possible, it may be huge
3082     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
3083                                                      u.firstname, u.lastname, u.email, u.picture
3084                                                 FROM {assignment_submissions} asb
3085                                                      JOIN {assignment} a      ON a.id = asb.assignment
3086                                                      JOIN {course_modules} cm ON cm.instance = a.id
3087                                                      JOIN {modules} md        ON md.id = cm.module
3088                                                      JOIN {user} u            ON u.id = asb.userid
3089                                                WHERE asb.timemodified > ? AND
3090                                                      a.course = ? AND
3091                                                      md.name = 'assignment'
3092                                             ORDER BY asb.timemodified ASC", array($timestart, $course->id))) {
3093          return false;
3094     }
3096     $modinfo =& get_fast_modinfo($course); // reference needed because we might load the groups
3097     $show    = array();
3098     $grader  = array();
3100     foreach($submissions as $submission) {
3101         if (!array_key_exists($submission->cmid, $modinfo->cms)) {
3102             continue;
3103         }
3104         $cm = $modinfo->cms[$submission->cmid];
3105         if (!$cm->uservisible) {
3106             continue;
3107         }
3108         if ($submission->userid == $USER->id) {
3109             $show[] = $submission;
3110             continue;
3111         }
3113         // the act of sumbitting of assignment may be considered private - only graders will see it if specified
3114         if (empty($CFG->assignment_showrecentsubmissions)) {
3115             if (!array_key_exists($cm->id, $grader)) {
3116                 $grader[$cm->id] = has_capability('moodle/grade:viewall', get_context_instance(CONTEXT_MODULE, $cm->id));
3117             }
3118             if (!$grader[$cm->id]) {
3119                 continue;
3120             }
3121         }
3123         $groupmode = groups_get_activity_groupmode($cm, $course);
3125         if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
3126             if (isguestuser()) {
3127                 // shortcut - guest user does not belong into any group
3128                 continue;
3129             }
3131             if (is_null($modinfo->groups)) {
3132                 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
3133             }
3135             // this will be slow - show only users that share group with me in this cm
3136             if (empty($modinfo->groups[$cm->id])) {
3137                 continue;
3138             }
3139             $usersgroups =  groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
3140             if (is_array($usersgroups)) {
3141                 $usersgroups = array_keys($usersgroups);
3142                 $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
3143                 if (empty($intersect)) {
3144                     continue;
3145                 }
3146             }
3147         }
3148         $show[] = $submission;
3149     }
3151     if (empty($show)) {
3152         return false;
3153     }
3155     echo $OUTPUT->heading(get_string('newsubmissions', 'assignment').':', 3);
3157     foreach ($show as $submission) {
3158         $cm = $modinfo->cms[$submission->cmid];
3159         $link = $CFG->wwwroot.'/mod/assignment/view.php?id='.$cm->id;
3160         print_recent_activity_note($submission->timemodified, $submission, $cm->name, $link, false, $viewfullnames);
3161     }
3163     return true;
3167 /**
3168  * Returns all assignments since a given time in specified forum.
3169  */
3170 function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0)  {
3171     global $CFG, $COURSE, $USER, $DB;
3173     if ($COURSE->id == $courseid) {
3174         $course = $COURSE;
3175     } else {
3176         $course = $DB->get_record('course', array('id'=>$courseid));
3177     }
3179     $modinfo =& get_fast_modinfo($course);
3181     $cm = $modinfo->cms[$cmid];
3183     $params = array();
3184     if ($userid) {
3185         $userselect = "AND u.id = :userid";
3186         $params['userid'] = $userid;
3187     } else {
3188         $userselect = "";
3189     }
3191     if ($groupid) {
3192         $groupselect = "AND gm.groupid = :groupid";
3193         $groupjoin   = "JOIN {groups_members} gm ON  gm.userid=u.id";
3194         $params['groupid'] = $groupid;
3195     } else {
3196         $groupselect = "";
3197         $groupjoin   = "";
3198     }
3200     $params['cminstance'] = $cm->instance;
3201     $params['timestart'] = $timestart;
3203     $userfields = user_picture::fields('u', null, 'userid');
3205     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified,
3206                                                      $userfields
3207                                                 FROM {assignment_submissions} asb
3208                                                 JOIN {assignment} a      ON a.id = asb.assignment
3209                                                 JOIN {user} u            ON u.id = asb.userid
3210                                           $groupjoin
3211                                                WHERE asb.timemodified > :timestart AND a.id = :cminstance
3212                                                      $userselect $groupselect
3213                                             ORDER BY asb.timemodified ASC", $params)) {
3214          return;
3215     }
3217     $groupmode       = groups_get_activity_groupmode($cm, $course);
3218     $cm_context      = get_context_instance(CONTEXT_MODULE, $cm->id);
3219     $grader          = has_capability('moodle/grade:viewall', $cm_context);
3220     $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
3221     $viewfullnames   = has_capability('moodle/site:viewfullnames', $cm_context);
3223     if (is_null($modinfo->groups)) {
3224         $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
3225     }
3227     $show = array();
3229     foreach($submissions as $submission) {
3230         if ($submission->userid == $USER->id) {
3231             $show[] = $submission;
3232             continue;
3233         }
3234         // the act of submitting of assignment may be considered private - only graders will see it if specified
3235         if (empty($CFG->assignment_showrecentsubmissions)) {
3236             if (!$grader) {
3237                 continue;
3238             }
3239         }
3241         if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
3242             if (isguestuser()) {
3243                 // shortcut - guest user does not belong into any group
3244                 continue;
3245             }
3247             // this will be slow - show only users that share group with me in this cm
3248             if (empty($modinfo->groups[$cm->id])) {
3249                 continue;
3250             }
3251             $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
3252             if (is_array($usersgroups)) {
3253                 $usersgroups = array_keys($usersgroups);
3254                 $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
3255                 if (empty($intersect)) {
3256                     continue;
3257                 }
3258             }
3259         }
3260         $show[] = $submission;
3261     }
3263     if (empty($show)) {
3264         return;
3265     }
3267     if ($grader) {
3268         require_once($CFG->libdir.'/gradelib.php');
3269         $userids = array();
3270         foreach ($show as $id=>$submission) {
3271             $userids[] = $submission->userid;
3273         }
3274         $grades = grade_get_grades($courseid, 'mod', 'assignment', $cm->instance, $userids);
3275     }
3277     $aname = format_string($cm->name,true);
3278     foreach ($show as $submission) {
3279         $tmpactivity = new stdClass();
3281         $tmpactivity->type         = 'assignment';
3282         $tmpactivity->cmid         = $cm->id;
3283         $tmpactivity->name         = $aname;
3284         $tmpactivity->sectionnum   = $cm->sectionnum;
3285         $tmpactivity->timestamp    = $submission->timemodified;
3287         if ($grader) {
3288             $tmpactivity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
3289         }
3291         $userfields = explode(',', user_picture::fields());
3292         foreach ($userfields as $userfield) {
3293             if ($userfield == 'id') {
3294                 $tmpactivity->user->{$userfield} = $submission->userid; // aliased in SQL above
3295             } else {
3296                 $tmpactivity->user->{$userfield} = $submission->{$userfield};
3297             }
3298         }
3299         $tmpactivity->user->fullname = fullname($submission, $viewfullnames);
3301         $activities[$index++] = $tmpactivity;
3302     }
3304     return;
3307 /**
3308  * Print recent activity from all assignments in a given course
3309  *
3310  * This is used by course/recent.php
3311  */
3312 function assignment_print_recent_mod_activity($activity, $courseid, $detail, $modnames)  {
3313     global $CFG, $OUTPUT;
3315     echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
3317     echo "<tr><td class=\"userpicture\" valign=\"top\">";
3318     echo $OUTPUT->user_picture($activity->user);
3319     echo "</td><td>";
3321     if ($detail) {
3322         $modname = $modnames[$activity->type];
3323         echo '<div class="title">';
3324         echo "<img src=\"" . $OUTPUT->pix_url('icon', 'assignment') . "\" ".
3325              "class=\"icon\" alt=\"$modname\">";
3326         echo "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id={$activity->cmid}\">{$activity->name}</a>";
3327         echo '</div>';
3328     }
3330     if (isset($activity->grade)) {
3331         echo '<div class="grade">';
3332         echo get_string('grade').': ';
3333         echo $activity->grade;
3334         echo '</div>';
3335