MDL-18910 moving modedit features to modname_supports()
[moodle.git] / mod / assignment / lib.php
1 <?PHP  // $Id$
3 /**
4  * assignment_base is the base class for assignment types
5  *
6  * This class provides all the functionality for an assignment
7  */
9 require_once($CFG->libdir.'/eventslib.php');
10 require_once($CFG->libdir.'/formslib.php');
11 require_once($CFG->libdir.'/portfoliolib.php');
13 DEFINE ('ASSIGNMENT_COUNT_WORDS', 1);
14 DEFINE ('ASSIGNMENT_COUNT_LETTERS', 2);
16 /**
17  * Standard base class for all assignment submodules (assignment types).
18  */
19 class assignment_base {
21     var $cm;
22     var $course;
23     var $assignment;
24     var $strassignment;
25     var $strassignments;
26     var $strsubmissions;
27     var $strlastmodified;
28     var $pagetitle;
29     var $usehtmleditor;
30     var $defaultformat;
31     var $context;
32     var $type;
34     /**
35      * Constructor for the base assignment class
36      *
37      * Constructor for the base assignment class.
38      * If cmid is set create the cm, course, assignment objects.
39      * If the assignment is hidden and the user is not a teacher then
40      * this prints a page header and notice.
41      *
42      * @param cmid   integer, the current course module id - not set for new assignments
43      * @param assignment   object, usually null, but if we have it we pass it to save db access
44      * @param cm   object, usually null, but if we have it we pass it to save db access
45      * @param course   object, usually null, but if we have it we pass it to save db access
46      */
47     function assignment_base($cmid='staticonly', $assignment=NULL, $cm=NULL, $course=NULL) {
48         global $COURSE, $DB;
50         if ($cmid == 'staticonly') {
51             //use static functions only!
52             return;
53         }
55         global $CFG;
57         if ($cm) {
58             $this->cm = $cm;
59         } else if (! $this->cm = get_coursemodule_from_id('assignment', $cmid)) {
60             print_error('invalidcoursemodule');
61         }
63         $this->context = get_context_instance(CONTEXT_MODULE, $this->cm->id);
65         if ($course) {
66             $this->course = $course;
67         } else if ($this->cm->course == $COURSE->id) {
68             $this->course = $COURSE;
69         } else if (! $this->course = $DB->get_record('course', array('id'=>$this->cm->course))) {
70             print_error('invalidid', 'assignment');
71         }
73         if ($assignment) {
74             $this->assignment = $assignment;
75         } else if (! $this->assignment = $DB->get_record('assignment', array('id'=>$this->cm->instance))) {
76             print_error('invalidid', 'assignment');
77         }
79         $this->assignment->cmidnumber = $this->cm->id;     // compatibility with modedit assignment obj
80         $this->assignment->courseid   = $this->course->id; // compatibility with modedit assignment obj
82         $this->strassignment = get_string('modulename', 'assignment');
83         $this->strassignments = get_string('modulenameplural', 'assignment');
84         $this->strsubmissions = get_string('submissions', 'assignment');
85         $this->strlastmodified = get_string('lastmodified');
86         $this->pagetitle = strip_tags($this->course->shortname.': '.$this->strassignment.': '.format_string($this->assignment->name,true));
88         // visibility handled by require_login() with $cm parameter
89         // get current group only when really needed
91     /// Set up things for a HTML editor if it's needed
92         if ($this->usehtmleditor = can_use_html_editor()) {
93             $this->defaultformat = FORMAT_HTML;
94         } else {
95             $this->defaultformat = FORMAT_MOODLE;
96         }
97     }
99     /**
100      * Display the assignment, used by view.php
101      *
102      * This in turn calls the methods producing individual parts of the page
103      */
104     function view() {
106         $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
107         require_capability('mod/assignment:view', $context);
109         add_to_log($this->course->id, "assignment", "view", "view.php?id={$this->cm->id}",
110                    $this->assignment->id, $this->cm->id);
112         $this->view_header();
114         $this->view_intro();
116         $this->view_dates();
118         $this->view_feedback();
120         $this->view_footer();
121     }
123     /**
124      * Display the header and top of a page
125      *
126      * (this doesn't change much for assignment types)
127      * This is used by the view() method to print the header of view.php but
128      * it can be used on other pages in which case the string to denote the
129      * page in the navigation trail should be passed as an argument
130      *
131      * @param $subpage string Description of subpage to be used in navigation trail
132      */
133     function view_header($subpage='') {
135         global $CFG;
138         if ($subpage) {
139             $navigation = build_navigation($subpage, $this->cm);
140         } else {
141             $navigation = build_navigation('', $this->cm);
142         }
144         print_header($this->pagetitle, $this->course->fullname, $navigation, '', '',
145                      true, update_module_button($this->cm->id, $this->course->id, $this->strassignment),
146                      navmenu($this->course, $this->cm));
148         groups_print_activity_menu($this->cm, 'view.php?id=' . $this->cm->id);
150         echo '<div class="reportlink">'.$this->submittedlink().'</div>';
151         echo '<div class="clearer"></div>';
152     }
155     /**
156      * Display the assignment intro
157      *
158      * This will most likely be extended by assignment type plug-ins
159      * The default implementation prints the assignment description in a box
160      */
161     function view_intro() {
162         print_simple_box_start('center', '', '', 0, 'generalbox', 'intro');
163         $formatoptions = new stdClass;
164         $formatoptions->noclean = true;
165         echo format_text($this->assignment->intro, $this->assignment->introformat, $formatoptions);
166         print_simple_box_end();
167     }
169     /**
170      * Display the assignment dates
171      *
172      * Prints the assignment start and end dates in a box.
173      * This will be suitable for most assignment types
174      */
175     function view_dates() {
176         if (!$this->assignment->timeavailable && !$this->assignment->timedue) {
177             return;
178         }
180         print_simple_box_start('center', '', '', 0, 'generalbox', 'dates');
181         echo '<table>';
182         if ($this->assignment->timeavailable) {
183             echo '<tr><td class="c0">'.get_string('availabledate','assignment').':</td>';
184             echo '    <td class="c1">'.userdate($this->assignment->timeavailable).'</td></tr>';
185         }
186         if ($this->assignment->timedue) {
187             echo '<tr><td class="c0">'.get_string('duedate','assignment').':</td>';
188             echo '    <td class="c1">'.userdate($this->assignment->timedue).'</td></tr>';
189         }
190         echo '</table>';
191         print_simple_box_end();
192     }
195     /**
196      * Display the bottom and footer of a page
197      *
198      * This default method just prints the footer.
199      * This will be suitable for most assignment types
200      */
201     function view_footer() {
202         print_footer($this->course);
203     }
205     /**
206      * Display the feedback to the student
207      *
208      * This default method prints the teacher picture and name, date when marked,
209      * grade and teacher submissioncomment.
210      *
211      * @param $submission object The submission object or NULL in which case it will be loaded
212      */
213     function view_feedback($submission=NULL) {
214         global $USER, $CFG, $DB;
215         require_once($CFG->libdir.'/gradelib.php');
217         if (!has_capability('mod/assignment:submit', $this->context, $USER->id, false)) {
218             // can not submit assignments -> no feedback
219             return;
220         }
222         if (!$submission) { /// Get submission for this assignment
223             $submission = $this->get_submission($USER->id);
224         }
226         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $USER->id);
227         $item = $grading_info->items[0];
228         $grade = $item->grades[$USER->id];
230         if ($grade->hidden or $grade->grade === false) { // hidden or error
231             return;
232         }
234         if ($grade->grade === null and empty($grade->str_feedback)) {   /// Nothing to show yet
235             return;
236         }
238         $graded_date = $grade->dategraded;
239         $graded_by   = $grade->usermodified;
241     /// We need the teacher info
242         if (!$teacher = $DB->get_record('user', array('id'=>$graded_by))) {
243             print_error('cannotfindteacher');
244         }
246     /// Print the feedback
247         print_heading(get_string('feedbackfromteacher', 'assignment', fullname($teacher)));
249         echo '<table cellspacing="0" class="feedback">';
251         echo '<tr>';
252         echo '<td class="left picture">';
253         if ($teacher) {
254             print_user_picture($teacher, $this->course->id, $teacher->picture);
255         }
256         echo '</td>';
257         echo '<td class="topic">';
258         echo '<div class="from">';
259         if ($teacher) {
260             echo '<div class="fullname">'.fullname($teacher).'</div>';
261         }
262         echo '<div class="time">'.userdate($graded_date).'</div>';
263         echo '</div>';
264         echo '</td>';
265         echo '</tr>';
267         echo '<tr>';
268         echo '<td class="left side">&nbsp;</td>';
269         echo '<td class="content">';
270         echo '<div class="grade">';
271         echo get_string("grade").': '.$grade->str_long_grade;
272         echo '</div>';
273         echo '<div class="clearer"></div>';
275         echo '<div class="comment">';
276         echo $grade->str_feedback;
277         echo '</div>';
278         echo '</tr>';
280         echo '</table>';
281     }
283     /**
284      * Returns a link with info about the state of the assignment submissions
285      *
286      * This is used by view_header to put this link at the top right of the page.
287      * For teachers it gives the number of submitted assignments with a link
288      * For students it gives the time of their submission.
289      * This will be suitable for most assignment types.
290      * @param bool $allgroup print all groups info if user can access all groups, suitable for index.php
291      * @return string
292      */
293     function submittedlink($allgroups=false) {
294         global $USER;
295         global $CFG;
297         $submitted = '';
298         $urlbase = "{$CFG->wwwroot}/mod/assignment/";
300         $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
301         if (has_capability('mod/assignment:grade', $context)) {
302             if ($allgroups and has_capability('moodle/site:accessallgroups', $context)) {
303                 $group = 0;
304             } else {
305                 $group = groups_get_activity_group($this->cm);
306             }
307             if ($count = $this->count_real_submissions($group)) {
308                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
309                              get_string('viewsubmissions', 'assignment', $count).'</a>';
310             } else {
311                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
312                              get_string('noattempts', 'assignment').'</a>';
313             }
314         } else {
315             if (!empty($USER->id)) {
316                 if ($submission = $this->get_submission($USER->id)) {
317                     if ($submission->timemodified) {
318                         if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
319                             $submitted = '<span class="early">'.userdate($submission->timemodified).'</span>';
320                         } else {
321                             $submitted = '<span class="late">'.userdate($submission->timemodified).'</span>';
322                         }
323                     }
324                 }
325             }
326         }
328         return $submitted;
329     }
332     function setup_elements(&$mform) {
334     }
336     /**
337      * Create a new assignment activity
338      *
339      * Given an object containing all the necessary data,
340      * (defined by the form in mod_form.php) this function
341      * will create a new instance and return the id number
342      * of the new instance.
343      * The due data is added to the calendar
344      * This is common to all assignment types.
345      *
346      * @param $assignment object The data from the form on mod_form.php
347      * @return int The id of the assignment
348      */
349     function add_instance($assignment) {
350         global $COURSE, $DB;
352         $assignment->timemodified = time();
353         $assignment->courseid = $assignment->course;
355         if ($returnid = $DB->insert_record("assignment", $assignment)) {
356             $assignment->id = $returnid;
358             if ($assignment->timedue) {
359                 $event = new object();
360                 $event->name        = $assignment->name;
361                 $event->description = $assignment->intro;
362                 $event->courseid    = $assignment->course;
363                 $event->groupid     = 0;
364                 $event->userid      = 0;
365                 $event->modulename  = 'assignment';
366                 $event->instance    = $returnid;
367                 $event->eventtype   = 'due';
368                 $event->timestart   = $assignment->timedue;
369                 $event->timeduration = 0;
371                 add_event($event);
372             }
374             assignment_grade_item_update($assignment);
376         }
379         return $returnid;
380     }
382     /**
383      * Deletes an assignment activity
384      *
385      * Deletes all database records, files and calendar events for this assignment.
386      * @param $assignment object The assignment to be deleted
387      * @return boolean False indicates error
388      */
389     function delete_instance($assignment) {
390         global $CFG, $DB;
392         $assignment->courseid = $assignment->course;
394         $result = true;
396         // now get rid of all files
397         $fs = get_file_storage();
398         if ($cm = get_coursemodule_from_instance('assignment', $assignment->id)) {
399             $context = get_context_instance(CONTEXT_MODULE, $cm->id);
400             $fs->delete_area_files($context->id);
401         }
403         if (! $DB->delete_records('assignment_submissions', array('assignment'=>$assignment->id))) {
404             $result = false;
405         }
407         if (! $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
408             $result = false;
409         }
411         if (! $DB->delete_records('assignment', array('id'=>$assignment->id))) {
412             $result = false;
413         }
415         assignment_grade_item_delete($assignment);
417         return $result;
418     }
420     /**
421      * Updates a new assignment activity
422      *
423      * Given an object containing all the necessary data,
424      * (defined by the form in mod_form.php) this function
425      * will update the assignment instance and return the id number
426      * The due date is updated in the calendar
427      * This is common to all assignment types.
428      *
429      * @param $assignment object The data from the form on mod_form.php
430      * @return int The assignment id
431      */
432     function update_instance($assignment) {
433         global $COURSE, $DB;
435         $assignment->timemodified = time();
437         $assignment->id = $assignment->instance;
438         $assignment->courseid = $assignment->course;
440         if (!$DB->update_record('assignment', $assignment)) {
441             return false;
442         }
444         if ($assignment->timedue) {
445             $event = new object();
447             if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
449                 $event->name        = $assignment->name;
450                 $event->description = $assignment->intro;
451                 $event->timestart   = $assignment->timedue;
453                 update_event($event);
454             } else {
455                 $event = new object();
456                 $event->name        = $assignment->name;
457                 $event->description = $assignment->intro;
458                 $event->courseid    = $assignment->course;
459                 $event->groupid     = 0;
460                 $event->userid      = 0;
461                 $event->modulename  = 'assignment';
462                 $event->instance    = $assignment->id;
463                 $event->eventtype   = 'due';
464                 $event->timestart   = $assignment->timedue;
465                 $event->timeduration = 0;
467                 add_event($event);
468             }
469         } else {
470             $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id));
471         }
473         // get existing grade item
474         assignment_grade_item_update($assignment);
476         return true;
477     }
479     /**
480      * Update grade item for this submission.
481      */
482     function update_grade($submission) {
483         assignment_update_grades($this->assignment, $submission->userid);
484     }
486     /**
487      * Top-level function for handling of submissions called by submissions.php
488      *
489      * This is for handling the teacher interaction with the grading interface
490      * This should be suitable for most assignment types.
491      *
492      * @param $mode string Specifies the kind of teacher interaction taking place
493      */
494     function submissions($mode) {
495         ///The main switch is changed to facilitate
496         ///1) Batch fast grading
497         ///2) Skip to the next one on the popup
498         ///3) Save and Skip to the next one on the popup
500         //make user global so we can use the id
501         global $USER;
503         $mailinfo = optional_param('mailinfo', null, PARAM_BOOL);
504         if (is_null($mailinfo)) {
505             $mailinfo = get_user_preferences('assignment_mailinfo', 0);
506         } else {
507             set_user_preference('assignment_mailinfo', $mailinfo);
508         }
510         switch ($mode) {
511             case 'grade':                         // We are in a popup window grading
512                 if ($submission = $this->process_feedback()) {
513                     //IE needs proper header with encoding
514                     print_header(get_string('feedback', 'assignment').':'.format_string($this->assignment->name));
515                     print_heading(get_string('changessaved'));
516                     print $this->update_main_listing($submission);
517                 }
518                 close_window();
519                 break;
521             case 'single':                        // We are in a popup window displaying submission
522                 $this->display_submission();
523                 break;
525             case 'all':                          // Main window, display everything
526                 $this->display_submissions();
527                 break;
529             case 'fastgrade':
530                 ///do the fast grading stuff  - this process should work for all 3 subclasses
532                 $grading    = false;
533                 $commenting = false;
534                 $col        = false;
535                 if (isset($_POST['submissioncomment'])) {
536                     $col = 'submissioncomment';
537                     $commenting = true;
538                 }
539                 if (isset($_POST['menu'])) {
540                     $col = 'menu';
541                     $grading = true;
542                 }
543                 if (!$col) {
544                     //both submissioncomment and grade columns collapsed..
545                     $this->display_submissions();
546                     break;
547                 }
549                 foreach ($_POST[$col] as $id => $unusedvalue){
551                     $id = (int)$id; //clean parameter name
553                     $this->process_outcomes($id);
555                     if (!$submission = $this->get_submission($id)) {
556                         $submission = $this->prepare_new_submission($id);
557                         $newsubmission = true;
558                     } else {
559                         $newsubmission = false;
560                     }
561                     unset($submission->data1);  // Don't need to update this.
562                     unset($submission->data2);  // Don't need to update this.
564                     //for fast grade, we need to check if any changes take place
565                     $updatedb = false;
567                     if ($grading) {
568                         $grade = $_POST['menu'][$id];
569                         $updatedb = $updatedb || ($submission->grade != $grade);
570                         $submission->grade = $grade;
571                     } else {
572                         if (!$newsubmission) {
573                             unset($submission->grade);  // Don't need to update this.
574                         }
575                     }
576                     if ($commenting) {
577                         $commentvalue = trim($_POST['submissioncomment'][$id]);
578                         $updatedb = $updatedb || ($submission->submissioncomment != $commentvalue);
579                         $submission->submissioncomment = $commentvalue;
580                     } else {
581                         unset($submission->submissioncomment);  // Don't need to update this.
582                     }
584                     $submission->teacher    = $USER->id;
585                     if ($updatedb) {
586                         $submission->mailed = (int)(!$mailinfo);
587                     }
589                     $submission->timemarked = time();
591                     //if it is not an update, we don't change the last modified time etc.
592                     //this will also not write into database if no submissioncomment and grade is entered.
594                     if ($updatedb){
595                         if ($newsubmission) {
596                             if (!isset($submission->submissioncomment)) {
597                                 $submission->submissioncomment = '';
598                             }
599                             if (!$sid = $DB->insert_record('assignment_submissions', $submission)) {
600                                 return false;
601                             }
602                             $submission->id = $sid;
603                         } else {
604                             if (!$DB->update_record('assignment_submissions', $submission)) {
605                                 return false;
606                             }
607                         }
609                         // triger grade event
610                         $this->update_grade($submission);
612                         //add to log only if updating
613                         add_to_log($this->course->id, 'assignment', 'update grades',
614                                    'submissions.php?id='.$this->assignment->id.'&user='.$submission->userid,
615                                    $submission->userid, $this->cm->id);
616                     }
618                 }
620                 $message = notify(get_string('changessaved'), 'notifysuccess', 'center', true);
622                 $this->display_submissions($message);
623                 break;
626             case 'next':
627                 /// We are currently in pop up, but we want to skip to next one without saving.
628                 ///    This turns out to be similar to a single case
629                 /// The URL used is for the next submission.
631                 $this->display_submission();
632                 break;
634             case 'saveandnext':
635                 ///We are in pop up. save the current one and go to the next one.
636                 //first we save the current changes
637                 if ($submission = $this->process_feedback()) {
638                     //print_heading(get_string('changessaved'));
639                     $extra_javascript = $this->update_main_listing($submission);
640                 }
642                 //then we display the next submission
643                 $this->display_submission($extra_javascript);
644                 break;
646             default:
647                 echo "something seriously is wrong!!";
648                 break;
649         }
650     }
652     /**
653     * Helper method updating the listing on the main script from popup using javascript
654     *
655     * @param $submission object The submission whose data is to be updated on the main page
656     */
657     function update_main_listing($submission) {
658         global $SESSION, $CFG;
660         $output = '';
662         $perpage = get_user_preferences('assignment_perpage', 10);
664         $quickgrade = get_user_preferences('assignment_quickgrade', 0);
666         /// Run some Javascript to try and update the parent page
667         $output .= '<script type="text/javascript">'."\n<!--\n";
668         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['submissioncomment'])) {
669             if ($quickgrade){
670                 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid.'").value="'
671                 .trim($submission->submissioncomment).'";'."\n";
672              } else {
673                 $output.= 'opener.document.getElementById("com'.$submission->userid.
674                 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment)), 15)."\";\n";
675             }
676         }
678         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['grade'])) {
679             //echo optional_param('menuindex');
680             if ($quickgrade){
681                 $output.= 'opener.document.getElementById("menumenu'.$submission->userid.
682                 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT).'";'."\n";
683             } else {
684                 $output.= 'opener.document.getElementById("g'.$submission->userid.'").innerHTML="'.
685                 $this->display_grade($submission->grade)."\";\n";
686             }
687         }
688         //need to add student's assignments in there too.
689         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemodified']) &&
690             $submission->timemodified) {
691             $output.= 'opener.document.getElementById("ts'.$submission->userid.
692                  '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid)).userdate($submission->timemodified)."\";\n";
693         }
695         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemarked']) &&
696             $submission->timemarked) {
697             $output.= 'opener.document.getElementById("tt'.$submission->userid.
698                  '").innerHTML="'.userdate($submission->timemarked)."\";\n";
699         }
701         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['status'])) {
702             $output.= 'opener.document.getElementById("up'.$submission->userid.'").className="s1";';
703             $buttontext = get_string('update');
704             $button = link_to_popup_window ('/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;userid='.$submission->userid.'&amp;mode=single'.'&amp;offset='.(optional_param('offset', '', PARAM_INT)-1),
705                       'grade'.$submission->userid, $buttontext, 450, 700, $buttontext, 'none', true, 'button'.$submission->userid);
706             $output.= 'opener.document.getElementById("up'.$submission->userid.'").innerHTML="'.addslashes_js($button).'";';
707         }
709         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $submission->userid);
711         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['finalgrade'])) {
712             $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid.
713             '").innerHTML="'.$grading_info->items[0]->grades[$submission->userid]->str_grade.'";'."\n";
714         }
716         if (!empty($CFG->enableoutcomes) and empty($SESSION->flextable['mod-assignment-submissions']->collapse['outcome'])) {
718             if (!empty($grading_info->outcomes)) {
719                 foreach($grading_info->outcomes as $n=>$outcome) {
720                     if ($outcome->grades[$submission->userid]->locked) {
721                         continue;
722                     }
724                     if ($quickgrade){
725                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.
726                         '").selectedIndex="'.$outcome->grades[$submission->userid]->grade.'";'."\n";
728                     } else {
729                         $options = make_grades_menu(-$outcome->scaleid);
730                         $options[0] = get_string('nooutcome', 'grades');
731                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.'").innerHTML="'.$options[$outcome->grades[$submission->userid]->grade]."\";\n";
732                     }
734                 }
735             }
736         }
738         $output .= "\n-->\n</script>";
739         return $output;
740     }
742     /**
743      *  Return a grade in user-friendly form, whether it's a scale or not
744      *
745      * @param $grade
746      * @return string User-friendly representation of grade
747      */
748     function display_grade($grade) {
749         global $DB;
751         static $scalegrades = array();   // Cache scales for each assignment - they might have different scales!!
753         if ($this->assignment->grade >= 0) {    // Normal number
754             if ($grade == -1) {
755                 return '-';
756             } else {
757                 return $grade.' / '.$this->assignment->grade;
758             }
760         } else {                                // Scale
761             if (empty($scalegrades[$this->assignment->id])) {
762                 if ($scale = $DB->get_record('scale', array('id'=>-($this->assignment->grade)))) {
763                     $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
764                 } else {
765                     return '-';
766                 }
767             }
768             if (isset($scalegrades[$this->assignment->id][$grade])) {
769                 return $scalegrades[$this->assignment->id][$grade];
770             }
771             return '-';
772         }
773     }
775     /**
776      *  Display a single submission, ready for grading on a popup window
777      *
778      * This default method prints the teacher info and submissioncomment box at the top and
779      * the student info and submission at the bottom.
780      * This method also fetches the necessary data in order to be able to
781      * provide a "Next submission" button.
782      * Calls preprocess_submission() to give assignment type plug-ins a chance
783      * to process submissions before they are graded
784      * This method gets its arguments from the page parameters userid and offset
785      */
786     function display_submission($extra_javascript = '') {
787         global $CFG, $DB;
788         require_once($CFG->libdir.'/gradelib.php');
789         require_once($CFG->libdir.'/tablelib.php');
791         $userid = required_param('userid', PARAM_INT);
792         $offset = required_param('offset', PARAM_INT);//offset for where to start looking for student.
794         if (!$user = $DB->get_record('user', array('id'=>$userid))) {
795             print_error('nousers');
796         }
798         if (!$submission = $this->get_submission($user->id)) {
799             $submission = $this->prepare_new_submission($userid);
800         }
801         if ($submission->timemodified > $submission->timemarked) {
802             $subtype = 'assignmentnew';
803         } else {
804             $subtype = 'assignmentold';
805         }
807         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
808         $disabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
810     /// construct SQL, using current offset to find the data of the next student
811         $course     = $this->course;
812         $assignment = $this->assignment;
813         $cm         = $this->cm;
814         $context    = get_context_instance(CONTEXT_MODULE, $cm->id);
816         /// Get all ppl that can submit assignments
818         $currentgroup = groups_get_activity_group($cm);
819         if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $currentgroup, '', false)) {
820             $users = array_keys($users);
821         }
823         // if groupmembersonly used, remove users who are not in any group
824         if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
825             if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
826                 $users = array_intersect($users, array_keys($groupingusers));
827             }
828         }
830         $nextid = 0;
832         if ($users) {
833             $select = 'SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt,
834                               s.id AS submissionid, s.grade, s.submissioncomment,
835                               s.timemodified, s.timemarked,
836                               COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ';
837             $sql = 'FROM {user} u '.
838                    'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
839                                                                       AND s.assignment = '.$this->assignment->id.' '.
840                    'WHERE u.id IN ('.implode(',', $users).') ';
842             if ($sort = flexible_table::get_sql_sort('mod-assignment-submissions')) {
843                 $sort = 'ORDER BY '.$sort.' ';
844             }
846             if (($auser = $DB->get_records_sql($select.$sql.$sort, null, $offset+1, 1)) !== false) {
847                 $nextuser = array_shift($auser);
848             /// Calculate user status
849                 $nextuser->status = ($nextuser->timemarked > 0) && ($nextuser->timemarked >= $nextuser->timemodified);
850                 $nextid = $nextuser->id;
851             }
852         }
854         print_header(get_string('feedback', 'assignment').':'.fullname($user, true).':'.format_string($this->assignment->name));
856         /// Print any extra javascript needed for saveandnext
857         echo $extra_javascript;
859         ///SOme javascript to help with setting up >.>
861         echo '<script type="text/javascript">'."\n";
862         echo 'function setNext(){'."\n";
863         echo 'document.getElementById(\'submitform\').mode.value=\'next\';'."\n";
864         echo 'document.getElementById(\'submitform\').userid.value="'.$nextid.'";'."\n";
865         echo '}'."\n";
867         echo 'function saveNext(){'."\n";
868         echo 'document.getElementById(\'submitform\').mode.value=\'saveandnext\';'."\n";
869         echo 'document.getElementById(\'submitform\').userid.value="'.$nextid.'";'."\n";
870         echo 'document.getElementById(\'submitform\').saveuserid.value="'.$userid.'";'."\n";
871         echo 'document.getElementById(\'submitform\').menuindex.value = document.getElementById(\'submitform\').grade.selectedIndex;'."\n";
872         echo '}'."\n";
874         echo '</script>'."\n";
875         echo '<table cellspacing="0" class="feedback '.$subtype.'" >';
877         ///Start of teacher info row
879         echo '<tr>';
880         echo '<td class="picture teacher">';
881         if ($submission->teacher) {
882             $teacher = $DB->get_record('user', array('id'=>$submission->teacher));
883         } else {
884             global $USER;
885             $teacher = $USER;
886         }
887         print_user_picture($teacher, $this->course->id, $teacher->picture);
888         echo '</td>';
889         echo '<td class="content">';
890         echo '<form id="submitform" action="submissions.php" method="post">';
891         echo '<div>'; // xhtml compatibility - invisiblefieldset was breaking layout here
892         echo '<input type="hidden" name="offset" value="'.($offset+1).'" />';
893         echo '<input type="hidden" name="userid" value="'.$userid.'" />';
894         echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
895         echo '<input type="hidden" name="mode" value="grade" />';
896         echo '<input type="hidden" name="menuindex" value="0" />';//selected menu index
898         //new hidden field, initialized to -1.
899         echo '<input type="hidden" name="saveuserid" value="-1" />';
901         if ($submission->timemarked) {
902             echo '<div class="from">';
903             echo '<div class="fullname">'.fullname($teacher, true).'</div>';
904             echo '<div class="time">'.userdate($submission->timemarked).'</div>';
905             echo '</div>';
906         }
907         echo '<div class="grade"><label for="menugrade">'.get_string('grade').'</label> ';
908         choose_from_menu(make_grades_menu($this->assignment->grade), 'grade', $submission->grade, get_string('nograde'), '', -1, false, $disabled);
909         echo '</div>';
911         echo '<div class="clearer"></div>';
912         echo '<div class="finalgrade">'.get_string('finalgrade', 'grades').': '.$grading_info->items[0]->grades[$userid]->str_grade.'</div>';
913         echo '<div class="clearer"></div>';
915         if (!empty($CFG->enableoutcomes)) {
916             foreach($grading_info->outcomes as $n=>$outcome) {
917                 echo '<div class="outcome"><label for="menuoutcome_'.$n.'">'.$outcome->name.'</label> ';
918                 $options = make_grades_menu(-$outcome->scaleid);
919                 if ($outcome->grades[$submission->userid]->locked) {
920                     $options[0] = get_string('nooutcome', 'grades');
921                     echo $options[$outcome->grades[$submission->userid]->grade];
922                 } else {
923                     choose_from_menu($options, 'outcome_'.$n.'['.$userid.']', $outcome->grades[$submission->userid]->grade, get_string('nooutcome', 'grades'), '', 0, false, false, 0, 'menuoutcome_'.$n);
924                 }
925                 echo '</div>';
926                 echo '<div class="clearer"></div>';
927             }
928         }
931         $this->preprocess_submission($submission);
933         if ($disabled) {
934             echo '<div class="disabledfeedback">'.$grading_info->items[0]->grades[$userid]->str_feedback.'</div>';
936         } else {
937             print_textarea($this->usehtmleditor, 14, 58, 0, 0, 'submissioncomment', $submission->submissioncomment, $this->course->id);
938             if ($this->usehtmleditor) {
939                 echo '<input type="hidden" name="format" value="'.FORMAT_HTML.'" />';
940             } else {
941                 echo '<div class="format">';
942                 choose_from_menu(format_text_menu(), "format", $submission->format, "");
943                 helpbutton("textformat", get_string("helpformatting"));
944                 echo '</div>';
945             }
946         }
948         $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? 'checked="checked"' : '';
950         ///Print Buttons in Single View
951         echo '<input type="hidden" name="mailinfo" value="0" />';
952         echo '<input type="checkbox" id="mailinfo" name="mailinfo" value="1" '.$lastmailinfo.' /><label for="mailinfo">'.get_string('enableemailnotification','assignment').'</label>';
953         echo '<div class="buttons">';
954         echo '<input type="submit" name="submit" value="'.get_string('savechanges').'" onclick = "document.getElementById(\'submitform\').menuindex.value = document.getElementById(\'submitform\').grade.selectedIndex" />';
955         echo '<input type="submit" name="cancel" value="'.get_string('cancel').'" />';
956         //if there are more to be graded.
957         if ($nextid) {
958             echo '<input type="submit" name="saveandnext" value="'.get_string('saveandnext').'" onclick="saveNext()" />';
959             echo '<input type="submit" name="next" value="'.get_string('next').'" onclick="setNext();" />';
960         }
961         echo '</div>';
962         echo '</div></form>';
964         $customfeedback = $this->custom_feedbackform($submission, true);
965         if (!empty($customfeedback)) {
966             echo $customfeedback;
967         }
969         echo '</td></tr>';
971         ///End of teacher info row, Start of student info row
972         echo '<tr>';
973         echo '<td class="picture user">';
974         print_user_picture($user, $this->course->id, $user->picture);
975         echo '</td>';
976         echo '<td class="topic">';
977         echo '<div class="from">';
978         echo '<div class="fullname">'.fullname($user, true).'</div>';
979         if ($submission->timemodified) {
980             echo '<div class="time">'.userdate($submission->timemodified).
981                                      $this->display_lateness($submission->timemodified).'</div>';
982         }
983         echo '</div>';
984         $this->print_user_files($user->id);
985         echo '</td>';
986         echo '</tr>';
988         ///End of student info row
990         echo '</table>';
992         print_footer('none');
993     }
995     /**
996      *  Preprocess submission before grading
997      *
998      * Called by display_submission()
999      * The default type does nothing here.
1000      * @param $submission object The submission object
1001      */
1002     function preprocess_submission(&$submission) {
1003     }
1005     /**
1006      *  Display all the submissions ready for grading
1007      */
1008     function display_submissions($message='') {
1009         global $CFG, $DB, $USER, $DB;
1010         require_once($CFG->libdir.'/gradelib.php');
1012         /* first we check to see if the form has just been submitted
1013          * to request user_preference updates
1014          */
1016         if (isset($_POST['updatepref'])){
1017             $perpage = optional_param('perpage', 10, PARAM_INT);
1018             $perpage = ($perpage <= 0) ? 10 : $perpage ;
1019             set_user_preference('assignment_perpage', $perpage);
1020             set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
1021         }
1023         /* next we get perpage and quickgrade (allow quick grade) params
1024          * from database
1025          */
1026         $perpage    = get_user_preferences('assignment_perpage', 10);
1028         $quickgrade = get_user_preferences('assignment_quickgrade', 0);
1030         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);
1032         if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
1033             $uses_outcomes = true;
1034         } else {
1035             $uses_outcomes = false;
1036         }
1038         $page    = optional_param('page', 0, PARAM_INT);
1039         $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
1041     /// Some shortcuts to make the code read better
1043         $course     = $this->course;
1044         $assignment = $this->assignment;
1045         $cm         = $this->cm;
1047         $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
1048         add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->cm->id, $this->assignment->id, $this->cm->id);
1049         $navigation = build_navigation($this->strsubmissions, $this->cm);
1050         print_header_simple(format_string($this->assignment->name,true), "", $navigation,
1051                 '', '', true, update_module_button($cm->id, $course->id, $this->strassignment), navmenu($course, $cm));
1053         $course_context = get_context_instance(CONTEXT_COURSE, $course->id);
1054         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
1055             echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">'
1056                 . get_string('seeallcoursegrades', 'grades') . '</a></div>';
1057         }
1059         if (!empty($message)) {
1060             echo $message;   // display messages here if any
1061         }
1063         $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1065     /// Check to see if groups are being used in this assignment
1067         /// find out current groups mode
1068         $groupmode = groups_get_activity_groupmode($cm);
1069         $currentgroup = groups_get_activity_group($cm, true);
1070         groups_print_activity_menu($cm, 'submissions.php?id=' . $this->cm->id);
1072         /// Get all ppl that are allowed to submit assignments
1073         if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $currentgroup, '', false)) {
1074             $users = array_keys($users);
1075         }
1077         // if groupmembersonly used, remove users who are not in any group
1078         if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
1079             if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1080                 $users = array_intersect($users, array_keys($groupingusers));
1081             }
1082         }
1084         $tablecolumns = array('picture', 'fullname', 'grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade');
1085         if ($uses_outcomes) {
1086             $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
1087         }
1089         $tableheaders = array('',
1090                               get_string('fullname'),
1091                               get_string('grade'),
1092                               get_string('comment', 'assignment'),
1093                               get_string('lastmodified').' ('.get_string('submission', 'assignment').')',
1094                               get_string('lastmodified').' ('.get_string('grade').')',
1095                               get_string('status'),
1096                               get_string('finalgrade', 'grades'));
1097         if ($uses_outcomes) {
1098             $tableheaders[] = get_string('outcome', 'grades');
1099         }
1101         require_once($CFG->libdir.'/tablelib.php');
1102         $table = new flexible_table('mod-assignment-submissions');
1104         $table->define_columns($tablecolumns);
1105         $table->define_headers($tableheaders);
1106         $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;currentgroup='.$currentgroup);
1108         $table->sortable(true, 'lastname');//sorted by lastname by default
1109         $table->collapsible(true);
1110         $table->initialbars(true);
1112         $table->column_suppress('picture');
1113         $table->column_suppress('fullname');
1115         $table->column_class('picture', 'picture');
1116         $table->column_class('fullname', 'fullname');
1117         $table->column_class('grade', 'grade');
1118         $table->column_class('submissioncomment', 'comment');
1119         $table->column_class('timemodified', 'timemodified');
1120         $table->column_class('timemarked', 'timemarked');
1121         $table->column_class('status', 'status');
1122         $table->column_class('finalgrade', 'finalgrade');
1123         if ($uses_outcomes) {
1124             $table->column_class('outcome', 'outcome');
1125         }
1127         $table->set_attribute('cellspacing', '0');
1128         $table->set_attribute('id', 'attempts');
1129         $table->set_attribute('class', 'submissions');
1130         $table->set_attribute('width', '100%');
1131         //$table->set_attribute('align', 'center');
1133         $table->no_sorting('finalgrade');
1134         $table->no_sorting('outcome');
1136         // Start working -- this is necessary as soon as the niceties are over
1137         $table->setup();
1139         if (empty($users)) {
1140             print_heading(get_string('nosubmitusers','assignment'));
1141             return true;
1142         }
1144     /// Construct the SQL
1146         if ($where = $table->get_sql_where()) {
1147             $where .= ' AND ';
1148         }
1150         if ($sort = $table->get_sql_sort()) {
1151             $sort = ' ORDER BY '.$sort;
1152         }
1154         $select = 'SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt,
1155                           s.id AS submissionid, s.grade, s.submissioncomment,
1156                           s.timemodified, s.timemarked,
1157                           COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ';
1158         $sql = 'FROM {user} u '.
1159                'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1160                                                                   AND s.assignment = '.$this->assignment->id.' '.
1161                'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1163         $table->pagesize($perpage, count($users));
1165         ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1166         $offset = $page * $perpage;
1168         $strupdate = get_string('update');
1169         $strgrade  = get_string('grade');
1170         $grademenu = make_grades_menu($this->assignment->grade);
1172         if (($ausers = $DB->get_records_sql($select.$sql.$sort, null, $table->get_page_start(), $table->get_page_size())) !== false) {
1173             $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
1174             foreach ($ausers as $auser) {
1175                 $final_grade = $grading_info->items[0]->grades[$auser->id];
1176                 $grademax = $grading_info->items[0]->grademax;
1177                 $final_grade->formatted_grade = round($final_grade->grade,2) .' / ' . round($grademax,2);
1178                 $locked_overridden = 'locked';
1179                 if ($final_grade->overridden) {
1180                     $locked_overridden = 'overridden';
1181                 }
1183             /// Calculate user status
1184                 $auser->status = ($auser->timemarked > 0) && ($auser->timemarked >= $auser->timemodified);
1185                 $picture = print_user_picture($auser, $course->id, $auser->picture, false, true);
1187                 if (empty($auser->submissionid)) {
1188                     $auser->grade = -1; //no submission yet
1189                 }
1191                 if (!empty($auser->submissionid)) {
1192                 ///Prints student answer and student modified date
1193                 ///attach file or print link to student answer, depending on the type of the assignment.
1194                 ///Refer to print_student_answer in inherited classes.
1195                     if ($auser->timemodified > 0) {
1196                         $studentmodified = '<div id="ts'.$auser->id.'">'.$this->print_student_answer($auser->id)
1197                                          . userdate($auser->timemodified).'</div>';
1198                     } else {
1199                         $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1200                     }
1201                 ///Print grade, dropdown or text
1202                     if ($auser->timemarked > 0) {
1203                         $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
1205                         if ($final_grade->locked or $final_grade->overridden) {
1206                             $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1207                         } else if ($quickgrade) {
1208                             $menu = choose_from_menu(make_grades_menu($this->assignment->grade),
1209                                                      'menu['.$auser->id.']', $auser->grade,
1210                                                      get_string('nograde'),'',-1,true,false,$tabindex++);
1211                             $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
1212                         } else {
1213                             $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1214                         }
1216                     } else {
1217                         $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1218                         if ($final_grade->locked or $final_grade->overridden) {
1219                             $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1220                         } else if ($quickgrade) {
1221                             $menu = choose_from_menu(make_grades_menu($this->assignment->grade),
1222                                                      'menu['.$auser->id.']', $auser->grade,
1223                                                      get_string('nograde'),'',-1,true,false,$tabindex++);
1224                             $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1225                         } else {
1226                             $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1227                         }
1228                     }
1229                 ///Print Comment
1230                     if ($final_grade->locked or $final_grade->overridden) {
1231                         $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';
1233                     } else if ($quickgrade) {
1234                         $comment = '<div id="com'.$auser->id.'">'
1235                                  . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1236                                  . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1237                     } else {
1238                         $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
1239                     }
1240                 } else {
1241                     $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1242                     $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1243                     $status          = '<div id="st'.$auser->id.'">&nbsp;</div>';
1245                     if ($final_grade->locked or $final_grade->overridden) {
1246                         $grade = '<div id="g'.$auser->id.'">'.$final_grade->formatted_grade . '</div>';
1247                     } else if ($quickgrade) {   // allow editing
1248                         $menu = choose_from_menu(make_grades_menu($this->assignment->grade),
1249                                                  'menu['.$auser->id.']', $auser->grade,
1250                                                  get_string('nograde'),'',-1,true,false,$tabindex++);
1251                         $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1252                     } else {
1253                         $grade = '<div id="g'.$auser->id.'">-</div>';
1254                     }
1256                     if ($final_grade->locked or $final_grade->overridden) {
1257                         $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
1258                     } else if ($quickgrade) {
1259                         $comment = '<div id="com'.$auser->id.'">'
1260                                  . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1261                                  . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1262                     } else {
1263                         $comment = '<div id="com'.$auser->id.'">&nbsp;</div>';
1264                     }
1265                 }
1267                 if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
1268                     $auser->status = 0;
1269                 } else {
1270                     $auser->status = 1;
1271                 }
1273                 $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
1275                 ///No more buttons, we use popups ;-).
1276                 $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1277                            . '&amp;userid='.$auser->id.'&amp;mode=single'.'&amp;offset='.$offset++;
1278                 $button = link_to_popup_window ($popup_url, 'grade'.$auser->id, $buttontext, 600, 780,
1279                                                 $buttontext, 'none', true, 'button'.$auser->id);
1281                 $status  = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
1283                 $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';
1285                 $outcomes = '';
1287                 if ($uses_outcomes) {
1289                     foreach($grading_info->outcomes as $n=>$outcome) {
1290                         $outcomes .= '<div class="outcome"><label>'.$outcome->name.'</label>';
1291                         $options = make_grades_menu(-$outcome->scaleid);
1293                         if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
1294                             $options[0] = get_string('nooutcome', 'grades');
1295                             $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
1296                         } else {
1297                             $outcomes .= ' ';
1298                             $outcomes .= choose_from_menu($options, 'outcome_'.$n.'['.$auser->id.']',
1299                                         $outcome->grades[$auser->id]->grade, get_string('nooutcome', 'grades'), '', 0, true, false, 0, 'outcome_'.$n.'_'.$auser->id);
1300                         }
1301                         $outcomes .= '</div>';
1302                     }
1303                 }
1305                                 $userlink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $auser->id . '&amp;course=' . $course->id . '">' . fullname($auser) . '</a>';
1306                 $row = array($picture, $userlink, $grade, $comment, $studentmodified, $teachermodified, $status, $finalgrade);
1307                 if ($uses_outcomes) {
1308                     $row[] = $outcomes;
1309                 }
1311                 $table->add_data($row);
1312             }
1313         }
1315         /// Print quickgrade form around the table
1316         if ($quickgrade){
1317             echo '<form action="submissions.php" id="fastg" method="post">';
1318             echo '<div>';
1319             echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
1320             echo '<input type="hidden" name="mode" value="fastgrade" />';
1321             echo '<input type="hidden" name="page" value="'.$page.'" />';
1322             echo '</div>';
1323         }
1325         $table->print_html();  /// Print the whole table
1327         if ($quickgrade){
1328             $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? 'checked="checked"' : '';
1329             echo '<div class="fgcontrols">';
1330             echo '<div class="emailnotification">';
1331             echo '<label for="mailinfo">'.get_string('enableemailnotification','assignment').'</label>';
1332             echo '<input type="hidden" name="mailinfo" value="0" />';
1333             echo '<input type="checkbox" id="mailinfo" name="mailinfo" value="1" '.$lastmailinfo.' />';
1334             helpbutton('emailnotification', get_string('enableemailnotification', 'assignment'), 'assignment').'</p></div>';
1335             echo '</div>';
1336             echo '<div class="fastgbutton"><input type="submit" name="fastg" value="'.get_string('saveallfeedback', 'assignment').'" /></div>';
1337             echo '</div>';
1338             echo '</form>';
1339         }
1340         /// End of fast grading form
1342         /// Mini form for setting user preference
1343         echo '<div class="qgprefs">';
1344         echo '<form id="options" action="submissions.php?id='.$this->cm->id.'" method="post"><div>';
1345         echo '<input type="hidden" name="updatepref" value="1" />';
1346         echo '<table id="optiontable">';
1347         echo '<tr><td>';
1348         echo '<label for="perpage">'.get_string('pagesize','assignment').'</label>';
1349         echo '</td>';
1350         echo '<td>';
1351         echo '<input type="text" id="perpage" name="perpage" size="1" value="'.$perpage.'" />';
1352         helpbutton('pagesize', get_string('pagesize','assignment'), 'assignment');
1353         echo '</td></tr>';
1354         echo '<tr><td>';
1355         echo '<label for="quickgrade">'.get_string('quickgrade','assignment').'</label>';
1356         echo '</td>';
1357         echo '<td>';
1358         $checked = $quickgrade ? 'checked="checked"' : '';
1359         echo '<input type="checkbox" id="quickgrade" name="quickgrade" value="1" '.$checked.' />';
1360         helpbutton('quickgrade', get_string('quickgrade', 'assignment'), 'assignment').'</p></div>';
1361         echo '</td></tr>';
1362         echo '<tr><td colspan="2">';
1363         echo '<input type="submit" value="'.get_string('savepreferences').'" />';
1364         echo '</td></tr></table>';
1365         echo '</div></form></div>';
1366         ///End of mini form
1367         print_footer($this->course);
1368     }
1370     /**
1371      *  Process teacher feedback submission
1372      *
1373      * This is called by submissions() when a grading even has taken place.
1374      * It gets its data from the submitted form.
1375      * @return object The updated submission object
1376      */
1377     function process_feedback() {
1378         global $CFG, $USER, $DB;
1379         require_once($CFG->libdir.'/gradelib.php');
1381         if (!$feedback = data_submitted()) {      // No incoming data?
1382             return false;
1383         }
1385         ///For save and next, we need to know the userid to save, and the userid to go
1386         ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1387         ///as the userid to store
1388         if ((int)$feedback->saveuserid !== -1){
1389             $feedback->userid = $feedback->saveuserid;
1390         }
1392         if (!empty($feedback->cancel)) {          // User hit cancel button
1393             return false;
1394         }
1396         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);
1398         // store outcomes if needed
1399         $this->process_outcomes($feedback->userid);
1401         $submission = $this->get_submission($feedback->userid, true);  // Get or make one
1403         if (!$grading_info->items[0]->grades[$feedback->userid]->locked and
1404             !$grading_info->items[0]->grades[$feedback->userid]->overridden) {
1406             $submission->grade      = $feedback->grade;
1407             $submission->submissioncomment    = $feedback->submissioncomment;
1408             $submission->format     = $feedback->format;
1409             $submission->teacher    = $USER->id;
1410             $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1411             if (!$mailinfo) {
1412                 $submission->mailed = 1;       // treat as already mailed
1413             } else {
1414                 $submission->mailed = 0;       // Make sure mail goes out (again, even)
1415             }
1416             $submission->timemarked = time();
1418             unset($submission->data1);  // Don't need to update this.
1419             unset($submission->data2);  // Don't need to update this.
1421             if (empty($submission->timemodified)) {   // eg for offline assignments
1422                 // $submission->timemodified = time();
1423             }
1425             if (! $DB->update_record('assignment_submissions', $submission)) {
1426                 return false;
1427             }
1429             // triger grade event
1430             $this->update_grade($submission);
1432             add_to_log($this->course->id, 'assignment', 'update grades',
1433                        'submissions.php?id='.$this->assignment->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
1434         }
1436         return $submission;
1438     }
1440     function process_outcomes($userid) {
1441         global $CFG, $USER;
1443         if (empty($CFG->enableoutcomes)) {
1444             return;
1445         }
1447         require_once($CFG->libdir.'/gradelib.php');
1449         if (!$formdata = data_submitted()) {
1450             return;
1451         }
1453         $data = array();
1454         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
1456         if (!empty($grading_info->outcomes)) {
1457             foreach($grading_info->outcomes as $n=>$old) {
1458                 $name = 'outcome_'.$n;
1459                 if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
1460                     $data[$n] = $formdata->{$name}[$userid];
1461                 }
1462             }
1463         }
1464         if (count($data) > 0) {
1465             grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1466         }
1468     }
1470     /**
1471      * Load the submission object for a particular user
1472      *
1473      * @param $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1474      * @param $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1475      * @param bool $teachermodified student submission set if false
1476      * @return object The submission
1477      */
1478     function get_submission($userid=0, $createnew=false, $teachermodified=false) {
1479         global $USER, $DB;
1481         if (empty($userid)) {
1482             $userid = $USER->id;
1483         }
1485         $submission = $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1487         if ($submission || !$createnew) {
1488             return $submission;
1489         }
1490         $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
1491         if (!$DB->insert_record("assignment_submissions", $newsubmission)) {
1492             print_error('cannotinsertempty', 'assignment');
1493         }
1495         return $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1496     }
1498     /**
1499      * Instantiates a new submission object for a given user
1500      *
1501      * Sets the assignment, userid and times, everything else is set to default values.
1502      * @param $userid int The userid for which we want a submission object
1503      * @param bool $teachermodified student submission set if false
1504      * @return object The submission
1505      */
1506     function prepare_new_submission($userid, $teachermodified=false) {
1507         $submission = new Object;
1508         $submission->assignment   = $this->assignment->id;
1509         $submission->userid       = $userid;
1510         //$submission->timecreated  = time();
1511         $submission->timecreated = '';
1512         // teachers should not be modifying modified date, except offline assignments
1513         if ($teachermodified) {
1514             $submission->timemodified = 0;
1515         } else {
1516             $submission->timemodified = $submission->timecreated;
1517         }
1518         $submission->numfiles     = 0;
1519         $submission->data1        = '';
1520         $submission->data2        = '';
1521         $submission->grade        = -1;
1522         $submission->submissioncomment      = '';
1523         $submission->format       = 0;
1524         $submission->teacher      = 0;
1525         $submission->timemarked   = 0;
1526         $submission->mailed       = 0;
1527         return $submission;
1528     }
1530     /**
1531      * Return all assignment submissions by ENROLLED students (even empty)
1532      *
1533      * @param $sort string optional field names for the ORDER BY in the sql query
1534      * @param $dir string optional specifying the sort direction, defaults to DESC
1535      * @return array The submission objects indexed by id
1536      */
1537     function get_submissions($sort='', $dir='DESC') {
1538         return assignment_get_all_submissions($this->assignment, $sort, $dir);
1539     }
1541     /**
1542      * Counts all real assignment submissions by ENROLLED students (not empty ones)
1543      *
1544      * @param $groupid int optional If nonzero then count is restricted to this group
1545      * @return int The number of submissions
1546      */
1547     function count_real_submissions($groupid=0) {
1548         return assignment_count_real_submissions($this->cm, $groupid);
1549     }
1551     /**
1552      * Alerts teachers by email of new or changed assignments that need grading
1553      *
1554      * First checks whether the option to email teachers is set for this assignment.
1555      * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1556      * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1557      * @param $submission object The submission that has changed
1558      */
1559     function email_teachers($submission) {
1560         global $CFG, $DB;
1562         if (empty($this->assignment->emailteachers)) {          // No need to do anything
1563             return;
1564         }
1566         $user = $DB->get_record('user', array('id'=>$submission->userid));
1568         if ($teachers = $this->get_graders($user)) {
1570             $strassignments = get_string('modulenameplural', 'assignment');
1571             $strassignment  = get_string('modulename', 'assignment');
1572             $strsubmitted  = get_string('submitted', 'assignment');
1574             foreach ($teachers as $teacher) {
1575                 $info = new object();
1576                 $info->username = fullname($user, true);
1577                 $info->assignment = format_string($this->assignment->name,true);
1578                 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
1580                 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1581                 $posttext = $this->email_teachers_text($info);
1582                 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
1584                 $eventdata = new object();
1585                 $eventdata->modulename       = 'assignment';
1586                 $eventdata->userfrom         = $user;
1587                 $eventdata->userto           = $teacher;
1588                 $eventdata->subject          = $postsubject;
1589                 $eventdata->fullmessage      = $posttext;
1590                 $eventdata->fullmessageformat = FORMAT_PLAIN;
1591                 $eventdata->fullmessagehtml  = $posthtml;
1592                 $eventdata->smallmessage     = '';
1593                 if ( events_trigger('message_send', $eventdata) > 0 ){
1594                 }
1595             }
1596         }
1597     }
1599     function send_file($filearea, $args) {
1600         debugging('plugin does not implement file sending', DEBUG_DEVELOPER);
1601         return false;
1602     }
1604     /**
1605      * Returns a list of teachers that should be grading given submission
1606      */
1607     function get_graders($user) {
1608         //potential graders
1609         $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false);
1611         $graders = array();
1612         if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) {   // Separate groups are being used
1613             if ($groups = groups_get_all_groups($this->course->id, $user->id)) {  // Try to find all groups
1614                 foreach ($groups as $group) {
1615                     foreach ($potgraders as $t) {
1616                         if ($t->id == $user->id) {
1617                             continue; // do not send self
1618                         }
1619                         if (groups_is_member($group->id, $t->id)) {
1620                             $graders[$t->id] = $t;
1621                         }
1622                     }
1623                 }
1624             } else {
1625                 // user not in group, try to find graders without group
1626                 foreach ($potgraders as $t) {
1627                     if ($t->id == $user->id) {
1628                         continue; // do not send self
1629                     }
1630                     if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
1631                         $graders[$t->id] = $t;
1632                     }
1633                 }
1634             }
1635         } else {
1636             foreach ($potgraders as $t) {
1637                 if ($t->id == $user->id) {
1638                     continue; // do not send self
1639                 }
1640                 $graders[$t->id] = $t;
1641             }
1642         }
1643         return $graders;
1644     }
1646     /**
1647      * Creates the text content for emails to teachers
1648      *
1649      * @param $info object The info used by the 'emailteachermail' language string
1650      * @return string
1651      */
1652     function email_teachers_text($info) {
1653         $posttext  = format_string($this->course->shortname).' -> '.$this->strassignments.' -> '.
1654                      format_string($this->assignment->name)."\n";
1655         $posttext .= '---------------------------------------------------------------------'."\n";
1656         $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
1657         $posttext .= "\n---------------------------------------------------------------------\n";
1658         return $posttext;
1659     }
1661      /**
1662      * Creates the html content for emails to teachers
1663      *
1664      * @param $info object The info used by the 'emailteachermailhtml' language string
1665      * @return string
1666      */
1667     function email_teachers_html($info) {
1668         global $CFG;
1669         $posthtml  = '<p><font face="sans-serif">'.
1670                      '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname).'</a> ->'.
1671                      '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
1672                      '<a href="'.$CFG->wwwroot.'/mod/assignment/view.php?id='.$this->cm->id.'">'.format_string($this->assignment->name).'</a></font></p>';
1673         $posthtml .= '<hr /><font face="sans-serif">';
1674         $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
1675         $posthtml .= '</font><hr />';
1676         return $posthtml;
1677     }
1679     /**
1680      * Produces a list of links to the files uploaded by a user
1681      *
1682      * @param $userid int optional id of the user. If 0 then $USER->id is used.
1683      * @param $return boolean optional defaults to false. If true the list is returned rather than printed
1684      * @return string optional
1685      */
1686     function print_user_files($userid=0, $return=false) {
1687         global $CFG, $USER;
1689         if (!$userid) {
1690             if (!isloggedin()) {
1691                 return '';
1692             }
1693             $userid = $USER->id;
1694         }
1696         $output = '';
1698         $fs = get_file_storage();
1699         $browser = get_file_browser();
1701         $found = false;
1703         if ($files = $fs->get_area_files($this->context->id, 'assignment_submission', $userid, "timemodified", false)) {
1704             $button = new portfolio_add_button();
1705             foreach ($files as $file) {
1706                 $filename = $file->get_filename();
1707                 $found = true;
1708                 $mimetype = $file->get_mimetype();
1709                 $icon = mimeinfo_from_type('icon', $mimetype);
1710                 $path = $browser->encodepath($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/assignment_submission/'.$userid.'/'.$filename);
1711                 $output .= '<a href="'.$path.'" ><img src="'.$CFG->pixpath.'/f/'.$icon.'" class="icon" alt="'.$icon.'" />'.s($filename).'</a>';
1712                 if ($this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1713                     $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id, 'fileid' => $file->get_id()));
1714                     $button->set_formats(portfolio_format_from_file($file));
1715                     $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
1716                 }
1717                 $output .= '<br />';
1718             }
1719             if (count($files) > 1  && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1720                 $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id));
1721                 $button->set_formats(PORTFOLIO_PORMAT_FILE);
1722                 $output .= '<br />'  . $button->to_html();
1723             }
1724         }
1726         $output = '<div class="files">'.$output.'</div>';
1728         if ($return) {
1729             return $output;
1730         }
1731         echo $output;
1732     }
1734     /**
1735      * Count the files uploaded by a given user
1736      *
1737      * @param $userid int The user id
1738      * @return int
1739      */
1740     function count_user_files($userid) {
1741         $fs = get_file_storage();
1742         $files = $fs->get_area_files($this->context->id, 'assignment_submission', $userid, "id", false);
1743         return count($files);
1744     }
1746     /**
1747      * Returns true if the student is allowed to submit
1748      *
1749      * Checks that the assignment has started and, if the option to prevent late
1750      * submissions is set, also checks that the assignment has not yet closed.
1751      * @return boolean
1752      */
1753     function isopen() {
1754         $time = time();
1755         if ($this->assignment->preventlate && $this->assignment->timedue) {
1756             return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
1757         } else {
1758             return ($this->assignment->timeavailable <= $time);
1759         }
1760     }
1763     /**
1764      * Return true if is set description is hidden till available date
1765      *
1766      * This is needed by calendar so that hidden descriptions do not
1767      * come up in upcoming events.
1768      *
1769      * Check that description is hidden till available date
1770      * By default return false
1771      * Assignments types should implement this method if needed
1772      * @return boolen
1773      */
1774     function description_is_hidden() {
1775         return false;
1776     }
1778     /**
1779      * Return an outline of the user's interaction with the assignment
1780      *
1781      * The default method prints the grade and timemodified
1782      * @param $user object
1783      * @return object with properties ->info and ->time
1784      */
1785     function user_outline($user) {
1786         if ($submission = $this->get_submission($user->id)) {
1788             $result = new object();
1789             $result->info = get_string('grade').': '.$this->display_grade($submission->grade);
1790             $result->time = $submission->timemodified;
1791             return $result;
1792         }
1793         return NULL;
1794     }
1796     /**
1797      * Print complete information about the user's interaction with the assignment
1798      *
1799      * @param $user object
1800      */
1801     function user_complete($user) {
1802         if ($submission = $this->get_submission($user->id)) {
1804             $fs = get_file_storage();
1805             $browser = get_file_browser();
1807             if ($files = $fs->get_area_files($this->context->id, 'assignment_submission', $user->id, "timemodified", false)) {
1808                 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
1809                 foreach ($files as $file) {
1810                     $countfiles .= "; ".$file->get_filename();
1811                 }
1812             }
1814             print_simple_box_start();
1815             echo get_string("lastmodified").": ";
1816             echo userdate($submission->timemodified);
1817             echo $this->display_lateness($submission->timemodified);
1819             $this->print_user_files($user->id);
1821             echo '<br />';
1823             if (empty($submission->timemarked)) {
1824                 print_string("notgradedyet", "assignment");
1825             } else {
1826                 $this->view_feedback($submission);
1827             }
1829             print_simple_box_end();
1831         } else {
1832             print_string("notsubmittedyet", "assignment");
1833         }
1834     }
1836     /**
1837      * Return a string indicating how late a submission is
1838      *
1839      * @param $timesubmitted int
1840      * @return string
1841      */
1842     function display_lateness($timesubmitted) {
1843         return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
1844     }
1846     /**
1847      * Empty method stub for all delete actions.
1848      */
1849     function delete() {
1850         //nothing by default
1851         redirect('view.php?id='.$this->cm->id);
1852     }
1854     /**
1855      * Empty custom feedback grading form.
1856      */
1857     function custom_feedbackform($submission, $return=false) {
1858         //nothing by default
1859         return '';
1860     }
1862     /**
1863      * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
1864      * for the course (see resource).
1865      *
1866      * Given a course_module object, this function returns any "extra" information that may be needed
1867      * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
1868      *
1869      * @param $coursemodule object The coursemodule object (record).
1870      * @return object An object on information that the coures will know about (most noticeably, an icon).
1871      *
1872      */
1873     function get_coursemodule_info($coursemodule) {
1874         return false;
1875     }
1877     /**
1878      * Plugin cron method - do not use $this here, create new assignment instances if needed.
1879      * @return void
1880      */
1881     function cron() {
1882         //no plugin cron by default - override if needed
1883     }
1885     /**
1886      * Reset all submissions
1887      */
1888     function reset_userdata($data) {
1889         global $CFG, $DB;
1891         if (!$DB->count_records('assignment', array('course'=>$data->courseid, 'assignmenttype'=>$this->type))) {
1892             return array(); // no assignments of this type present
1893         }
1895         $componentstr = get_string('modulenameplural', 'assignment');
1896         $status = array();
1898         $typestr = get_string('type'.$this->type, 'assignment');
1900         if (!empty($data->reset_assignment_submissions)) {
1901             $assignmentssql = "SELECT a.id
1902                                  FROM {assignment} a
1903                                 WHERE a.course=? AND a.assignmenttype=?";
1904             $params = array($data->courseid, $this->type);
1906             // now get rid of all submissions and responses
1907             $fs = get_file_storage();
1908             if ($assignments = $DB->get_records_sql($assignmentssql, $params)) {
1909                 foreach ($assignments as $assignmentid=>$unused) {
1910                     if (!$cm = get_coursemodule_from_instance('assignment', $assignmentid)) {
1911                         continue;
1912                     }
1913                     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1914                     $fs->delete_area_files($context->id, 'assignment_submission');
1915                     $fs->delete_area_files($context->id, 'assignment_response');
1916                 }
1917             }
1919             $DB->delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)", $params);
1921             $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
1923             if (empty($data->reset_gradebook_grades)) {
1924                 // remove all grades from gradebook
1925                 assignment_reset_gradebook($data->courseid, $this->type);
1926             }
1927         }
1929         /// updating dates - shift may be negative too
1930         if ($data->timeshift) {
1931             shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
1932             $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
1933         }
1935         return $status;
1936     }
1939     function portfolio_exportable() {
1940         return false;
1941     }
1942 } ////// End of the assignment_base class
1944 class mod_assignment_upload_file_form extends moodleform {
1945     function definition() {
1946         $mform = $this->_form;
1947         $instance = $this->_customdata;
1949         //TODO: improve upload size checking
1950         $mform->setMaxFileSize($instance->assignment->maxbytes);
1952         // visible elements
1953         $mform->addElement('file', 'newfile', get_string('uploadafile'));
1955         // hidden params
1956         $mform->addElement('hidden', 'id', $instance->cm->id);
1957         $mform->setType('id', PARAM_INT);
1958         $mform->addElement('hidden', 'action', 'uploadfile');
1959         $mform->setType('action', PARAM_ALPHA);
1961         // buttons
1962         $this->add_action_buttons(false, get_string('uploadthisfile'));
1963     }
1967 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
1969 /**
1970  * Deletes an assignment instance
1971  *
1972  * This is done by calling the delete_instance() method of the assignment type class
1973  */
1974 function assignment_delete_instance($id){
1975     global $CFG, $DB;
1977     if (! $assignment = $DB->get_record('assignment', array('id'=>$id))) {
1978         return false;
1979     }
1981     // fall back to base class if plugin missing
1982     $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
1983     if (file_exists($classfile)) {
1984         require_once($classfile);
1985         $assignmentclass = "assignment_$assignment->assignmenttype";
1987     } else {
1988         debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
1989         $assignmentclass = "assignment_base";
1990     }
1992     $ass = new $assignmentclass();
1993     return $ass->delete_instance($assignment);
1997 /**
1998  * Updates an assignment instance
1999  *
2000  * This is done by calling the update_instance() method of the assignment type class
2001  */
2002 function assignment_update_instance($assignment){
2003     global $CFG;
2005     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2007     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2008     $assignmentclass = "assignment_$assignment->assignmenttype";
2009     $ass = new $assignmentclass();
2010     return $ass->update_instance($assignment);
2014 /**
2015  * Adds an assignment instance
2016  *
2017  * This is done by calling the add_instance() method of the assignment type class
2018  */
2019 function assignment_add_instance($assignment) {
2020     global $CFG;
2022     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2024     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2025     $assignmentclass = "assignment_$assignment->assignmenttype";
2026     $ass = new $assignmentclass();
2027     return $ass->add_instance($assignment);
2031 /**
2032  * Returns an outline of a user interaction with an assignment
2033  *
2034  * This is done by calling the user_outline() method of the assignment type class
2035  */
2036 function assignment_user_outline($course, $user, $mod, $assignment) {
2037     global $CFG;
2039     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2040     $assignmentclass = "assignment_$assignment->assignmenttype";
2041     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2042     return $ass->user_outline($user);
2045 /**
2046  * Prints the complete info about a user's interaction with an assignment
2047  *
2048  * This is done by calling the user_complete() method of the assignment type class
2049  */
2050 function assignment_user_complete($course, $user, $mod, $assignment) {
2051     global $CFG;
2053     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2054     $assignmentclass = "assignment_$assignment->assignmenttype";
2055     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2056     return $ass->user_complete($user);
2059 /**
2060  * Function to be run periodically according to the moodle cron
2061  *
2062  * Finds all assignment notifications that have yet to be mailed out, and mails them
2063  */
2064 function assignment_cron () {
2065     global $CFG, $USER, $DB;
2067     /// first execute all crons in plugins
2068     if ($plugins = get_list_of_plugins('mod/assignment/type')) {
2069         foreach ($plugins as $plugin) {
2070             require_once("$CFG->dirroot/mod/assignment/type/$plugin/assignment.class.php");
2071             $assignmentclass = "assignment_$plugin";
2072             $ass = new $assignmentclass();
2073             $ass->cron();
2074         }
2075     }
2077     /// Notices older than 1 day will not be mailed.  This is to avoid the problem where
2078     /// cron has not been running for a long time, and then suddenly people are flooded
2079     /// with mail from the past few weeks or months
2081     $timenow   = time();
2082     $endtime   = $timenow - $CFG->maxeditingtime;
2083     $starttime = $endtime - 24 * 3600;   /// One day earlier
2085     if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2087         $realuser = clone($USER);
2089         foreach ($submissions as $key => $submission) {
2090             if (! $DB->set_field("assignment_submissions", "mailed", "1", array("id"=>$submission->id))) {
2091                 echo "Could not update the mailed field for id $submission->id.  Not mailed.\n";
2092                 unset($submissions[$key]);
2093             }
2094         }
2096         $timenow = time();
2098         foreach ($submissions as $submission) {
2100             echo "Processing assignment submission $submission->id\n";
2102             if (! $user = $DB->get_record("user", array("id"=>$submission->userid))) {
2103                 echo "Could not find user $post->userid\n";
2104                 continue;
2105             }
2107             if (! $course = $DB->get_record("course", array("id"=>$submission->course))) {
2108                 echo "Could not find course $submission->course\n";
2109                 continue;
2110             }
2112             /// Override the language and timezone of the "current" user, so that
2113             /// mail is customised for the receiver.
2114             cron_setup_user($user, $course);
2116             if (!has_capability('moodle/course:view', get_context_instance(CONTEXT_COURSE, $submission->course), $user->id)) {
2117                 echo fullname($user)." not an active participant in " . format_string($course->shortname) . "\n";
2118                 continue;
2119             }
2121             if (! $teacher = $DB->get_record("user", array("id"=>$submission->teacher))) {
2122                 echo "Could not find teacher $submission->teacher\n";
2123                 continue;
2124             }
2126             if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2127                 echo "Could not find course module for assignment id $submission->assignment\n";
2128                 continue;
2129             }
2131             if (! $mod->visible) {    /// Hold mail notification for hidden assignments until later
2132                 continue;
2133             }
2135             $strassignments = get_string("modulenameplural", "assignment");
2136             $strassignment  = get_string("modulename", "assignment");
2138             $assignmentinfo = new object();
2139             $assignmentinfo->teacher = fullname($teacher);
2140             $assignmentinfo->assignment = format_string($submission->name,true);
2141             $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2143             $postsubject = "$course->shortname: $strassignments: ".format_string($submission->name,true);
2144             $posttext  = "$course->shortname -> $strassignments -> ".format_string($submission->name,true)."\n";
2145             $posttext .= "---------------------------------------------------------------------\n";
2146             $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2147             $posttext .= "---------------------------------------------------------------------\n";
2149             if ($user->mailformat == 1) {  // HTML
2150                 $posthtml = "<p><font face=\"sans-serif\">".
2151                 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> ->".
2152                 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2153                 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2154                 $posthtml .= "<hr /><font face=\"sans-serif\">";
2155                 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2156                 $posthtml .= "</font><hr />";
2157             } else {
2158                 $posthtml = "";
2159             }
2161             $eventdata = new object();
2162             $eventdata->modulename       = 'assignment';
2163             $eventdata->userfrom         = $teacher;
2164             $eventdata->userto           = $user;
2165             $eventdata->subject          = $postsubject;
2166             $eventdata->fullmessage      = $posttext;
2167             $eventdata->fullmessageformat = FORMAT_PLAIN;
2168             $eventdata->fullmessagehtml  = $posthtml;
2169             $eventdata->smallmessage     = '';
2170             if ( events_trigger('message_send', $eventdata) > 0 ){
2171                 echo "Error: assignment cron: Could not send out mail for id $submission->id to user $user->id ($user->email)\n";
2172             }
2173         }
2175         cron_setup_user();
2176     }
2178     return true;
2181 /**
2182  * Return grade for given user or all users.
2183  *
2184  * @param int $assignmentid id of assignment
2185  * @param int $userid optional user id, 0 means all users
2186  * @return array array of grades, false if none
2187  */
2188 function assignment_get_user_grades($assignment, $userid=0) {
2189     global $CFG, $DB;
2191     if ($userid) {
2192         $user = "AND u.id = :userid";
2193         $params = array('userid'=>$userid);
2194     } else {
2195         $user = "";
2196     }
2197     $params['aid'] = $assignment->id;
2199     $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2200                    s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2201               FROM {user} u, {assignment_submissions} s
2202              WHERE u.id = s.userid AND s.assignment = :aid
2203                    $user";
2205     return $DB->get_records_sql($sql, $params);
2208 /**
2209  * Update activity grades
2210  *
2211  * @param object $assignment
2212  * @param int $userid specific user only, 0 means all
2213  */
2214 function assignment_update_grades($assignment, $userid=0, $nullifnone=true) {
2215     global $CFG, $DB;
2216     require_once($CFG->libdir.'/gradelib.php');
2218     if ($assignment->grade == 0) {
2219         assignment_grade_item_update($assignment);
2221     } else if ($grades = assignment_get_user_grades($assignment, $userid)) {
2222         foreach($grades as $k=>$v) {
2223             if ($v->rawgrade == -1) {
2224                 $grades[$k]->rawgrade = null;
2225             }
2226         }
2227         assignment_grade_item_update($assignment, $grades);
2229     } else {
2230         assignment_grade_item_update($assignment);
2231     }
2234 /**
2235  * Update all grades in gradebook.
2236  */
2237 function assignment_upgrade_grades() {
2238     global $DB;
2240     $sql = "SELECT COUNT('x')
2241               FROM {assignment} a, {course_modules} cm, {modules} m
2242              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2243     $count = $DB->count_records_sql($sql);
2245     $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
2246               FROM {assignment} a, {course_modules} cm, {modules} m
2247              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2248     if ($rs = $DB->get_recordset_sql($sql)) {
2249         // too much debug output
2250         $pbar = new progress_bar('assignmentupgradegrades', 500, true);
2251         $i=0;
2252         foreach ($rs as $assignment) {
2253             $i++;
2254             upgrade_set_timeout(60*5); // set up timeout, may also abort execution
2255             assignment_update_grades($assignment);
2256             $pbar->update($i, $count, "Updating Assignment grades ($i/$count).");
2257         }
2258         $rs->close();
2259         upgrade_set_timeout(); // reset to default timeout
2260     }
2263 /**
2264  * Create grade item for given assignment
2265  *
2266  * @param object $assignment object with extra cmidnumber
2267  * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
2268  * @return int 0 if ok, error code otherwise
2269  */
2270 function assignment_grade_item_update($assignment, $grades=NULL) {
2271     global $CFG;
2272     require_once($CFG->libdir.'/gradelib.php');
2274     if (!isset($assignment->courseid)) {
2275         $assignment->courseid = $assignment->course;
2276     }
2278     $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
2280     if ($assignment->grade > 0) {
2281         $params['gradetype'] = GRADE_TYPE_VALUE;
2282         $params['grademax']  = $assignment->grade;
2283         $params['grademin']  = 0;
2285     } else if ($assignment->grade < 0) {
2286         $params['gradetype'] = GRADE_TYPE_SCALE;
2287         $params['scaleid']   = -$assignment->grade;
2289     } else {
2290         $params['gradetype'] = GRADE_TYPE_TEXT; // allow text comments only
2291     }
2293     if ($grades  === 'reset') {
2294         $params['reset'] = true;
2295         $grades = NULL;
2296     }
2298     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades, $params);
2301 /**
2302  * Delete grade item for given assignment
2303  *
2304  * @param object $assignment object
2305  * @return object assignment
2306  */
2307 function assignment_grade_item_delete($assignment) {
2308     global $CFG;
2309     require_once($CFG->libdir.'/gradelib.php');
2311     if (!isset($assignment->courseid)) {
2312         $assignment->courseid = $assignment->course;
2313     }
2315     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
2318 /**
2319  * Returns the users with data in one assignment (students and teachers)
2320  *
2321  * @param $assignmentid int
2322  * @return array of user objects
2323  */
2324 function assignment_get_participants($assignmentid) {
2325     global $CFG, $DB;
2327     //Get students
2328     $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2329                                         FROM {user} u,
2330                                              {assignment_submissions} a
2331                                        WHERE a.assignment = ? and
2332                                              u.id = a.userid", array($assignmentid));
2333     //Get teachers
2334     $teachers = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2335                                         FROM {user} u,
2336                                              {assignment_submissions} a
2337                                        WHERE a.assignment = ? and
2338                                              u.id = a.teacher", array($assignmentid));
2340     //Add teachers to students
2341     if ($teachers) {
2342         foreach ($teachers as $teacher) {
2343             $students[$teacher->id] = $teacher;
2344         }
2345     }
2346     //Return students array (it contains an array of unique users)
2347     return ($students);
2350 function assignment_pluginfile($course, $cminfo, $context, $filearea, $args) {
2351     global $CFG, $DB;
2353     if (!$assignment = $DB->get_record('assignment', array('id'=>$cminfo->instance))) {
2354         return false;
2355     }
2356     if (!$cm = get_coursemodule_from_instance('assignment', $assignment->id, $course->id)) {
2357         return false;
2358     }
2360     require_once($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
2361     $assignmentclass = 'assignment_'.$assignment->assignmenttype;
2362     $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm, $course);
2364     return $assignmentinstance->send_file($filearea, $args);
2366 /**
2367  * Checks if a scale is being used by an assignment
2368  *
2369  * This is used by the backup code to decide whether to back up a scale
2370  * @param $assignmentid int
2371  * @param $scaleid int
2372  * @return boolean True if the scale is used by the assignment
2373  */
2374 function assignment_scale_used($assignmentid, $scaleid) {
2375     global $DB;
2377     $return = false;
2379     $rec = $DB->get_record('assignment', array('id'=>$assignmentid,'grade'=>-$scaleid));
2381     if (!empty($rec) && !empty($scaleid)) {
2382         $return = true;
2383     }
2385     return $return;
2388 /**
2389  * Checks if scale is being used by any instance of assignment
2390  *
2391  * This is used to find out if scale used anywhere
2392  * @param $scaleid int
2393  * @return boolean True if the scale is used by any assignment
2394  */
2395 function assignment_scale_used_anywhere($scaleid) {
2396     global $DB;
2398     if ($scaleid and $DB->record_exists('assignment', array('grade'=>-$scaleid))) {
2399         return true;
2400     } else {
2401         return false;
2402     }
2405 /**
2406  * Make sure up-to-date events are created for all assignment instances
2407  *
2408  * This standard function will check all instances of this module
2409  * and make sure there are up-to-date events created for each of them.
2410  * If courseid = 0, then every assignment event in the site is checked, else
2411  * only assignment events belonging to the course specified are checked.
2412  * This function is used, in its new format, by restore_refresh_events()
2413  *
2414  * @param $courseid int optional If zero then all assignments for all courses are covered
2415  * @return boolean Always returns true
2416  */
2417 function assignment_refresh_events($courseid = 0) {
2418     global $DB;
2420     if ($courseid == 0) {
2421         if (! $assignments = $DB->get_records("assignment")) {
2422             return true;
2423         }
2424     } else {
2425         if (! $assignments = $DB->get_records("assignment", array("course"=>$courseid))) {
2426             return true;
2427         }
2428     }
2429     $moduleid = $DB->get_field('modules', 'id', array('name'=>'assignment'));
2431     foreach ($assignments as $assignment) {
2432         $event = NULL;
2433         $event->name        = $assignment->name;
2434         $event->description = $assignment->intro;
2435         $event->timestart   = $assignment->timedue;
2437         if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
2438             update_event($event);
2440         } else {
2441             $event->courseid    = $assignment->course;
2442             $event->groupid     = 0;
2443             $event->userid      = 0;
2444             $event->modulename  = 'assignment';
2445             $event->instance    = $assignment->id;
2446             $event->eventtype   = 'due';
2447             $event->timeduration = 0;
2448             $event->visible     = $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$assignment->id));
2449             add_event($event);
2450         }
2452     }
2453     return true;
2456 /**
2457  * Print recent activity from all assignments in a given course
2458  *
2459  * This is used by the recent activity block
2460  */
2461 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
2462     global $CFG, $USER, $DB;
2464     // do not use log table if possible, it may be huge
2466     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
2467                                                      u.firstname, u.lastname, u.email, u.picture
2468                                                 FROM {assignment_submissions} asb
2469                                                      JOIN {assignment} a      ON a.id = asb.assignment
2470                                                      JOIN {course_modules} cm ON cm.instance = a.id
2471                                                      JOIN {modules} md        ON md.id = cm.module
2472                                                      JOIN {user} u            ON u.id = asb.userid
2473                                                WHERE asb.timemodified > ? AND
2474                                                      a.course = ? AND
2475                                                      md.name = 'assignment'
2476                                             ORDER BY asb.timemodified ASC", array($timestart, $course->id))) {
2477          return false;
2478     }
2480     $modinfo =& get_fast_modinfo($course); // reference needed because we might load the groups
2481     $show    = array();
2482     $grader  = array();
2484     foreach($submissions as $submission) {
2485         if (!array_key_exists($submission->cmid, $modinfo->cms)) {
2486             continue;
2487         }
2488         $cm = $modinfo->cms[$submission->cmid];
2489         if (!$cm->uservisible) {
2490             continue;
2491         }
2492         if ($submission->userid == $USER->id) {
2493             $show[] = $submission;
2494             continue;
2495         }
2497         // the act of sumbitting of assignment may be considered private - only graders will see it if specified
2498         if (empty($CFG->assignment_showrecentsubmissions)) {
2499             if (!array_key_exists($cm->id, $grader)) {
2500                 $grader[$cm->id] = has_capability('moodle/grade:viewall', get_context_instance(CONTEXT_MODULE, $cm->id));
2501             }
2502             if (!$grader[$cm->id]) {
2503                 continue;
2504             }
2505         }
2507         $groupmode = groups_get_activity_groupmode($cm, $course);
2509         if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2510             if (isguestuser()) {
2511                 // shortcut - guest user does not belong into any group
2512                 continue;
2513             }
2515             if (is_null($modinfo->groups)) {
2516                 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2517             }
2519             // this will be slow - show only users that share group with me in this cm
2520             if (empty($modinfo->groups[$cm->id])) {
2521                 continue;
2522             }
2523             $usersgroups =  groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
2524             if (is_array($usersgroups)) {
2525                 $usersgroups = array_keys($usersgroups);
2526                 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2527                 if (empty($intersect)) {
2528                     continue;
2529                 }
2530             }
2531         }
2532         $show[] = $submission;
2533     }
2535     if (empty($show)) {
2536         return false;
2537     }
2539     print_headline(get_string('newsubmissions', 'assignment').':');
2541     foreach ($show as $submission) {
2542         $cm = $modinfo->cms[$submission->cmid];
2543         $link = $CFG->wwwroot.'/mod/assignment/view.php?id='.$cm->id;
2544         print_recent_activity_note($submission->timemodified, $submission, $cm->name, $link, false, $viewfullnames);
2545     }
2547     return true;
2551 /**
2552  * Returns all assignments since a given time in specified forum.
2553  */
2554 function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0)  {
2555     global $CFG, $COURSE, $USER, $DB;
2557     if ($COURSE->id == $courseid) {
2558         $course = $COURSE;
2559     } else {
2560         $course = $DB->get_record('course', array('id'=>$courseid));
2561     }
2563     $modinfo =& get_fast_modinfo($course);
2565     $cm = $modinfo->cms[$cmid];
2567     $params = array();
2568     if ($userid) {
2569         $userselect = "AND u.id = :userid";
2570         $params['userid'] = $userid;
2571     } else {
2572         $userselect = "";
2573     }
2575     if ($groupid) {
2576         $groupselect = "AND gm.groupid = :groupid";
2577         $groupjoin   = "JOIN {groups_members} gm ON  gm.userid=u.id";
2578         $params['groupid'] = $groupid;
2579     } else {
2580         $groupselect = "";
2581         $groupjoin   = "";
2582     }
2584     $params['cminstance'] = $cm->instance;
2585     $params['timestart'] = $timestart;
2587     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, asb.userid,
2588                                                      u.firstname, u.lastname, u.email, u.picture
2589                                                 FROM {assignment_submissions} asb
2590                                                 JOIN {assignment} a      ON a.id = asb.assignment
2591                                                 JOIN {user} u            ON u.id = asb.userid
2592                                           $groupjoin
2593                                                WHERE asb.timemodified > :timestart AND a.id = :cminstance
2594                                                      $userselect $groupselect
2595                                             ORDER BY asb.timemodified ASC", $params)) {
2596          return;
2597     }
2599     $groupmode       = groups_get_activity_groupmode($cm, $course);
2600     $cm_context      = get_context_instance(CONTEXT_MODULE, $cm->id);
2601     $grader          = has_capability('moodle/grade:viewall', $cm_context);
2602     $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
2603     $viewfullnames   = has_capability('moodle/site:viewfullnames', $cm_context);
2605     if (is_null($modinfo->groups)) {
2606         $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2607     }
2609     $show = array();
2611     foreach($submissions as $submission) {
2612         if ($submission->userid == $USER->id) {
2613             $show[] = $submission;
2614             continue;
2615         }
2616         // the act of submitting of assignment may be considered private - only graders will see it if specified
2617         if (empty($CFG->assignment_showrecentsubmissions)) {
2618             if (!$grader) {
2619                 continue;
2620             }
2621         }
2623         if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
2624             if (isguestuser()) {
2625                 // shortcut - guest user does not belong into any group
2626                 continue;
2627             }
2629             // this will be slow - show only users that share group with me in this cm
2630             if (empty($modinfo->groups[$cm->id])) {
2631                 continue;
2632             }
2633             $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
2634             if (is_array($usersgroups)) {
2635                 $usersgroups = array_keys($usersgroups);
2636                 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2637                 if (empty($intersect)) {
2638                     continue;
2639                 }
2640             }
2641         }
2642         $show[] = $submission;
2643     }
2645     if (empty($show)) {
2646         return;
2647     }
2649     if ($grader) {
2650         require_once($CFG->libdir.'/gradelib.php');
2651         $userids = array();
2652         foreach ($show as $id=>$submission) {
2653             $userids[] = $submission->userid;
2655         }
2656         $grades = grade_get_grades($courseid, 'mod', 'assignment', $cm->instance, $userids);
2657     }
2659     $aname = format_string($cm->name,true);
2660     foreach ($show as $submission) {
2661         $tmpactivity = new object();
2663         $tmpactivity->type         = 'assignment';
2664         $tmpactivity->cmid         = $cm->id;
2665         $tmpactivity->name         = $aname;
2666         $tmpactivity->sectionnum   = $cm->sectionnum;
2667         $tmpactivity->timestamp    = $submission->timemodified;
2669         if ($grader) {
2670             $tmpactivity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
2671         }
2673         $tmpactivity->user->userid   = $submission->userid;
2674         $tmpactivity->user->fullname = fullname($submission, $viewfullnames);
2675         $tmpactivity->user->picture  = $submission->picture;
2677         $activities[$index++] = $tmpactivity;
2678     }
2680     return;
2683 /**
2684  * Print recent activity from all assignments in a given course
2685  *
2686  * This is used by course/recent.php
2687  */
2688 function assignment_print_recent_mod_activity($activity, $courseid, $detail, $modnames)  {
2689     global $CFG;
2691     echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
2693     echo "<tr><td class=\"userpicture\" valign=\"top\">";
2694     print_user_picture($activity->user->userid, $courseid, $activity->user->picture);
2695     echo "</td><td>";
2697     if ($detail) {
2698         $modname = $modnames[$activity->type];
2699         echo '<div class="title">';
2700         echo "<img src=\"$CFG->modpixpath/assignment/icon.gif\" ".
2701              "class=\"icon\" alt=\"$modname\">";
2702         echo "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id={$activity->cmid}\">{$activity->name}</a>";
2703         echo '</div>';
2704     }
2706     if (isset($activity->grade)) {
2707         echo '<div class="grade">';
2708         echo get_string('grade').': ';
2709         echo $activity->grade;
2710         echo '</div>';
2711     }
2713     echo '<div class="user">';
2714     echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->userid}&amp;course=$courseid\">"
2715          ."{$activity->user->fullname}</a>  - ".userdate($activity->timestamp);
2716     echo '</div>';
2718     echo "</td></tr></table>";
2721 /// GENERIC SQL FUNCTIONS
2723 /**
2724  * Fetch info from logs
2725  *
2726  * @param $log object with properties ->info (the assignment id) and ->userid
2727  * @return array with assignment name and user firstname and lastname
2728  */
2729 function assignment_log_info($log) {
2730     global $CFG, $DB;
2732     return $DB->get_record_sql("SELECT a.name, u.firstname, u.lastname
2733                                   FROM {assignment} a, {user} u
2734                                  WHERE a.id = ? AND u.id = ?", array($log->info, $log->userid));
2737 /**
2738  * Return list of marked submissions that have not been mailed out for currently enrolled students
2739  *
2740  * @return array
2741  */
2742 function assignment_get_unmailed_submissions($starttime, $endtime) {
2743     global $CFG, $DB;
2745     return $DB->get_records_sql("SELECT s.*, a.course, a.name
2746                                    FROM {assignment_submissions} s,
2747                                         {assignment} a
2748                                   WHERE s.mailed = 0
2749                                         AND s.timemarked <= ?
2750                                         AND s.timemarked >= ?
2751                                         AND s.assignment = a.id", array($endtime, $starttime));
2754 /**
2755  * Counts all real assignment submissions by ENROLLED students (not empty ones)
2756  *
2757  * There are also assignment type methods count_real_submissions() wich in the default
2758  * implementation simply call this function.
2759  * @param $groupid int optional If nonzero then count is restricted to this group
2760  * @return int The number of submissions
2761  */
2762 function assignment_count_real_submissions($cm, $groupid=0) {
2763     global $CFG, $DB;
2765     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2767     // this is all the users with this capability set, in this context or higher
2768     if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $groupid, '', false)) {
2769         $users = array_keys($users);
2770     }
2772     // if groupmembersonly used, remove users who are not in any group
2773     if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
2774         if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
2775             $users = array_intersect($users, array_keys($groupingusers));
2776         }
2777     }
2779     if (empty($users)) {
2780         return 0;
2781     }
2783     $userlists = implode(',', $users);
2785     return $DB->count_records_sql("SELECT COUNT('x')
2786                                      FROM {assignment_submissions}
2787                                     WHERE assignment = ? AND
2788                                           timemodified > 0 AND
2789                                           userid IN ($userlists)", array($cm->instance));
2793 /**
2794  * Return all assignment submissions by ENROLLED students (even empty)
2795  *
2796  * There are also assignment type methods get_submissions() wich in the default
2797  * implementation simply call this function.
2798  * @param $sort string optional field names for the ORDER BY in the sql query
2799  * @param $dir string optional specifying the sort direction, defaults to DESC
2800  * @return array The submission objects indexed by id
2801  */
2802 function assignment_get_all_submissions($assignment, $sort="", $dir="DESC") {
2803 /// Return all assignment submissions by ENROLLED students (even empty)
2804     global $CFG, $DB;
2806     if ($sort == "lastname" or $sort == "firstname") {
2807         $sort = "u.$sort $dir";
2808     } else if (empty($sort)) {
2809         $sort = "a.timemodified DESC";
2810     } else {
2811         $sort = "a.$sort $dir";
2812     }
2814     /* not sure this is needed at all since assignmenet already has a course define, so this join?
2815     $select = "s.course = '$assignment->course' AND";
2816     if ($assignment->course == SITEID) {
2817         $select = '';
2818     }*/
2820     return $DB->get_records_sql("SELECT a.*
2821                                    FROM {assignment_submissions} a, {user} u
2822                                   WHERE u.id = a.userid
2823                                         AND a.assignment = ?
2824                                ORDER BY $sort", array($assignment->id));
2828 /**
2829  * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
2830  * for the course (see resource).
2831  *
2832  * Given a course_module object, this function returns any "extra" information that may be needed
2833  * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
2834  *
2835  * @param $coursemodule object The coursemodule object (record).
2836  * @return object An object on information that the coures will know about (most noticeably, an icon).
2837  *
2838  */
2839 function assignment_get_coursemodule_info($coursemodule) {
2840     global $CFG, $DB;
2842     if (! $assignment = $DB->get_record('assignment', array('id'=>$coursemodule->instance), 'id, assignmenttype, name')) {
2843         return false;
2844     }
2846     $libfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2848     if (file_exists($libfile)) {
2849         require_once($libfile);
2850         $assignmentclass = "assignment_$assignment->assignmenttype";
2851         $ass = new $assignmentclass('staticonly');
2852         if ($result = $ass->get_coursemodule_info($coursemodule)) {
2853             return $result;
2854         } else {
2855             $info = new object();
2856             $info->name = $assignment->name;
2857             return $info;
2858         }
2860     } else {
2861         debugging('Incorrect assignment type: '.$assignment->assignmenttype);
2862         return false;
2863     }
2868 /// OTHER GENERAL FUNCTIONS FOR ASSIGNMENTS  ///////////////////////////////////////
2870 /**
2871  * Returns an array of installed assignment types indexed and sorted by name
2872  *
2873  * @return array The index is the name of the assignment type, the value its full name from the language strings
2874  */
2875 function assignment_types() {
2876     $types = array();
2877     $names = get_list_of_plugins('mod/assignment/type');
2878     foreach ($names as $name) {
2879         $types[$name] = get_string('type'.$name, 'assignment');
2880     }
2881     asort($types);
2882     return $types;
2885 function assignment_print_overview($courses, &$htmlarray) {
2886     global $USER, $CFG, $DB;
2888     if (empty($courses) || !is_array($courses) || count($courses) == 0) {
2889         return array();
2890     }
2892     if (!$assignments = get_all_instances_in_courses('assignment',$courses)) {
2893         return;
2894     }
2896     $assignmentids = array();
2898     // Do assignment_base::isopen() here without loading the whole thing for speed
2899     foreach ($assignments as $key => $assignment) {
2900         $time = time();
2901         if ($assignment->timedue) {
2902             if ($assignment->preventlate) {
2903                 $isopen = ($assignment->timeavailable <= $time && $time <= $assignment->timedue);
2904             } else {
2905                 $isopen = ($assignment->timeavailable <= $time);
2906             }
2907         }
2908         if (empty($isopen) || empty($assignment->timedue)) {
2909             unset($assignments[$key]);
2910         }else{
2911             $assignmentids[] = $assignment->id;
2912         }
2913     }
2915     if(empty($assignmentids)){
2916         // no assigments to look at - we're done
2917         return true;
2918     }
2920     $strduedate = get_string('duedate', 'assignment');
2921     $strduedateno = get_string('duedateno', 'assignment');
2922     $strgraded = get_string('graded', 'assignment');
2923     $strnotgradedyet = get_string('notgradedyet', 'assignment');
2924     $strnotsubmittedyet = get_string('notsubmittedyet', 'assignment');
2925     $strsubmitted = get_string('submitted', 'assignment');
2926     $strassignment = get_string('modulename', 'assignment');
2927     $strreviewed = get_string('reviewed','assignment');
2930     // NOTE: we do all possible database work here *outside* of the loop to ensure this scales 
2931     //
2932     list($sqlassignmentids, $assignmentidparams) = $DB->get_in_or_equal($assignmentids);
2933     
2934     // build up and array of unmarked submissions indexed by assigment id/ userid
2935     // for use where the user has grading rights on assigment
2936     $rs = $DB->get_recordset_sql("SELECT id, assignment, userid 
2937                             FROM {assignment_submissions}
2938                             WHERE teacher = 0 AND timemarked = 0
2939                             AND assignment $sqlassignmentids", $assignmentidparams);
2941     $unmarkedsubmissions = array();
2942     foreach ($rs as $rd) {
2943         $unmarkedsubmissions[$rd->assignment][$rd->userid] = $rd->id;
2944     }
2945     $rs->close();
2948     // get all user submissions, indexed by assigment id
2949     $mysubmissions = $DB->get_records_sql("SELECT assignment, timemarked, teacher, grade
2950                                       FROM {assignment_submissions}
2951                                       WHERE userid = ? AND 
2952                                       assignment $sqlassignmentids", array_merge(array($USER->id), $assignmentidparams));
2954     foreach ($assignments as $assignment) {
2955         $str = '<div class="assignment overview"><div class="name">'.$strassignment. ': '.
2956                '<a '.($assignment->visible ? '':' class="dimmed"').
2957                'title="'.$strassignment.'" href="'.$CFG->wwwroot.
2958                '/mod/assignment/view.php?id='.$assignment->coursemodule.'">'.
2959                $assignment->name.'</a></div>';
2960         if ($assignment->timedue) {
2961             $str .= '<div class="info">'.$strduedate.': '.userdate($assignment->timedue).'</div>';
2962         } else {
2963             $str .= '<div class="info">'.$strduedateno.'</div>';
2964         }
2965         $context = get_context_instance(CONTEXT_MODULE, $assignment->coursemodule);
2966         if (has_capability('mod/assignment:grade', $context)) {
2968             // count how many people can submit
2969             $submissions = 0; // init
2970             if ($students = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', 0, '', false)) {
2971                 foreach($students as $student){
2972                     if(isset($unmarkedsubmissions[$assignment->id][$student->id])){
2973                         $submissions++;
2974                     }
2975                 }
2976             }
2978             if ($submissions) {
2979                 $str .= get_string('submissionsnotgraded', 'assignment', $submissions);
2980             }
2981         } else {
2982             if(isset($mysubmissions[$assignment->id])){
2984                 $submission = $mysubmissions[$assignment->id];
2986                 if ($submission->teacher == 0 && $submission->timemarked == 0) {
2987                     $str .= $strsubmitted . ', ' . $strnotgradedyet;
2988                 } else if ($submission->grade <= 0) {
2989                     $str .= $strsubmitted . ', ' . $strreviewed;
2990                 } else {
2991                     $str .= $strsubmitted . ', ' . $strgraded;
2992                 }
2993             } else {
2994                 $str .= $strnotsubmittedyet . ' ' . assignment_display_lateness(time(), $assignment->timedue);
2995             }
2996         }
2997         $str .= '</div>';
2998         if (empty($htmlarray[$assignment->course]['assignment'])) {
2999             $htmlarray[$assignment->course]['assignment'] = $str;
3000         } else {
3001             $htmlarray[$assignment->course]['assignment'] .= $str;
3002         }
3003     }
3006 function assignment_display_lateness($timesubmitted, $timedue) {
3007     if (!$timedue) {
3008         return '';
3009     }
3010     $time = $timedue - $timesubmitted;
3011     if ($time < 0) {
3012         $timetext = get_string('late', 'assignment', format_time($time));
3013         return ' (<span class="late">'.$timetext.'</span>)';
3014     } else {
3015         $timetext = get_string('early', 'assignment', format_time($time));
3016         return ' (<span class="early">'.$timetext.'</span>)';
3017     }
3020 function assignment_get_view_actions() {
3021     return array('view');
3024 function assignment_get_post_actions() {
3025     return array('upload');
3028 function assignment_get_types() {
3029     global $CFG;
3030     $types = array();
3032     $type = new object();
3033     $type->modclass = MOD_CLASS_ACTIVITY;
3034     $type->type = "assignment_group_start";
3035     $type->typestr = '--'.get_string('modulenameplural', 'assignment');
3036     $types[] = $type;
3038     $standardassignments = array('upload','online','uploadsingle','offline');
3039     foreach ($standardassignments as $assignmenttype) {
3040         $type = new object();
3041         $type->modclass = MOD_CLASS_ACTIVITY;
3042         $type->type = "assignment&amp;type=$assignmenttype";
3043         $type->typestr = get_string("type$assignmenttype", 'assignment');
3044         $types[] = $type;
3045     }
3047     /// Drop-in extra assignment types
3048     $assignmenttypes = get_list_of_plugins('mod/assignment/type');
3049     foreach ($assignmenttypes as $assignmenttype) {
3050         if (!empty($CFG->{'assignment_hide_'.$assignmenttype})) {  // Not wanted
3051             continue;
3052         }
3053         if (!in_array($assignmenttype, $standardassignments)) {
3054             $type = new object();
3055             $type->modclass = MOD_CLASS_ACTIVITY;
3056             $type->type = "assignment&amp;type=$assignmenttype";
3057             $type->typestr = get_string("type$assignmenttype", 'assignment');
3058             $types[] = $type;
3059         }
3060     }
3062     $type = new object();
3063     $type->modclass = MOD_CLASS_ACTIVITY;
3064     $type->type = "assignment_group_end";
3065     $type->typestr = '--';
3066     $types[] = $type;
3068     return $types;
3071 /**
3072  * Removes all grades from gradebook
3073  * @param int $courseid
3074  * @param string optional type
3075  */
3076 function assignment_reset_gradebook($courseid, $type='') {
3077     global $CFG, $DB;
3079     $params = array('courseid'=>$courseid);
3080     if ($type) {
3081         $type = "AND a.assignmenttype= :type";
3082         $params['type'] = $type;
3083     }
3085     $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
3086               FROM {assignment} a, {course_modules} cm, {modules} m
3087              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id AND a.course=:courseid $type";
3089     if ($assignments = $DB->get_records_sql($sql, $params)) {
3090         foreach ($assignments as $assignment) {
3091             assignment_grade_item_update($assignment, 'reset');
3092         }
3093     }
3096 /**
3097  * This function is used by the reset_course_userdata function in moodlelib.
3098  * This function will remove all posts from the specified assignment
3099  * and clean up any related data.
3100  * @param $data the data submitted from the reset course.
3101  * @return array status array
3102  */
3103 function assignment_reset_userdata($data) {
3104     global $CFG;
3106     $status = array();
3108     foreach (get_list_of_plugins('mod/assignment/type') as $type) {
3109         require_once("$CFG->dirroot/mod/assignment/type/$type/assignment.class.php");
3110         $assignmentclass = "assignment_$type";
3111         $ass = new $assignmentclass();
3112         $status = array_merge($status, $ass->reset_userdata($data));
3113     }
3115     return $status;
3118 /**
3119  * Implementation of the function for printing the form elements that control
3120  * whether the course reset functionality affects the assignment.
3121  * @param $mform form passed by reference
3122  */
3123 function assignment_reset_course_form_definition(&$mform) {
3124     $mform->addElement('header', 'assignmentheader', get_string('modulenameplural', 'assignment'));
3125     $mform->addElement('advcheckbox', 'reset_assignment_submissions', get_string('deleteallsubmissions','assignment'));
3128 /**
3129  * Course reset form defaults.
3130  */
3131 function assignment_reset_course_form_defaults($course) {
3132     return array('reset_assignment_submissions'=>1);
3135 /**
3136  * Returns all other caps used in module
3137  */
3138 function assignment_get_extra_capabilities() {
3139     return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames');
3142 class assignment_portfolio_caller extends portfolio_module_caller_base {
3144     /**
3145     * the assignment subclass
3146     */
3147     private $assignment;
3149     /**
3150     * the file to include when waking up to load the assignment subclass def
3151     */
3152     private $assignmentfile;
3154     /**
3155     * callback arg for a single file export
3156     */
3157     protected $fileid;
3159     public static function expected_callbackargs() {
3160         return array(
3161             'id'     => true,
3162             'fileid' => false,
3163         );
3164     }
3166     public function load_data() {
3167         global $DB, $CFG;
3169         if (! $this->cm = get_coursemodule_from_id('assignment', $this->id)) {
3170             throw new portfolio_caller_exception('invalidcoursemodule');
3171         }
3173         if (! $assignment = $DB->get_record("assignment", array("id"=>$this->cm->instance))) {
3174             throw new portfolio_caller_exception('invalidid', 'assignment');
3175         }
3177         $this->assignmentfile = $CFG->dirroot . '/mod/assignment/type/' . $assignment->assignmenttype . '/assignment.class.php';
3178         require_once($this->assignmentfile);
3179         $assignmentclass = "assignment_$assignment->assignmenttype";
3181         $this->assignment = new $assignmentclass($this->cm->id, $assignment, $this->cm);
3183         if (!$this->assignment->portfolio_exportable()) {
3184             throw new portfolio_caller_exception('notexportable', 'portfolio', $this->get_return_url());
3185         }
3187         $this->set_file_and_format_data($this->fileid, $this->assignment->context->id, 'assignment_submission', $this->user->id);
3188         if (empty($this->supportedformats) && is_callable(array($this->assignment, 'portfolio_supported_formats'))) {
3189             $this->supportedformats = $this->assignment->portfolio_supported_formats();
3190         }
3191     }
3193     public function prepare_package() {
3194         global $CFG;
3195         if (is_callable(array($this->assignment, 'portfolio_prepare_package'))) {
3196             return $this->assignment->portfolio_prepare_package($this->exporter, $this->user->id);
3197         }
3198         return $this->prepare_package_file();
3199     }
3201     public function get_sha1() {
3202         global $CFG;
3203         if (is_callable(array($this->assignment, 'portfolio_get_sha1'))) {
3204             return $this->assignment->portfolio_get_sha1($this->user->id);
3205         }
3206         return $this->get_sha1_file();
3207     }
3209     public function expected_time() {
3210         if (is_callable(array($this->assignment, 'portfolio_get_expected_time'))) {
3211             return $this->assignment->portfolio_get_expected_time();
3212         }
3213         return $this->expected_time_file();
3214     }
3216     public function check_permissions() {
3217         $context = get_context_instance(CONTEXT_MODULE, $this->assignment->cm->id);
3218         return has_capability('mod/assignment:exportownsubmission', $context);
3219     }
3221     public function __wakeup() {
3222         global $CFG;
3223         if (empty($CFG)) {
3224             return true; // too early yet
3225         }
3226         require_once($this->assignmentfile);
3227         $this->assignment = unserialize(serialize($this->assignment));
3228     }
3230     public static function display_name() {
3231         return get_string('modulename', 'assignment');
3232     }
3235 /**
3236  * @param string $feature FEATURE_xx constant for requested feature
3237  * @return mixed True if module supports feature, null if doesn't know
3238  */
3239 function assignment_supports($feature) {
3240     switch($feature) {
3241         case FEATURE_GROUPS:                  return true;
3242         case FEATURE_GROUPINGS:               return true;
3243         case FEATURE_GROUPMEMBERSONLY:        return true;
3244         case FEATURE_MODEDIT_INTRO_EDITOR:    return true;
3245         case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
3246         case FEATURE_GRADE_HAS_GRADE:         return true;
3247         case FEATURE_GRADE_OUTCOMES:          return true;
3249         default: return null;
3250     }