MDL-20700 coding style cleanup - cvs keywords removed, closign php tag removed, trail...
[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 portfoliolib.php */
33 require_once($CFG->libdir.'/portfoliolib.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     /** @var object */
50     var $cm;
51     /** @var object */
52     var $course;
53     /** @var object */
54     var $assignment;
55     /** @var string */
56     var $strassignment;
57     /** @var string */
58     var $strassignments;
59     /** @var string */
60     var $strsubmissions;
61     /** @var string */
62     var $strlastmodified;
63     /** @var string */
64     var $pagetitle;
65     /** @var bool */
66     var $usehtmleditor;
67     /**
68      * @todo document this var
69      */
70     var $defaultformat;
71     /**
72      * @todo document this var
73      */
74     var $context;
75     /** @var string */
76     var $type;
78     /**
79      * Constructor for the base assignment class
80      *
81      * Constructor for the base assignment class.
82      * If cmid is set create the cm, course, assignment objects.
83      * If the assignment is hidden and the user is not a teacher then
84      * this prints a page header and notice.
85      *
86      * @global object
87      * @global object
88      * @param int $cmid the current course module id - not set for new assignments
89      * @param object $assignment usually null, but if we have it we pass it to save db access
90      * @param object $cm usually null, but if we have it we pass it to save db access
91      * @param object $course usually null, but if we have it we pass it to save db access
92      */
93     function assignment_base($cmid='staticonly', $assignment=NULL, $cm=NULL, $course=NULL) {
94         global $COURSE, $DB;
96         if ($cmid == 'staticonly') {
97             //use static functions only!
98             return;
99         }
101         global $CFG;
103         if ($cm) {
104             $this->cm = $cm;
105         } else if (! $this->cm = get_coursemodule_from_id('assignment', $cmid)) {
106             print_error('invalidcoursemodule');
107         }
109         $this->context = get_context_instance(CONTEXT_MODULE, $this->cm->id);
111         if ($course) {
112             $this->course = $course;
113         } else if ($this->cm->course == $COURSE->id) {
114             $this->course = $COURSE;
115         } else if (! $this->course = $DB->get_record('course', array('id'=>$this->cm->course))) {
116             print_error('invalidid', 'assignment');
117         }
119         if ($assignment) {
120             $this->assignment = $assignment;
121         } else if (! $this->assignment = $DB->get_record('assignment', array('id'=>$this->cm->instance))) {
122             print_error('invalidid', 'assignment');
123         }
125         $this->assignment->cmidnumber = $this->cm->id;     // compatibility with modedit assignment obj
126         $this->assignment->courseid   = $this->course->id; // compatibility with modedit assignment obj
128         $this->strassignment = get_string('modulename', 'assignment');
129         $this->strassignments = get_string('modulenameplural', 'assignment');
130         $this->strsubmissions = get_string('submissions', 'assignment');
131         $this->strlastmodified = get_string('lastmodified');
132         $this->pagetitle = strip_tags($this->course->shortname.': '.$this->strassignment.': '.format_string($this->assignment->name,true));
134         // visibility handled by require_login() with $cm parameter
135         // get current group only when really needed
137     /// Set up things for a HTML editor if it's needed
138         if ($this->usehtmleditor = can_use_html_editor()) {
139             $this->defaultformat = FORMAT_HTML;
140         } else {
141             $this->defaultformat = FORMAT_MOODLE;
142         }
143     }
145     /**
146      * Display the assignment, used by view.php
147      *
148      * This in turn calls the methods producing individual parts of the page
149      */
150     function view() {
152         $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
153         require_capability('mod/assignment:view', $context);
155         add_to_log($this->course->id, "assignment", "view", "view.php?id={$this->cm->id}",
156                    $this->assignment->id, $this->cm->id);
158         $this->view_header();
160         $this->view_intro();
162         $this->view_dates();
164         $this->view_feedback();
166         $this->view_footer();
167     }
169     /**
170      * Display the header and top of a page
171      *
172      * (this doesn't change much for assignment types)
173      * This is used by the view() method to print the header of view.php but
174      * it can be used on other pages in which case the string to denote the
175      * page in the navigation trail should be passed as an argument
176      *
177      * @global object
178      * @param string $subpage Description of subpage to be used in navigation trail
179      */
180     function view_header($subpage='') {
181         global $CFG, $PAGE, $OUTPUT;
183         if ($subpage) {
184             $PAGE->navbar->add($subpage);
185         }
187         $PAGE->set_title($this->pagetitle);
188         $PAGE->set_heading($this->course->fullname);
189         $PAGE->set_button($OUTPUT->update_module_button($this->cm->id, 'assignment'));
191         echo $OUTPUT->header();
193         groups_print_activity_menu($this->cm, 'view.php?id=' . $this->cm->id);
195         echo '<div class="reportlink">'.$this->submittedlink().'</div>';
196         echo '<div class="clearer"></div>';
197     }
200     /**
201      * Display the assignment intro
202      *
203      * This will most likely be extended by assignment type plug-ins
204      * The default implementation prints the assignment description in a box
205      */
206     function view_intro() {
207         global $OUTPUT;
208         echo $OUTPUT->box_start('generalbox boxaligncenter', 'intro');
209         echo format_module_intro('assignment', $this->assignment, $this->cm->id);
210         echo $OUTPUT->box_end();
211     }
213     /**
214      * Display the assignment dates
215      *
216      * Prints the assignment start and end dates in a box.
217      * This will be suitable for most assignment types
218      */
219     function view_dates() {
220         global $OUTPUT;
221         if (!$this->assignment->timeavailable && !$this->assignment->timedue) {
222             return;
223         }
225         echo $OUTPUT->box_start('generalbox boxaligncenter', 'dates');
226         echo '<table>';
227         if ($this->assignment->timeavailable) {
228             echo '<tr><td class="c0">'.get_string('availabledate','assignment').':</td>';
229             echo '    <td class="c1">'.userdate($this->assignment->timeavailable).'</td></tr>';
230         }
231         if ($this->assignment->timedue) {
232             echo '<tr><td class="c0">'.get_string('duedate','assignment').':</td>';
233             echo '    <td class="c1">'.userdate($this->assignment->timedue).'</td></tr>';
234         }
235         echo '</table>';
236         echo $OUTPUT->box_end();
237     }
240     /**
241      * Display the bottom and footer of a page
242      *
243      * This default method just prints the footer.
244      * This will be suitable for most assignment types
245      */
246     function view_footer() {
247         global $OUTPUT;
248         echo $OUTPUT->footer();
249     }
251     /**
252      * Display the feedback to the student
253      *
254      * This default method prints the teacher picture and name, date when marked,
255      * grade and teacher submissioncomment.
256      *
257      * @global object
258      * @global object
259      * @global object
260      * @param object $submission The submission object or NULL in which case it will be loaded
261      */
262     function view_feedback($submission=NULL) {
263         global $USER, $CFG, $DB, $OUTPUT;
264         require_once($CFG->libdir.'/gradelib.php');
266         if (!has_capability('mod/assignment:submit', $this->context, $USER->id, false)) {
267             // can not submit assignments -> no feedback
268             return;
269         }
271         if (!$submission) { /// Get submission for this assignment
272             $submission = $this->get_submission($USER->id);
273         }
275         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $USER->id);
276         $item = $grading_info->items[0];
277         $grade = $item->grades[$USER->id];
279         if ($grade->hidden or $grade->grade === false) { // hidden or error
280             return;
281         }
283         if ($grade->grade === null and empty($grade->str_feedback)) {   /// Nothing to show yet
284             return;
285         }
287         $graded_date = $grade->dategraded;
288         $graded_by   = $grade->usermodified;
290     /// We need the teacher info
291         if (!$teacher = $DB->get_record('user', array('id'=>$graded_by))) {
292             print_error('cannotfindteacher');
293         }
295     /// Print the feedback
296         echo $OUTPUT->heading(get_string('feedbackfromteacher', 'assignment', fullname($teacher)));
298         echo '<table cellspacing="0" class="feedback">';
300         echo '<tr>';
301         echo '<td class="left picture">';
302         if ($teacher) {
303             echo $OUTPUT->user_picture(moodle_user_picture::make($teacher, $this->course->id));
304         }
305         echo '</td>';
306         echo '<td class="topic">';
307         echo '<div class="from">';
308         if ($teacher) {
309             echo '<div class="fullname">'.fullname($teacher).'</div>';
310         }
311         echo '<div class="time">'.userdate($graded_date).'</div>';
312         echo '</div>';
313         echo '</td>';
314         echo '</tr>';
316         echo '<tr>';
317         echo '<td class="left side">&nbsp;</td>';
318         echo '<td class="content">';
319         echo '<div class="grade">';
320         echo get_string("grade").': '.$grade->str_long_grade;
321         echo '</div>';
322         echo '<div class="clearer"></div>';
324         echo '<div class="comment">';
325         echo $grade->str_feedback;
326         echo '</div>';
327         echo '</tr>';
329         echo '</table>';
330     }
332     /**
333      * Returns a link with info about the state of the assignment submissions
334      *
335      * This is used by view_header to put this link at the top right of the page.
336      * For teachers it gives the number of submitted assignments with a link
337      * For students it gives the time of their submission.
338      * This will be suitable for most assignment types.
339      *
340      * @global object
341      * @global object
342      * @param bool $allgroup print all groups info if user can access all groups, suitable for index.php
343      * @return string
344      */
345     function submittedlink($allgroups=false) {
346         global $USER;
347         global $CFG;
349         $submitted = '';
350         $urlbase = "{$CFG->wwwroot}/mod/assignment/";
352         $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
353         if (has_capability('mod/assignment:grade', $context)) {
354             if ($allgroups and has_capability('moodle/site:accessallgroups', $context)) {
355                 $group = 0;
356             } else {
357                 $group = groups_get_activity_group($this->cm);
358             }
359             if ($count = $this->count_real_submissions($group)) {
360                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
361                              get_string('viewsubmissions', 'assignment', $count).'</a>';
362             } else {
363                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
364                              get_string('noattempts', 'assignment').'</a>';
365             }
366         } else {
367             if (!empty($USER->id)) {
368                 if ($submission = $this->get_submission($USER->id)) {
369                     if ($submission->timemodified) {
370                         if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
371                             $submitted = '<span class="early">'.userdate($submission->timemodified).'</span>';
372                         } else {
373                             $submitted = '<span class="late">'.userdate($submission->timemodified).'</span>';
374                         }
375                     }
376                 }
377             }
378         }
380         return $submitted;
381     }
384     /**
385      * @todo Document this function
386      */
387     function setup_elements(&$mform) {
389     }
391     /**
392      * Create a new assignment activity
393      *
394      * Given an object containing all the necessary data,
395      * (defined by the form in mod_form.php) this function
396      * will create a new instance and return the id number
397      * of the new instance.
398      * The due data is added to the calendar
399      * This is common to all assignment types.
400      *
401      * @global object
402      * @global object
403      * @param object $assignment The data from the form on mod_form.php
404      * @return int The id of the assignment
405      */
406     function add_instance($assignment) {
407         global $COURSE, $DB;
409         $assignment->timemodified = time();
410         $assignment->courseid = $assignment->course;
412         if ($returnid = $DB->insert_record("assignment", $assignment)) {
413             $assignment->id = $returnid;
415             if ($assignment->timedue) {
416                 $event = new object();
417                 $event->name        = $assignment->name;
418                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
419                 $event->courseid    = $assignment->course;
420                 $event->groupid     = 0;
421                 $event->userid      = 0;
422                 $event->modulename  = 'assignment';
423                 $event->instance    = $returnid;
424                 $event->eventtype   = 'due';
425                 $event->timestart   = $assignment->timedue;
426                 $event->timeduration = 0;
428                 add_event($event);
429             }
431             assignment_grade_item_update($assignment);
433         }
436         return $returnid;
437     }
439     /**
440      * Deletes an assignment activity
441      *
442      * Deletes all database records, files and calendar events for this assignment.
443      *
444      * @global object
445      * @global object
446      * @param object $assignment The assignment to be deleted
447      * @return boolean False indicates error
448      */
449     function delete_instance($assignment) {
450         global $CFG, $DB;
452         $assignment->courseid = $assignment->course;
454         $result = true;
456         // now get rid of all files
457         $fs = get_file_storage();
458         if ($cm = get_coursemodule_from_instance('assignment', $assignment->id)) {
459             $context = get_context_instance(CONTEXT_MODULE, $cm->id);
460             $fs->delete_area_files($context->id);
461         }
463         if (! $DB->delete_records('assignment_submissions', array('assignment'=>$assignment->id))) {
464             $result = false;
465         }
467         if (! $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
468             $result = false;
469         }
471         if (! $DB->delete_records('assignment', array('id'=>$assignment->id))) {
472             $result = false;
473         }
475         assignment_grade_item_delete($assignment);
477         return $result;
478     }
480     /**
481      * Updates a new assignment activity
482      *
483      * Given an object containing all the necessary data,
484      * (defined by the form in mod_form.php) this function
485      * will update the assignment instance and return the id number
486      * The due date is updated in the calendar
487      * This is common to all assignment types.
488      *
489      * @global object
490      * @global object
491      * @param object $assignment The data from the form on mod_form.php
492      * @return int The assignment id
493      */
494     function update_instance($assignment) {
495         global $COURSE, $DB;
497         $assignment->timemodified = time();
499         $assignment->id = $assignment->instance;
500         $assignment->courseid = $assignment->course;
502         $DB->update_record('assignment', $assignment);
504         if ($assignment->timedue) {
505             $event = new object();
507             if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
509                 $event->name        = $assignment->name;
510                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
511                 $event->timestart   = $assignment->timedue;
513                 update_event($event);
514             } else {
515                 $event = new object();
516                 $event->name        = $assignment->name;
517                 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
518                 $event->courseid    = $assignment->course;
519                 $event->groupid     = 0;
520                 $event->userid      = 0;
521                 $event->modulename  = 'assignment';
522                 $event->instance    = $assignment->id;
523                 $event->eventtype   = 'due';
524                 $event->timestart   = $assignment->timedue;
525                 $event->timeduration = 0;
527                 add_event($event);
528             }
529         } else {
530             $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id));
531         }
533         // get existing grade item
534         assignment_grade_item_update($assignment);
536         return true;
537     }
539     /**
540      * Update grade item for this submission.
541      */
542     function update_grade($submission) {
543         assignment_update_grades($this->assignment, $submission->userid);
544     }
546     /**
547      * Top-level function for handling of submissions called by submissions.php
548      *
549      * This is for handling the teacher interaction with the grading interface
550      * This should be suitable for most assignment types.
551      *
552      * @global object
553      * @param string $mode Specifies the kind of teacher interaction taking place
554      */
555     function submissions($mode) {
556         ///The main switch is changed to facilitate
557         ///1) Batch fast grading
558         ///2) Skip to the next one on the popup
559         ///3) Save and Skip to the next one on the popup
561         //make user global so we can use the id
562         global $USER, $OUTPUT;
564         $mailinfo = optional_param('mailinfo', null, PARAM_BOOL);
565         if (is_null($mailinfo)) {
566             $mailinfo = get_user_preferences('assignment_mailinfo', 0);
567         } else {
568             set_user_preference('assignment_mailinfo', $mailinfo);
569         }
571         switch ($mode) {
572             case 'grade':                         // We are in a popup window grading
573                 if ($submission = $this->process_feedback()) {
574                     //IE needs proper header with encoding
575                     $PAGE->set_title(get_string('feedback', 'assignment').':'.format_string($this->assignment->name));
576                     echo $OUTPUT->header();
577                     echo $OUTPUT->heading(get_string('changessaved'));
578                     print $this->update_main_listing($submission);
579                 }
580                 close_window();
581                 break;
583             case 'single':                        // We are in a popup window displaying submission
584                 $this->display_submission();
585                 break;
587             case 'all':                          // Main window, display everything
588                 $this->display_submissions();
589                 break;
591             case 'fastgrade':
592                 ///do the fast grading stuff  - this process should work for all 3 subclasses
594                 $grading    = false;
595                 $commenting = false;
596                 $col        = false;
597                 if (isset($_POST['submissioncomment'])) {
598                     $col = 'submissioncomment';
599                     $commenting = true;
600                 }
601                 if (isset($_POST['menu'])) {
602                     $col = 'menu';
603                     $grading = true;
604                 }
605                 if (!$col) {
606                     //both submissioncomment and grade columns collapsed..
607                     $this->display_submissions();
608                     break;
609                 }
611                 foreach ($_POST[$col] as $id => $unusedvalue){
613                     $id = (int)$id; //clean parameter name
615                     $this->process_outcomes($id);
617                     if (!$submission = $this->get_submission($id)) {
618                         $submission = $this->prepare_new_submission($id);
619                         $newsubmission = true;
620                     } else {
621                         $newsubmission = false;
622                     }
623                     unset($submission->data1);  // Don't need to update this.
624                     unset($submission->data2);  // Don't need to update this.
626                     //for fast grade, we need to check if any changes take place
627                     $updatedb = false;
629                     if ($grading) {
630                         $grade = $_POST['menu'][$id];
631                         $updatedb = $updatedb || ($submission->grade != $grade);
632                         $submission->grade = $grade;
633                     } else {
634                         if (!$newsubmission) {
635                             unset($submission->grade);  // Don't need to update this.
636                         }
637                     }
638                     if ($commenting) {
639                         $commentvalue = trim($_POST['submissioncomment'][$id]);
640                         $updatedb = $updatedb || ($submission->submissioncomment != $commentvalue);
641                         $submission->submissioncomment = $commentvalue;
642                     } else {
643                         unset($submission->submissioncomment);  // Don't need to update this.
644                     }
646                     $submission->teacher    = $USER->id;
647                     if ($updatedb) {
648                         $submission->mailed = (int)(!$mailinfo);
649                     }
651                     $submission->timemarked = time();
653                     //if it is not an update, we don't change the last modified time etc.
654                     //this will also not write into database if no submissioncomment and grade is entered.
656                     if ($updatedb){
657                         if ($newsubmission) {
658                             if (!isset($submission->submissioncomment)) {
659                                 $submission->submissioncomment = '';
660                             }
661                             $sid = $DB->insert_record('assignment_submissions', $submission);
662                             $submission->id = $sid;
663                         } else {
664                             $DB->update_record('assignment_submissions', $submission);
665                         }
667                         // triger grade event
668                         $this->update_grade($submission);
670                         //add to log only if updating
671                         add_to_log($this->course->id, 'assignment', 'update grades',
672                                    'submissions.php?id='.$this->assignment->id.'&user='.$submission->userid,
673                                    $submission->userid, $this->cm->id);
674                     }
676                 }
678                 $message = $OUTPUT->notification(get_string('changessaved'), 'notifysuccess');
680                 $this->display_submissions($message);
681                 break;
684             case 'next':
685                 /// We are currently in pop up, but we want to skip to next one without saving.
686                 ///    This turns out to be similar to a single case
687                 /// The URL used is for the next submission.
689                 $this->display_submission();
690                 break;
692             case 'saveandnext':
693                 ///We are in pop up. save the current one and go to the next one.
694                 //first we save the current changes
695                 if ($submission = $this->process_feedback()) {
696                     //print_heading(get_string('changessaved'));
697                     $extra_javascript = $this->update_main_listing($submission);
698                 }
700                 //then we display the next submission
701                 $this->display_submission($extra_javascript);
702                 break;
704             default:
705                 echo "something seriously is wrong!!";
706                 break;
707         }
708     }
710     /**
711      * Helper method updating the listing on the main script from popup using javascript
712      *
713      * @global object
714      * @global object
715      * @param $submission object The submission whose data is to be updated on the main page
716      */
717     function update_main_listing($submission) {
718         global $SESSION, $CFG, $OUTPUT;
720         $output = '';
722         $perpage = get_user_preferences('assignment_perpage', 10);
724         $quickgrade = get_user_preferences('assignment_quickgrade', 0);
726         /// Run some Javascript to try and update the parent page
727         $output .= '<script type="text/javascript">'."\n<!--\n";
728         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['submissioncomment'])) {
729             if ($quickgrade){
730                 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid.'").value="'
731                 .trim($submission->submissioncomment).'";'."\n";
732              } else {
733                 $output.= 'opener.document.getElementById("com'.$submission->userid.
734                 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment)), 15)."\";\n";
735             }
736         }
738         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['grade'])) {
739             //echo optional_param('menuindex');
740             if ($quickgrade){
741                 $output.= 'opener.document.getElementById("menumenu'.$submission->userid.
742                 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT).'";'."\n";
743             } else {
744                 $output.= 'opener.document.getElementById("g'.$submission->userid.'").innerHTML="'.
745                 $this->display_grade($submission->grade)."\";\n";
746             }
747         }
748         //need to add student's assignments in there too.
749         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemodified']) &&
750             $submission->timemodified) {
751             $output.= 'opener.document.getElementById("ts'.$submission->userid.
752                  '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid)).userdate($submission->timemodified)."\";\n";
753         }
755         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemarked']) &&
756             $submission->timemarked) {
757             $output.= 'opener.document.getElementById("tt'.$submission->userid.
758                  '").innerHTML="'.userdate($submission->timemarked)."\";\n";
759         }
761         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['status'])) {
762             $output.= 'opener.document.getElementById("up'.$submission->userid.'").className="s1";';
763             $buttontext = get_string('update');
764             $url = new moodle_url('/mod/assignment/submissions.php', array(
765                     'id' => $this->cm->id,
766                     'userid' => $submission->userid,
767                     'mode' => 'single',
768                     'offset' => (optional_param('offset', '', PARAM_INT)-1)));
770             $link = html_link::make($url, $buttontext);
771             $link->add_action(new popup_action('click', $link->url, 'grade'.$submission->userid, array('height' => 450, 'width' => 700)));
772             $link->title = $buttontext;
773             $button = $OUTPUT->link($link);
775             $output.= 'opener.document.getElementById("up'.$submission->userid.'").innerHTML="'.addslashes_js($button).'";';
776         }
778         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $submission->userid);
780         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['finalgrade'])) {
781             $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid.
782             '").innerHTML="'.$grading_info->items[0]->grades[$submission->userid]->str_grade.'";'."\n";
783         }
785         if (!empty($CFG->enableoutcomes) and empty($SESSION->flextable['mod-assignment-submissions']->collapse['outcome'])) {
787             if (!empty($grading_info->outcomes)) {
788                 foreach($grading_info->outcomes as $n=>$outcome) {
789                     if ($outcome->grades[$submission->userid]->locked) {
790                         continue;
791                     }
793                     if ($quickgrade){
794                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.
795                         '").selectedIndex="'.$outcome->grades[$submission->userid]->grade.'";'."\n";
797                     } else {
798                         $options = make_grades_menu(-$outcome->scaleid);
799                         $options[0] = get_string('nooutcome', 'grades');
800                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.'").innerHTML="'.$options[$outcome->grades[$submission->userid]->grade]."\";\n";
801                     }
803                 }
804             }
805         }
807         $output .= "\n-->\n</script>";
808         return $output;
809     }
811     /**
812      *  Return a grade in user-friendly form, whether it's a scale or not
813      *
814      * @global object
815      * @param mixed $grade
816      * @return string User-friendly representation of grade
817      */
818     function display_grade($grade) {
819         global $DB;
821         static $scalegrades = array();   // Cache scales for each assignment - they might have different scales!!
823         if ($this->assignment->grade >= 0) {    // Normal number
824             if ($grade == -1) {
825                 return '-';
826             } else {
827                 return $grade.' / '.$this->assignment->grade;
828             }
830         } else {                                // Scale
831             if (empty($scalegrades[$this->assignment->id])) {
832                 if ($scale = $DB->get_record('scale', array('id'=>-($this->assignment->grade)))) {
833                     $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
834                 } else {
835                     return '-';
836                 }
837             }
838             if (isset($scalegrades[$this->assignment->id][$grade])) {
839                 return $scalegrades[$this->assignment->id][$grade];
840             }
841             return '-';
842         }
843     }
845     /**
846      *  Display a single submission, ready for grading on a popup window
847      *
848      * This default method prints the teacher info and submissioncomment box at the top and
849      * the student info and submission at the bottom.
850      * This method also fetches the necessary data in order to be able to
851      * provide a "Next submission" button.
852      * Calls preprocess_submission() to give assignment type plug-ins a chance
853      * to process submissions before they are graded
854      * This method gets its arguments from the page parameters userid and offset
855      *
856      * @global object
857      * @global object
858      * @param string $extra_javascript
859      */
860     function display_submission($extra_javascript = '') {
861         global $CFG, $DB, $PAGE, $OUTPUT;
862         require_once($CFG->libdir.'/gradelib.php');
863         require_once($CFG->libdir.'/tablelib.php');
865         $userid = required_param('userid', PARAM_INT);
866         $offset = required_param('offset', PARAM_INT);//offset for where to start looking for student.
868         if (!$user = $DB->get_record('user', array('id'=>$userid))) {
869             print_error('nousers');
870         }
872         if (!$submission = $this->get_submission($user->id)) {
873             $submission = $this->prepare_new_submission($userid);
874         }
875         if ($submission->timemodified > $submission->timemarked) {
876             $subtype = 'assignmentnew';
877         } else {
878             $subtype = 'assignmentold';
879         }
881         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
882         $disabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
884     /// construct SQL, using current offset to find the data of the next student
885         $course     = $this->course;
886         $assignment = $this->assignment;
887         $cm         = $this->cm;
888         $context    = get_context_instance(CONTEXT_MODULE, $cm->id);
890         /// Get all ppl that can submit assignments
892         $currentgroup = groups_get_activity_group($cm);
893         if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $currentgroup, '', false)) {
894             $users = array_keys($users);
895         }
897         // if groupmembersonly used, remove users who are not in any group
898         if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
899             if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
900                 $users = array_intersect($users, array_keys($groupingusers));
901             }
902         }
904         $nextid = 0;
906         if ($users) {
907             $select = 'SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt,
908                               s.id AS submissionid, s.grade, s.submissioncomment,
909                               s.timemodified, s.timemarked,
910                               COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ';
911             $sql = 'FROM {user} u '.
912                    'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
913                                                                       AND s.assignment = '.$this->assignment->id.' '.
914                    'WHERE u.id IN ('.implode(',', $users).') ';
916             if ($sort = flexible_table::get_sql_sort('mod-assignment-submissions')) {
917                 $sort = 'ORDER BY '.$sort.' ';
918             }
920             if (($auser = $DB->get_records_sql($select.$sql.$sort, null, $offset+1, 1)) !== false) {
921                 $nextuser = array_shift($auser);
922             /// Calculate user status
923                 $nextuser->status = ($nextuser->timemarked > 0) && ($nextuser->timemarked >= $nextuser->timemodified);
924                 $nextid = $nextuser->id;
925             }
926         }
928         $PAGE->set_title(get_string('feedback', 'assignment').':'.fullname($user, true).':'.format_string($this->assignment->name));
929         echo $OUTPUT->header();
931         /// Print any extra javascript needed for saveandnext
932         echo $extra_javascript;
934         echo $PAGE->requires->data_for_js('assignment', Array('nextid'=>$nextid, 'userid'=>$userid))->asap();
935         echo $PAGE->requires->js('mod/assignment/assignment.js')->asap();
937         echo '<table cellspacing="0" class="feedback '.$subtype.'" >';
939         ///Start of teacher info row
941         echo '<tr>';
942         echo '<td class="picture teacher">';
943         if ($submission->teacher) {
944             $teacher = $DB->get_record('user', array('id'=>$submission->teacher));
945         } else {
946             global $USER;
947             $teacher = $USER;
948         }
949         echo $OUTPUT->user_picture(moodle_user_picture::make($teacher, $this->course->id));
950         echo '</td>';
951         echo '<td class="content">';
952         echo '<form id="submitform" action="submissions.php" method="post">';
953         echo '<div>'; // xhtml compatibility - invisiblefieldset was breaking layout here
954         echo '<input type="hidden" name="offset" value="'.($offset+1).'" />';
955         echo '<input type="hidden" name="userid" value="'.$userid.'" />';
956         echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
957         echo '<input type="hidden" name="mode" value="grade" />';
958         echo '<input type="hidden" name="menuindex" value="0" />';//selected menu index
960         //new hidden field, initialized to -1.
961         echo '<input type="hidden" name="saveuserid" value="-1" />';
963         if ($submission->timemarked) {
964             echo '<div class="from">';
965             echo '<div class="fullname">'.fullname($teacher, true).'</div>';
966             echo '<div class="time">'.userdate($submission->timemarked).'</div>';
967             echo '</div>';
968         }
969         echo '<div class="grade"><label for="menugrade">'.get_string('grade').'</label> ';
970         $select = html_select::make(make_grades_menu($this->assignment->grade), 'grade', $submission->grade, get_string('nograde'));
971         $select->nothingvalue = '-1';
972         $select->disabled = $disabled;
973         echo $OUTPUT->select($select);
974         echo '</div>';
976         echo '<div class="clearer"></div>';
977         echo '<div class="finalgrade">'.get_string('finalgrade', 'grades').': '.$grading_info->items[0]->grades[$userid]->str_grade.'</div>';
978         echo '<div class="clearer"></div>';
980         if (!empty($CFG->enableoutcomes)) {
981             foreach($grading_info->outcomes as $n=>$outcome) {
982                 echo '<div class="outcome"><label for="menuoutcome_'.$n.'">'.$outcome->name.'</label> ';
983                 $options = make_grades_menu(-$outcome->scaleid);
984                 if ($outcome->grades[$submission->userid]->locked) {
985                     $options[0] = get_string('nooutcome', 'grades');
986                     echo $options[$outcome->grades[$submission->userid]->grade];
987                 } else {
988                     $select = html_select::make($options, 'outcome_'.$n.'['.$userid.']', $outcome->grades[$submission->userid]->grade, get_string('nooutcome', 'grades'));
989                     $select->id = 'menuoutcome_'.$n;
990                     echo $OUTPUT->select($select);
991                 }
992                 echo '</div>';
993                 echo '<div class="clearer"></div>';
994             }
995         }
998         $this->preprocess_submission($submission);
1000         if ($disabled) {
1001             echo '<div class="disabledfeedback">'.$grading_info->items[0]->grades[$userid]->str_feedback.'</div>';
1003         } else {
1004             print_textarea($this->usehtmleditor, 14, 58, 0, 0, 'submissioncomment', $submission->submissioncomment, $this->course->id);
1005             if ($this->usehtmleditor) {
1006                 echo '<input type="hidden" name="format" value="'.FORMAT_HTML.'" />';
1007             } else {
1008                 echo '<div class="format">';
1009                 echo $OUTPUT->select(html_select::make(format_text_menu(), "format", $submission->format, false));
1010                 echo $OUTPUT->help_icon(moodle_help_icon::make("textformat", get_string("helpformatting")));
1011                 echo '</div>';
1012             }
1013         }
1015         $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? 'checked="checked"' : '';
1017         ///Print Buttons in Single View
1018         echo '<input type="hidden" name="mailinfo" value="0" />';
1019         echo '<input type="checkbox" id="mailinfo" name="mailinfo" value="1" '.$lastmailinfo.' /><label for="mailinfo">'.get_string('enableemailnotification','assignment').'</label>';
1020         echo '<div class="buttons">';
1021         echo '<input type="submit" name="submit" value="'.get_string('savechanges').'" onclick = "document.getElementById(\'submitform\').menuindex.value = document.getElementById(\'submitform\').grade.selectedIndex" />';
1022         echo '<input type="submit" name="cancel" value="'.get_string('cancel').'" />';
1023         //if there are more to be graded.
1024         if ($nextid) {
1025             echo '<input type="submit" name="saveandnext" value="'.get_string('saveandnext').'" onclick="saveNext()" />';
1026             echo '<input type="submit" name="next" value="'.get_string('next').'" onclick="setNext();" />';
1027         }
1028         echo '</div>';
1029         echo '</div></form>';
1031         $customfeedback = $this->custom_feedbackform($submission, true);
1032         if (!empty($customfeedback)) {
1033             echo $customfeedback;
1034         }
1036         echo '</td></tr>';
1038         ///End of teacher info row, Start of student info row
1039         echo '<tr>';
1040         echo '<td class="picture user">';
1041         echo $OUTPUT->user_picture(moodle_user_picture::make($user, $this->course->id));
1042         echo '</td>';
1043         echo '<td class="topic">';
1044         echo '<div class="from">';
1045         echo '<div class="fullname">'.fullname($user, true).'</div>';
1046         if ($submission->timemodified) {
1047             echo '<div class="time">'.userdate($submission->timemodified).
1048                                      $this->display_lateness($submission->timemodified).'</div>';
1049         }
1050         echo '</div>';
1051         $this->print_user_files($user->id);
1052         echo '</td>';
1053         echo '</tr>';
1055         ///End of student info row
1057         echo '</table>';
1059         echo $OUTPUT->footer();
1060     }
1062     /**
1063      *  Preprocess submission before grading
1064      *
1065      * Called by display_submission()
1066      * The default type does nothing here.
1067      *
1068      * @param object $submission The submission object
1069      */
1070     function preprocess_submission(&$submission) {
1071     }
1073     /**
1074      *  Display all the submissions ready for grading
1075      *
1076      * @global object
1077      * @global object
1078      * @global object
1079      * @global object
1080      * @param string $message
1081      * @return bool|void
1082      */
1083     function display_submissions($message='') {
1084         global $CFG, $DB, $USER, $DB, $OUTPUT, $PAGE;
1085         require_once($CFG->libdir.'/gradelib.php');
1087         /* first we check to see if the form has just been submitted
1088          * to request user_preference updates
1089          */
1091         if (isset($_POST['updatepref'])){
1092             $perpage = optional_param('perpage', 10, PARAM_INT);
1093             $perpage = ($perpage <= 0) ? 10 : $perpage ;
1094             set_user_preference('assignment_perpage', $perpage);
1095             set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
1096         }
1098         /* next we get perpage and quickgrade (allow quick grade) params
1099          * from database
1100          */
1101         $perpage    = get_user_preferences('assignment_perpage', 10);
1103         $quickgrade = get_user_preferences('assignment_quickgrade', 0);
1105         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);
1107         if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
1108             $uses_outcomes = true;
1109         } else {
1110             $uses_outcomes = false;
1111         }
1113         $page    = optional_param('page', 0, PARAM_INT);
1114         $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
1116     /// Some shortcuts to make the code read better
1118         $course     = $this->course;
1119         $assignment = $this->assignment;
1120         $cm         = $this->cm;
1122         $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
1123         add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->cm->id, $this->assignment->id, $this->cm->id);
1124         $PAGE->navbar->add($this->strsubmissions);
1125         $PAGE->set_title(format_string($this->assignment->name,true));
1126         $PAGE->set_button( update_module_button($cm->id, $course->id, $this->strassignment));
1127         echo $OUTPUT->header();
1129         $course_context = get_context_instance(CONTEXT_COURSE, $course->id);
1130         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
1131             echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">'
1132                 . get_string('seeallcoursegrades', 'grades') . '</a></div>';
1133         }
1135         if (!empty($message)) {
1136             echo $message;   // display messages here if any
1137         }
1139         $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1141     /// Check to see if groups are being used in this assignment
1143         /// find out current groups mode
1144         $groupmode = groups_get_activity_groupmode($cm);
1145         $currentgroup = groups_get_activity_group($cm, true);
1146         groups_print_activity_menu($cm, 'submissions.php?id=' . $this->cm->id);
1148         /// Get all ppl that are allowed to submit assignments
1149         if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $currentgroup, '', false)) {
1150             $users = array_keys($users);
1151         }
1153         // if groupmembersonly used, remove users who are not in any group
1154         if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
1155             if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1156                 $users = array_intersect($users, array_keys($groupingusers));
1157             }
1158         }
1160         $tablecolumns = array('picture', 'fullname', 'grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade');
1161         if ($uses_outcomes) {
1162             $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
1163         }
1165         $tableheaders = array('',
1166                               get_string('fullname'),
1167                               get_string('grade'),
1168                               get_string('comment', 'assignment'),
1169                               get_string('lastmodified').' ('.get_string('submission', 'assignment').')',
1170                               get_string('lastmodified').' ('.get_string('grade').')',
1171                               get_string('status'),
1172                               get_string('finalgrade', 'grades'));
1173         if ($uses_outcomes) {
1174             $tableheaders[] = get_string('outcome', 'grades');
1175         }
1177         require_once($CFG->libdir.'/tablelib.php');
1178         $table = new flexible_table('mod-assignment-submissions');
1180         $table->define_columns($tablecolumns);
1181         $table->define_headers($tableheaders);
1182         $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;currentgroup='.$currentgroup);
1184         $table->sortable(true, 'lastname');//sorted by lastname by default
1185         $table->collapsible(true);
1186         $table->initialbars(true);
1188         $table->column_suppress('picture');
1189         $table->column_suppress('fullname');
1191         $table->column_class('picture', 'picture');
1192         $table->column_class('fullname', 'fullname');
1193         $table->column_class('grade', 'grade');
1194         $table->column_class('submissioncomment', 'comment');
1195         $table->column_class('timemodified', 'timemodified');
1196         $table->column_class('timemarked', 'timemarked');
1197         $table->column_class('status', 'status');
1198         $table->column_class('finalgrade', 'finalgrade');
1199         if ($uses_outcomes) {
1200             $table->column_class('outcome', 'outcome');
1201         }
1203         $table->set_attribute('cellspacing', '0');
1204         $table->set_attribute('id', 'attempts');
1205         $table->set_attribute('class', 'submissions');
1206         $table->set_attribute('width', '100%');
1207         //$table->set_attribute('align', 'center');
1209         $table->no_sorting('finalgrade');
1210         $table->no_sorting('outcome');
1212         // Start working -- this is necessary as soon as the niceties are over
1213         $table->setup();
1215         if (empty($users)) {
1216             echo $OUTPUT->heading(get_string('nosubmitusers','assignment'));
1217             return true;
1218         }
1220     /// Construct the SQL
1222         if ($where = $table->get_sql_where()) {
1223             $where .= ' AND ';
1224         }
1226         if ($sort = $table->get_sql_sort()) {
1227             $sort = ' ORDER BY '.$sort;
1228         }
1230         $select = 'SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt,
1231                           s.id AS submissionid, s.grade, s.submissioncomment,
1232                           s.timemodified, s.timemarked,
1233                           COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ';
1234         $sql = 'FROM {user} u '.
1235                'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1236                                                                   AND s.assignment = '.$this->assignment->id.' '.
1237                'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1239         $table->pagesize($perpage, count($users));
1241         ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1242         $offset = $page * $perpage;
1244         $strupdate = get_string('update');
1245         $strgrade  = get_string('grade');
1246         $grademenu = make_grades_menu($this->assignment->grade);
1248         if (($ausers = $DB->get_records_sql($select.$sql.$sort, null, $table->get_page_start(), $table->get_page_size())) !== false) {
1249             $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
1250             foreach ($ausers as $auser) {
1251                 $final_grade = $grading_info->items[0]->grades[$auser->id];
1252                 $grademax = $grading_info->items[0]->grademax;
1253                 $final_grade->formatted_grade = round($final_grade->grade,2) .' / ' . round($grademax,2);
1254                 $locked_overridden = 'locked';
1255                 if ($final_grade->overridden) {
1256                     $locked_overridden = 'overridden';
1257                 }
1259             /// Calculate user status
1260                 $auser->status = ($auser->timemarked > 0) && ($auser->timemarked >= $auser->timemodified);
1261                 $picture = $OUTPUT->user_picture(moodle_user_picture::make($auser, $course->id));
1263                 if (empty($auser->submissionid)) {
1264                     $auser->grade = -1; //no submission yet
1265                 }
1267                 if (!empty($auser->submissionid)) {
1268                 ///Prints student answer and student modified date
1269                 ///attach file or print link to student answer, depending on the type of the assignment.
1270                 ///Refer to print_student_answer in inherited classes.
1271                     if ($auser->timemodified > 0) {
1272                         $studentmodified = '<div id="ts'.$auser->id.'">'.$this->print_student_answer($auser->id)
1273                                          . userdate($auser->timemodified).'</div>';
1274                     } else {
1275                         $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1276                     }
1277                 ///Print grade, dropdown or text
1278                     if ($auser->timemarked > 0) {
1279                         $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
1281                         if ($final_grade->locked or $final_grade->overridden) {
1282                             $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1283                         } else if ($quickgrade) {
1284                             $select = html_select::make(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, get_string('nograde'));
1285                             $select->nothingvalue = '-1';
1286                             $select->tabindex = $tabindex++;
1287                             $menu = $OUTPUT->select($select);
1288                             $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
1289                         } else {
1290                             $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1291                         }
1293                     } else {
1294                         $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1295                         if ($final_grade->locked or $final_grade->overridden) {
1296                             $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1297                         } else if ($quickgrade) {
1298                             $select = html_select::make(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, get_string('nograde'));
1299                             $select->nothingvalue = '-1';
1300                             $select->tabindex = $tabindex++;
1301                             $menu = $OUTPUT->select($select);
1302                             $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1303                         } else {
1304                             $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1305                         }
1306                     }
1307                 ///Print Comment
1308                     if ($final_grade->locked or $final_grade->overridden) {
1309                         $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';
1311                     } else if ($quickgrade) {
1312                         $comment = '<div id="com'.$auser->id.'">'
1313                                  . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1314                                  . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1315                     } else {
1316                         $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
1317                     }
1318                 } else {
1319                     $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1320                     $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1321                     $status          = '<div id="st'.$auser->id.'">&nbsp;</div>';
1323                     if ($final_grade->locked or $final_grade->overridden) {
1324                         $grade = '<div id="g'.$auser->id.'">'.$final_grade->formatted_grade . '</div>';
1325                     } else if ($quickgrade) {   // allow editing
1326                         $select = html_select::make(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, get_string('nograde'));
1327                         $select->nothingvalue = '-1';
1328                         $select->tabindex = $tabindex++;
1329                         $menu = $OUTPUT->select($select);
1330                         $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1331                     } else {
1332                         $grade = '<div id="g'.$auser->id.'">-</div>';
1333                     }
1335                     if ($final_grade->locked or $final_grade->overridden) {
1336                         $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
1337                     } else if ($quickgrade) {
1338                         $comment = '<div id="com'.$auser->id.'">'
1339                                  . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1340                                  . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1341                     } else {
1342                         $comment = '<div id="com'.$auser->id.'">&nbsp;</div>';
1343                     }
1344                 }
1346                 if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
1347                     $auser->status = 0;
1348                 } else {
1349                     $auser->status = 1;
1350                 }
1352                 $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
1354                 ///No more buttons, we use popups ;-).
1355                 $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1356                            . '&userid='.$auser->id.'&mode=single'.'&offset='.$offset++;
1358                 $link = html_link::make($popup_url, $buttontext);
1359                 $link->add_action(new popup_action('click', $link->url, 'grade'.$auser->id, array('height' => 600, 'width' => 700)));
1360                 $link->title = $buttontext;
1361                 $button = $OUTPUT->link($link);
1363                 $status  = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
1365                 $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';
1367                 $outcomes = '';
1369                 if ($uses_outcomes) {
1371                     foreach($grading_info->outcomes as $n=>$outcome) {
1372                         $outcomes .= '<div class="outcome"><label>'.$outcome->name.'</label>';
1373                         $options = make_grades_menu(-$outcome->scaleid);
1375                         if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
1376                             $options[0] = get_string('nooutcome', 'grades');
1377                             $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
1378                         } else {
1379                             $outcomes .= ' ';
1380                             $select = html_select::make($options, 'outcome_'.$n.'['.$auser->id.']', $outcome->grades[$auser->id]->grade, get_string('nooutcome', 'grades'));
1381                             $select->nothingvalue = '0';
1382                             $select->tabindex = $tabindex++;
1383                             $select->id = 'outcome_'.$n.'_'.$auser->id;
1384                             $outcomes .= $OUTPUT->select($select);
1385                         }
1386                         $outcomes .= '</div>';
1387                     }
1388                 }
1390                                 $userlink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $auser->id . '&amp;course=' . $course->id . '">' . fullname($auser) . '</a>';
1391                 $row = array($picture, $userlink, $grade, $comment, $studentmodified, $teachermodified, $status, $finalgrade);
1392                 if ($uses_outcomes) {
1393                     $row[] = $outcomes;
1394                 }
1396                 $table->add_data($row);
1397             }
1398         }
1400         /// Print quickgrade form around the table
1401         if ($quickgrade){
1402             echo '<form action="submissions.php" id="fastg" method="post">';
1403             echo '<div>';
1404             echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
1405             echo '<input type="hidden" name="mode" value="fastgrade" />';
1406             echo '<input type="hidden" name="page" value="'.$page.'" />';
1407             echo '</div>';
1408         }
1410         $table->print_html();  /// Print the whole table
1412         if ($quickgrade){
1413             $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? 'checked="checked"' : '';
1414             echo '<div class="fgcontrols">';
1415             echo '<div class="emailnotification">';
1416             echo '<label for="mailinfo">'.get_string('enableemailnotification','assignment').'</label>';
1417             echo '<input type="hidden" name="mailinfo" value="0" />';
1418             echo '<input type="checkbox" id="mailinfo" name="mailinfo" value="1" '.$lastmailinfo.' />';
1419             echo $OUTPUT->help_icon(moodle_help_icon::make('emailnotification', get_string('enableemailnotification', 'assignment'), 'assignment')).'</p></div>';
1420             echo '</div>';
1421             echo '<div class="fastgbutton"><input type="submit" name="fastg" value="'.get_string('saveallfeedback', 'assignment').'" /></div>';
1422             echo '</div>';
1423             echo '</form>';
1424         }
1425         /// End of fast grading form
1427         /// Mini form for setting user preference
1428         echo '<div class="qgprefs">';
1429         echo '<form id="options" action="submissions.php?id='.$this->cm->id.'" method="post"><div>';
1430         echo '<input type="hidden" name="updatepref" value="1" />';
1431         echo '<table id="optiontable">';
1432         echo '<tr><td>';
1433         echo '<label for="perpage">'.get_string('pagesize','assignment').'</label>';
1434         echo '</td>';
1435         echo '<td>';
1436         echo '<input type="text" id="perpage" name="perpage" size="1" value="'.$perpage.'" />';
1437         echo $OUTPUT->help_icon(moodle_help_icon::make('pagesize', get_string('pagesize','assignment'), 'assignment'));
1438         echo '</td></tr>';
1439         echo '<tr><td>';
1440         echo '<label for="quickgrade">'.get_string('quickgrade','assignment').'</label>';
1441         echo '</td>';
1442         echo '<td>';
1443         $checked = $quickgrade ? 'checked="checked"' : '';
1444         echo '<input type="checkbox" id="quickgrade" name="quickgrade" value="1" '.$checked.' />';
1445         echo $OUTPUT->help_icon(moodle_help_icon::make('quickgrade', get_string('quickgrade', 'assignment'), 'assignment')).'</p></div>';
1446         echo '</td></tr>';
1447         echo '<tr><td colspan="2">';
1448         echo '<input type="submit" value="'.get_string('savepreferences').'" />';
1449         echo '</td></tr></table>';
1450         echo '</div></form></div>';
1451         ///End of mini form
1452         echo $OUTPUT->footer();
1453     }
1455     /**
1456      *  Process teacher feedback submission
1457      *
1458      * This is called by submissions() when a grading even has taken place.
1459      * It gets its data from the submitted form.
1460      *
1461      * @global object
1462      * @global object
1463      * @global object
1464      * @return object|bool The updated submission object or false
1465      */
1466     function process_feedback() {
1467         global $CFG, $USER, $DB;
1468         require_once($CFG->libdir.'/gradelib.php');
1470         if (!$feedback = data_submitted()) {      // No incoming data?
1471             return false;
1472         }
1474         ///For save and next, we need to know the userid to save, and the userid to go
1475         ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1476         ///as the userid to store
1477         if ((int)$feedback->saveuserid !== -1){
1478             $feedback->userid = $feedback->saveuserid;
1479         }
1481         if (!empty($feedback->cancel)) {          // User hit cancel button
1482             return false;
1483         }
1485         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);
1487         // store outcomes if needed
1488         $this->process_outcomes($feedback->userid);
1490         $submission = $this->get_submission($feedback->userid, true);  // Get or make one
1492         if (!$grading_info->items[0]->grades[$feedback->userid]->locked and
1493             !$grading_info->items[0]->grades[$feedback->userid]->overridden) {
1495             $submission->grade      = $feedback->grade;
1496             $submission->submissioncomment    = $feedback->submissioncomment;
1497             $submission->format     = $feedback->format;
1498             $submission->teacher    = $USER->id;
1499             $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1500             if (!$mailinfo) {
1501                 $submission->mailed = 1;       // treat as already mailed
1502             } else {
1503                 $submission->mailed = 0;       // Make sure mail goes out (again, even)
1504             }
1505             $submission->timemarked = time();
1507             unset($submission->data1);  // Don't need to update this.
1508             unset($submission->data2);  // Don't need to update this.
1510             if (empty($submission->timemodified)) {   // eg for offline assignments
1511                 // $submission->timemodified = time();
1512             }
1514             $DB->update_record('assignment_submissions', $submission);
1516             // triger grade event
1517             $this->update_grade($submission);
1519             add_to_log($this->course->id, 'assignment', 'update grades',
1520                        'submissions.php?id='.$this->assignment->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
1521         }
1523         return $submission;
1525     }
1527     function process_outcomes($userid) {
1528         global $CFG, $USER;
1530         if (empty($CFG->enableoutcomes)) {
1531             return;
1532         }
1534         require_once($CFG->libdir.'/gradelib.php');
1536         if (!$formdata = data_submitted()) {
1537             return;
1538         }
1540         $data = array();
1541         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
1543         if (!empty($grading_info->outcomes)) {
1544             foreach($grading_info->outcomes as $n=>$old) {
1545                 $name = 'outcome_'.$n;
1546                 if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
1547                     $data[$n] = $formdata->{$name}[$userid];
1548                 }
1549             }
1550         }
1551         if (count($data) > 0) {
1552             grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1553         }
1555     }
1557     /**
1558      * Load the submission object for a particular user
1559      *
1560      * @global object
1561      * @global object
1562      * @param $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1563      * @param $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1564      * @param bool $teachermodified student submission set if false
1565      * @return object The submission
1566      */
1567     function get_submission($userid=0, $createnew=false, $teachermodified=false) {
1568         global $USER, $DB;
1570         if (empty($userid)) {
1571             $userid = $USER->id;
1572         }
1574         $submission = $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1576         if ($submission || !$createnew) {
1577             return $submission;
1578         }
1579         $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
1580         $DB->insert_record("assignment_submissions", $newsubmission);
1582         return $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1583     }
1585     /**
1586      * Instantiates a new submission object for a given user
1587      *
1588      * Sets the assignment, userid and times, everything else is set to default values.
1589      *
1590      * @param int $userid The userid for which we want a submission object
1591      * @param bool $teachermodified student submission set if false
1592      * @return object The submission
1593      */
1594     function prepare_new_submission($userid, $teachermodified=false) {
1595         $submission = new Object;
1596         $submission->assignment   = $this->assignment->id;
1597         $submission->userid       = $userid;
1598         $submission->timecreated = time();
1599         // teachers should not be modifying modified date, except offline assignments
1600         if ($teachermodified) {
1601             $submission->timemodified = 0;
1602         } else {
1603             $submission->timemodified = $submission->timecreated;
1604         }
1605         $submission->numfiles     = 0;
1606         $submission->data1        = '';
1607         $submission->data2        = '';
1608         $submission->grade        = -1;
1609         $submission->submissioncomment      = '';
1610         $submission->format       = 0;
1611         $submission->teacher      = 0;
1612         $submission->timemarked   = 0;
1613         $submission->mailed       = 0;
1614         return $submission;
1615     }
1617     /**
1618      * Return all assignment submissions by ENROLLED students (even empty)
1619      *
1620      * @param string $sort optional field names for the ORDER BY in the sql query
1621      * @param string $dir optional specifying the sort direction, defaults to DESC
1622      * @return array The submission objects indexed by id
1623      */
1624     function get_submissions($sort='', $dir='DESC') {
1625         return assignment_get_all_submissions($this->assignment, $sort, $dir);
1626     }
1628     /**
1629      * Counts all real assignment submissions by ENROLLED students (not empty ones)
1630      *
1631      * @param int $groupid optional If nonzero then count is restricted to this group
1632      * @return int The number of submissions
1633      */
1634     function count_real_submissions($groupid=0) {
1635         return assignment_count_real_submissions($this->cm, $groupid);
1636     }
1638     /**
1639      * Alerts teachers by email of new or changed assignments that need grading
1640      *
1641      * First checks whether the option to email teachers is set for this assignment.
1642      * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1643      * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1644      *
1645      * @global object
1646      * @global object
1647      * @param $submission object The submission that has changed
1648      * @return void
1649      */
1650     function email_teachers($submission) {
1651         global $CFG, $DB;
1653         if (empty($this->assignment->emailteachers)) {          // No need to do anything
1654             return;
1655         }
1657         $user = $DB->get_record('user', array('id'=>$submission->userid));
1659         if ($teachers = $this->get_graders($user)) {
1661             $strassignments = get_string('modulenameplural', 'assignment');
1662             $strassignment  = get_string('modulename', 'assignment');
1663             $strsubmitted  = get_string('submitted', 'assignment');
1665             foreach ($teachers as $teacher) {
1666                 $info = new object();
1667                 $info->username = fullname($user, true);
1668                 $info->assignment = format_string($this->assignment->name,true);
1669                 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
1671                 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1672                 $posttext = $this->email_teachers_text($info);
1673                 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
1675                 $eventdata = new object();
1676                 $eventdata->modulename       = 'assignment';
1677                 $eventdata->userfrom         = $user;
1678                 $eventdata->userto           = $teacher;
1679                 $eventdata->subject          = $postsubject;
1680                 $eventdata->fullmessage      = $posttext;
1681                 $eventdata->fullmessageformat = FORMAT_PLAIN;
1682                 $eventdata->fullmessagehtml  = $posthtml;
1683                 $eventdata->smallmessage     = '';
1684                 if ( events_trigger('message_send', $eventdata) > 0 ){
1685                 }
1686             }
1687         }
1688     }
1690     /**
1691      * @param string $filearea
1692      * @param array $args
1693      * @return bool
1694      */
1695     function send_file($filearea, $args) {
1696         debugging('plugin does not implement file sending', DEBUG_DEVELOPER);
1697         return false;
1698     }
1700     /**
1701      * Returns a list of teachers that should be grading given submission
1702      *
1703      * @param object $user
1704      * @return array
1705      */
1706     function get_graders($user) {
1707         //potential graders
1708         $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false);
1710         $graders = array();
1711         if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) {   // Separate groups are being used
1712             if ($groups = groups_get_all_groups($this->course->id, $user->id)) {  // Try to find all groups
1713                 foreach ($groups as $group) {
1714                     foreach ($potgraders as $t) {
1715                         if ($t->id == $user->id) {
1716                             continue; // do not send self
1717                         }
1718                         if (groups_is_member($group->id, $t->id)) {
1719                             $graders[$t->id] = $t;
1720                         }
1721                     }
1722                 }
1723             } else {
1724                 // user not in group, try to find graders without group
1725                 foreach ($potgraders as $t) {
1726                     if ($t->id == $user->id) {
1727                         continue; // do not send self
1728                     }
1729                     if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
1730                         $graders[$t->id] = $t;
1731                     }
1732                 }
1733             }
1734         } else {
1735             foreach ($potgraders as $t) {
1736                 if ($t->id == $user->id) {
1737                     continue; // do not send self
1738                 }
1739                 $graders[$t->id] = $t;
1740             }
1741         }
1742         return $graders;
1743     }
1745     /**
1746      * Creates the text content for emails to teachers
1747      *
1748      * @param $info object The info used by the 'emailteachermail' language string
1749      * @return string
1750      */
1751     function email_teachers_text($info) {
1752         $posttext  = format_string($this->course->shortname).' -> '.$this->strassignments.' -> '.
1753                      format_string($this->assignment->name)."\n";
1754         $posttext .= '---------------------------------------------------------------------'."\n";
1755         $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
1756         $posttext .= "\n---------------------------------------------------------------------\n";
1757         return $posttext;
1758     }
1760      /**
1761      * Creates the html content for emails to teachers
1762      *
1763      * @param $info object The info used by the 'emailteachermailhtml' language string
1764      * @return string
1765      */
1766     function email_teachers_html($info) {
1767         global $CFG;
1768         $posthtml  = '<p><font face="sans-serif">'.
1769                      '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname).'</a> ->'.
1770                      '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
1771                      '<a href="'.$CFG->wwwroot.'/mod/assignment/view.php?id='.$this->cm->id.'">'.format_string($this->assignment->name).'</a></font></p>';
1772         $posthtml .= '<hr /><font face="sans-serif">';
1773         $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
1774         $posthtml .= '</font><hr />';
1775         return $posthtml;
1776     }
1778     /**
1779      * Produces a list of links to the files uploaded by a user
1780      *
1781      * @param $userid int optional id of the user. If 0 then $USER->id is used.
1782      * @param $return boolean optional defaults to false. If true the list is returned rather than printed
1783      * @return string optional
1784      */
1785     function print_user_files($userid=0, $return=false) {
1786         global $CFG, $USER, $OUTPUT;
1788         if (!$userid) {
1789             if (!isloggedin()) {
1790                 return '';
1791             }
1792             $userid = $USER->id;
1793         }
1795         $output = '';
1797         $fs = get_file_storage();
1798         $browser = get_file_browser();
1800         $found = false;
1802         if ($files = $fs->get_area_files($this->context->id, 'assignment_submission', $userid, "timemodified", false)) {
1803             $button = new portfolio_add_button();
1804             foreach ($files as $file) {
1805                 $filename = $file->get_filename();
1806                 $found = true;
1807                 $mimetype = $file->get_mimetype();
1808                 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/assignment_submission/'.$userid.'/'.$filename);
1809                 $output .= '<a href="'.$path.'" ><img src="'.$OUTPUT->old_icon_url(file_mimetype_icon($mimetype)).'" class="icon" alt="'.$mimetype.'" />'.s($filename).'</a>';
1810                 if ($this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1811                     $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id, 'fileid' => $file->get_id()));
1812                     $button->set_formats(portfolio_format_from_file($file));
1813                     $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
1814                 }
1815                 $output .= '<br />';
1816             }
1817             if (count($files) > 1  && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1818                 $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id));
1819                 $button->set_formats(PORTFOLIO_PORMAT_FILE);
1820                 $output .= '<br />'  . $button->to_html();
1821             }
1822         }
1824         $output = '<div class="files">'.$output.'</div>';
1826         if ($return) {
1827             return $output;
1828         }
1829         echo $output;
1830     }
1832     /**
1833      * Count the files uploaded by a given user
1834      *
1835      * @param $userid int The user id
1836      * @return int
1837      */
1838     function count_user_files($userid) {
1839         $fs = get_file_storage();
1840         $files = $fs->get_area_files($this->context->id, 'assignment_submission', $userid, "id", false);
1841         return count($files);
1842     }
1844     /**
1845      * Returns true if the student is allowed to submit
1846      *
1847      * Checks that the assignment has started and, if the option to prevent late
1848      * submissions is set, also checks that the assignment has not yet closed.
1849      * @return boolean
1850      */
1851     function isopen() {
1852         $time = time();
1853         if ($this->assignment->preventlate && $this->assignment->timedue) {
1854             return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
1855         } else {
1856             return ($this->assignment->timeavailable <= $time);
1857         }
1858     }
1861     /**
1862      * Return true if is set description is hidden till available date
1863      *
1864      * This is needed by calendar so that hidden descriptions do not
1865      * come up in upcoming events.
1866      *
1867      * Check that description is hidden till available date
1868      * By default return false
1869      * Assignments types should implement this method if needed
1870      * @return boolen
1871      */
1872     function description_is_hidden() {
1873         return false;
1874     }
1876     /**
1877      * Return an outline of the user's interaction with the assignment
1878      *
1879      * The default method prints the grade and timemodified
1880      * @param $grade object
1881      * @return object with properties ->info and ->time
1882      */
1883     function user_outline($grade) {
1885         $result = new object();
1886         $result->info = get_string('grade').': '.$grade->str_long_grade;
1887         $result->time = $grade->dategraded;
1888         return $result;
1889     }
1891     /**
1892      * Print complete information about the user's interaction with the assignment
1893      *
1894      * @param $user object
1895      */
1896     function user_complete($user, $grade=null) {
1897         global $OUTPUT;
1898         if ($grade) {
1899             echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
1900             if ($grade->str_feedback) {
1901                 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
1902             }
1903         }
1905         if ($submission = $this->get_submission($user->id)) {
1907             $fs = get_file_storage();
1908             $browser = get_file_browser();
1910             if ($files = $fs->get_area_files($this->context->id, 'assignment_submission', $user->id, "timemodified", false)) {
1911                 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
1912                 foreach ($files as $file) {
1913                     $countfiles .= "; ".$file->get_filename();
1914                 }
1915             }
1917             echo $OUTPUT->box_start();
1918             echo get_string("lastmodified").": ";
1919             echo userdate($submission->timemodified);
1920             echo $this->display_lateness($submission->timemodified);
1922             $this->print_user_files($user->id);
1924             echo '<br />';
1926             $this->view_feedback($submission);
1928             echo $OUTPUT->box_end();
1930         } else {
1931             print_string("notsubmittedyet", "assignment");
1932         }
1933     }
1935     /**
1936      * Return a string indicating how late a submission is
1937      *
1938      * @param $timesubmitted int
1939      * @return string
1940      */
1941     function display_lateness($timesubmitted) {
1942         return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
1943     }
1945     /**
1946      * Empty method stub for all delete actions.
1947      */
1948     function delete() {
1949         //nothing by default
1950         redirect('view.php?id='.$this->cm->id);
1951     }
1953     /**
1954      * Empty custom feedback grading form.
1955      */
1956     function custom_feedbackform($submission, $return=false) {
1957         //nothing by default
1958         return '';
1959     }
1961     /**
1962      * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
1963      * for the course (see resource).
1964      *
1965      * Given a course_module object, this function returns any "extra" information that may be needed
1966      * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
1967      *
1968      * @param $coursemodule object The coursemodule object (record).
1969      * @return object An object on information that the coures will know about (most noticeably, an icon).
1970      *
1971      */
1972     function get_coursemodule_info($coursemodule) {
1973         return false;
1974     }
1976     /**
1977      * Plugin cron method - do not use $this here, create new assignment instances if needed.
1978      * @return void
1979      */
1980     function cron() {
1981         //no plugin cron by default - override if needed
1982     }
1984     /**
1985      * Reset all submissions
1986      */
1987     function reset_userdata($data) {
1988         global $CFG, $DB;
1990         if (!$DB->count_records('assignment', array('course'=>$data->courseid, 'assignmenttype'=>$this->type))) {
1991             return array(); // no assignments of this type present
1992         }
1994         $componentstr = get_string('modulenameplural', 'assignment');
1995         $status = array();
1997         $typestr = get_string('type'.$this->type, 'assignment');
1998         // ugly hack to support pluggable assignment type titles...
1999         if($typestr === '[[type'.$this->type.']]'){
2000             $typestr = get_string('type'.$this->type, 'assignment_'.$this->type);
2001         }
2003         if (!empty($data->reset_assignment_submissions)) {
2004             $assignmentssql = "SELECT a.id
2005                                  FROM {assignment} a
2006                                 WHERE a.course=? AND a.assignmenttype=?";
2007             $params = array($data->courseid, $this->type);
2009             // now get rid of all submissions and responses
2010             $fs = get_file_storage();
2011             if ($assignments = $DB->get_records_sql($assignmentssql, $params)) {
2012                 foreach ($assignments as $assignmentid=>$unused) {
2013                     if (!$cm = get_coursemodule_from_instance('assignment', $assignmentid)) {
2014                         continue;
2015                     }
2016                     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2017                     $fs->delete_area_files($context->id, 'assignment_submission');
2018                     $fs->delete_area_files($context->id, 'assignment_response');
2019                 }
2020             }
2022             $DB->delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)", $params);
2024             $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
2026             if (empty($data->reset_gradebook_grades)) {
2027                 // remove all grades from gradebook
2028                 assignment_reset_gradebook($data->courseid, $this->type);
2029             }
2030         }
2032         /// updating dates - shift may be negative too
2033         if ($data->timeshift) {
2034             shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
2035             $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
2036         }
2038         return $status;
2039     }
2042     function portfolio_exportable() {
2043         return false;
2044     }
2046     /**
2047      * base implementation for backing up subtype specific information
2048      * for one single module
2049      *
2050      * @param filehandle $bf file handle for xml file to write to
2051      * @param mixed $preferences the complete backup preference object
2052      *
2053      * @return boolean
2054      *
2055      * @static
2056      */
2057     static function backup_one_mod($bf, $preferences, $assignment) {
2058         return true;
2059     }
2061     /**
2062      * base implementation for backing up subtype specific information
2063      * for one single submission
2064      *
2065      * @param filehandle $bf file handle for xml file to write to
2066      * @param mixed $preferences the complete backup preference object
2067      * @param object $submission the assignment submission db record
2068      *
2069      * @return boolean
2070      *
2071      * @static
2072      */
2073     static function backup_one_submission($bf, $preferences, $assignment, $submission) {
2074         return true;
2075     }
2077     /**
2078      * base implementation for restoring subtype specific information
2079      * for one single module
2080      *
2081      * @param array  $info the array representing the xml
2082      * @param object $restore the restore preferences
2083      *
2084      * @return boolean
2085      *
2086      * @static
2087      */
2088     static function restore_one_mod($info, $restore, $assignment) {
2089         return true;
2090     }
2092     /**
2093      * base implementation for restoring subtype specific information
2094      * for one single submission
2095      *
2096      * @param object $submission the newly created submission
2097      * @param array  $info the array representing the xml
2098      * @param object $restore the restore preferences
2099      *
2100      * @return boolean
2101      *
2102      * @static
2103      */
2104     static function restore_one_submission($info, $restore, $assignment, $submission) {
2105         return true;
2106     }
2108 } ////// End of the assignment_base class
2110 /**
2111  * @package   mod-assignment
2112  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
2113  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2114  */
2115 class mod_assignment_upload_file_form extends moodleform {
2116     function definition() {
2117         $mform = $this->_form;
2118         $instance = $this->_customdata;
2120         //TODO: improve upload size checking
2121         $mform->setMaxFileSize($instance->assignment->maxbytes);
2123         // visible elements
2124         $mform->addElement('file', 'newfile', get_string('uploadafile'));
2126         // hidden params
2127         $mform->addElement('hidden', 'id', $instance->cm->id);
2128         $mform->setType('id', PARAM_INT);
2129         $mform->addElement('hidden', 'action', 'uploadfile');
2130         $mform->setType('action', PARAM_ALPHA);
2132         // buttons
2133         $this->add_action_buttons(false, get_string('uploadthisfile'));
2134     }
2138 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
2140 /**
2141  * Deletes an assignment instance
2142  *
2143  * This is done by calling the delete_instance() method of the assignment type class
2144  */
2145 function assignment_delete_instance($id){
2146     global $CFG, $DB;
2148     if (! $assignment = $DB->get_record('assignment', array('id'=>$id))) {
2149         return false;
2150     }
2152     // fall back to base class if plugin missing
2153     $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2154     if (file_exists($classfile)) {
2155         require_once($classfile);
2156         $assignmentclass = "assignment_$assignment->assignmenttype";
2158     } else {
2159         debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
2160         $assignmentclass = "assignment_base";
2161     }
2163     $ass = new $assignmentclass();
2164     return $ass->delete_instance($assignment);
2168 /**
2169  * Updates an assignment instance
2170  *
2171  * This is done by calling the update_instance() method of the assignment type class
2172  */
2173 function assignment_update_instance($assignment){
2174     global $CFG;
2176     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2178     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2179     $assignmentclass = "assignment_$assignment->assignmenttype";
2180     $ass = new $assignmentclass();
2181     return $ass->update_instance($assignment);
2185 /**
2186  * Adds an assignment instance
2187  *
2188  * This is done by calling the add_instance() method of the assignment type class
2189  */
2190 function assignment_add_instance($assignment) {
2191     global $CFG;
2193     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2195     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2196     $assignmentclass = "assignment_$assignment->assignmenttype";
2197     $ass = new $assignmentclass();
2198     return $ass->add_instance($assignment);
2202 /**
2203  * Returns an outline of a user interaction with an assignment
2204  *
2205  * This is done by calling the user_outline() method of the assignment type class
2206  */
2207 function assignment_user_outline($course, $user, $mod, $assignment) {
2208     global $CFG;
2210     require_once("$CFG->libdir/gradelib.php");
2211     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2212     $assignmentclass = "assignment_$assignment->assignmenttype";
2213     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2214     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2215     if (!empty($grades->items[0]->grades)) {
2216         return $ass->user_outline(reset($grades->items[0]->grades));
2217     } else {
2218         return null;
2219     }
2222 /**
2223  * Prints the complete info about a user's interaction with an assignment
2224  *
2225  * This is done by calling the user_complete() method of the assignment type class
2226  */
2227 function assignment_user_complete($course, $user, $mod, $assignment) {
2228     global $CFG;
2230     require_once("$CFG->libdir/gradelib.php");
2231     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2232     $assignmentclass = "assignment_$assignment->assignmenttype";
2233     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2234     $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2235     if (empty($grades->items[0]->grades)) {
2236         $grade = false;
2237     } else {
2238         $grade = reset($grades->items[0]->grades);
2239     }
2240     return $ass->user_complete($user, $grade);
2243 /**
2244  * Function to be run periodically according to the moodle cron
2245  *
2246  * Finds all assignment notifications that have yet to be mailed out, and mails them
2247  */
2248 function assignment_cron () {
2249     global $CFG, $USER, $DB;
2251     /// first execute all crons in plugins
2252     if ($plugins = get_plugin_list('assignment')) {
2253         foreach ($plugins as $plugin=>$dir) {
2254             require_once("$dir/assignment.class.php");
2255             $assignmentclass = "assignment_$plugin";
2256             $ass = new $assignmentclass();
2257             $ass->cron();
2258         }
2259     }
2261     /// Notices older than 1 day will not be mailed.  This is to avoid the problem where
2262     /// cron has not been running for a long time, and then suddenly people are flooded
2263     /// with mail from the past few weeks or months
2265     $timenow   = time();
2266     $endtime   = $timenow - $CFG->maxeditingtime;
2267     $starttime = $endtime - 24 * 3600;   /// One day earlier
2269     if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2271         $realuser = clone($USER);
2273         foreach ($submissions as $key => $submission) {
2274             if (! $DB->set_field("assignment_submissions", "mailed", "1", array("id"=>$submission->id))) {
2275                 echo "Could not update the mailed field for id $submission->id.  Not mailed.\n";
2276                 unset($submissions[$key]);
2277             }
2278         }
2280         $timenow = time();
2282         foreach ($submissions as $submission) {
2284             echo "Processing assignment submission $submission->id\n";
2286             if (! $user = $DB->get_record("user", array("id"=>$submission->userid))) {
2287                 echo "Could not find user $post->userid\n";
2288                 continue;
2289             }
2291             if (! $course = $DB->get_record("course", array("id"=>$submission->course))) {
2292                 echo "Could not find course $submission->course\n";
2293                 continue;
2294             }
2296             /// Override the language and timezone of the "current" user, so that
2297             /// mail is customised for the receiver.
2298             cron_setup_user($user, $course);
2300             if (!has_capability('moodle/course:view', get_context_instance(CONTEXT_COURSE, $submission->course), $user->id)) {
2301                 echo fullname($user)." not an active participant in " . format_string($course->shortname) . "\n";
2302                 continue;
2303             }
2305             if (! $teacher = $DB->get_record("user", array("id"=>$submission->teacher))) {
2306                 echo "Could not find teacher $submission->teacher\n";
2307                 continue;
2308             }
2310             if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2311                 echo "Could not find course module for assignment id $submission->assignment\n";
2312                 continue;
2313             }
2315             if (! $mod->visible) {    /// Hold mail notification for hidden assignments until later
2316                 continue;
2317             }
2319             $strassignments = get_string("modulenameplural", "assignment");
2320             $strassignment  = get_string("modulename", "assignment");
2322             $assignmentinfo = new object();
2323             $assignmentinfo->teacher = fullname($teacher);
2324             $assignmentinfo->assignment = format_string($submission->name,true);
2325             $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2327             $postsubject = "$course->shortname: $strassignments: ".format_string($submission->name,true);
2328             $posttext  = "$course->shortname -> $strassignments -> ".format_string($submission->name,true)."\n";
2329             $posttext .= "---------------------------------------------------------------------\n";
2330             $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2331             $posttext .= "---------------------------------------------------------------------\n";
2333             if ($user->mailformat == 1) {  // HTML
2334                 $posthtml = "<p><font face=\"sans-serif\">".
2335                 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> ->".
2336                 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2337                 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2338                 $posthtml .= "<hr /><font face=\"sans-serif\">";
2339                 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2340                 $posthtml .= "</font><hr />";
2341             } else {
2342                 $posthtml = "";
2343             }
2345             $eventdata = new object();
2346             $eventdata->modulename       = 'assignment';
2347             $eventdata->userfrom         = $teacher;
2348             $eventdata->userto           = $user;
2349             $eventdata->subject          = $postsubject;
2350             $eventdata->fullmessage      = $posttext;
2351             $eventdata->fullmessageformat = FORMAT_PLAIN;
2352             $eventdata->fullmessagehtml  = $posthtml;
2353             $eventdata->smallmessage     = '';
2354             if ( events_trigger('message_send', $eventdata) > 0 ){
2355                 echo "Error: assignment cron: Could not send out mail for id $submission->id to user $user->id ($user->email)\n";
2356             }
2357         }
2359         cron_setup_user();
2360     }
2362     return true;
2365 /**
2366  * Return grade for given user or all users.
2367  *
2368  * @param int $assignmentid id of assignment
2369  * @param int $userid optional user id, 0 means all users
2370  * @return array array of grades, false if none
2371  */
2372 function assignment_get_user_grades($assignment, $userid=0) {
2373     global $CFG, $DB;
2375     if ($userid) {
2376         $user = "AND u.id = :userid";
2377         $params = array('userid'=>$userid);
2378     } else {
2379         $user = "";
2380     }
2381     $params['aid'] = $assignment->id;
2383     $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2384                    s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2385               FROM {user} u, {assignment_submissions} s
2386              WHERE u.id = s.userid AND s.assignment = :aid
2387                    $user";
2389     return $DB->get_records_sql($sql, $params);
2392 /**
2393  * Update activity grades
2394  *
2395  * @param object $assignment
2396  * @param int $userid specific user only, 0 means all
2397  */
2398 function assignment_update_grades($assignment, $userid=0, $nullifnone=true) {
2399     global $CFG, $DB;
2400     require_once($CFG->libdir.'/gradelib.php');
2402     if ($assignment->grade == 0) {
2403         assignment_grade_item_update($assignment);
2405     } else if ($grades = assignment_get_user_grades($assignment, $userid)) {
2406         foreach($grades as $k=>$v) {
2407             if ($v->rawgrade == -1) {
2408                 $grades[$k]->rawgrade = null;
2409             }
2410         }
2411         assignment_grade_item_update($assignment, $grades);
2413     } else {
2414         assignment_grade_item_update($assignment);
2415     }
2418 /**
2419  * Update all grades in gradebook.
2420  */
2421 function assignment_upgrade_grades() {
2422     global $DB;
2424     $sql = "SELECT COUNT('x')
2425               FROM {assignment} a, {course_modules} cm, {modules} m
2426              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2427     $count = $DB->count_records_sql($sql);
2429     $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
2430               FROM {assignment} a, {course_modules} cm, {modules} m
2431              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2432     if ($rs = $DB->get_recordset_sql($sql)) {
2433         // too much debug output
2434         $pbar = new progress_bar('assignmentupgradegrades', 500, true);
2435         $i=0;
2436         foreach ($rs as $assignment) {
2437             $i++;
2438             upgrade_set_timeout(60*5); // set up timeout, may also abort execution
2439             assignment_update_grades($assignment);
2440             $pbar->update($i, $count, "Updating Assignment grades ($i/$count).");
2441         }
2442         $rs->close();
2443         upgrade_set_timeout(); // reset to default timeout
2444     }
2447 /**
2448  * Create grade item for given assignment
2449  *
2450  * @param object $assignment object with extra cmidnumber
2451  * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
2452  * @return int 0 if ok, error code otherwise
2453  */
2454 function assignment_grade_item_update($assignment, $grades=NULL) {
2455     global $CFG;
2456     require_once($CFG->libdir.'/gradelib.php');
2458     if (!isset($assignment->courseid)) {
2459         $assignment->courseid = $assignment->course;
2460     }
2462     $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
2464     if ($assignment->grade > 0) {
2465         $params['gradetype'] = GRADE_TYPE_VALUE;
2466         $params['grademax']  = $assignment->grade;
2467         $params['grademin']  = 0;
2469     } else if ($assignment->grade < 0) {
2470         $params['gradetype'] = GRADE_TYPE_SCALE;
2471         $params['scaleid']   = -$assignment->grade;
2473     } else {
2474         $params['gradetype'] = GRADE_TYPE_TEXT; // allow text comments only
2475     }
2477     if ($grades  === 'reset') {
2478         $params['reset'] = true;
2479         $grades = NULL;
2480     }
2482     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades, $params);
2485 /**
2486  * Delete grade item for given assignment
2487  *
2488  * @param object $assignment object
2489  * @return object assignment
2490  */
2491 function assignment_grade_item_delete($assignment) {
2492     global $CFG;
2493     require_once($CFG->libdir.'/gradelib.php');
2495     if (!isset($assignment->courseid)) {
2496         $assignment->courseid = $assignment->course;
2497     }
2499     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
2502 /**
2503  * Returns the users with data in one assignment (students and teachers)
2504  *
2505  * @param $assignmentid int
2506  * @return array of user objects
2507  */
2508 function assignment_get_participants($assignmentid) {
2509     global $CFG, $DB;
2511     //Get students
2512     $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2513                                         FROM {user} u,
2514                                              {assignment_submissions} a
2515                                        WHERE a.assignment = ? and
2516                                              u.id = a.userid", array($assignmentid));
2517     //Get teachers
2518     $teachers = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2519                                         FROM {user} u,
2520                                              {assignment_submissions} a
2521                                        WHERE a.assignment = ? and
2522                                              u.id = a.teacher", array($assignmentid));
2524     //Add teachers to students
2525     if ($teachers) {
2526         foreach ($teachers as $teacher) {
2527             $students[$teacher->id] = $teacher;
2528         }
2529     }
2530     //Return students array (it contains an array of unique users)
2531     return ($students);
2534 /**
2535  * Serves assingment submissions and otehr files.
2536  *
2537  * @param object $course
2538  * @param object $cminfo
2539  * @param object $context
2540  * @param string $filearea
2541  * @param array $args
2542  * @param bool $forcedownload
2543  * @return bool false if file not found, does not return if found - justsend the file
2544  */
2545 function assignment_pluginfile($course, $cminfo, $context, $filearea, $args, $forcedownload) {
2546     global $CFG, $DB;
2548     if (!$assignment = $DB->get_record('assignment', array('id'=>$cminfo->instance))) {
2549         return false;
2550     }
2551     if (!$cm = get_coursemodule_from_instance('assignment', $assignment->id, $course->id)) {
2552         return false;
2553     }
2555     require_login($course, false, $cm);
2557     require_once($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
2558     $assignmentclass = 'assignment_'.$assignment->assignmenttype;
2559     $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm, $course);
2561     return $assignmentinstance->send_file($filearea, $args);
2563 /**
2564  * Checks if a scale is being used by an assignment
2565  *
2566  * This is used by the backup code to decide whether to back up a scale
2567  * @param $assignmentid int
2568  * @param $scaleid int
2569  * @return boolean True if the scale is used by the assignment
2570  */
2571 function assignment_scale_used($assignmentid, $scaleid) {
2572     global $DB;
2574     $return = false;
2576     $rec = $DB->get_record('assignment', array('id'=>$assignmentid,'grade'=>-$scaleid));
2578     if (!empty($rec) && !empty($scaleid)) {
2579         $return = true;
2580     }
2582     return $return;
2585 /**
2586  * Checks if scale is being used by any instance of assignment
2587  *
2588  * This is used to find out if scale used anywhere
2589  * @param $scaleid int
2590  * @return boolean True if the scale is used by any assignment
2591  */
2592 function assignment_scale_used_anywhere($scaleid) {
2593     global $DB;
2595     if ($scaleid and $DB->record_exists('assignment', array('grade'=>-$scaleid))) {
2596         return true;
2597     } else {
2598         return false;
2599     }
2602 /**
2603  * Make sure up-to-date events are created for all assignment instances
2604  *
2605  * This standard function will check all instances of this module
2606  * and make sure there are up-to-date events created for each of them.
2607  * If courseid = 0, then every assignment event in the site is checked, else
2608  * only assignment events belonging to the course specified are checked.
2609  * This function is used, in its new format, by restore_refresh_events()
2610  *
2611  * @param $courseid int optional If zero then all assignments for all courses are covered
2612  * @return boolean Always returns true
2613  */
2614 function assignment_refresh_events($courseid = 0) {
2615     global $DB;
2617     if ($courseid == 0) {
2618         if (! $assignments = $DB->get_records("assignment")) {
2619             return true;
2620         }
2621     } else {
2622         if (! $assignments = $DB->get_records("assignment", array("course"=>$courseid))) {
2623             return true;
2624         }
2625     }
2626     $moduleid = $DB->get_field('modules', 'id', array('name'=>'assignment'));
2628     foreach ($assignments as $assignment) {
2629         $cm = get_coursemodule_from_id('assignment', $assignment->id);
2630         $event = new object();
2631         $event->name        = $assignment->name;
2632         $event->description = format_module_intro('assignment', $assignment, $cm->id);
2633         $event->timestart   = $assignment->timedue;
2635         if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
2636             update_event($event);
2638         } else {
2639             $event->courseid    = $assignment->course;
2640             $event->groupid     = 0;
2641             $event->userid      = 0;
2642             $event->modulename  = 'assignment';
2643             $event->instance    = $assignment->id;
2644             $event->eventtype   = 'due';
2645             $event->timeduration = 0;
2646             $event->visible     = $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$assignment->id));
2647             add_event($event);
2648         }
2650     }
2651     return true;
2654 /**
2655  * Print recent activity from all assignments in a given course
2656  *
2657  * This is used by the recent activity block
2658  */
2659 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
2660     global $CFG, $USER, $DB, $OUTPUT;
2662     // do not use log table if possible, it may be huge
2664     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
2665                                                      u.firstname, u.lastname, u.email, u.picture
2666                                                 FROM {assignment_submissions} asb
2667                                                      JOIN {assignment} a      ON a.id = asb.assignment
2668                                                      JOIN {course_modules} cm ON cm.instance = a.id
2669                                                      JOIN {modules} md        ON md.id = cm.module
2670                                                      JOIN {user} u            ON u.id = asb.userid
2671                                                WHERE asb.timemodified > ? AND
2672                                                      a.course = ? AND
2673                                                      md.name = 'assignment'
2674                                             ORDER BY asb.timemodified ASC", array($timestart, $course->id))) {
2675          return false;
2676     }
2678     $modinfo =& get_fast_modinfo($course); // reference needed because we might load the groups
2679     $show    = array();
2680     $grader  = array();
2682     foreach($submissions as $submission) {
2683         if (!array_key_exists($submission->cmid, $modinfo->cms)) {
2684             continue;
2685         }
2686         $cm = $modinfo->cms[$submission->cmid];
2687         if (!$cm->uservisible) {
2688             continue;
2689         }
2690         if ($submission->userid == $USER->id) {
2691             $show[] = $submission;
2692             continue;
2693         }
2695         // the act of sumbitting of assignment may be considered private - only graders will see it if specified
2696         if (empty($CFG->assignment_showrecentsubmissions)) {
2697             if (!array_key_exists($cm->id, $grader)) {
2698                 $grader[$cm->id] = has_capability('moodle/grade:viewall', get_context_instance(CONTEXT_MODULE, $cm->id));
2699             }
2700             if (!$grader[$cm->id]) {
2701                 continue;
2702             }
2703         }
2705         $groupmode = groups_get_activity_groupmode($cm, $course);
2707         if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2708             if (isguestuser()) {
2709                 // shortcut - guest user does not belong into any group
2710                 continue;
2711             }
2713             if (is_null($modinfo->groups)) {
2714                 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2715             }
2717             // this will be slow - show only users that share group with me in this cm
2718             if (empty($modinfo->groups[$cm->id])) {
2719                 continue;
2720             }
2721             $usersgroups =  groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
2722             if (is_array($usersgroups)) {
2723                 $usersgroups = array_keys($usersgroups);
2724                 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2725                 if (empty($intersect)) {
2726                     continue;
2727                 }
2728             }
2729         }
2730         $show[] = $submission;
2731     }
2733     if (empty($show)) {
2734         return false;
2735     }
2737     echo $OUTPUT->heading(get_string('newsubmissions', 'assignment').':');
2739     foreach ($show as $submission) {
2740         $cm = $modinfo->cms[$submission->cmid];
2741         $link = $CFG->wwwroot.'/mod/assignment/view.php?id='.$cm->id;
2742         print_recent_activity_note($submission->timemodified, $submission, $cm->name, $link, false, $viewfullnames);
2743     }
2745     return true;
2749 /**
2750  * Returns all assignments since a given time in specified forum.
2751  */
2752 function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0)  {
2753     global $CFG, $COURSE, $USER, $DB;
2755     if ($COURSE->id == $courseid) {
2756         $course = $COURSE;
2757     } else {
2758         $course = $DB->get_record('course', array('id'=>$courseid));
2759     }
2761     $modinfo =& get_fast_modinfo($course);
2763     $cm = $modinfo->cms[$cmid];
2765     $params = array();
2766     if ($userid) {
2767         $userselect = "AND u.id = :userid";
2768         $params['userid'] = $userid;
2769     } else {
2770         $userselect = "";
2771     }
2773     if ($groupid) {
2774         $groupselect = "AND gm.groupid = :groupid";
2775         $groupjoin   = "JOIN {groups_members} gm ON  gm.userid=u.id";
2776         $params['groupid'] = $groupid;
2777     } else {
2778         $groupselect = "";
2779         $groupjoin   = "";
2780     }
2782     $params['cminstance'] = $cm->instance;
2783     $params['timestart'] = $timestart;
2785     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, asb.userid,
2786                                                      u.firstname, u.lastname, u.email, u.picture
2787                                                 FROM {assignment_submissions} asb
2788                                                 JOIN {assignment} a      ON a.id = asb.assignment
2789                                                 JOIN {user} u            ON u.id = asb.userid
2790                                           $groupjoin
2791                                                WHERE asb.timemodified > :timestart AND a.id = :cminstance
2792                                                      $userselect $groupselect
2793                                             ORDER BY asb.timemodified ASC", $params)) {
2794          return;
2795     }
2797     $groupmode       = groups_get_activity_groupmode($cm, $course);
2798     $cm_context      = get_context_instance(CONTEXT_MODULE, $cm->id);
2799     $grader          = has_capability('moodle/grade:viewall', $cm_context);
2800     $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
2801     $viewfullnames   = has_capability('moodle/site:viewfullnames', $cm_context);
2803     if (is_null($modinfo->groups)) {
2804         $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2805     }
2807     $show = array();
2809     foreach($submissions as $submission) {
2810         if ($submission->userid == $USER->id) {
2811             $show[] = $submission;
2812             continue;
2813         }
2814         // the act of submitting of assignment may be considered private - only graders will see it if specified
2815         if (empty($CFG->assignment_showrecentsubmissions)) {
2816             if (!$grader) {
2817                 continue;
2818             }
2819         }
2821         if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
2822             if (isguestuser()) {
2823                 // shortcut - guest user does not belong into any group
2824                 continue;
2825             }
2827             // this will be slow - show only users that share group with me in this cm
2828             if (empty($modinfo->groups[$cm->id])) {
2829                 continue;
2830             }
2831             $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
2832             if (is_array($usersgroups)) {
2833                 $usersgroups = array_keys($usersgroups);
2834                 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2835                 if (empty($intersect)) {
2836                     continue;
2837                 }
2838             }
2839         }
2840         $show[] = $submission;
2841     }
2843     if (empty($show)) {
2844         return;
2845     }
2847     if ($grader) {
2848         require_once($CFG->libdir.'/gradelib.php');
2849         $userids = array();
2850         foreach ($show as $id=>$submission) {
2851             $userids[] = $submission->userid;
2853         }
2854         $grades = grade_get_grades($courseid, 'mod', 'assignment', $cm->instance, $userids);
2855     }
2857     $aname = format_string($cm->name,true);
2858     foreach ($show as $submission) {
2859         $tmpactivity = new object();
2861         $tmpactivity->type         = 'assignment';
2862         $tmpactivity->cmid         = $cm->id;
2863         $tmpactivity->name         = $aname;
2864         $tmpactivity->sectionnum   = $cm->sectionnum;
2865         $tmpactivity->timestamp    = $submission->timemodified;
2867         if ($grader) {
2868             $tmpactivity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
2869         }
2871         $tmpactivity->user->userid   = $submission->userid;
2872         $tmpactivity->user->fullname = fullname($submission, $viewfullnames);
2873         $tmpactivity->user->picture  = $submission->picture;
2875         $activities[$index++] = $tmpactivity;
2876     }
2878     return;
2881 /**
2882  * Print recent activity from all assignments in a given course
2883  *
2884  * This is used by course/recent.php
2885  */
2886 function assignment_print_recent_mod_activity($activity, $courseid, $detail, $modnames)  {
2887     global $CFG, $OUTPUT;
2889     echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
2891     echo "<tr><td class=\"userpicture\" valign=\"top\">";
2892     echo $OUTPUT->user_picture(moodle_user_picture::make($activity->user, $courseid));
2893     echo "</td><td>";
2895     if ($detail) {
2896         $modname = $modnames[$activity->type];
2897         echo '<div class="title">';
2898         echo "<img src=\"" . $OUTPUT->mod_icon_url('icon', 'assignment') . "\" ".
2899              "class=\"icon\" alt=\"$modname\">";
2900         echo "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id={$activity->cmid}\">{$activity->name}</a>";
2901         echo '</div>';
2902     }
2904     if (isset($activity->grade)) {
2905         echo '<div class="grade">';
2906         echo get_string('grade').': ';
2907         echo $activity->grade;
2908         echo '</div>';
2909     }
2911     echo '<div class="user">';
2912     echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->userid}&amp;course=$courseid\">"
2913          ."{$activity->user->fullname}</a>  - ".userdate($activity->timestamp);
2914     echo '</div>';
2916     echo "</td></tr></table>";
2919 /// GENERIC SQL FUNCTIONS
2921 /**
2922  * Fetch info from logs
2923  *
2924  * @param $log object with properties ->info (the assignment id) and ->userid
2925  * @return array with assignment name and user firstname and lastname
2926  */
2927 function assignment_log_info($log) {
2928     global $CFG, $DB;
2930     return $DB->get_record_sql("SELECT a.name, u.firstname, u.lastname
2931                                   FROM {assignment} a, {user} u
2932                                  WHERE a.id = ? AND u.id = ?", array($log->info, $log->userid));
2935 /**
2936  * Return list of marked submissions that have not been mailed out for currently enrolled students
2937  *
2938  * @return array
2939  */
2940 function assignment_get_unmailed_submissions($starttime, $endtime) {
2941     global $CFG, $DB;
2943     return $DB->get_records_sql("SELECT s.*, a.course, a.name
2944                                    FROM {assignment_submissions} s,
2945                                         {assignment} a
2946                                   WHERE s.mailed = 0
2947                                         AND s.timemarked <= ?
2948                                         AND s.timemarked >= ?
2949                                         AND s.assignment = a.id", array($endtime, $starttime));
2952 /**
2953  * Counts all real assignment submissions by ENROLLED students (not empty ones)
2954  *
2955  * There are also assignment type methods count_real_submissions() wich in the default
2956  * implementation simply call this function.
2957  * @param $groupid int optional If nonzero then count is restricted to this group
2958  * @return int The number of submissions
2959  */
2960 function assignment_count_real_submissions($cm, $groupid=0) {
2961     global $CFG, $DB;
2963     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2965     // this is all the users with this capability set, in this context or higher
2966     if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $groupid, '', false)) {
2967         $users = array_keys($users);
2968     }
2970     // if groupmembersonly used, remove users who are not in any group
2971     if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
2972         if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
2973             $users = array_intersect($users, array_keys($groupingusers));
2974         }
2975     }
2977     if (empty($users)) {
2978         return 0;
2979     }
2981     $userlists = implode(',', $users);
2983     return $DB->count_records_sql("SELECT COUNT('x')
2984                                      FROM {assignment_submissions}
2985                                     WHERE assignment = ? AND
2986                                           timemodified > 0 AND
2987                                           userid IN ($userlists)", array($cm->instance));
2991 /**
2992  * Return all assignment submissions by ENROLLED students (even empty)
2993  *
2994  * There are also assignment type methods get_submissions() wich in the default
2995  * implementation simply call this function.
2996  * @param $sort string optional field names for the ORDER BY in the sql query
2997  * @param $dir string optional specifying the sort direction, defaults to DESC
2998  * @return array The submission objects indexed by id
2999  */
3000 function assignment_get_all_submissions($assignment, $sort="", $dir="DESC") {
3001 /// Return all assignment submissions by ENROLLED students (even empty)
3002     global $CFG, $DB;
3004     if ($sort == "lastname" or $sort == "firstname") {
3005         $sort = "u.$sort $dir";
3006     } else if (empty($sort)) {
3007         $sort = "a.timemodified DESC";
3008     } else {
3009         $sort = "a.$sort $dir";
3010     }
3012     /* not sure this is needed at all since assignmenet already has a course define, so this join?
3013     $select = "s.course = '$assignment->course' AND";
3014     if ($assignment->course == SITEID) {
3015         $select = '';
3016     }*/
3018     return $DB->get_records_sql("SELECT a.*
3019                                    FROM {assignment_submissions} a, {user} u
3020                                   WHERE u.id = a.userid
3021                                         AND a.assignment = ?
3022                                ORDER BY $sort", array($assignment->id));
3026 /**
3027  * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
3028  * for the course (see resource).
3029  *
3030  * Given a course_module object, this function returns any "extra" information that may be needed
3031  * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
3032  *
3033  * @param $coursemodule object The coursemodule object (record).
3034  * @return object An object on information that the coures will know about (most noticeably, an icon).
3035  *
3036  */
3037 function assignment_get_coursemodule_info($coursemodule) {
3038     global $CFG, $DB;
3040     if (! $assignment = $DB->get_record('assignment', array('id'=>$coursemodule->instance), 'id, assignmenttype, name')) {
3041         return false;
3042     }
3044     $libfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
3046     if (file_exists($libfile)) {
3047         require_once($libfile);
3048         $assignmentclass = "assignment_$assignment->assignmenttype";
3049         $ass = new $assignmentclass('staticonly');
3050         if ($result = $ass->get_coursemodule_info($coursemodule)) {
3051             return $result;
3052         } else {
3053             $info = new object();
3054             $info->name = $assignment->name;
3055             return $info;
3056         }
3058     } else {
3059         debugging('Incorrect assignment type: '.$assignment->assignmenttype);
3060         return false;
3061     }
3066 /// OTHER GENERAL FUNCTIONS FOR ASSIGNMENTS  ///////////////////////////////////////
3068 /**
3069  * Returns an array of installed assignment types indexed and sorted by name
3070  *
3071  * @return array The index is the name of the assignment type, the value its full name from the language strings
3072  */
3073 function assignment_types() {
3074     $types = array();
3075     $names = get_plugin_list('assignment');
3076     foreach ($names as $name=>$dir) {
3077         $types[$name] = get_string('type'.$name, 'assignment');
3079         // ugly hack to support pluggable assignment type titles..
3080         if ($types[$name] == '[[type'.$name.']]') {
3081             $types[$name] = get_string('type'.$name, 'assignment_'.$name);
3082         }
3083     }
3084     asort($types);
3085     return $types;
3088 function assignment_print_overview($courses, &$htmlarray) {
3089     global $USER, $CFG, $DB;
3091     if (empty($courses) || !is_array($courses) || count($courses) == 0) {
3092         return array();
3093     }
3095     if (!$assignments = get_all_instances_in_courses('assignment',$courses)) {
3096         return;
3097     }
3099     $assignmentids = array();
3101     // Do assignment_base::isopen() here without loading the whole thing for speed
3102     foreach ($assignments as $key => $assignment) {
3103         $time = time();
3104         if ($assignment->timedue) {
3105             if ($assignment->preventlate) {
3106                 $isopen = ($assignment->timeavailable <= $time && $time <= $assignment->timedue);
3107             } else {
3108                 $isopen = ($assignment->timeavailable <= $time);
3109             }
3110         }
3111         if (empty($isopen) || empty($assignment->timedue)) {
3112             unset($assignments[$key]);
3113         }else{
3114             $assignmentids[] = $assignment->id;
3115         }
3116     }
3118     if(empty($assignmentids)){
3119         // no assigments to look at - we're done
3120         return true;
3121     }
3123     $strduedate = get_string('duedate', 'assignment');
3124     $strduedateno = get_string('duedateno', 'assignment');
3125     $strgraded = get_string('graded', 'assignment');
3126     $strnotgradedyet = get_string('notgradedyet', 'assignment');
3127     $strnotsubmittedyet = get_string('notsubmittedyet', 'assignment');
3128     $strsubmitted = get_string('submitted', 'assignment');
3129     $strassignment = get_string('modulename', 'assignment');
3130     $strreviewed = get_string('reviewed','assignment');
3133     // NOTE: we do all possible database work here *outside* of the loop to ensure this scales
3134     //
3135     list($sqlassignmentids, $assignmentidparams) = $DB->get_in_or_equal($assignmentids);
3137     // build up and array of unmarked submissions indexed by assigment id/ userid
3138     // for use where the user has grading rights on assigment
3139     $rs = $DB->get_recordset_sql("SELECT id, assignment, userid
3140                             FROM {assignment_submissions}
3141                             WHERE teacher = 0 AND timemarked = 0
3142                             AND assignment $sqlassignmentids", $assignmentidparams);
3144     $unmarkedsubmissions = array();
3145     foreach ($rs as $rd) {
3146         $unmarkedsubmissions[$rd->assignment][$rd->userid] = $rd->id;
3147     }
3148     $rs->close();
3151     // get all user submissions, indexed by assigment id
3152     $mysubmissions = $DB->get_records_sql("SELECT assignment, timemarked, teacher, grade
3153                                       FROM {assignment_submissions}
3154                                       WHERE userid = ? AND
3155                                       assignment $sqlassignmentids", array_merge(array($USER->id), $assignmentidparams));
3157     foreach ($assignments as $assignment) {
3158         $str = '<div class="assignment overview"><div class="name">'.$strassignment. ': '.
3159                '<a '.($assignment->visible ? '':' class="dimmed"').
3160                'title="'.$strassignment.'" href="'.$CFG->wwwroot.
3161                '/mod/assignment/view.php?id='.$assignment->coursemodule.'">'.
3162                $assignment->name.'</a></div>';
3163         if ($assignment->timedue) {
3164             $str .= '<div class="info">'.$strduedate.': '.userdate($assignment->timedue).'</div>';
3165         } else {
3166             $str .= '<div class="info">'.$strduedateno.'</div>';
3167         }
3168         $context = get_context_instance(CONTEXT_MODULE, $assignment->coursemodule);
3169         if (has_capability('mod/assignment:grade', $context)) {
3171             // count how many people can submit
3172             $submissions = 0; // init
3173             if ($students = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', 0, '', false)) {
3174                 foreach($students as $student){
3175                     if(isset($unmarkedsubmissions[$assignment->id][$student->id])){
3176                         $submissions++;
3177                     }
3178                 }
3179             }
3181             if ($submissions) {
3182                 $str .= get_string('submissionsnotgraded', 'assignment', $submissions);
3183             }
3184         } else {
3185             if(isset($mysubmissions[$assignment->id])){
3187                 $submission = $mysubmissions[$assignment->id];
3189                 if ($submission->teacher == 0 && $submission->timemarked == 0) {
3190                     $str .= $strsubmitted . ', ' . $strnotgradedyet;
3191                 } else if ($submission->grade <= 0) {
3192                     $str .= $strsubmitted . ', ' . $strreviewed;
3193                 } else {
3194                     $str .= $strsubmitted . ', ' . $strgraded;
3195                 }
3196             } else {
3197                 $str .= $strnotsubmittedyet . ' ' . assignment_display_lateness(time(), $assignment->timedue);
3198             }
3199         }
3200         $str .= '</div>';
3201         if (empty($htmlarray[$assignment->course]['assignment'])) {
3202             $htmlarray[$assignment->course]['assignment'] = $str;
3203         } else {
3204             $htmlarray[$assignment->course]['assignment'] .= $str;
3205         }
3206     }
3209 function assignment_display_lateness($timesubmitted, $timedue) {
3210     if (!$timedue) {
3211         return '';
3212     }
3213     $time = $timedue - $timesubmitted;
3214     if ($time < 0) {
3215         $timetext = get_string('late', 'assignment', format_time($time));
3216         return ' (<span class="late">'.$timetext.'</span>)';
3217     } else {
3218         $timetext = get_string('early', 'assignment', format_time($time));
3219         return ' (<span class="early">'.$timetext.'</span>)';
3220     }
3223 function assignment_get_view_actions() {
3224     return array('view');
3227 function assignment_get_post_actions() {
3228     return array('upload');
3231 function assignment_get_types() {
3232     global $CFG;
3233     $types = array();
3235     $type = new object();
3236     $type->modclass = MOD_CLASS_ACTIVITY;
3237     $type->type = "assignment_group_start";
3238     $type->typestr = '--'.get_string('modulenameplural', 'assignment');
3239     $types[] = $type;
3241     $standardassignments = array('upload','online','uploadsingle','offline');
3242     foreach ($standardassignments as $assignmenttype) {
3243         $type = new object();
3244         $type->modclass = MOD_CLASS_ACTIVITY;
3245         $type->type = "assignment&amp;type=$assignmenttype";
3246         $type->typestr = get_string("type$assignmenttype", 'assignment');
3247         $types[] = $type;
3248     }
3250     /// Drop-in extra assignment types
3251     $assignmenttypes = get_list_of_plugins('mod/assignment/type');
3252     foreach ($assignmenttypes as $assignmenttype) {
3253         if (!empty($CFG->{'assignment_hide_'.$assignmenttype})) {  // Not wanted
3254             continue;
3255         }
3256         if (!in_array($assignmenttype, $standardassignments)) {
3257             $type = new object();
3258             $type->modclass = MOD_CLASS_ACTIVITY;
3259             $type->type = "assignment&amp;type=$assignmenttype";
3260             $type->typestr = get_string("type$assignmenttype", 'assignment_'.$assignmenttype);
3261             $types[] = $type;
3262         }
3263     }
3265     $type = new object();
3266     $type->modclass = MOD_CLASS_ACTIVITY;
3267     $type->type = "assignment_group_end";
3268     $type->typestr = '--';
3269     $types[] = $type;
3271     return $types;
3274 /**
3275  * Removes all grades from gradebook
3276  * @param int $courseid
3277  * @param string optional type
3278  */
3279 function assignment_reset_gradebook($courseid, $type='') {
3280     global $CFG, $DB;
3282     $params = array('courseid'=>$courseid);
3283     if ($type) {
3284         $type = "AND a.assignmenttype= :type";
3285         $params['type'] = $type;
3286     }
3288     $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
3289               FROM {assignment} a, {course_modules} cm, {modules} m
3290              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id AND a.course=:courseid $type";
3292     if ($assignments = $DB->get_records_sql($sql, $params)) {
3293         foreach ($assignments as $assignment) {
3294             assignment_grade_item_update($assignment, 'reset');
3295         }
3296     }
3299 /**
3300  * This function is used by the reset_course_userdata function in moodlelib.
3301  * This function will remove all posts from the specified assignment
3302  * and clean up any related data.
3303  * @param $data the data submitted from the reset course.
3304  * @return array status array
3305  */
3306 function assignment_reset_userdata($data) {
3307     global $CFG;
3309     $status = array();
3311     foreach (get_plugin_list('mod/assignment/type') as $type=>$dir) {
3312         require_once("$dir/assignment.class.php");
3313         $assignmentclass = "assignment_$type";
3314         $ass = new $assignmentclass();
3315         $status = array_merge($status, $ass->reset_userdata($data));
3316     }
3318     return $status;
3321 /**
3322  * Implementation of the function for printing the form elements that control
3323  * whether the course reset functionality affects the assignment.
3324  * @param $mform form passed by reference
3325  */
3326 function assignment_reset_course_form_definition(&$mform) {
3327     $mform->addElement('header', 'assignmentheader', get_string('modulenameplural', 'assignment'));
3328     $mform->addElement('advcheckbox', 'reset_assignment_submissions', get_string('deleteallsubmissions','assignment'));
3331 /**
3332  * Course reset form defaults.
3333  */
3334 function assignment_reset_course_form_defaults($course) {
3335     return array('reset_assignment_submissions'=>1);
3338 /**
3339  * Returns all other caps used in module
3340  */
3341 function assignment_get_extra_capabilities() {
3342     return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames');
3345 /**
3346  * @package   mod-assignment
3347  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
3348  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3349  */
3350 class assignment_portfolio_caller extends portfolio_module_caller_base {
3352     /**
3353     * the assignment subclass
3354     */
3355     private $assignment;
3357     /**
3358     * the file to include when waking up to load the assignment subclass def
3359     */
3360     private $assignmentfile;
3362     /**
3363     * callback arg for a single file export
3364     */
3365     protected $fileid;
3367     public static function expected_callbackargs() {
3368         return array(
3369             'id'     => true,
3370             'fileid' => false,
3371         );
3372     }
3374     public function load_data() {
3375         global $DB, $CFG;
3377         if (! $this->cm = get_coursemodule_from_id('assignment', $this->id)) {
3378             throw new portfolio_caller_exception('invalidcoursemodule');
3379         }
3381         if (! $assignment = $DB->get_record("assignment", array("id"=>$this->cm->instance))) {
3382             throw new portfolio_caller_exception('invalidid', 'assignment');
3383         }
3385         $this->assignmentfile = $CFG->dirroot . '/mod/assignment/type/' . $assignment->assignmenttype . '/assignment.class.php';
3386         require_once($this->assignmentfile);
3387         $assignmentclass = "assignment_$assignment->assignmenttype";
3389         $this->assignment = new $assignmentclass($this->cm->id, $assignment, $this->cm);
3391         if (!$this->assignment->portfolio_exportable()) {
3392             throw new portfolio_caller_exception('notexportable', 'portfolio', $this->get_return_url());
3393         }
3395         $this->set_file_and_format_data($this->fileid, $this->assignment->context->id, 'assignment_submission', $this->user->id);
3396         if (empty($this->supportedformats) && is_callable(array($this->assignment, 'portfolio_supported_formats'))) {
3397             $this->supportedformats = $this->assignment->portfolio_supported_formats();
3398         }
3399     }
3401     public function prepare_package() {