weekly release 2.2dev
[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;
268         require_once($CFG->libdir.'/gradelib.php');
270         if (!is_enrolled($this->context, $USER, 'mod/assignment:view')) {
271             // can not submit assignments -> no feedback
272             return;
273         }
275         if (!$submission) { /// Get submission for this assignment
276             $submission = $this->get_submission($USER->id);
277         }
278         // Check the user can submit
279         $cansubmit = has_capability('mod/assignment:submit', $this->context, $USER->id, false);
280         // If not then check if the user still has the view cap and has a previous submission
281         $cansubmit = $cansubmit || (!empty($submission) && has_capability('mod/assignment:view', $this->context, $USER->id, false));
283         if (!$cansubmit) {
284             // can not submit assignments -> no feedback
285             return;
286         }
288         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $USER->id);
289         $item = $grading_info->items[0];
290         $grade = $item->grades[$USER->id];
292         if ($grade->hidden or $grade->grade === false) { // hidden or error
293             return;
294         }
296         if ($grade->grade === null and empty($grade->str_feedback)) {   /// Nothing to show yet
297             return;
298         }
300         $graded_date = $grade->dategraded;
301         $graded_by   = $grade->usermodified;
303     /// We need the teacher info
304         if (!$teacher = $DB->get_record('user', array('id'=>$graded_by))) {
305             print_error('cannotfindteacher');
306         }
308     /// Print the feedback
309         echo $OUTPUT->heading(get_string('feedbackfromteacher', 'assignment', fullname($teacher)));
311         echo '<table cellspacing="0" class="feedback">';
313         echo '<tr>';
314         echo '<td class="left picture">';
315         if ($teacher) {
316             echo $OUTPUT->user_picture($teacher);
317         }
318         echo '</td>';
319         echo '<td class="topic">';
320         echo '<div class="from">';
321         if ($teacher) {
322             echo '<div class="fullname">'.fullname($teacher).'</div>';
323         }
324         echo '<div class="time">'.userdate($graded_date).'</div>';
325         echo '</div>';
326         echo '</td>';
327         echo '</tr>';
329         echo '<tr>';
330         echo '<td class="left side">&nbsp;</td>';
331         echo '<td class="content">';
332         echo '<div class="grade">';
333         echo get_string("grade").': '.$grade->str_long_grade;
334         echo '</div>';
335         echo '<div class="clearer"></div>';
337         echo '<div class="comment">';
338         echo $grade->str_feedback;
339         echo '</div>';
340         echo '</tr>';
342          if ($this->type == 'uploadsingle') { //@TODO: move to overload view_feedback method in the class or is uploadsingle merging into upload?
343             $responsefiles = $this->print_responsefiles($submission->userid, true);
344             if (!empty($responsefiles)) {
345                 echo '<tr>';
346                 echo '<td class="left side">&nbsp;</td>';
347                 echo '<td class="content">';
348                 echo $responsefiles;
349                 echo '</tr>';
350             }
351          }
353         echo '</table>';
354     }
356     /**
357      * Returns a link with info about the state of the assignment submissions
358      *
359      * This is used by view_header to put this link at the top right of the page.
360      * For teachers it gives the number of submitted assignments with a link
361      * For students it gives the time of their submission.
362      * This will be suitable for most assignment types.
363      *
364      * @global object
365      * @global object
366      * @param bool $allgroup print all groups info if user can access all groups, suitable for index.php
367      * @return string
368      */
369     function submittedlink($allgroups=false) {
370         global $USER;
371         global $CFG;
373         $submitted = '';
374         $urlbase = "{$CFG->wwwroot}/mod/assignment/";
376         $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
377         if (has_capability('mod/assignment:grade', $context)) {
378             if ($allgroups and has_capability('moodle/site:accessallgroups', $context)) {
379                 $group = 0;
380             } else {
381                 $group = groups_get_activity_group($this->cm);
382             }
383             if ($this->type == 'offline') {
384                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
385                              get_string('viewfeedback', 'assignment').'</a>';
386             } else if ($count = $this->count_real_submissions($group)) {
387                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
388                              get_string('viewsubmissions', 'assignment', $count).'</a>';
389             } else {
390                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
391                              get_string('noattempts', 'assignment').'</a>';
392             }
393         } else {
394             if (isloggedin()) {
395                 if ($submission = $this->get_submission($USER->id)) {
396                     if ($submission->timemodified) {
397                         if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
398                             $submitted = '<span class="early">'.userdate($submission->timemodified).'</span>';
399                         } else {
400                             $submitted = '<span class="late">'.userdate($submission->timemodified).'</span>';
401                         }
402                     }
403                 }
404             }
405         }
407         return $submitted;
408     }
411     /**
412      * @todo Document this function
413      */
414     function setup_elements(&$mform) {
416     }
418     /**
419      * Any preprocessing needed for the settings form for
420      * this assignment type
421      *
422      * @param array $default_values - array to fill in with the default values
423      *      in the form 'formelement' => 'value'
424      * @param object $form - the form that is to be displayed
425      * @return none
426      */
427     function form_data_preprocessing(&$default_values, $form) {
428     }
430     /**
431      * Any extra validation checks needed for the settings
432      * form for this assignment type
433      *
434      * See lib/formslib.php, 'validation' function for details
435      */
436     function form_validation($data, $files) {
437         return array();
438     }
440     /**
441      * Create a new assignment activity
442      *
443      * Given an object containing all the necessary data,
444      * (defined by the form in mod_form.php) this function
445      * will create a new instance and return the id number
446      * of the new instance.
447      * The due data is added to the calendar
448      * This is common to all assignment types.
449      *
450      * @global object
451      * @global object
452      * @param object $assignment The data from the form on mod_form.php
453      * @return int The id of the assignment
454      */
455     function add_instance($assignment) {
456         global $COURSE, $DB;
458         $assignment->timemodified = time();
459         $assignment->courseid = $assignment->course;
461         $returnid = $DB->insert_record("assignment", $assignment);
462         $assignment->id = $returnid;
464         if ($assignment->timedue) {
465             $event = new stdClass();
466             $event->name        = $assignment->name;
467             $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
468             $event->courseid    = $assignment->course;
469             $event->groupid     = 0;
470             $event->userid      = 0;
471             $event->modulename  = 'assignment';
472             $event->instance    = $returnid;
473             $event->eventtype   = 'due';
474             $event->timestart   = $assignment->timedue;
475             $event->timeduration = 0;
477             calendar_event::create($event);
478         }
480         assignment_grade_item_update($assignment);
482         return $returnid;
483     }
485     /**
486      * Deletes an assignment activity
487      *
488      * Deletes all database records, files and calendar events for this assignment.
489      *
490      * @global object
491      * @global object
492      * @param object $assignment The assignment to be deleted
493      * @return boolean False indicates error
494      */
495     function delete_instance($assignment) {
496         global $CFG, $DB;
498         $assignment->courseid = $assignment->course;
500         $result = true;
502         // now get rid of all files
503         $fs = get_file_storage();
504         if ($cm = get_coursemodule_from_instance('assignment', $assignment->id)) {
505             $context = get_context_instance(CONTEXT_MODULE, $cm->id);
506             $fs->delete_area_files($context->id);
507         }
509         if (! $DB->delete_records('assignment_submissions', array('assignment'=>$assignment->id))) {
510             $result = false;
511         }
513         if (! $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
514             $result = false;
515         }
517         if (! $DB->delete_records('assignment', array('id'=>$assignment->id))) {
518             $result = false;
519         }
520         $mod = $DB->get_field('modules','id',array('name'=>'assignment'));
522         assignment_grade_item_delete($assignment);
524         return $result;
525     }
527     /**
528      * Updates a new assignment activity
529      *
530      * Given an object containing all the necessary data,
531      * (defined by the form in mod_form.php) this function
532      * will update the assignment instance and return the id number
533      * The due date is updated in the calendar
534      * This is common to all assignment types.
535      *
536      * @global object
537      * @global object
538      * @param object $assignment The data from the form on mod_form.php
539      * @return bool success
540      */
541     function update_instance($assignment) {
542         global $COURSE, $DB;
544         $assignment->timemodified = time();
546         $assignment->id = $assignment->instance;
547         $assignment->courseid = $assignment->course;
549         $DB->update_record('assignment', $assignment);
551         if ($assignment->timedue) {
552             $event = new stdClass();
554             if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
556                 $event->name        = $assignment->name;
557                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
558                 $event->timestart   = $assignment->timedue;
560                 $calendarevent = calendar_event::load($event->id);
561                 $calendarevent->update($event);
562             } else {
563                 $event = new stdClass();
564                 $event->name        = $assignment->name;
565                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
566                 $event->courseid    = $assignment->course;
567                 $event->groupid     = 0;
568                 $event->userid      = 0;
569                 $event->modulename  = 'assignment';
570                 $event->instance    = $assignment->id;
571                 $event->eventtype   = 'due';
572                 $event->timestart   = $assignment->timedue;
573                 $event->timeduration = 0;
575                 calendar_event::create($event);
576             }
577         } else {
578             $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id));
579         }
581         // get existing grade item
582         assignment_grade_item_update($assignment);
584         return true;
585     }
587     /**
588      * Update grade item for this submission.
589      */
590     function update_grade($submission) {
591         assignment_update_grades($this->assignment, $submission->userid);
592     }
594     /**
595      * Top-level function for handling of submissions called by submissions.php
596      *
597      * This is for handling the teacher interaction with the grading interface
598      * This should be suitable for most assignment types.
599      *
600      * @global object
601      * @param string $mode Specifies the kind of teacher interaction taking place
602      */
603     function submissions($mode) {
604         ///The main switch is changed to facilitate
605         ///1) Batch fast grading
606         ///2) Skip to the next one on the popup
607         ///3) Save and Skip to the next one on the popup
609         //make user global so we can use the id
610         global $USER, $OUTPUT, $DB, $PAGE;
612         $mailinfo = optional_param('mailinfo', null, PARAM_BOOL);
614         if (optional_param('next', null, PARAM_BOOL)) {
615             $mode='next';
616         }
617         if (optional_param('saveandnext', null, PARAM_BOOL)) {
618             $mode='saveandnext';
619         }
621         if (is_null($mailinfo)) {
622             if (optional_param('sesskey', null, PARAM_BOOL)) {
623                 set_user_preference('assignment_mailinfo', $mailinfo);
624             } else {
625                 $mailinfo = get_user_preferences('assignment_mailinfo', 0);
626             }
627         } else {
628             set_user_preference('assignment_mailinfo', $mailinfo);
629         }
631         switch ($mode) {
632             case 'grade':                         // We are in a main window grading
633                 if ($submission = $this->process_feedback()) {
634                     $this->display_submissions(get_string('changessaved'));
635                 } else {
636                     $this->display_submissions();
637                 }
638                 break;
640             case 'single':                        // We are in a main window displaying one submission
641                 if ($submission = $this->process_feedback()) {
642                     $this->display_submissions(get_string('changessaved'));
643                 } else {
644                     $this->display_submission();
645                 }
646                 break;
648             case 'all':                          // Main window, display everything
649                 $this->display_submissions();
650                 break;
652             case 'fastgrade':
653                 ///do the fast grading stuff  - this process should work for all 3 subclasses
654                 $grading    = false;
655                 $commenting = false;
656                 $col        = false;
657                 if (isset($_POST['submissioncomment'])) {
658                     $col = 'submissioncomment';
659                     $commenting = true;
660                 }
661                 if (isset($_POST['menu'])) {
662                     $col = 'menu';
663                     $grading = true;
664                 }
665                 if (!$col) {
666                     //both submissioncomment and grade columns collapsed..
667                     $this->display_submissions();
668                     break;
669                 }
671                 foreach ($_POST[$col] as $id => $unusedvalue){
673                     $id = (int)$id; //clean parameter name
675                     $this->process_outcomes($id);
677                     if (!$submission = $this->get_submission($id)) {
678                         $submission = $this->prepare_new_submission($id);
679                         $newsubmission = true;
680                     } else {
681                         $newsubmission = false;
682                     }
683                     unset($submission->data1);  // Don't need to update this.
684                     unset($submission->data2);  // Don't need to update this.
686                     //for fast grade, we need to check if any changes take place
687                     $updatedb = false;
689                     if ($grading) {
690                         $grade = $_POST['menu'][$id];
691                         $updatedb = $updatedb || ($submission->grade != $grade);
692                         $submission->grade = $grade;
693                     } else {
694                         if (!$newsubmission) {
695                             unset($submission->grade);  // Don't need to update this.
696                         }
697                     }
698                     if ($commenting) {
699                         $commentvalue = trim($_POST['submissioncomment'][$id]);
700                         $updatedb = $updatedb || ($submission->submissioncomment != $commentvalue);
701                         $submission->submissioncomment = $commentvalue;
702                     } else {
703                         unset($submission->submissioncomment);  // Don't need to update this.
704                     }
706                     $submission->teacher    = $USER->id;
707                     if ($updatedb) {
708                         $submission->mailed = (int)(!$mailinfo);
709                     }
711                     $submission->timemarked = time();
713                     //if it is not an update, we don't change the last modified time etc.
714                     //this will also not write into database if no submissioncomment and grade is entered.
716                     if ($updatedb){
717                         if ($newsubmission) {
718                             if (!isset($submission->submissioncomment)) {
719                                 $submission->submissioncomment = '';
720                             }
721                             $sid = $DB->insert_record('assignment_submissions', $submission);
722                             $submission->id = $sid;
723                         } else {
724                             $DB->update_record('assignment_submissions', $submission);
725                         }
727                         // trigger grade event
728                         $this->update_grade($submission);
730                         //add to log only if updating
731                         add_to_log($this->course->id, 'assignment', 'update grades',
732                                    'submissions.php?id='.$this->cm->id.'&user='.$submission->userid,
733                                    $submission->userid, $this->cm->id);
734                     }
736                 }
738                 $message = $OUTPUT->notification(get_string('changessaved'), 'notifysuccess');
740                 $this->display_submissions($message);
741                 break;
744             case 'saveandnext':
745                 ///We are in pop up. save the current one and go to the next one.
746                 //first we save the current changes
747                 if ($submission = $this->process_feedback()) {
748                     //print_heading(get_string('changessaved'));
749                     //$extra_javascript = $this->update_main_listing($submission);
750                 }
752             case 'next':
753                 /// We are currently in pop up, but we want to skip to next one without saving.
754                 ///    This turns out to be similar to a single case
755                 /// The URL used is for the next submission.
756                 $offset = required_param('offset', PARAM_INT);
757                 $nextid = required_param('nextid', PARAM_INT);
758                 $id = required_param('id', PARAM_INT);
759                 $offset = (int)$offset+1;
760                 //$this->display_submission($offset+1 , $nextid);
761                 redirect('submissions.php?id='.$id.'&userid='. $nextid . '&mode=single&offset='.$offset);
762                 break;
764             case 'singlenosave':
765                 $this->display_submission();
766                 break;
768             default:
769                 echo "something seriously is wrong!!";
770                 break;
771         }
772     }
774     /**
775      * Helper method updating the listing on the main script from popup using javascript
776      *
777      * @global object
778      * @global object
779      * @param $submission object The submission whose data is to be updated on the main page
780      */
781     function update_main_listing($submission) {
782         global $SESSION, $CFG, $OUTPUT;
784         $output = '';
786         $perpage = get_user_preferences('assignment_perpage', 10);
788         $quickgrade = get_user_preferences('assignment_quickgrade', 0);
790         /// Run some Javascript to try and update the parent page
791         $output .= '<script type="text/javascript">'."\n<!--\n";
792         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['submissioncomment'])) {
793             if ($quickgrade){
794                 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid.'").value="'
795                 .trim($submission->submissioncomment).'";'."\n";
796              } else {
797                 $output.= 'opener.document.getElementById("com'.$submission->userid.
798                 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment)), 15)."\";\n";
799             }
800         }
802         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['grade'])) {
803             //echo optional_param('menuindex');
804             if ($quickgrade){
805                 $output.= 'opener.document.getElementById("menumenu'.$submission->userid.
806                 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT).'";'."\n";
807             } else {
808                 $output.= 'opener.document.getElementById("g'.$submission->userid.'").innerHTML="'.
809                 $this->display_grade($submission->grade)."\";\n";
810             }
811         }
812         //need to add student's assignments in there too.
813         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemodified']) &&
814             $submission->timemodified) {
815             $output.= 'opener.document.getElementById("ts'.$submission->userid.
816                  '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid)).userdate($submission->timemodified)."\";\n";
817         }
819         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemarked']) &&
820             $submission->timemarked) {
821             $output.= 'opener.document.getElementById("tt'.$submission->userid.
822                  '").innerHTML="'.userdate($submission->timemarked)."\";\n";
823         }
825         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['status'])) {
826             $output.= 'opener.document.getElementById("up'.$submission->userid.'").className="s1";';
827             $buttontext = get_string('update');
828             $url = new moodle_url('/mod/assignment/submissions.php', array(
829                     'id' => $this->cm->id,
830                     'userid' => $submission->userid,
831                     'mode' => 'single',
832                     'offset' => (optional_param('offset', '', PARAM_INT)-1)));
833             $button = $OUTPUT->action_link($url, $buttontext, new popup_action('click', $url, 'grade'.$submission->userid, array('height' => 450, 'width' => 700)), array('ttile'=>$buttontext));
835             $output .= 'opener.document.getElementById("up'.$submission->userid.'").innerHTML="'.addslashes_js($button).'";';
836         }
838         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $submission->userid);
840         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['finalgrade'])) {
841             $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid.
842             '").innerHTML="'.$grading_info->items[0]->grades[$submission->userid]->str_grade.'";'."\n";
843         }
845         if (!empty($CFG->enableoutcomes) and empty($SESSION->flextable['mod-assignment-submissions']->collapse['outcome'])) {
847             if (!empty($grading_info->outcomes)) {
848                 foreach($grading_info->outcomes as $n=>$outcome) {
849                     if ($outcome->grades[$submission->userid]->locked) {
850                         continue;
851                     }
853                     if ($quickgrade){
854                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.
855                         '").selectedIndex="'.$outcome->grades[$submission->userid]->grade.'";'."\n";
857                     } else {
858                         $options = make_grades_menu(-$outcome->scaleid);
859                         $options[0] = get_string('nooutcome', 'grades');
860                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.'").innerHTML="'.$options[$outcome->grades[$submission->userid]->grade]."\";\n";
861                     }
863                 }
864             }
865         }
867         $output .= "\n-->\n</script>";
868         return $output;
869     }
871     /**
872      *  Return a grade in user-friendly form, whether it's a scale or not
873      *
874      * @global object
875      * @param mixed $grade
876      * @return string User-friendly representation of grade
877      */
878     function display_grade($grade) {
879         global $DB;
881         static $scalegrades = array();   // Cache scales for each assignment - they might have different scales!!
883         if ($this->assignment->grade >= 0) {    // Normal number
884             if ($grade == -1) {
885                 return '-';
886             } else {
887                 return $grade.' / '.$this->assignment->grade;
888             }
890         } else {                                // Scale
891             if (empty($scalegrades[$this->assignment->id])) {
892                 if ($scale = $DB->get_record('scale', array('id'=>-($this->assignment->grade)))) {
893                     $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
894                 } else {
895                     return '-';
896                 }
897             }
898             if (isset($scalegrades[$this->assignment->id][$grade])) {
899                 return $scalegrades[$this->assignment->id][$grade];
900             }
901             return '-';
902         }
903     }
905     /**
906      *  Display a single submission, ready for grading on a popup window
907      *
908      * This default method prints the teacher info and submissioncomment box at the top and
909      * the student info and submission at the bottom.
910      * This method also fetches the necessary data in order to be able to
911      * provide a "Next submission" button.
912      * Calls preprocess_submission() to give assignment type plug-ins a chance
913      * to process submissions before they are graded
914      * This method gets its arguments from the page parameters userid and offset
915      *
916      * @global object
917      * @global object
918      * @param string $extra_javascript
919      */
920     function display_submission($offset=-1,$userid =-1, $display=true) {
921         global $CFG, $DB, $PAGE, $OUTPUT;
922         require_once($CFG->libdir.'/gradelib.php');
923         require_once($CFG->libdir.'/tablelib.php');
924         require_once("$CFG->dirroot/repository/lib.php");
925         if ($userid==-1) {
926             $userid = required_param('userid', PARAM_INT);
927         }
928         if ($offset==-1) {
929             $offset = required_param('offset', PARAM_INT);//offset for where to start looking for student.
930         }
931         $filter = optional_param('filter', 0, PARAM_INT);
933         if (!$user = $DB->get_record('user', array('id'=>$userid))) {
934             print_error('nousers');
935         }
937         if (!$submission = $this->get_submission($user->id)) {
938             $submission = $this->prepare_new_submission($userid);
939         }
940         if ($submission->timemodified > $submission->timemarked) {
941             $subtype = 'assignmentnew';
942         } else {
943             $subtype = 'assignmentold';
944         }
946         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
947         $gradingdisabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
949     /// construct SQL, using current offset to find the data of the next student
950         $course     = $this->course;
951         $assignment = $this->assignment;
952         $cm         = $this->cm;
953         $context    = get_context_instance(CONTEXT_MODULE, $cm->id);
955         //reset filter to all for offline assignment
956         if ($assignment->assignmenttype == 'offline' && $filter == self::FILTER_SUBMITTED) {
957             $filter = self::FILTER_ALL;
958         }
959         /// Get all ppl that can submit assignments
961         $currentgroup = groups_get_activity_group($cm);
962         $users = get_enrolled_users($context, 'mod/assignment:view', $currentgroup, 'u.id');
963         if ($users) {
964             $users = array_keys($users);
965             // if groupmembersonly used, remove users who are not in any group
966             if (!empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
967                 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
968                     $users = array_intersect($users, array_keys($groupingusers));
969                 }
970             }
971         }
973         $nextid = 0;
974         $where = '';
975         if($filter == self::FILTER_SUBMITTED) {
976             $where .= 's.timemodified > 0 AND ';
977         } else if($filter == self::FILTER_REQUIRE_GRADING) {
978             $where .= 's.timemarked < s.timemodified AND ';
979         }
981         if ($users) {
982             $userfields = user_picture::fields('u', array('lastaccess'));
983             $select = "SELECT $userfields,
984                               s.id AS submissionid, s.grade, s.submissioncomment,
985                               s.timemodified, s.timemarked ";
986             $sql = 'FROM {user} u '.
987                    'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
988                    AND s.assignment = '.$this->assignment->id.' '.
989                    'WHERE '.$where.'u.id IN ('.implode(',', $users).') ';
991             if ($sort = flexible_table::get_sort_for_table('mod-assignment-submissions')) {
992                 $sort = 'ORDER BY '.$sort.' ';
993             }
994             $auser = $DB->get_records_sql($select.$sql.$sort, null, $offset, 2);
996             if (is_array($auser) && count($auser)>1) {
997                 $nextuser = next($auser);
998             /// Calculate user status
999                 $nextuser->status = ($nextuser->timemarked > 0) && ($nextuser->timemarked >= $nextuser->timemodified);
1000                 $nextid = $nextuser->id;
1001             }
1002         }
1004         if ($submission->teacher) {
1005             $teacher = $DB->get_record('user', array('id'=>$submission->teacher));
1006         } else {
1007             global $USER;
1008             $teacher = $USER;
1009         }
1011         $this->preprocess_submission($submission);
1013         $mformdata = new stdClass();
1014         $mformdata->context = $this->context;
1015         $mformdata->maxbytes = $this->course->maxbytes;
1016         $mformdata->courseid = $this->course->id;
1017         $mformdata->teacher = $teacher;
1018         $mformdata->assignment = $assignment;
1019         $mformdata->submission = $submission;
1020         $mformdata->lateness = $this->display_lateness($submission->timemodified);
1021         $mformdata->auser = $auser;
1022         $mformdata->user = $user;
1023         $mformdata->offset = $offset;
1024         $mformdata->userid = $userid;
1025         $mformdata->cm = $this->cm;
1026         $mformdata->grading_info = $grading_info;
1027         $mformdata->enableoutcomes = $CFG->enableoutcomes;
1028         $mformdata->grade = $this->assignment->grade;
1029         $mformdata->gradingdisabled = $gradingdisabled;
1030         $mformdata->nextid = $nextid;
1031         $mformdata->submissioncomment= $submission->submissioncomment;
1032         $mformdata->submissioncommentformat= FORMAT_HTML;
1033         $mformdata->submission_content= $this->print_user_files($user->id,true);
1034         $mformdata->filter = $filter;
1035         $mformdata->mailinfo = get_user_preferences('assignment_mailinfo', 0);
1036          if ($assignment->assignmenttype == 'upload') {
1037             $mformdata->fileui_options = array('subdirs'=>1, 'maxbytes'=>$assignment->maxbytes, 'maxfiles'=>$assignment->var1, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL);
1038         } elseif ($assignment->assignmenttype == 'uploadsingle') {
1039             $mformdata->fileui_options = array('subdirs'=>0, 'maxbytes'=>$CFG->userquota, 'maxfiles'=>1, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL);
1040         }
1042         $submitform = new mod_assignment_grading_form( null, $mformdata );
1044          if (!$display) {
1045             $ret_data = new stdClass();
1046             $ret_data->mform = $submitform;
1047             $ret_data->fileui_options = $mformdata->fileui_options;
1048             return $ret_data;
1049         }
1051         if ($submitform->is_cancelled()) {
1052             redirect('submissions.php?id='.$this->cm->id);
1053         }
1055         $submitform->set_data($mformdata);
1057         $PAGE->set_title($this->course->fullname . ': ' .get_string('feedback', 'assignment').' - '.fullname($user, true));
1058         $PAGE->set_heading($this->course->fullname);
1059         $PAGE->navbar->add(get_string('submissions', 'assignment'), new moodle_url('/mod/assignment/submissions.php', array('id'=>$cm->id)));
1060         $PAGE->navbar->add(fullname($user, true));
1062         echo $OUTPUT->header();
1063         echo $OUTPUT->heading(get_string('feedback', 'assignment').': '.fullname($user, true));
1065         // display mform here...
1066         $submitform->display();
1068         $customfeedback = $this->custom_feedbackform($submission, true);
1069         if (!empty($customfeedback)) {
1070             echo $customfeedback;
1071         }
1073         echo $OUTPUT->footer();
1074     }
1076     /**
1077      *  Preprocess submission before grading
1078      *
1079      * Called by display_submission()
1080      * The default type does nothing here.
1081      *
1082      * @param object $submission The submission object
1083      */
1084     function preprocess_submission(&$submission) {
1085     }
1087     /**
1088      *  Display all the submissions ready for grading
1089      *
1090      * @global object
1091      * @global object
1092      * @global object
1093      * @global object
1094      * @param string $message
1095      * @return bool|void
1096      */
1097     function display_submissions($message='') {
1098         global $CFG, $DB, $USER, $DB, $OUTPUT, $PAGE;
1099         require_once($CFG->libdir.'/gradelib.php');
1101         /* first we check to see if the form has just been submitted
1102          * to request user_preference updates
1103          */
1105        $filters = array(self::FILTER_ALL             => get_string('all'),
1106                         self::FILTER_REQUIRE_GRADING => get_string('requiregrading', 'assignment'));
1108         $updatepref = optional_param('updatepref', 0, PARAM_BOOL);
1109         if ($updatepref) {
1110             $perpage = optional_param('perpage', 10, PARAM_INT);
1111             $perpage = ($perpage <= 0) ? 10 : $perpage ;
1112             $filter = optional_param('filter', 0, PARAM_INT);
1113             set_user_preference('assignment_perpage', $perpage);
1114             set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
1115             set_user_preference('assignment_filter', $filter);
1116         }
1118         /* next we get perpage and quickgrade (allow quick grade) params
1119          * from database
1120          */
1121         $perpage    = get_user_preferences('assignment_perpage', 10);
1122         $quickgrade = get_user_preferences('assignment_quickgrade', 0);
1123         $filter = get_user_preferences('assignment_filter', 0);
1124         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);
1126         if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
1127             $uses_outcomes = true;
1128         } else {
1129             $uses_outcomes = false;
1130         }
1132         $page    = optional_param('page', 0, PARAM_INT);
1133         $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
1135     /// Some shortcuts to make the code read better
1137         $course     = $this->course;
1138         $assignment = $this->assignment;
1139         $cm         = $this->cm;
1140         $hassubmission = false;
1142         // reset filter to all for offline assignment only.
1143         if ($assignment->assignmenttype == 'offline') {
1144             if ($filter == self::FILTER_SUBMITTED) {
1145                 $filter = self::FILTER_ALL;
1146             }
1147         } else {
1148             $filters[self::FILTER_SUBMITTED] = get_string('submitted', 'assignment');
1149         }
1151         $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
1152         add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->cm->id, $this->assignment->id, $this->cm->id);
1154         $PAGE->set_title(format_string($this->assignment->name,true));
1155         $PAGE->set_heading($this->course->fullname);
1156         echo $OUTPUT->header();
1158         echo '<div class="usersubmissions">';
1160         //hook to allow plagiarism plugins to update status/print links.
1161         plagiarism_update_status($this->course, $this->cm);
1163         $course_context = get_context_instance(CONTEXT_COURSE, $course->id);
1164         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
1165             echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">'
1166                 . get_string('seeallcoursegrades', 'grades') . '</a></div>';
1167         }
1169         if (!empty($message)) {
1170             echo $message;   // display messages here if any
1171         }
1173         $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1175     /// Check to see if groups are being used in this assignment
1177         /// find out current groups mode
1178         $groupmode = groups_get_activity_groupmode($cm);
1179         $currentgroup = groups_get_activity_group($cm, true);
1180         groups_print_activity_menu($cm, $CFG->wwwroot . '/mod/assignment/submissions.php?id=' . $this->cm->id);
1182         /// Print quickgrade form around the table
1183         if ($quickgrade) {
1184             $formattrs = array();
1185             $formattrs['action'] = new moodle_url('/mod/assignment/submissions.php');
1186             $formattrs['id'] = 'fastg';
1187             $formattrs['method'] = 'post';
1189             echo html_writer::start_tag('form', $formattrs);
1190             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'id',      'value'=> $this->cm->id));
1191             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'mode',    'value'=> 'fastgrade'));
1192             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'page',    'value'=> $page));
1193             echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=> sesskey()));
1194         }
1196         /// Get all ppl that are allowed to submit assignments
1197         list($esql, $params) = get_enrolled_sql($context, 'mod/assignment:submit', $currentgroup);
1199         if ($filter == self::FILTER_ALL) {
1200             $sql = "SELECT u.id FROM {user} u ".
1201                    "LEFT JOIN ($esql) eu ON eu.id=u.id ".
1202                    "WHERE u.deleted = 0 AND eu.id=u.id ";
1203         } else {
1204             $wherefilter = ' AND s.assignment = '. $this->assignment->id;
1205             $assignmentsubmission = "LEFT JOIN {assignment_submissions} s ON (u.id = s.userid) ";
1206             if($filter == self::FILTER_SUBMITTED) {
1207                 $wherefilter .= ' AND s.timemodified > 0 ';
1208             } else if($filter == self::FILTER_REQUIRE_GRADING && $assignment->assignmenttype != 'offline') {
1209                 $wherefilter .= ' AND s.timemarked < s.timemodified ';
1210             } else { // require grading for offline assignment
1211                 $assignmentsubmission = "";
1212                 $wherefilter = "";
1213             }
1215             $sql = "SELECT u.id FROM {user} u ".
1216                    "LEFT JOIN ($esql) eu ON eu.id=u.id ".
1217                    $assignmentsubmission.
1218                    "WHERE u.deleted = 0 AND eu.id=u.id ".
1219                    $wherefilter;
1220         }
1222         $users = $DB->get_records_sql($sql, $params);
1223         if (!empty($users)) {
1224             if($assignment->assignmenttype == 'offline' && $filter == self::FILTER_REQUIRE_GRADING) {
1225                 //remove users who has submitted their assignment
1226                 foreach ($this->get_submissions() as $submission) {
1227                     if (array_key_exists($submission->userid, $users)) {
1228                         unset($users[$submission->userid]);
1229                     }
1230                 }
1231             }
1232             $users = array_keys($users);
1233         }
1235         // if groupmembersonly used, remove users who are not in any group
1236         if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
1237             if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1238                 $users = array_intersect($users, array_keys($groupingusers));
1239             }
1240         }
1242         $tablecolumns = array('picture', 'fullname', 'grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade');
1243         if ($uses_outcomes) {
1244             $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
1245         }
1247         $tableheaders = array('',
1248                               get_string('fullnameuser'),
1249                               get_string('grade'),
1250                               get_string('comment', 'assignment'),
1251                               get_string('lastmodified').' ('.get_string('submission', 'assignment').')',
1252                               get_string('lastmodified').' ('.get_string('grade').')',
1253                               get_string('status'),
1254                               get_string('finalgrade', 'grades'));
1255         if ($uses_outcomes) {
1256             $tableheaders[] = get_string('outcome', 'grades');
1257         }
1259         require_once($CFG->libdir.'/tablelib.php');
1260         $table = new flexible_table('mod-assignment-submissions');
1262         $table->define_columns($tablecolumns);
1263         $table->define_headers($tableheaders);
1264         $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;currentgroup='.$currentgroup);
1266         $table->sortable(true, 'lastname');//sorted by lastname by default
1267         $table->collapsible(true);
1268         $table->initialbars(true);
1270         $table->column_suppress('picture');
1271         $table->column_suppress('fullname');
1273         $table->column_class('picture', 'picture');
1274         $table->column_class('fullname', 'fullname');
1275         $table->column_class('grade', 'grade');
1276         $table->column_class('submissioncomment', 'comment');
1277         $table->column_class('timemodified', 'timemodified');
1278         $table->column_class('timemarked', 'timemarked');
1279         $table->column_class('status', 'status');
1280         $table->column_class('finalgrade', 'finalgrade');
1281         if ($uses_outcomes) {
1282             $table->column_class('outcome', 'outcome');
1283         }
1285         $table->set_attribute('cellspacing', '0');
1286         $table->set_attribute('id', 'attempts');
1287         $table->set_attribute('class', 'submissions');
1288         $table->set_attribute('width', '100%');
1290         $table->no_sorting('finalgrade');
1291         $table->no_sorting('outcome');
1293         // Start working -- this is necessary as soon as the niceties are over
1294         $table->setup();
1296         /// Construct the SQL
1297         list($where, $params) = $table->get_sql_where();
1298         if ($where) {
1299             $where .= ' AND ';
1300         }
1302         if ($filter == self::FILTER_SUBMITTED) {
1303            $where .= 's.timemodified > 0 AND ';
1304         } else if($filter == self::FILTER_REQUIRE_GRADING) {
1305             $where = '';
1306             if ($assignment->assignmenttype != 'offline') {
1307                $where .= 's.timemarked < s.timemodified AND ';
1308             }
1309         }
1311         if ($sort = $table->get_sql_sort()) {
1312             $sort = ' ORDER BY '.$sort;
1313         }
1315         $ufields = user_picture::fields('u');
1316         if (!empty($users)) {
1317             $select = "SELECT $ufields,
1318                               s.id AS submissionid, s.grade, s.submissioncomment,
1319                               s.timemodified, s.timemarked ";
1320             $sql = 'FROM {user} u '.
1321                    'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1322                     AND s.assignment = '.$this->assignment->id.' '.
1323                    'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1325             $ausers = $DB->get_records_sql($select.$sql.$sort, $params, $table->get_page_start(), $table->get_page_size());
1327             $table->pagesize($perpage, count($users));
1329             ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1330             $offset = $page * $perpage;
1331             $strupdate = get_string('update');
1332             $strgrade  = get_string('grade');
1333             $grademenu = make_grades_menu($this->assignment->grade);
1335             if ($ausers !== false) {
1336                 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
1337                 $endposition = $offset + $perpage;
1338                 $currentposition = 0;
1339                 foreach ($ausers as $auser) {
1340                     if ($currentposition == $offset && $offset < $endposition) {
1341                         $final_grade = $grading_info->items[0]->grades[$auser->id];
1342                         $grademax = $grading_info->items[0]->grademax;
1343                         $final_grade->formatted_grade = round($final_grade->grade,2) .' / ' . round($grademax,2);
1344                         $locked_overridden = 'locked';
1345                         if ($final_grade->overridden) {
1346                             $locked_overridden = 'overridden';
1347                         }
1349                     /// Calculate user status
1350                         $auser->status = ($auser->timemarked > 0) && ($auser->timemarked >= $auser->timemodified);
1351                         $picture = $OUTPUT->user_picture($auser);
1353                         if (empty($auser->submissionid)) {
1354                             $auser->grade = -1; //no submission yet
1355                         }
1357                         if (!empty($auser->submissionid)) {
1358                             $hassubmission = true;
1359                         ///Prints student answer and student modified date
1360                         ///attach file or print link to student answer, depending on the type of the assignment.
1361                         ///Refer to print_student_answer in inherited classes.
1362                             if ($auser->timemodified > 0) {
1363                                 $studentmodified = '<div id="ts'.$auser->id.'">'.$this->print_student_answer($auser->id)
1364                                                  . userdate($auser->timemodified).'</div>';
1365                             } else {
1366                                 $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1367                             }
1368                         ///Print grade, dropdown or text
1369                             if ($auser->timemarked > 0) {
1370                                 $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
1372                                 if ($final_grade->locked or $final_grade->overridden) {
1373                                     $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1374                                 } else if ($quickgrade) {
1375                                     $attributes = array();
1376                                     $attributes['tabindex'] = $tabindex++;
1377                                     $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1378                                     $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
1379                                 } else {
1380                                     $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1381                                 }
1383                             } else {
1384                                 $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1385                                 if ($final_grade->locked or $final_grade->overridden) {
1386                                     $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1387                                 } else if ($quickgrade) {
1388                                     $attributes = array();
1389                                     $attributes['tabindex'] = $tabindex++;
1390                                     $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1391                                     $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1392                                 } else {
1393                                     $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1394                                 }
1395                             }
1396                         ///Print Comment
1397                             if ($final_grade->locked or $final_grade->overridden) {
1398                                 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';
1400                             } else if ($quickgrade) {
1401                                 $comment = '<div id="com'.$auser->id.'">'
1402                                          . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1403                                          . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1404                             } else {
1405                                 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
1406                             }
1407                         } else {
1408                             $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1409                             $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1410                             $status          = '<div id="st'.$auser->id.'">&nbsp;</div>';
1412                             if ($final_grade->locked or $final_grade->overridden) {
1413                                 $grade = '<div id="g'.$auser->id.'">'.$final_grade->formatted_grade . '</div>';
1414                                 $hassubmission = true;
1415                             } else if ($quickgrade) {   // allow editing
1416                                 $attributes = array();
1417                                 $attributes['tabindex'] = $tabindex++;
1418                                 $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1419                                 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1420                                 $hassubmission = true;
1421                             } else {
1422                                 $grade = '<div id="g'.$auser->id.'">-</div>';
1423                             }
1425                             if ($final_grade->locked or $final_grade->overridden) {
1426                                 $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
1427                             } else if ($quickgrade) {
1428                                 $comment = '<div id="com'.$auser->id.'">'
1429                                          . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1430                                          . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1431                             } else {
1432                                 $comment = '<div id="com'.$auser->id.'">&nbsp;</div>';
1433                             }
1434                         }
1436                         if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
1437                             $auser->status = 0;
1438                         } else {
1439                             $auser->status = 1;
1440                         }
1442                         $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
1444                         ///No more buttons, we use popups ;-).
1445                         $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1446                                    . '&amp;userid='.$auser->id.'&amp;mode=single'.'&amp;filter='.$filter.'&amp;offset='.$offset++;
1448                         $button = $OUTPUT->action_link($popup_url, $buttontext);
1450                         $status  = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
1452                         $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';
1454                         $outcomes = '';
1456                         if ($uses_outcomes) {
1458                             foreach($grading_info->outcomes as $n=>$outcome) {
1459                                 $outcomes .= '<div class="outcome"><label>'.$outcome->name.'</label>';
1460                                 $options = make_grades_menu(-$outcome->scaleid);
1462                                 if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
1463                                     $options[0] = get_string('nooutcome', 'grades');
1464                                     $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
1465                                 } else {
1466                                     $attributes = array();
1467                                     $attributes['tabindex'] = $tabindex++;
1468                                     $attributes['id'] = 'outcome_'.$n.'_'.$auser->id;
1469                                     $outcomes .= ' '.html_writer::select($options, 'outcome_'.$n.'['.$auser->id.']', $outcome->grades[$auser->id]->grade, array(0=>get_string('nooutcome', 'grades')), $attributes);
1470                                 }
1471                                 $outcomes .= '</div>';
1472                             }
1473                         }
1475                         $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>';
1476                         $row = array($picture, $userlink, $grade, $comment, $studentmodified, $teachermodified, $status, $finalgrade);
1477                         if ($uses_outcomes) {
1478                             $row[] = $outcomes;
1479                         }
1480                         $table->add_data($row);
1481                     }
1482                     $currentposition++;
1483                 }
1484                 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)
1485                     echo html_writer::start_tag('div', array('class' => 'mod-assignment-download-link'));
1486                     echo html_writer::link(new moodle_url('/mod/assignment/submissions.php', array('id' => $this->cm->id, 'download' => 'zip')), get_string('downloadall', 'assignment'));
1487                     echo html_writer::end_tag('div');
1488                 }
1489                 $table->print_html();  /// Print the whole table
1490             } else {
1491                 if ($filter == self::FILTER_SUBMITTED) {
1492                     echo html_writer::tag('div', get_string('nosubmisson', 'assignment'), array('class'=>'nosubmisson'));
1493                 } else if ($filter == self::FILTER_REQUIRE_GRADING) {
1494                     echo html_writer::tag('div', get_string('norequiregrading', 'assignment'), array('class'=>'norequiregrading'));
1495                 }
1496             }
1497         }
1499         /// Print quickgrade form around the table
1500         if ($quickgrade && $table->started_output && !empty($users)){
1501             $mailinfopref = false;
1502             if (get_user_preferences('assignment_mailinfo', 1)) {
1503                 $mailinfopref = true;
1504             }
1505             $emailnotification =  html_writer::checkbox('mailinfo', 1, $mailinfopref, get_string('enablenotification','assignment'));
1507             $emailnotification .= $OUTPUT->help_icon('enablenotification', 'assignment');
1508             echo html_writer::tag('div', $emailnotification, array('class'=>'emailnotification'));
1510             $savefeedback = html_writer::empty_tag('input', array('type'=>'submit', 'name'=>'fastg', 'value'=>get_string('saveallfeedback', 'assignment')));
1511             echo html_writer::tag('div', $savefeedback, array('class'=>'fastgbutton'));
1513             echo html_writer::end_tag('form');
1514         } else if ($quickgrade) {
1515             echo html_writer::end_tag('form');
1516         }
1518         echo '</div>';
1519         /// End of fast grading form
1521         /// Mini form for setting user preference
1523         $formaction = new moodle_url('/mod/assignment/submissions.php', array('id'=>$this->cm->id));
1524         $mform = new MoodleQuickForm('optionspref', 'post', $formaction, '', array('class'=>'optionspref'));
1526         $mform->addElement('hidden', 'updatepref');
1527         $mform->setDefault('updatepref', 1);
1528         $mform->addElement('header', 'qgprefs', get_string('optionalsettings', 'assignment'));
1529         $mform->addElement('select', 'filter', get_string('show'),  $filters);
1531         $mform->setDefault('filter', $filter);
1533         $mform->addElement('text', 'perpage', get_string('pagesize', 'assignment'), array('size'=>1));
1534         $mform->setDefault('perpage', $perpage);
1536         $mform->addElement('checkbox', 'quickgrade', get_string('quickgrade','assignment'));
1537         $mform->setDefault('quickgrade', $quickgrade);
1538         $mform->addHelpButton('quickgrade', 'quickgrade', 'assignment');
1540         $mform->addElement('submit', 'savepreferences', get_string('savepreferences'));
1542         $mform->display();
1544         echo $OUTPUT->footer();
1545     }
1547     /**
1548      *  Process teacher feedback submission
1549      *
1550      * This is called by submissions() when a grading even has taken place.
1551      * It gets its data from the submitted form.
1552      *
1553      * @global object
1554      * @global object
1555      * @global object
1556      * @return object|bool The updated submission object or false
1557      */
1558     function process_feedback($formdata=null) {
1559         global $CFG, $USER, $DB;
1560         require_once($CFG->libdir.'/gradelib.php');
1562         if (!$feedback = data_submitted() or !confirm_sesskey()) {      // No incoming data?
1563             return false;
1564         }
1566         ///For save and next, we need to know the userid to save, and the userid to go
1567         ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1568         ///as the userid to store
1569         if ((int)$feedback->saveuserid !== -1){
1570             $feedback->userid = $feedback->saveuserid;
1571         }
1573         if (!empty($feedback->cancel)) {          // User hit cancel button
1574             return false;
1575         }
1577         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);
1579         // store outcomes if needed
1580         $this->process_outcomes($feedback->userid);
1582         $submission = $this->get_submission($feedback->userid, true);  // Get or make one
1584         if (!($grading_info->items[0]->grades[$feedback->userid]->locked ||
1585             $grading_info->items[0]->grades[$feedback->userid]->overridden) ) {
1587             $submission->grade      = $feedback->xgrade;
1588             $submission->submissioncomment    = $feedback->submissioncomment_editor['text'];
1589             $submission->teacher    = $USER->id;
1590             $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1591             if (!$mailinfo) {
1592                 $submission->mailed = 1;       // treat as already mailed
1593             } else {
1594                 $submission->mailed = 0;       // Make sure mail goes out (again, even)
1595             }
1596             $submission->timemarked = time();
1598             unset($submission->data1);  // Don't need to update this.
1599             unset($submission->data2);  // Don't need to update this.
1601             if (empty($submission->timemodified)) {   // eg for offline assignments
1602                 // $submission->timemodified = time();
1603             }
1605             $DB->update_record('assignment_submissions', $submission);
1607             // triger grade event
1608             $this->update_grade($submission);
1610             add_to_log($this->course->id, 'assignment', 'update grades',
1611                        'submissions.php?id='.$this->cm->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
1612              if (!is_null($formdata)) {
1613                     if ($this->type == 'upload' || $this->type == 'uploadsingle') {
1614                         $mformdata = $formdata->mform->get_data();
1615                         $mformdata = file_postupdate_standard_filemanager($mformdata, 'files', $formdata->fileui_options, $this->context, 'mod_assignment', 'response', $submission->id);
1616                     }
1617              }
1618         }
1620         return $submission;
1622     }
1624     function process_outcomes($userid) {
1625         global $CFG, $USER;
1627         if (empty($CFG->enableoutcomes)) {
1628             return;
1629         }
1631         require_once($CFG->libdir.'/gradelib.php');
1633         if (!$formdata = data_submitted() or !confirm_sesskey()) {
1634             return;
1635         }
1637         $data = array();
1638         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
1640         if (!empty($grading_info->outcomes)) {
1641             foreach($grading_info->outcomes as $n=>$old) {
1642                 $name = 'outcome_'.$n;
1643                 if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
1644                     $data[$n] = $formdata->{$name}[$userid];
1645                 }
1646             }
1647         }
1648         if (count($data) > 0) {
1649             grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1650         }
1652     }
1654     /**
1655      * Load the submission object for a particular user
1656      *
1657      * @global object
1658      * @global object
1659      * @param $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1660      * @param $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1661      * @param bool $teachermodified student submission set if false
1662      * @return object The submission
1663      */
1664     function get_submission($userid=0, $createnew=false, $teachermodified=false) {
1665         global $USER, $DB;
1667         if (empty($userid)) {
1668             $userid = $USER->id;
1669         }
1671         $submission = $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1673         if ($submission || !$createnew) {
1674             return $submission;
1675         }
1676         $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
1677         $DB->insert_record("assignment_submissions", $newsubmission);
1679         return $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1680     }
1682     /**
1683      * Instantiates a new submission object for a given user
1684      *
1685      * Sets the assignment, userid and times, everything else is set to default values.
1686      *
1687      * @param int $userid The userid for which we want a submission object
1688      * @param bool $teachermodified student submission set if false
1689      * @return object The submission
1690      */
1691     function prepare_new_submission($userid, $teachermodified=false) {
1692         $submission = new stdClass();
1693         $submission->assignment   = $this->assignment->id;
1694         $submission->userid       = $userid;
1695         $submission->timecreated = time();
1696         // teachers should not be modifying modified date, except offline assignments
1697         if ($teachermodified) {
1698             $submission->timemodified = 0;
1699         } else {
1700             $submission->timemodified = $submission->timecreated;
1701         }
1702         $submission->numfiles     = 0;
1703         $submission->data1        = '';
1704         $submission->data2        = '';
1705         $submission->grade        = -1;
1706         $submission->submissioncomment      = '';
1707         $submission->format       = 0;
1708         $submission->teacher      = 0;
1709         $submission->timemarked   = 0;
1710         $submission->mailed       = 0;
1711         return $submission;
1712     }
1714     /**
1715      * Return all assignment submissions by ENROLLED students (even empty)
1716      *
1717      * @param string $sort optional field names for the ORDER BY in the sql query
1718      * @param string $dir optional specifying the sort direction, defaults to DESC
1719      * @return array The submission objects indexed by id
1720      */
1721     function get_submissions($sort='', $dir='DESC') {
1722         return assignment_get_all_submissions($this->assignment, $sort, $dir);
1723     }
1725     /**
1726      * Counts all real assignment submissions by ENROLLED students (not empty ones)
1727      *
1728      * @param int $groupid optional If nonzero then count is restricted to this group
1729      * @return int The number of submissions
1730      */
1731     function count_real_submissions($groupid=0) {
1732         return assignment_count_real_submissions($this->cm, $groupid);
1733     }
1735     /**
1736      * Alerts teachers by email of new or changed assignments that need grading
1737      *
1738      * First checks whether the option to email teachers is set for this assignment.
1739      * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1740      * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1741      *
1742      * @global object
1743      * @global object
1744      * @param $submission object The submission that has changed
1745      * @return void
1746      */
1747     function email_teachers($submission) {
1748         global $CFG, $DB;
1750         if (empty($this->assignment->emailteachers)) {          // No need to do anything
1751             return;
1752         }
1754         $user = $DB->get_record('user', array('id'=>$submission->userid));
1756         if ($teachers = $this->get_graders($user)) {
1758             $strassignments = get_string('modulenameplural', 'assignment');
1759             $strassignment  = get_string('modulename', 'assignment');
1760             $strsubmitted  = get_string('submitted', 'assignment');
1762             foreach ($teachers as $teacher) {
1763                 $info = new stdClass();
1764                 $info->username = fullname($user, true);
1765                 $info->assignment = format_string($this->assignment->name,true);
1766                 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
1767                 $info->timeupdated = strftime('%c',$submission->timemodified);
1769                 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1770                 $posttext = $this->email_teachers_text($info);
1771                 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
1773                 $eventdata = new stdClass();
1774                 $eventdata->modulename       = 'assignment';
1775                 $eventdata->userfrom         = $user;
1776                 $eventdata->userto           = $teacher;
1777                 $eventdata->subject          = $postsubject;
1778                 $eventdata->fullmessage      = $posttext;
1779                 $eventdata->fullmessageformat = FORMAT_PLAIN;
1780                 $eventdata->fullmessagehtml  = $posthtml;
1781                 $eventdata->smallmessage     = $postsubject;
1783                 $eventdata->name            = 'assignment_updates';
1784                 $eventdata->component       = 'mod_assignment';
1785                 $eventdata->notification    = 1;
1786                 $eventdata->contexturl      = $info->url;
1787                 $eventdata->contexturlname  = $info->assignment;
1789                 message_send($eventdata);
1790             }
1791         }
1792     }
1794     /**
1795      * @param string $filearea
1796      * @param array $args
1797      * @return bool
1798      */
1799     function send_file($filearea, $args) {
1800         debugging('plugin does not implement file sending', DEBUG_DEVELOPER);
1801         return false;
1802     }
1804     /**
1805      * Returns a list of teachers that should be grading given submission
1806      *
1807      * @param object $user
1808      * @return array
1809      */
1810     function get_graders($user) {
1811         //potential graders
1812         $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false);
1814         $graders = array();
1815         if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) {   // Separate groups are being used
1816             if ($groups = groups_get_all_groups($this->course->id, $user->id)) {  // Try to find all groups
1817                 foreach ($groups as $group) {
1818                     foreach ($potgraders as $t) {
1819                         if ($t->id == $user->id) {
1820                             continue; // do not send self
1821                         }
1822                         if (groups_is_member($group->id, $t->id)) {
1823                             $graders[$t->id] = $t;
1824                         }
1825                     }
1826                 }
1827             } else {
1828                 // user not in group, try to find graders without group
1829                 foreach ($potgraders as $t) {
1830                     if ($t->id == $user->id) {
1831                         continue; // do not send self
1832                     }
1833                     if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
1834                         $graders[$t->id] = $t;
1835                     }
1836                 }
1837             }
1838         } else {
1839             foreach ($potgraders as $t) {
1840                 if ($t->id == $user->id) {
1841                     continue; // do not send self
1842                 }
1843                 $graders[$t->id] = $t;
1844             }
1845         }
1846         return $graders;
1847     }
1849     /**
1850      * Creates the text content for emails to teachers
1851      *
1852      * @param $info object The info used by the 'emailteachermail' language string
1853      * @return string
1854      */
1855     function email_teachers_text($info) {
1856         $posttext  = format_string($this->course->shortname, true, array('context' => $this->coursecontext)).' -> '.
1857                      $this->strassignments.' -> '.
1858                      format_string($this->assignment->name, true, array('context' => $this->context))."\n";
1859         $posttext .= '---------------------------------------------------------------------'."\n";
1860         $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
1861         $posttext .= "\n---------------------------------------------------------------------\n";
1862         return $posttext;
1863     }
1865      /**
1866      * Creates the html content for emails to teachers
1867      *
1868      * @param $info object The info used by the 'emailteachermailhtml' language string
1869      * @return string
1870      */
1871     function email_teachers_html($info) {
1872         global $CFG;
1873         $posthtml  = '<p><font face="sans-serif">'.
1874                      '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname, true, array('context' => $this->coursecontext)).'</a> ->'.
1875                      '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
1876                      '<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>';
1877         $posthtml .= '<hr /><font face="sans-serif">';
1878         $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
1879         $posthtml .= '</font><hr />';
1880         return $posthtml;
1881     }
1883     /**
1884      * Produces a list of links to the files uploaded by a user
1885      *
1886      * @param $userid int optional id of the user. If 0 then $USER->id is used.
1887      * @param $return boolean optional defaults to false. If true the list is returned rather than printed
1888      * @return string optional
1889      */
1890     function print_user_files($userid=0, $return=false) {
1891         global $CFG, $USER, $OUTPUT;
1893         if (!$userid) {
1894             if (!isloggedin()) {
1895                 return '';
1896             }
1897             $userid = $USER->id;
1898         }
1900         $output = '';
1902         $submission = $this->get_submission($userid);
1903         if (!$submission) {
1904             return $output;
1905         }
1907         $fs = get_file_storage();
1908         $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false);
1909         if (!empty($files)) {
1910             require_once($CFG->dirroot . '/mod/assignment/locallib.php');
1911             if ($CFG->enableportfolios) {
1912                 require_once($CFG->libdir.'/portfoliolib.php');
1913                 $button = new portfolio_add_button();
1914             }
1915             foreach ($files as $file) {
1916                 $filename = $file->get_filename();
1917                 $mimetype = $file->get_mimetype();
1918                 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/mod_assignment/submission/'.$submission->id.'/'.$filename);
1919                 $output .= '<a href="'.$path.'" ><img src="'.$OUTPUT->pix_url(file_mimetype_icon($mimetype)).'" class="icon" alt="'.$mimetype.'" />'.s($filename).'</a>';
1920                 if ($CFG->enableportfolios && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1921                     $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id, 'submissionid' => $submission->id, 'fileid' => $file->get_id()), '/mod/assignment/locallib.php');
1922                     $button->set_format_by_file($file);
1923                     $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
1924                 }
1926                 if ($CFG->enableplagiarism) {
1927                     require_once($CFG->libdir.'/plagiarismlib.php');
1928                     $output .= plagiarism_get_links(array('userid'=>$userid, 'file'=>$file, 'cmid'=>$this->cm->id, 'course'=>$this->course, 'assignment'=>$this->assignment));
1929                     $output .= '<br />';
1930                 }
1931             }
1932             if ($CFG->enableportfolios && count($files) > 1  && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1933                 $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id, 'submissionid' => $submission->id), '/mod/assignment/locallib.php');
1934                 $output .= '<br />'  . $button->to_html(PORTFOLIO_ADD_TEXT_LINK);
1935             }
1936         }
1938         $output = '<div class="files">'.$output.'</div>';
1940         if ($return) {
1941             return $output;
1942         }
1943         echo $output;
1944     }
1946     /**
1947      * Count the files uploaded by a given user
1948      *
1949      * @param $itemid int The submission's id as the file's itemid.
1950      * @return int
1951      */
1952     function count_user_files($itemid) {
1953         $fs = get_file_storage();
1954         $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $itemid, "id", false);
1955         return count($files);
1956     }
1958     /**
1959      * Returns true if the student is allowed to submit
1960      *
1961      * Checks that the assignment has started and, if the option to prevent late
1962      * submissions is set, also checks that the assignment has not yet closed.
1963      * @return boolean
1964      */
1965     function isopen() {
1966         $time = time();
1967         if ($this->assignment->preventlate && $this->assignment->timedue) {
1968             return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
1969         } else {
1970             return ($this->assignment->timeavailable <= $time);
1971         }
1972     }
1975     /**
1976      * Return true if is set description is hidden till available date
1977      *
1978      * This is needed by calendar so that hidden descriptions do not
1979      * come up in upcoming events.
1980      *
1981      * Check that description is hidden till available date
1982      * By default return false
1983      * Assignments types should implement this method if needed
1984      * @return boolen
1985      */
1986     function description_is_hidden() {
1987         return false;
1988     }
1990     /**
1991      * Return an outline of the user's interaction with the assignment
1992      *
1993      * The default method prints the grade and timemodified
1994      * @param $grade object
1995      * @return object with properties ->info and ->time
1996      */
1997     function user_outline($grade) {
1999         $result = new stdClass();
2000         $result->info = get_string('grade').': '.$grade->str_long_grade;
2001         $result->time = $grade->dategraded;
2002         return $result;
2003     }
2005     /**
2006      * Print complete information about the user's interaction with the assignment
2007      *
2008      * @param $user object
2009      */
2010     function user_complete($user, $grade=null) {
2011         global $OUTPUT;
2012         if ($grade) {
2013             echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
2014             if ($grade->str_feedback) {
2015                 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
2016             }
2017         }
2019         if ($submission = $this->get_submission($user->id)) {
2021             $fs = get_file_storage();
2023             if ($files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false)) {
2024                 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
2025                 foreach ($files as $file) {
2026                     $countfiles .= "; ".$file->get_filename();
2027                 }
2028             }
2030             echo $OUTPUT->box_start();
2031             echo get_string("lastmodified").": ";
2032             echo userdate($submission->timemodified);
2033             echo $this->display_lateness($submission->timemodified);
2035             $this->print_user_files($user->id);
2037             echo '<br />';
2039             $this->view_feedback($submission);
2041             echo $OUTPUT->box_end();
2043         } else {
2044             print_string("notsubmittedyet", "assignment");
2045         }
2046     }
2048     /**
2049      * Return a string indicating how late a submission is
2050      *
2051      * @param $timesubmitted int
2052      * @return string
2053      */
2054     function display_lateness($timesubmitted) {
2055         return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
2056     }
2058     /**
2059      * Empty method stub for all delete actions.
2060      */
2061     function delete() {
2062         //nothing by default
2063         redirect('view.php?id='.$this->cm->id);
2064     }
2066     /**
2067      * Empty custom feedback grading form.
2068      */
2069     function custom_feedbackform($submission, $return=false) {
2070         //nothing by default
2071         return '';
2072     }
2074     /**
2075      * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
2076      * for the course (see resource).
2077      *
2078      * Given a course_module object, this function returns any "extra" information that may be needed
2079      * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
2080      *
2081      * @param $coursemodule object The coursemodule object (record).
2082      * @return cached_cm_info Object used to customise appearance on course page
2083      */
2084     function get_coursemodule_info($coursemodule) {
2085         return null;
2086     }
2088     /**
2089      * Plugin cron method - do not use $this here, create new assignment instances if needed.
2090      * @return void
2091      */
2092     function cron() {
2093         //no plugin cron by default - override if needed
2094     }
2096     /**
2097      * Reset all submissions
2098      */
2099     function reset_userdata($data) {
2100         global $CFG, $DB;
2102         if (!$DB->count_records('assignment', array('course'=>$data->courseid, 'assignmenttype'=>$this->type))) {
2103             return array(); // no assignments of this type present
2104         }
2106         $componentstr = get_string('modulenameplural', 'assignment');
2107         $status = array();
2109         $typestr = get_string('type'.$this->type, 'assignment');
2110         // ugly hack to support pluggable assignment type titles...
2111         if($typestr === '[[type'.$this->type.']]'){
2112             $typestr = get_string('type'.$this->type, 'assignment_'.$this->type);
2113         }
2115         if (!empty($data->reset_assignment_submissions)) {
2116             $assignmentssql = "SELECT a.id
2117                                  FROM {assignment} a
2118                                 WHERE a.course=? AND a.assignmenttype=?";
2119             $params = array($data->courseid, $this->type);
2121             // now get rid of all submissions and responses
2122             $fs = get_file_storage();
2123             if ($assignments = $DB->get_records_sql($assignmentssql, $params)) {
2124                 foreach ($assignments as $assignmentid=>$unused) {
2125                     if (!$cm = get_coursemodule_from_instance('assignment', $assignmentid)) {
2126                         continue;
2127                     }
2128                     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2129                     $fs->delete_area_files($context->id, 'mod_assignment', 'submission');
2130                     $fs->delete_area_files($context->id, 'mod_assignment', 'response');
2131                 }
2132             }
2134             $DB->delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)", $params);
2136             $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
2138             if (empty($data->reset_gradebook_grades)) {
2139                 // remove all grades from gradebook
2140                 assignment_reset_gradebook($data->courseid, $this->type);
2141             }
2142         }
2144         /// updating dates - shift may be negative too
2145         if ($data->timeshift) {
2146             shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
2147             $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
2148         }
2150         return $status;
2151     }
2154     function portfolio_exportable() {
2155         return false;
2156     }
2158     /**
2159      * base implementation for backing up subtype specific information
2160      * for one single module
2161      *
2162      * @param filehandle $bf file handle for xml file to write to
2163      * @param mixed $preferences the complete backup preference object
2164      *
2165      * @return boolean
2166      *
2167      * @static
2168      */
2169     static function backup_one_mod($bf, $preferences, $assignment) {
2170         return true;
2171     }
2173     /**
2174      * base implementation for backing up subtype specific information
2175      * for one single submission
2176      *
2177      * @param filehandle $bf file handle for xml file to write to
2178      * @param mixed $preferences the complete backup preference object
2179      * @param object $submission the assignment submission db record
2180      *
2181      * @return boolean
2182      *
2183      * @static
2184      */
2185     static function backup_one_submission($bf, $preferences, $assignment, $submission) {
2186         return true;
2187     }
2189     /**
2190      * base implementation for restoring subtype specific information
2191      * for one single module
2192      *
2193      * @param array  $info the array representing the xml
2194      * @param object $restore the restore preferences
2195      *
2196      * @return boolean
2197      *
2198      * @static
2199      */
2200     static function restore_one_mod($info, $restore, $assignment) {
2201         return true;
2202     }
2204     /**
2205      * base implementation for restoring subtype specific information
2206      * for one single submission
2207      *
2208      * @param object $submission the newly created submission
2209      * @param array  $info the array representing the xml
2210      * @param object $restore the restore preferences
2211      *
2212      * @return boolean
2213      *
2214      * @static
2215      */
2216     static function restore_one_submission($info, $restore, $assignment, $submission) {
2217         return true;
2218     }
2220 } ////// End of the assignment_base class
2223 class mod_assignment_grading_form extends moodleform {
2225     function definition() {
2226         global $OUTPUT;
2227         $mform =& $this->_form;
2229         $formattr = $mform->getAttributes();
2230         $formattr['id'] = 'submitform';
2231         $mform->setAttributes($formattr);
2232         // hidden params
2233         $mform->addElement('hidden', 'offset', ($this->_customdata->offset+1));
2234         $mform->setType('offset', PARAM_INT);
2235         $mform->addElement('hidden', 'userid', $this->_customdata->userid);
2236         $mform->setType('userid', PARAM_INT);
2237         $mform->addElement('hidden', 'nextid', $this->_customdata->nextid);
2238         $mform->setType('nextid', PARAM_INT);
2239         $mform->addElement('hidden', 'id', $this->_customdata->cm->id);
2240         $mform->setType('id', PARAM_INT);
2241         $mform->addElement('hidden', 'sesskey', sesskey());
2242         $mform->setType('sesskey', PARAM_ALPHANUM);
2243         $mform->addElement('hidden', 'mode', 'grade');
2244         $mform->setType('mode', PARAM_TEXT);
2245         $mform->addElement('hidden', 'menuindex', "0");
2246         $mform->setType('menuindex', PARAM_INT);
2247         $mform->addElement('hidden', 'saveuserid', "-1");
2248         $mform->setType('saveuserid', PARAM_INT);
2249         $mform->addElement('hidden', 'filter', "0");
2250         $mform->setType('filter', PARAM_INT);
2252         $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->user),
2253                                                 fullname($this->_customdata->user, true) . '<br/>' .
2254                                                 userdate($this->_customdata->submission->timemodified) .
2255                                                 $this->_customdata->lateness );
2257         $this->add_submission_content();
2258         $this->add_grades_section();
2260         $this->add_feedback_section();
2262         if ($this->_customdata->submission->timemarked) {
2263             $datestring = userdate($this->_customdata->submission->timemarked)."&nbsp; (".format_time(time() - $this->_customdata->submission->timemarked).")";
2264             $mform->addElement('header', 'Last Grade', get_string('lastgrade', 'assignment'));
2265             $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->teacher) ,
2266                                                     fullname($this->_customdata->teacher,true).
2267                                                     '<br/>'.$datestring);
2268         }
2269         // buttons
2270         $this->add_action_buttons();
2272     }
2274     function add_grades_section() {
2275         global $CFG;
2276         $mform =& $this->_form;
2277         $attributes = array();
2278         if ($this->_customdata->gradingdisabled) {
2279             $attributes['disabled'] ='disabled';
2280         }
2282         $grademenu = make_grades_menu($this->_customdata->assignment->grade);
2283         $grademenu['-1'] = get_string('nograde');
2285         $mform->addElement('header', 'Grades', get_string('grades', 'grades'));
2286         $mform->addElement('select', 'xgrade', get_string('grade').':', $grademenu, $attributes);
2287         $mform->setDefault('xgrade', $this->_customdata->submission->grade ); //@fixme some bug when element called 'grade' makes it break
2288         $mform->setType('xgrade', PARAM_INT);
2290         if (!empty($this->_customdata->enableoutcomes)) {
2291             foreach($this->_customdata->grading_info->outcomes as $n=>$outcome) {
2292                 $options = make_grades_menu(-$outcome->scaleid);
2293                 if ($outcome->grades[$this->_customdata->submission->userid]->locked) {
2294                     $options[0] = get_string('nooutcome', 'grades');
2295                     echo $options[$outcome->grades[$this->_customdata->submission->userid]->grade];
2296                 } else {
2297                     $options[''] = get_string('nooutcome', 'grades');
2298                     $attributes = array('id' => 'menuoutcome_'.$n );
2299                     $mform->addElement('select', 'outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->name.':', $options, $attributes );
2300                     $mform->setType('outcome_'.$n.'['.$this->_customdata->userid.']', PARAM_INT);
2301                     $mform->setDefault('outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->grades[$this->_customdata->submission->userid]->grade );
2302                 }
2303             }
2304         }
2305         $course_context = get_context_instance(CONTEXT_MODULE , $this->_customdata->cm->id);
2306         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
2307             $grade = '<a href="'.$CFG->wwwroot.'/grade/report/grader/index.php?id='. $this->_customdata->courseid .'" >'.
2308                         $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade . '</a>';
2309         }else{
2310             $grade = $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade;
2311         }
2312         $mform->addElement('static', 'finalgrade', get_string('currentgrade', 'assignment').':' ,$grade);
2313         $mform->setType('finalgrade', PARAM_INT);
2314     }
2316     /**
2317      *
2318      * @global core_renderer $OUTPUT
2319      */
2320     function add_feedback_section() {
2321         global $OUTPUT;
2322         $mform =& $this->_form;
2323         $mform->addElement('header', 'Feed Back', get_string('feedback', 'grades'));
2325         if ($this->_customdata->gradingdisabled) {
2326             $mform->addElement('static', 'disabledfeedback', $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_feedback );
2327         } else {
2328             // visible elements
2330             $mform->addElement('editor', 'submissioncomment_editor', get_string('feedback', 'assignment').':', null, $this->get_editor_options() );
2331             $mform->setType('submissioncomment_editor', PARAM_RAW); // to be cleaned before display
2332             $mform->setDefault('submissioncomment_editor', $this->_customdata->submission->submissioncomment);
2333             //$mform->addRule('submissioncomment', get_string('required'), 'required', null, 'client');
2334             switch ($this->_customdata->assignment->assignmenttype) {
2335                 case 'upload' :
2336                 case 'uploadsingle' :
2337                     $mform->addElement('filemanager', 'files_filemanager', get_string('responsefiles', 'assignment'). ':', null, $this->_customdata->fileui_options);
2338                     break;
2339                 default :
2340                     break;
2341             }
2342             $mform->addElement('hidden', 'mailinfo_h', "0");
2343             $mform->setType('mailinfo_h', PARAM_INT);
2344             $mform->addElement('checkbox', 'mailinfo',get_string('enablenotification','assignment').
2345             $OUTPUT->help_icon('enablenotification', 'assignment') .':' );
2346             $mform->setType('mailinfo', PARAM_INT);
2347         }
2348     }
2350     function add_action_buttons() {
2351         $mform =& $this->_form;
2352         //if there are more to be graded.
2353         if ($this->_customdata->nextid>0) {
2354             $buttonarray=array();
2355             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2356             //@todo: fix accessibility: javascript dependency not necessary
2357             $buttonarray[] = &$mform->createElement('submit', 'saveandnext', get_string('saveandnext'));
2358             $buttonarray[] = &$mform->createElement('submit', 'next', get_string('next'));
2359             $buttonarray[] = &$mform->createElement('cancel');
2360         } else {
2361             $buttonarray=array();
2362             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2363             $buttonarray[] = &$mform->createElement('cancel');
2364         }
2365         $mform->addGroup($buttonarray, 'grading_buttonar', '', array(' '), false);
2366         $mform->closeHeaderBefore('grading_buttonar');
2367         $mform->setType('grading_buttonar', PARAM_RAW);
2368     }
2370     function add_submission_content() {
2371         $mform =& $this->_form;
2372         $mform->addElement('header', 'Submission', get_string('submission', 'assignment'));
2373         $mform->addElement('static', '', '' , $this->_customdata->submission_content );
2374     }
2376     protected function get_editor_options() {
2377         $editoroptions = array();
2378         $editoroptions['component'] = 'mod_assignment';
2379         $editoroptions['filearea'] = 'feedback';
2380         $editoroptions['noclean'] = false;
2381         $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)
2382         $editoroptions['maxbytes'] = $this->_customdata->maxbytes;
2383         $editoroptions['context'] = $this->_customdata->context;
2384         return $editoroptions;
2385     }
2387     public function set_data($data) {
2388         $editoroptions = $this->get_editor_options();
2389         if (!isset($data->text)) {
2390             $data->text = '';
2391         }
2392         if (!isset($data->format)) {
2393             $data->textformat = FORMAT_HTML;
2394         } else {
2395             $data->textformat = $data->format;
2396         }
2398         if (!empty($this->_customdata->submission->id)) {
2399             $itemid = $this->_customdata->submission->id;
2400         } else {
2401             $itemid = null;
2402         }
2404         switch ($this->_customdata->assignment->assignmenttype) {
2405                 case 'upload' :
2406                 case 'uploadsingle' :
2407                     $data = file_prepare_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2408                     break;
2409                 default :
2410                     break;
2411         }
2413         $data = file_prepare_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2414         return parent::set_data($data);
2415     }
2417     public function get_data() {
2418         $data = parent::get_data();
2420         if (!empty($this->_customdata->submission->id)) {
2421             $itemid = $this->_customdata->submission->id;
2422         } else {
2423             $itemid = null; //TODO: this is wrong, itemid MUST be known when saving files!! (skodak)
2424         }
2426         if ($data) {
2427             $editoroptions = $this->get_editor_options();
2428             switch ($this->_customdata->assignment->assignmenttype) {
2429                 case 'upload' :
2430                 case 'uploadsingle' :
2431                     $data = file_postupdate_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2432                     break;
2433                 default :
2434                     break;
2435             }
2436             $data = file_postupdate_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2437         }
2438         return $data;
2439     }
2442 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
2444 /**
2445  * Deletes an assignment instance
2446  *
2447  * This is done by calling the delete_instance() method of the assignment type class
2448  */
2449 function assignment_delete_instance($id){
2450     global $CFG, $DB;
2452     if (! $assignment = $DB->get_record('assignment', array('id'=>$id))) {
2453         return false;
2454     }
2456     // fall back to base class if plugin missing
2457     $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2458     if (file_exists($classfile)) {
2459         require_once($classfile);
2460         $assignmentclass = "assignment_$assignment->assignmenttype";
2462     } else {
2463         debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
2464         $assignmentclass = "assignment_base";
2465     }
2467     $ass = new $assignmentclass();
2468     return $ass->delete_instance($assignment);
2472 /**
2473  * Updates an assignment instance
2474  *
2475  * This is done by calling the update_instance() method of the assignment type class
2476  */
2477 function assignment_update_instance($assignment){
2478     global $CFG;
2480     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_PLUGIN);
2482     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2483     $assignmentclass = "assignment_$assignment->assignmenttype";
2484     $ass = new $assignmentclass();
2485     return $ass->update_instance($assignment);
2489 /**
2490  * Adds an assignment instance
2491  *
2492  * This is done by calling the add_instance() method of the assignment type class
2493  */
2494 function assignment_add_instance($assignment) {
2495     global $CFG;
2497     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_PLUGIN);
2499     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2500     $assignmentclass = "assignment_$assignment->assignmenttype";
2501     $ass = new $assignmentclass();
2502     return $ass->add_instance($assignment);
2506 /**
2507  * Returns an outline of a user interaction with an assignment
2508  *
2509  * This is done by calling the user_outline() method of the assignment type class
2510  */
2511 function assignment_user_outline($course, $user, $mod, $assignment) {
2512     global $CFG;
2514     require_once("$CFG->libdir/gradelib.php");
2515     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2516     $assignmentclass = "assignment_$assignment->assignmenttype";
2517     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2518     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2519     if (!empty($grades->items[0]->grades)) {
2520         return $ass->user_outline(reset($grades->items[0]->grades));
2521     } else {
2522         return null;
2523     }
2526 /**
2527  * Prints the complete info about a user's interaction with an assignment
2528  *
2529  * This is done by calling the user_complete() method of the assignment type class
2530  */
2531 function assignment_user_complete($course, $user, $mod, $assignment) {
2532     global $CFG;
2534     require_once("$CFG->libdir/gradelib.php");
2535     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2536     $assignmentclass = "assignment_$assignment->assignmenttype";
2537     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2538     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2539     if (empty($grades->items[0]->grades)) {
2540         $grade = false;
2541     } else {
2542         $grade = reset($grades->items[0]->grades);
2543     }
2544     return $ass->user_complete($user, $grade);
2547 /**
2548  * Function to be run periodically according to the moodle cron
2549  *
2550  * Finds all assignment notifications that have yet to be mailed out, and mails them
2551  */
2552 function assignment_cron () {
2553     global $CFG, $USER, $DB;
2555     /// first execute all crons in plugins
2556     if ($plugins = get_plugin_list('assignment')) {
2557         foreach ($plugins as $plugin=>$dir) {
2558             require_once("$dir/assignment.class.php");
2559             $assignmentclass = "assignment_$plugin";
2560             $ass = new $assignmentclass();
2561             $ass->cron();
2562         }
2563     }
2565     /// Notices older than 1 day will not be mailed.  This is to avoid the problem where
2566     /// cron has not been running for a long time, and then suddenly people are flooded
2567     /// with mail from the past few weeks or months
2569     $timenow   = time();
2570     $endtime   = $timenow - $CFG->maxeditingtime;
2571     $starttime = $endtime - 24 * 3600;   /// One day earlier
2573     if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2575         $realuser = clone($USER);
2577         foreach ($submissions as $key => $submission) {
2578             $DB->set_field("assignment_submissions", "mailed", "1", array("id"=>$submission->id));
2579         }
2581         $timenow = time();
2583         foreach ($submissions as $submission) {
2585             echo "Processing assignment submission $submission->id\n";
2587             if (! $user = $DB->get_record("user", array("id"=>$submission->userid))) {
2588                 echo "Could not find user $user->id\n";
2589                 continue;
2590             }
2592             if (! $course = $DB->get_record("course", array("id"=>$submission->course))) {
2593                 echo "Could not find course $submission->course\n";
2594                 continue;
2595             }
2597             /// Override the language and timezone of the "current" user, so that
2598             /// mail is customised for the receiver.
2599             cron_setup_user($user, $course);
2601             $coursecontext = get_context_instance(CONTEXT_COURSE, $submission->course);
2602             $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
2603             if (!is_enrolled($coursecontext, $user->id)) {
2604                 echo fullname($user)." not an active participant in " . $courseshortname . "\n";
2605                 continue;
2606             }
2608             if (! $teacher = $DB->get_record("user", array("id"=>$submission->teacher))) {
2609                 echo "Could not find teacher $submission->teacher\n";
2610                 continue;
2611             }
2613             if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2614                 echo "Could not find course module for assignment id $submission->assignment\n";
2615                 continue;
2616             }
2618             if (! $mod->visible) {    /// Hold mail notification for hidden assignments until later
2619                 continue;
2620             }
2622             $strassignments = get_string("modulenameplural", "assignment");
2623             $strassignment  = get_string("modulename", "assignment");
2625             $assignmentinfo = new stdClass();
2626             $assignmentinfo->teacher = fullname($teacher);
2627             $assignmentinfo->assignment = format_string($submission->name,true);
2628             $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2630             $postsubject = "$courseshortname: $strassignments: ".format_string($submission->name,true);
2631             $posttext  = "$courseshortname -> $strassignments -> ".format_string($submission->name,true)."\n";
2632             $posttext .= "---------------------------------------------------------------------\n";
2633             $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2634             $posttext .= "---------------------------------------------------------------------\n";
2636             if ($user->mailformat == 1) {  // HTML
2637                 $posthtml = "<p><font face=\"sans-serif\">".
2638                 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$courseshortname</a> ->".
2639                 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2640                 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2641                 $posthtml .= "<hr /><font face=\"sans-serif\">";
2642                 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2643                 $posthtml .= "</font><hr />";
2644             } else {
2645                 $posthtml = "";
2646             }
2648             $eventdata = new stdClass();
2649             $eventdata->modulename       = 'assignment';
2650             $eventdata->userfrom         = $teacher;
2651             $eventdata->userto           = $user;
2652             $eventdata->subject          = $postsubject;
2653             $eventdata->fullmessage      = $posttext;
2654             $eventdata->fullmessageformat = FORMAT_PLAIN;
2655             $eventdata->fullmessagehtml  = $posthtml;
2656             $eventdata->smallmessage     = get_string('assignmentmailsmall', 'assignment', $assignmentinfo);
2658             $eventdata->name            = 'assignment_updates';
2659             $eventdata->component       = 'mod_assignment';
2660             $eventdata->notification    = 1;
2661             $eventdata->contexturl      = $assignmentinfo->url;
2662             $eventdata->contexturlname  = $assignmentinfo->assignment;
2664             message_send($eventdata);
2665         }
2667         cron_setup_user();
2668     }
2670     return true;
2673 /**
2674  * Return grade for given user or all users.
2675  *
2676  * @param int $assignmentid id of assignment
2677  * @param int $userid optional user id, 0 means all users
2678  * @return array array of grades, false if none
2679  */
2680 function assignment_get_user_grades($assignment, $userid=0) {
2681     global $CFG, $DB;
2683     if ($userid) {
2684         $user = "AND u.id = :userid";
2685         $params = array('userid'=>$userid);
2686     } else {
2687         $user = "";
2688     }
2689     $params['aid'] = $assignment->id;
2691     $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2692                    s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2693               FROM {user} u, {assignment_submissions} s
2694              WHERE u.id = s.userid AND s.assignment = :aid
2695                    $user";
2697     return $DB->get_records_sql($sql, $params);
2700 /**
2701  * Update activity grades
2702  *
2703  * @param object $assignment
2704  * @param int $userid specific user only, 0 means all
2705  */
2706 function assignment_update_grades($assignment, $userid=0, $nullifnone=true) {
2707     global $CFG, $DB;
2708     require_once($CFG->libdir.'/gradelib.php');
2710     if ($assignment->grade == 0) {
2711         assignment_grade_item_update($assignment);
2713     } else if ($grades = assignment_get_user_grades($assignment, $userid)) {
2714         foreach($grades as $k=>$v) {
2715             if ($v->rawgrade == -1) {
2716                 $grades[$k]->rawgrade = null;
2717             }
2718         }
2719         assignment_grade_item_update($assignment, $grades);
2721     } else {
2722         assignment_grade_item_update($assignment);
2723     }
2726 /**
2727  * Update all grades in gradebook.
2728  */
2729 function assignment_upgrade_grades() {
2730     global $DB;
2732     $sql = "SELECT COUNT('x')
2733               FROM {assignment} a, {course_modules} cm, {modules} m
2734              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2735     $count = $DB->count_records_sql($sql);
2737     $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
2738               FROM {assignment} a, {course_modules} cm, {modules} m
2739              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2740     $rs = $DB->get_recordset_sql($sql);
2741     if ($rs->valid()) {
2742         // too much debug output
2743         $pbar = new progress_bar('assignmentupgradegrades', 500, true);
2744         $i=0;
2745         foreach ($rs as $assignment) {
2746             $i++;
2747             upgrade_set_timeout(60*5); // set up timeout, may also abort execution
2748             assignment_update_grades($assignment);
2749             $pbar->update($i, $count, "Updating Assignment grades ($i/$count).");
2750         }
2751         upgrade_set_timeout(); // reset to default timeout
2752     }
2753     $rs->close();
2756 /**
2757  * Create grade item for given assignment
2758  *
2759  * @param object $assignment object with extra cmidnumber
2760  * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
2761  * @return int 0 if ok, error code otherwise
2762  */
2763 function assignment_grade_item_update($assignment, $grades=NULL) {
2764     global $CFG;
2765     require_once($CFG->libdir.'/gradelib.php');
2767     if (!isset($assignment->courseid)) {
2768         $assignment->courseid = $assignment->course;
2769     }
2771     $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
2773     if ($assignment->grade > 0) {
2774         $params['gradetype'] = GRADE_TYPE_VALUE;
2775         $params['grademax']  = $assignment->grade;
2776         $params['grademin']  = 0;
2778     } else if ($assignment->grade < 0) {
2779         $params['gradetype'] = GRADE_TYPE_SCALE;
2780         $params['scaleid']   = -$assignment->grade;
2782     } else {
2783         $params['gradetype'] = GRADE_TYPE_TEXT; // allow text comments only
2784     }
2786     if ($grades  === 'reset') {
2787         $params['reset'] = true;
2788         $grades = NULL;
2789     }
2791     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades, $params);
2794 /**
2795  * Delete grade item for given assignment
2796  *
2797  * @param object $assignment object
2798  * @return object assignment
2799  */
2800 function assignment_grade_item_delete($assignment) {
2801     global $CFG;
2802     require_once($CFG->libdir.'/gradelib.php');
2804     if (!isset($assignment->courseid)) {
2805         $assignment->courseid = $assignment->course;
2806     }
2808     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
2811 /**
2812  * Returns the users with data in one assignment (students and teachers)
2813  *
2814  * @todo: deprecated - to be deleted in 2.2
2815  *
2816  * @param $assignmentid int
2817  * @return array of user objects
2818  */
2819 function assignment_get_participants($assignmentid) {
2820     global $CFG, $DB;
2822     //Get students
2823     $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2824                                         FROM {user} u,
2825                                              {assignment_submissions} a
2826                                        WHERE a.assignment = ? and
2827                                              u.id = a.userid", array($assignmentid));
2828     //Get teachers
2829     $teachers = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2830                                         FROM {user} u,
2831                                              {assignment_submissions} a
2832                                        WHERE a.assignment = ? and
2833                                              u.id = a.teacher", array($assignmentid));
2835     //Add teachers to students
2836     if ($teachers) {
2837         foreach ($teachers as $teacher) {
2838             $students[$teacher->id] = $teacher;
2839         }
2840     }
2841     //Return students array (it contains an array of unique users)
2842     return ($students);
2845 /**
2846  * Serves assignment submissions and other files.
2847  *
2848  * @param object $course
2849  * @param object $cm
2850  * @param object $context
2851  * @param string $filearea
2852  * @param array $args
2853  * @param bool $forcedownload
2854  * @return bool false if file not found, does not return if found - just send the file
2855  */
2856 function assignment_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) {
2857     global $CFG, $DB;
2859     if ($context->contextlevel != CONTEXT_MODULE) {
2860         return false;
2861     }
2863     require_login($course, false, $cm);
2865     if (!$assignment = $DB->get_record('assignment', array('id'=>$cm->instance))) {
2866         return false;
2867     }
2869     require_once($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
2870     $assignmentclass = 'assignment_'.$assignment->assignmenttype;
2871     $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm, $course);
2873     return $assignmentinstance->send_file($filearea, $args);
2875 /**
2876  * Checks if a scale is being used by an assignment
2877  *
2878  * This is used by the backup code to decide whether to back up a scale
2879  * @param $assignmentid int
2880  * @param $scaleid int
2881  * @return boolean True if the scale is used by the assignment
2882  */
2883 function assignment_scale_used($assignmentid, $scaleid) {
2884     global $DB;
2886     $return = false;
2888     $rec = $DB->get_record('assignment', array('id'=>$assignmentid,'grade'=>-$scaleid));
2890     if (!empty($rec) && !empty($scaleid)) {
2891         $return = true;
2892     }
2894     return $return;
2897 /**
2898  * Checks if scale is being used by any instance of assignment
2899  *
2900  * This is used to find out if scale used anywhere
2901  * @param $scaleid int
2902  * @return boolean True if the scale is used by any assignment
2903  */
2904 function assignment_scale_used_anywhere($scaleid) {
2905     global $DB;
2907     if ($scaleid and $DB->record_exists('assignment', array('grade'=>-$scaleid))) {
2908         return true;
2909     } else {
2910         return false;
2911     }
2914 /**
2915  * Make sure up-to-date events are created for all assignment instances
2916  *
2917  * This standard function will check all instances of this module
2918  * and make sure there are up-to-date events created for each of them.
2919  * If courseid = 0, then every assignment event in the site is checked, else
2920  * only assignment events belonging to the course specified are checked.
2921  * This function is used, in its new format, by restore_refresh_events()
2922  *
2923  * @param $courseid int optional If zero then all assignments for all courses are covered
2924  * @return boolean Always returns true
2925  */
2926 function assignment_refresh_events($courseid = 0) {
2927     global $DB;
2929     if ($courseid == 0) {
2930         if (! $assignments = $DB->get_records("assignment")) {
2931             return true;
2932         }
2933     } else {
2934         if (! $assignments = $DB->get_records("assignment", array("course"=>$courseid))) {
2935             return true;
2936         }
2937     }
2938     $moduleid = $DB->get_field('modules', 'id', array('name'=>'assignment'));
2940     foreach ($assignments as $assignment) {
2941         $cm = get_coursemodule_from_id('assignment', $assignment->id);
2942         $event = new stdClass();
2943         $event->name        = $assignment->name;
2944         $event->description = format_module_intro('assignment', $assignment, $cm->id);
2945         $event->timestart   = $assignment->timedue;
2947         if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
2948             update_event($event);
2950         } else {
2951             $event->courseid    = $assignment->course;
2952             $event->groupid     = 0;
2953             $event->userid      = 0;
2954             $event->modulename  = 'assignment';
2955             $event->instance    = $assignment->id;
2956             $event->eventtype   = 'due';
2957             $event->timeduration = 0;
2958             $event->visible     = $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$assignment->id));
2959             add_event($event);
2960         }
2962     }
2963     return true;
2966 /**
2967  * Print recent activity from all assignments in a given course
2968  *
2969  * This is used by the recent activity block
2970  */
2971 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
2972     global $CFG, $USER, $DB, $OUTPUT;
2974     // do not use log table if possible, it may be huge
2976     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
2977                                                      u.firstname, u.lastname, u.email, u.picture
2978                                                 FROM {assignment_submissions} asb
2979                                                      JOIN {assignment} a      ON a.id = asb.assignment
2980                                                      JOIN {course_modules} cm ON cm.instance = a.id
2981                                                      JOIN {modules} md        ON md.id = cm.module
2982                                                      JOIN {user} u            ON u.id = asb.userid
2983                                                WHERE asb.timemodified > ? AND
2984                                                      a.course = ? AND
2985                                                      md.name = 'assignment'
2986                                             ORDER BY asb.timemodified ASC", array($timestart, $course->id))) {
2987          return false;
2988     }
2990     $modinfo =& get_fast_modinfo($course); // reference needed because we might load the groups
2991     $show    = array();
2992     $grader  = array();
2994     foreach($submissions as $submission) {
2995         if (!array_key_exists($submission->cmid, $modinfo->cms)) {
2996             continue;
2997         }
2998         $cm = $modinfo->cms[$submission->cmid];
2999         if (!$cm->uservisible) {
3000             continue;
3001         }
3002         if ($submission->userid == $USER->id) {
3003             $show[] = $submission;
3004             continue;
3005         }
3007         // the act of sumbitting of assignment may be considered private - only graders will see it if specified
3008         if (empty($CFG->assignment_showrecentsubmissions)) {
3009             if (!array_key_exists($cm->id, $grader)) {
3010                 $grader[$cm->id] = has_capability('moodle/grade:viewall', get_context_instance(CONTEXT_MODULE, $cm->id));
3011             }
3012             if (!$grader[$cm->id]) {
3013                 continue;
3014             }
3015         }
3017         $groupmode = groups_get_activity_groupmode($cm, $course);
3019         if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
3020             if (isguestuser()) {
3021                 // shortcut - guest user does not belong into any group
3022                 continue;
3023             }
3025             if (is_null($modinfo->groups)) {
3026                 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
3027             }
3029             // this will be slow - show only users that share group with me in this cm
3030             if (empty($modinfo->groups[$cm->id])) {
3031                 continue;
3032             }
3033             $usersgroups =  groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
3034             if (is_array($usersgroups)) {
3035                 $usersgroups = array_keys($usersgroups);
3036                 $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
3037                 if (empty($intersect)) {
3038                     continue;
3039                 }
3040             }
3041         }
3042         $show[] = $submission;
3043     }
3045     if (empty($show)) {
3046         return false;
3047     }
3049     echo $OUTPUT->heading(get_string('newsubmissions', 'assignment').':', 3);
3051     foreach ($show as $submission) {
3052         $cm = $modinfo->cms[$submission->cmid];
3053         $link = $CFG->wwwroot.'/mod/assignment/view.php?id='.$cm->id;
3054         print_recent_activity_note($submission->timemodified, $submission, $cm->name, $link, false, $viewfullnames);
3055     }
3057     return true;
3061 /**
3062  * Returns all assignments since a given time in specified forum.
3063  */
3064 function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0)  {
3065     global $CFG, $COURSE, $USER, $DB;
3067     if ($COURSE->id == $courseid) {
3068         $course = $COURSE;
3069     } else {
3070         $course = $DB->get_record('course', array('id'=>$courseid));
3071     }
3073     $modinfo =& get_fast_modinfo($course);
3075     $cm = $modinfo->cms[$cmid];
3077     $params = array();
3078     if ($userid) {
3079         $userselect = "AND u.id = :userid";
3080         $params['userid'] = $userid;
3081     } else {
3082         $userselect = "";
3083     }
3085     if ($groupid) {
3086         $groupselect = "AND gm.groupid = :groupid";
3087         $groupjoin   = "JOIN {groups_members} gm ON  gm.userid=u.id";
3088         $params['groupid'] = $groupid;
3089     } else {
3090         $groupselect = "";
3091         $groupjoin   = "";
3092     }
3094     $params['cminstance'] = $cm->instance;
3095     $params['timestart'] = $timestart;
3097     $userfields = user_picture::fields('u', null, 'userid');
3099     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified,
3100                                                      $userfields
3101                                                 FROM {assignment_submissions} asb
3102                                                 JOIN {assignment} a      ON a.id = asb.assignment
3103                                                 JOIN {user} u            ON u.id = asb.userid
3104                                           $groupjoin
3105                                                WHERE asb.timemodified > :timestart AND a.id = :cminstance
3106                                                      $userselect $groupselect
3107                                             ORDER BY asb.timemodified ASC", $params)) {
3108          return;
3109     }
3111     $groupmode       = groups_get_activity_groupmode($cm, $course);
3112     $cm_context      = get_context_instance(CONTEXT_MODULE, $cm->id);
3113     $grader          = has_capability('moodle/grade:viewall', $cm_context);
3114     $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
3115     $viewfullnames   = has_capability('moodle/site:viewfullnames', $cm_context);
3117     if (is_null($modinfo->groups)) {
3118         $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
3119     }
3121     $show = array();
3123     foreach($submissions as $submission) {
3124         if ($submission->userid == $USER->id) {
3125             $show[] = $submission;
3126             continue;
3127         }
3128         // the act of submitting of assignment may be considered private - only graders will see it if specified
3129         if (empty($CFG->assignment_showrecentsubmissions)) {
3130             if (!$grader) {
3131                 continue;
3132             }
3133         }
3135         if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
3136             if (isguestuser()) {
3137                 // shortcut - guest user does not belong into any group
3138                 continue;
3139             }
3141             // this will be slow - show only users that share group with me in this cm
3142             if (empty($modinfo->groups[$cm->id])) {
3143                 continue;
3144             }
3145             $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
3146             if (is_array($usersgroups)) {
3147                 $usersgroups = array_keys($usersgroups);
3148                 $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
3149                 if (empty($intersect)) {
3150                     continue;
3151                 }
3152             }
3153         }
3154         $show[] = $submission;
3155     }
3157     if (empty($show)) {
3158         return;
3159     }
3161     if ($grader) {
3162         require_once($CFG->libdir.'/gradelib.php');
3163         $userids = array();
3164         foreach ($show as $id=>$submission) {
3165             $userids[] = $submission->userid;
3167         }
3168         $grades = grade_get_grades($courseid, 'mod', 'assignment', $cm->instance, $userids);
3169     }
3171     $aname = format_string($cm->name,true);
3172     foreach ($show as $submission) {
3173         $tmpactivity = new stdClass();
3175         $tmpactivity->type         = 'assignment';
3176         $tmpactivity->cmid         = $cm->id;
3177         $tmpactivity->name         = $aname;
3178         $tmpactivity->sectionnum   = $cm->sectionnum;
3179         $tmpactivity->timestamp    = $submission->timemodified;
3181         if ($grader) {
3182             $tmpactivity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
3183         }
3185         $userfields = explode(',', user_picture::fields());
3186         foreach ($userfields as $userfield) {
3187             if ($userfield == 'id') {
3188                 $tmpactivity->user->{$userfield} = $submission->userid; // aliased in SQL above
3189             } else {
3190                 $tmpactivity->user->{$userfield} = $submission->{$userfield};
3191             }
3192         }
3193         $tmpactivity->user->fullname = fullname($submission, $viewfullnames);
3195         $activities[$index++] = $tmpactivity;
3196     }
3198     return;
3201 /**
3202  * Print recent activity from all assignments in a given course
3203  *
3204  * This is used by course/recent.php
3205  */
3206 function assignment_print_recent_mod_activity($activity, $courseid, $detail, $modnames)  {
3207     global $CFG, $OUTPUT;
3209     echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
3211     echo "<tr><td class=\"userpicture\" valign=\"top\">";
3212     echo $OUTPUT->user_picture($activity->user);
3213     echo "</td><td>";
3215     if ($detail) {
3216         $modname = $modnames[$activity->type];
3217         echo '<div class="title">';
3218         echo "<img src=\"" . $OUTPUT->pix_url('icon', 'assignment') . "\" ".
3219              "class=\"icon\" alt=\"$modname\">";
3220         echo "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id={$activity->cmid}\">{$activity->name}</a>";
3221         echo '</div>';
3222     }
3224     if (isset($activity->grade)) {
3225         echo '<div class="grade">';
3226         echo get_string('grade').': ';
3227         echo $activity->grade;
3228         echo '</div>';
3229     }
3231     echo '<div class="user">';
3232     echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->id}&amp;course=$courseid\">"
3233          ."{$activity->user->fullname}</a>  - ".userdate($activity->timestamp);
3234     echo '</div>';
3236     echo "</td></tr></table>";
3239 /// GENERIC SQL FUNCTIONS
3241 /**
3242  * Fetch info from logs
3243  *
3244  * @param $log object with properties ->info (the assignment id) and ->userid
3245  * @return array with assignment name and user firstname and lastname
3246  */
3247 function assignment_log_info($log) {
3248     global $CFG, $DB;
3250     return $DB->get_record_sql("SELECT a.name, u.firstname, u.lastname
3251                                   FROM {assignment} a, {user} u
3252                                  WHERE a.id = ? AND u.id = ?", array($log->info, $log->userid));
3255 /**
3256  * Return list of marked submissions that have not been mailed out for currently enrolled students
3257  *
3258  * @return array
3259  */
3260 function assignment_get_unmailed_submissions($starttime, $endtime) {
3261     global $CFG, $DB;
3263     return $DB->get_records_sql("SELECT s.*, a.course, a.name
3264                                    FROM {assignment_submissions} s,
3265                                         {assignment} a
3266                                   WHERE s.mailed = 0
3267                                         AND s.timemarked <= ?
3268                                         AND s.timemarked >= ?
3269                                         AND s.assignment = a.id", array($endtime, $starttime));
3272 /**
3273  * Counts all real assignment submissions by ENROLLED students (not empty ones)
3274  *
3275  * There are also assignment type methods count_real_submissions() which in the default
3276  * implementation simply call this function.
3277  * @param $groupid int optional If nonzero then count is restricted to this group
3278  * @return int The number of submissions
3279  */
3280 function assignment_count_real_submissions($cm, $groupid=0) {
3281     global $CFG, $DB;
3283     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
3285     // this is all the users with this capability set, in this context or higher
3286     if ($users = get_enrolled_users($context, 'mod/assignment:view', $groupid, 'u.id')) {
3287         $users = array_keys($users);
3288     }
3290     // if groupmembersonly used, remove users who are not in any group
3291     if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
3292         if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
3293             $users = array_intersect($users, array_keys($groupingusers));
3294         }
3295     }
3297     if (empty($users)) {
3298         return 0;
3299     }
3301     $userlists = implode(',', $users);
3303     return $DB->count_records_sql("SELECT COUNT('x')
3304                                      FROM {assignment_submissions}
3305                                     WHERE assignment = ? AND
3306                                           timemodified > 0 AND
3307                                           userid IN ($userlists)", array($cm->instance));
3311 /**
3312  * Return all assignment submissions by ENROLLED students (even empty)
3313  *
3314  * There are also assignment type methods get_submissions() wich in the default
3315  * implementation simply call this function.
3316  * @param $sort string optional field names for the ORDER BY in the sql query
3317  * @param $dir string optional specifying the sort direction, defaults to DESC
3318  * @return array The submission objects indexed by id
3319  */
3320 function assignment_get_all_submissions($assignment, $sort="", $dir="DESC") {
3321 /// Return all assignment submissions by ENROLLED students (even empty)
3322     global $CFG, $DB;
3324     if ($sort == "lastname" or $sort == "firstname") {
3325         $sort = "u.$sort $dir";
3326     } else if (empty($sort)) {
3327         $sort = "a.timemodified DESC";
3328     } else {
3329         $sort = "a.$sort $dir";
3330     }
3332     /* not sure this is needed at all since assignment already has a course define, so this join?
3333     $select = "s.course = '$assignment->course' AND";
3334     if ($assignment->course == SITEID) {
3335         $select = '';
3336     }*/
3338     return $DB->get_records_sql("SELECT a.*
3339                                    FROM {assignment_submissions} a, {user} u
3340                                   WHERE u.id = a.userid
3341                                      &nbs