MDL-14679 fixed references to mod.html
[moodle.git] / mod / assignment / lib.php
1 <?PHP  // $Id$
2 /**
3  * assignment_base is the base class for assignment types
4  *
5  * This class provides all the functionality for an assignment
6  */
8 DEFINE ('ASSIGNMENT_COUNT_WORDS', 1);
9 DEFINE ('ASSIGNMENT_COUNT_LETTERS', 2);
11 /**
12  * Standard base class for all assignment submodules (assignment types).
13  */
14 class assignment_base {
16     var $cm;
17     var $course;
18     var $assignment;
19     var $strassignment;
20     var $strassignments;
21     var $strsubmissions;
22     var $strlastmodified;
23     var $pagetitle;
24     var $usehtmleditor;
25     var $defaultformat;
26     var $context;
27     var $type;
29     /**
30      * Constructor for the base assignment class
31      *
32      * Constructor for the base assignment class.
33      * If cmid is set create the cm, course, assignment objects.
34      * If the assignment is hidden and the user is not a teacher then
35      * this prints a page header and notice.
36      *
37      * @param cmid   integer, the current course module id - not set for new assignments
38      * @param assignment   object, usually null, but if we have it we pass it to save db access
39      * @param cm   object, usually null, but if we have it we pass it to save db access
40      * @param course   object, usually null, but if we have it we pass it to save db access
41      */
42     function assignment_base($cmid='staticonly', $assignment=NULL, $cm=NULL, $course=NULL) {
43         global $COURSE;
45         if ($cmid == 'staticonly') {
46             //use static functions only!
47             return;
48         }
50         global $CFG;
52         if ($cm) {
53             $this->cm = $cm;
54         } else if (! $this->cm = get_coursemodule_from_id('assignment', $cmid)) {
55             print_error('invalidcoursemodule');
56         }
58         $this->context = get_context_instance(CONTEXT_MODULE, $this->cm->id);
60         if ($course) {
61             $this->course = $course;
62         } else if ($this->cm->course == $COURSE->id) {
63             $this->course = $COURSE;
64         } else if (! $this->course = get_record('course', 'id', $this->cm->course)) {
65             print_error('invalidid', 'assignment');
66         }
68         if ($assignment) {
69             $this->assignment = $assignment;
70         } else if (! $this->assignment = get_record('assignment', 'id', $this->cm->instance)) {
71             print_error('invalidid', 'assignment');
72         }
74         $this->assignment->cmidnumber = $this->cm->id;     // compatibility with modedit assignment obj
75         $this->assignment->courseid   = $this->course->id; // compatibility with modedit assignment obj
77         $this->strassignment = get_string('modulename', 'assignment');
78         $this->strassignments = get_string('modulenameplural', 'assignment');
79         $this->strsubmissions = get_string('submissions', 'assignment');
80         $this->strlastmodified = get_string('lastmodified');
81         $this->pagetitle = strip_tags($this->course->shortname.': '.$this->strassignment.': '.format_string($this->assignment->name,true));
83         // visibility handled by require_login() with $cm parameter
84         // get current group only when really needed
86     /// Set up things for a HTML editor if it's needed
87         if ($this->usehtmleditor = can_use_html_editor()) {
88             $this->defaultformat = FORMAT_HTML;
89         } else {
90             $this->defaultformat = FORMAT_MOODLE;
91         }
92     }
94     /**
95      * Display the assignment, used by view.php
96      *
97      * This in turn calls the methods producing individual parts of the page
98      */
99     function view() {
101         $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
102         require_capability('mod/assignment:view', $context);
104         add_to_log($this->course->id, "assignment", "view", "view.php?id={$this->cm->id}",
105                    $this->assignment->id, $this->cm->id);
107         $this->view_header();
109         $this->view_intro();
111         $this->view_dates();
113         $this->view_feedback();
115         $this->view_footer();
116     }
118     /**
119      * Display the header and top of a page
120      *
121      * (this doesn't change much for assignment types)
122      * This is used by the view() method to print the header of view.php but
123      * it can be used on other pages in which case the string to denote the
124      * page in the navigation trail should be passed as an argument
125      *
126      * @param $subpage string Description of subpage to be used in navigation trail
127      */
128     function view_header($subpage='') {
130         global $CFG;
133         if ($subpage) {
134             $navigation = build_navigation($subpage, $this->cm);
135         } else {
136             $navigation = build_navigation('', $this->cm);
137         }
139         print_header($this->pagetitle, $this->course->fullname, $navigation, '', '',
140                      true, update_module_button($this->cm->id, $this->course->id, $this->strassignment),
141                      navmenu($this->course, $this->cm));
143         groups_print_activity_menu($this->cm, 'view.php?id=' . $this->cm->id);
145         echo '<div class="reportlink">'.$this->submittedlink().'</div>';
146         echo '<div class="clearer"></div>';
147     }
150     /**
151      * Display the assignment intro
152      *
153      * This will most likely be extended by assignment type plug-ins
154      * The default implementation prints the assignment description in a box
155      */
156     function view_intro() {
157         print_simple_box_start('center', '', '', 0, 'generalbox', 'intro');
158         $formatoptions = new stdClass;
159         $formatoptions->noclean = true;
160         echo format_text($this->assignment->description, $this->assignment->format, $formatoptions);
161         print_simple_box_end();
162     }
164     /**
165      * Display the assignment dates
166      *
167      * Prints the assignment start and end dates in a box.
168      * This will be suitable for most assignment types
169      */
170     function view_dates() {
171         if (!$this->assignment->timeavailable && !$this->assignment->timedue) {
172             return;
173         }
175         print_simple_box_start('center', '', '', 0, 'generalbox', 'dates');
176         echo '<table>';
177         if ($this->assignment->timeavailable) {
178             echo '<tr><td class="c0">'.get_string('availabledate','assignment').':</td>';
179             echo '    <td class="c1">'.userdate($this->assignment->timeavailable).'</td></tr>';
180         }
181         if ($this->assignment->timedue) {
182             echo '<tr><td class="c0">'.get_string('duedate','assignment').':</td>';
183             echo '    <td class="c1">'.userdate($this->assignment->timedue).'</td></tr>';
184         }
185         echo '</table>';
186         print_simple_box_end();
187     }
190     /**
191      * Display the bottom and footer of a page
192      *
193      * This default method just prints the footer.
194      * This will be suitable for most assignment types
195      */
196     function view_footer() {
197         print_footer($this->course);
198     }
200     /**
201      * Display the feedback to the student
202      *
203      * This default method prints the teacher picture and name, date when marked,
204      * grade and teacher submissioncomment.
205      *
206      * @param $submission object The submission object or NULL in which case it will be loaded
207      */
208     function view_feedback($submission=NULL) {
209         global $USER, $CFG;
210         require_once($CFG->libdir.'/gradelib.php');
212         if (!has_capability('mod/assignment:submit', $this->context, $USER->id, false)) {
213             // can not submit assignments -> no feedback
214             return;
215         }
217         if (!$submission) { /// Get submission for this assignment
218             $submission = $this->get_submission($USER->id);
219         }
221         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $USER->id);
222         $item = $grading_info->items[0];
223         $grade = $item->grades[$USER->id];
225         if ($grade->hidden or $grade->grade === false) { // hidden or error
226             return;
227         }
229         if ($grade->grade === null and empty($grade->str_feedback)) {   /// Nothing to show yet
230             return;
231         }
233         $graded_date = $grade->dategraded;
234         $graded_by   = $grade->usermodified;
236     /// We need the teacher info
237         if (!$teacher = get_record('user', 'id', $graded_by)) {
238             print_error('cannotfindteacher');
239         }
241     /// Print the feedback
242         print_heading(get_string('feedbackfromteacher', 'assignment', $this->course->teacher)); // TODO: fix teacher string
244         echo '<table cellspacing="0" class="feedback">';
246         echo '<tr>';
247         echo '<td class="left picture">';
248         if ($teacher) {
249             print_user_picture($teacher, $this->course->id, $teacher->picture);
250         }
251         echo '</td>';
252         echo '<td class="topic">';
253         echo '<div class="from">';
254         if ($teacher) {
255             echo '<div class="fullname">'.fullname($teacher).'</div>';
256         }
257         echo '<div class="time">'.userdate($graded_date).'</div>';
258         echo '</div>';
259         echo '</td>';
260         echo '</tr>';
262         echo '<tr>';
263         echo '<td class="left side">&nbsp;</td>';
264         echo '<td class="content">';
265         echo '<div class="grade">';
266         echo get_string("grade").': '.$grade->str_long_grade;
267         echo '</div>';
268         echo '<div class="clearer"></div>';
270         echo '<div class="comment">';
271         echo $grade->str_feedback;
272         echo '</div>';
273         echo '</tr>';
275         echo '</table>';
276     }
278     /**
279      * Returns a link with info about the state of the assignment submissions
280      *
281      * This is used by view_header to put this link at the top right of the page.
282      * For teachers it gives the number of submitted assignments with a link
283      * For students it gives the time of their submission.
284      * This will be suitable for most assignment types.
285      * @param bool $allgroup print all groups info if user can access all groups, suitable for index.php
286      * @return string
287      */
288     function submittedlink($allgroups=false) {
289         global $USER;
290         global $CFG;
292         $submitted = '';
293         $urlbase = "{$CFG->wwwroot}/mod/assignment/";
295         $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
296         if (has_capability('mod/assignment:grade', $context)) {
297             if ($allgroups and has_capability('moodle/site:accessallgroups', $context)) {
298                 $group = 0;
299             } else {
300                 $group = groups_get_activity_group($this->cm);
301             }
302             if ($count = $this->count_real_submissions($group)) {
303                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
304                              get_string('viewsubmissions', 'assignment', $count).'</a>';
305             } else {
306                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
307                              get_string('noattempts', 'assignment').'</a>';
308             }
309         } else {
310             if (!empty($USER->id)) {
311                 if ($submission = $this->get_submission($USER->id)) {
312                     if ($submission->timemodified) {
313                         if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
314                             $submitted = '<span class="early">'.userdate($submission->timemodified).'</span>';
315                         } else {
316                             $submitted = '<span class="late">'.userdate($submission->timemodified).'</span>';
317                         }
318                     }
319                 }
320             }
321         }
323         return $submitted;
324     }
327     function setup_elements(&$mform) {
329     }
331     /**
332      * Create a new assignment activity
333      *
334      * Given an object containing all the necessary data,
335      * (defined by the form in mod_form.php) this function
336      * will create a new instance and return the id number
337      * of the new instance.
338      * The due data is added to the calendar
339      * This is common to all assignment types.
340      *
341      * @param $assignment object The data from the form on mod_form.php
342      * @return int The id of the assignment
343      */
344     function add_instance($assignment) {
345         global $COURSE;
347         $assignment->timemodified = time();
348         $assignment->courseid = $assignment->course;
350         if ($returnid = insert_record("assignment", $assignment)) {
351             $assignment->id = $returnid;
353             if ($assignment->timedue) {
354                 $event = new object();
355                 $event->name        = $assignment->name;
356                 $event->description = $assignment->description;
357                 $event->courseid    = $assignment->course;
358                 $event->groupid     = 0;
359                 $event->userid      = 0;
360                 $event->modulename  = 'assignment';
361                 $event->instance    = $returnid;
362                 $event->eventtype   = 'due';
363                 $event->timestart   = $assignment->timedue;
364                 $event->timeduration = 0;
366                 add_event($event);
367             }
369             $assignment = stripslashes_recursive($assignment);
370             assignment_grade_item_update($assignment);
372         }
375         return $returnid;
376     }
378     /**
379      * Deletes an assignment activity
380      *
381      * Deletes all database records, files and calendar events for this assignment.
382      * @param $assignment object The assignment to be deleted
383      * @return boolean False indicates error
384      */
385     function delete_instance($assignment) {
386         global $CFG;
388         $assignment->courseid = $assignment->course;
390         $result = true;
392         if (! delete_records('assignment_submissions', 'assignment', $assignment->id)) {
393             $result = false;
394         }
396         if (! delete_records('assignment', 'id', $assignment->id)) {
397             $result = false;
398         }
400         if (! delete_records('event', 'modulename', 'assignment', 'instance', $assignment->id)) {
401             $result = false;
402         }
404         // delete file area with all attachments - ignore errors
405         require_once($CFG->libdir.'/filelib.php');
406         fulldelete($CFG->dataroot.'/'.$assignment->course.'/'.$CFG->moddata.'/assignment/'.$assignment->id);
408         assignment_grade_item_delete($assignment);
410         return $result;
411     }
413     /**
414      * Updates a new assignment activity
415      *
416      * Given an object containing all the necessary data,
417      * (defined by the form in mod_form.php) this function
418      * will update the assignment instance and return the id number
419      * The due date is updated in the calendar
420      * This is common to all assignment types.
421      *
422      * @param $assignment object The data from the form on mod_form.php
423      * @return int The assignment id
424      */
425     function update_instance($assignment) {
426         global $COURSE;
428         $assignment->timemodified = time();
430         $assignment->id = $assignment->instance;
431         $assignment->courseid = $assignment->course;
433         if (!update_record('assignment', $assignment)) {
434             return false;
435         }
437         if ($assignment->timedue) {
438             $event = new object();
440             if ($event->id = get_field('event', 'id', 'modulename', 'assignment', 'instance', $assignment->id)) {
442                 $event->name        = $assignment->name;
443                 $event->description = $assignment->description;
444                 $event->timestart   = $assignment->timedue;
446                 update_event($event);
447             } else {
448                 $event = new object();
449                 $event->name        = $assignment->name;
450                 $event->description = $assignment->description;
451                 $event->courseid    = $assignment->course;
452                 $event->groupid     = 0;
453                 $event->userid      = 0;
454                 $event->modulename  = 'assignment';
455                 $event->instance    = $assignment->id;
456                 $event->eventtype   = 'due';
457                 $event->timestart   = $assignment->timedue;
458                 $event->timeduration = 0;
460                 add_event($event);
461             }
462         } else {
463             delete_records('event', 'modulename', 'assignment', 'instance', $assignment->id);
464         }
466         // get existing grade item
467         $assignment = stripslashes_recursive($assignment);
469         assignment_grade_item_update($assignment);
471         return true;
472     }
474     /**
475      * Update grade item for this submission.
476      */
477     function update_grade($submission) {
478         assignment_update_grades($this->assignment, $submission->userid);
479     }
481     /**
482      * Top-level function for handling of submissions called by submissions.php
483      *
484      * This is for handling the teacher interaction with the grading interface
485      * This should be suitable for most assignment types.
486      *
487      * @param $mode string Specifies the kind of teacher interaction taking place
488      */
489     function submissions($mode) {
490         ///The main switch is changed to facilitate
491         ///1) Batch fast grading
492         ///2) Skip to the next one on the popup
493         ///3) Save and Skip to the next one on the popup
495         //make user global so we can use the id
496         global $USER;
498         $mailinfo = optional_param('mailinfo', null, PARAM_BOOL);
499         if (is_null($mailinfo)) {
500             $mailinfo = get_user_preferences('assignment_mailinfo', 0);
501         } else {
502             set_user_preference('assignment_mailinfo', $mailinfo);
503         }
505         switch ($mode) {
506             case 'grade':                         // We are in a popup window grading
507                 if ($submission = $this->process_feedback()) {
508                     //IE needs proper header with encoding
509                     print_header(get_string('feedback', 'assignment').':'.format_string($this->assignment->name));
510                     print_heading(get_string('changessaved'));
511                     print $this->update_main_listing($submission);
512                 }
513                 close_window();
514                 break;
516             case 'single':                        // We are in a popup window displaying submission
517                 $this->display_submission();
518                 break;
520             case 'all':                          // Main window, display everything
521                 $this->display_submissions();
522                 break;
524             case 'fastgrade':
525                 ///do the fast grading stuff  - this process should work for all 3 subclasses
527                 $grading    = false;
528                 $commenting = false;
529                 $col        = false;
530                 if (isset($_POST['submissioncomment'])) {
531                     $col = 'submissioncomment';
532                     $commenting = true;
533                 }
534                 if (isset($_POST['menu'])) {
535                     $col = 'menu';
536                     $grading = true;
537                 }
538                 if (!$col) {
539                     //both submissioncomment and grade columns collapsed..
540                     $this->display_submissions();
541                     break;
542                 }
544                 foreach ($_POST[$col] as $id => $unusedvalue){
546                     $id = (int)$id; //clean parameter name
548                     $this->process_outcomes($id);
550                     if (!$submission = $this->get_submission($id)) {
551                         $submission = $this->prepare_new_submission($id);
552                         $newsubmission = true;
553                     } else {
554                         $newsubmission = false;
555                     }
556                     unset($submission->data1);  // Don't need to update this.
557                     unset($submission->data2);  // Don't need to update this.
559                     //for fast grade, we need to check if any changes take place
560                     $updatedb = false;
562                     if ($grading) {
563                         $grade = $_POST['menu'][$id];
564                         $updatedb = $updatedb || ($submission->grade != $grade);
565                         $submission->grade = $grade;
566                     } else {
567                         if (!$newsubmission) {
568                             unset($submission->grade);  // Don't need to update this.
569                         }
570                     }
571                     if ($commenting) {
572                         $commentvalue = trim($_POST['submissioncomment'][$id]);
573                         $updatedb = $updatedb || ($submission->submissioncomment != stripslashes($commentvalue));
574                         $submission->submissioncomment = $commentvalue;
575                     } else {
576                         unset($submission->submissioncomment);  // Don't need to update this.
577                     }
579                     $submission->teacher    = $USER->id;
580                     if ($updatedb) {
581                         $submission->mailed = (int)(!$mailinfo);
582                     }
584                     $submission->timemarked = time();
586                     //if it is not an update, we don't change the last modified time etc.
587                     //this will also not write into database if no submissioncomment and grade is entered.
589                     if ($updatedb){
590                         if ($newsubmission) {
591                             if (!isset($submission->submissioncomment)) {
592                                 $submission->submissioncomment = '';
593                             }
594                             if (!$sid = insert_record('assignment_submissions', $submission)) {
595                                 return false;
596                             }
597                             $submission->id = $sid;
598                         } else {
599                             if (!update_record('assignment_submissions', $submission)) {
600                                 return false;
601                             }
602                         }
604                         // triger grade event
605                         $this->update_grade($submission);
607                         //add to log only if updating
608                         add_to_log($this->course->id, 'assignment', 'update grades',
609                                    'submissions.php?id='.$this->assignment->id.'&user='.$submission->userid,
610                                    $submission->userid, $this->cm->id);
611                     }
613                 }
615                 $message = notify(get_string('changessaved'), 'notifysuccess', 'center', true);
617                 $this->display_submissions($message);
618                 break;
621             case 'next':
622                 /// We are currently in pop up, but we want to skip to next one without saving.
623                 ///    This turns out to be similar to a single case
624                 /// The URL used is for the next submission.
626                 $this->display_submission();
627                 break;
629             case 'saveandnext':
630                 ///We are in pop up. save the current one and go to the next one.
631                 //first we save the current changes
632                 if ($submission = $this->process_feedback()) {
633                     //print_heading(get_string('changessaved'));
634                     $extra_javascript = $this->update_main_listing($submission);
635                 }
637                 //then we display the next submission
638                 $this->display_submission($extra_javascript);
639                 break;
641             default:
642                 echo "something seriously is wrong!!";
643                 break;
644         }
645     }
647     /**
648     * Helper method updating the listing on the main script from popup using javascript
649     *
650     * @param $submission object The submission whose data is to be updated on the main page
651     */
652     function update_main_listing($submission) {
653         global $SESSION, $CFG;
655         $output = '';
657         $perpage = get_user_preferences('assignment_perpage', 10);
659         $quickgrade = get_user_preferences('assignment_quickgrade', 0);
661         /// Run some Javascript to try and update the parent page
662         $output .= '<script type="text/javascript">'."\n<!--\n";
663         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['submissioncomment'])) {
664             if ($quickgrade){
665                 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid.'").value="'
666                 .trim($submission->submissioncomment).'";'."\n";
667              } else {
668                 $output.= 'opener.document.getElementById("com'.$submission->userid.
669                 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment)), 15)."\";\n";
670             }
671         }
673         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['grade'])) {
674             //echo optional_param('menuindex');
675             if ($quickgrade){
676                 $output.= 'opener.document.getElementById("menumenu'.$submission->userid.
677                 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT).'";'."\n";
678             } else {
679                 $output.= 'opener.document.getElementById("g'.$submission->userid.'").innerHTML="'.
680                 $this->display_grade($submission->grade)."\";\n";
681             }
682         }
683         //need to add student's assignments in there too.
684         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemodified']) &&
685             $submission->timemodified) {
686             $output.= 'opener.document.getElementById("ts'.$submission->userid.
687                  '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid)).userdate($submission->timemodified)."\";\n";
688         }
690         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemarked']) &&
691             $submission->timemarked) {
692             $output.= 'opener.document.getElementById("tt'.$submission->userid.
693                  '").innerHTML="'.userdate($submission->timemarked)."\";\n";
694         }
696         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['status'])) {
697             $output.= 'opener.document.getElementById("up'.$submission->userid.'").className="s1";';
698             $buttontext = get_string('update');
699             $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),
700                       'grade'.$submission->userid, $buttontext, 450, 700, $buttontext, 'none', true, 'button'.$submission->userid);
701             $output.= 'opener.document.getElementById("up'.$submission->userid.'").innerHTML="'.addslashes_js($button).'";';
702         }
704         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $submission->userid);
706         if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['finalgrade'])) {
707             $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid.
708             '").innerHTML="'.$grading_info->items[0]->grades[$submission->userid]->str_grade.'";'."\n";
709         }
711         if (!empty($CFG->enableoutcomes) and empty($SESSION->flextable['mod-assignment-submissions']->collapse['outcome'])) {
713             if (!empty($grading_info->outcomes)) {
714                 foreach($grading_info->outcomes as $n=>$outcome) {
715                     if ($outcome->grades[$submission->userid]->locked) {
716                         continue;
717                     }
719                     if ($quickgrade){
720                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.
721                         '").selectedIndex="'.$outcome->grades[$submission->userid]->grade.'";'."\n";
723                     } else {
724                         $options = make_grades_menu(-$outcome->scaleid);
725                         $options[0] = get_string('nooutcome', 'grades');
726                         $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.'").innerHTML="'.$options[$outcome->grades[$submission->userid]->grade]."\";\n";
727                     }
729                 }
730             }
731         }
733         $output .= "\n-->\n</script>";
734         return $output;
735     }
737     /**
738      *  Return a grade in user-friendly form, whether it's a scale or not
739      *
740      * @param $grade
741      * @return string User-friendly representation of grade
742      */
743     function display_grade($grade) {
745         static $scalegrades = array();   // Cache scales for each assignment - they might have different scales!!
747         if ($this->assignment->grade >= 0) {    // Normal number
748             if ($grade == -1) {
749                 return '-';
750             } else {
751                 return $grade.' / '.$this->assignment->grade;
752             }
754         } else {                                // Scale
755             if (empty($scalegrades[$this->assignment->id])) {
756                 if ($scale = get_record('scale', 'id', -($this->assignment->grade))) {
757                     $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
758                 } else {
759                     return '-';
760                 }
761             }
762             if (isset($scalegrades[$this->assignment->id][$grade])) {
763                 return $scalegrades[$this->assignment->id][$grade];
764             }
765             return '-';
766         }
767     }
769     /**
770      *  Display a single submission, ready for grading on a popup window
771      *
772      * This default method prints the teacher info and submissioncomment box at the top and
773      * the student info and submission at the bottom.
774      * This method also fetches the necessary data in order to be able to
775      * provide a "Next submission" button.
776      * Calls preprocess_submission() to give assignment type plug-ins a chance
777      * to process submissions before they are graded
778      * This method gets its arguments from the page parameters userid and offset
779      */
780     function display_submission($extra_javascript = '') {
782         global $CFG;
783         require_once($CFG->libdir.'/gradelib.php');
784         require_once($CFG->libdir.'/tablelib.php');
786         $userid = required_param('userid', PARAM_INT);
787         $offset = required_param('offset', PARAM_INT);//offset for where to start looking for student.
789         if (!$user = get_record('user', 'id', $userid)) {
790             print_error('nousers');
791         }
793         if (!$submission = $this->get_submission($user->id)) {
794             $submission = $this->prepare_new_submission($userid);
795         }
796         if ($submission->timemodified > $submission->timemarked) {
797             $subtype = 'assignmentnew';
798         } else {
799             $subtype = 'assignmentold';
800         }
802         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
803         $disabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
805     /// construct SQL, using current offset to find the data of the next student
806         $course     = $this->course;
807         $assignment = $this->assignment;
808         $cm         = $this->cm;
809         $context    = get_context_instance(CONTEXT_MODULE, $cm->id);
811         /// Get all ppl that can submit assignments
813         $currentgroup = groups_get_activity_group($cm);
814         if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $currentgroup, '', false)) {
815             $users = array_keys($users);
816         }
818         // if groupmembersonly used, remove users who are not in any group
819         if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
820             if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
821                 $users = array_intersect($users, array_keys($groupingusers));
822             }
823         }
825         $nextid = 0;
827         if ($users) {
828             $select = 'SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt,
829                               s.id AS submissionid, s.grade, s.submissioncomment,
830                               s.timemodified, s.timemarked,
831                               COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ';
832             $sql = 'FROM '.$CFG->prefix.'user u '.
833                    'LEFT JOIN '.$CFG->prefix.'assignment_submissions s ON u.id = s.userid
834                                                                       AND s.assignment = '.$this->assignment->id.' '.
835                    'WHERE u.id IN ('.implode(',', $users).') ';
837             if ($sort = flexible_table::get_sql_sort('mod-assignment-submissions')) {
838                 $sort = 'ORDER BY '.$sort.' ';
839             }
841             if (($auser = get_records_sql($select.$sql.$sort, $offset+1, 1)) !== false) {
842                 $nextuser = array_shift($auser);
843             /// Calculate user status
844                 $nextuser->status = ($nextuser->timemarked > 0) && ($nextuser->timemarked >= $nextuser->timemodified);
845                 $nextid = $nextuser->id;
846             }
847         }
849         print_header(get_string('feedback', 'assignment').':'.fullname($user, true).':'.format_string($this->assignment->name));
851         /// Print any extra javascript needed for saveandnext
852         echo $extra_javascript;
854         ///SOme javascript to help with setting up >.>
856         echo '<script type="text/javascript">'."\n";
857         echo 'function setNext(){'."\n";
858         echo 'document.getElementById(\'submitform\').mode.value=\'next\';'."\n";
859         echo 'document.getElementById(\'submitform\').userid.value="'.$nextid.'";'."\n";
860         echo '}'."\n";
862         echo 'function saveNext(){'."\n";
863         echo 'document.getElementById(\'submitform\').mode.value=\'saveandnext\';'."\n";
864         echo 'document.getElementById(\'submitform\').userid.value="'.$nextid.'";'."\n";
865         echo 'document.getElementById(\'submitform\').saveuserid.value="'.$userid.'";'."\n";
866         echo 'document.getElementById(\'submitform\').menuindex.value = document.getElementById(\'submitform\').grade.selectedIndex;'."\n";
867         echo '}'."\n";
869         echo '</script>'."\n";
870         echo '<table cellspacing="0" class="feedback '.$subtype.'" >';
872         ///Start of teacher info row
874         echo '<tr>';
875         echo '<td class="picture teacher">';
876         if ($submission->teacher) {
877             $teacher = get_record('user', 'id', $submission->teacher);
878         } else {
879             global $USER;
880             $teacher = $USER;
881         }
882         print_user_picture($teacher, $this->course->id, $teacher->picture);
883         echo '</td>';
884         echo '<td class="content">';
885         echo '<form id="submitform" action="submissions.php" method="post">';
886         echo '<div>'; // xhtml compatibility - invisiblefieldset was breaking layout here
887         echo '<input type="hidden" name="offset" value="'.($offset+1).'" />';
888         echo '<input type="hidden" name="userid" value="'.$userid.'" />';
889         echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
890         echo '<input type="hidden" name="mode" value="grade" />';
891         echo '<input type="hidden" name="menuindex" value="0" />';//selected menu index
893         //new hidden field, initialized to -1.
894         echo '<input type="hidden" name="saveuserid" value="-1" />';
896         if ($submission->timemarked) {
897             echo '<div class="from">';
898             echo '<div class="fullname">'.fullname($teacher, true).'</div>';
899             echo '<div class="time">'.userdate($submission->timemarked).'</div>';
900             echo '</div>';
901         }
902         echo '<div class="grade"><label for="menugrade">'.get_string('grade').'</label> ';
903         choose_from_menu(make_grades_menu($this->assignment->grade), 'grade', $submission->grade, get_string('nograde'), '', -1, false, $disabled);
904         echo '</div>';
906         echo '<div class="clearer"></div>';
907         echo '<div class="finalgrade">'.get_string('finalgrade', 'grades').': '.$grading_info->items[0]->grades[$userid]->str_grade.'</div>';
908         echo '<div class="clearer"></div>';
910         if (!empty($CFG->enableoutcomes)) {
911             foreach($grading_info->outcomes as $n=>$outcome) {
912                 echo '<div class="outcome"><label for="menuoutcome_'.$n.'">'.$outcome->name.'</label> ';
913                 $options = make_grades_menu(-$outcome->scaleid);
914                 if ($outcome->grades[$submission->userid]->locked) {
915                     $options[0] = get_string('nooutcome', 'grades');
916                     echo $options[$outcome->grades[$submission->userid]->grade];
917                 } else {
918                     choose_from_menu($options, 'outcome_'.$n.'['.$userid.']', $outcome->grades[$submission->userid]->grade, get_string('nooutcome', 'grades'), '', 0, false, false, 0, 'menuoutcome_'.$n);
919                 }
920                 echo '</div>';
921                 echo '<div class="clearer"></div>';
922             }
923         }
926         $this->preprocess_submission($submission);
928         if ($disabled) {
929             echo '<div class="disabledfeedback">'.$grading_info->items[0]->grades[$userid]->str_feedback.'</div>';
931         } else {
932             print_textarea($this->usehtmleditor, 14, 58, 0, 0, 'submissioncomment', $submission->submissioncomment, $this->course->id);
933             if ($this->usehtmleditor) {
934                 echo '<input type="hidden" name="format" value="'.FORMAT_HTML.'" />';
935             } else {
936                 echo '<div class="format">';
937                 choose_from_menu(format_text_menu(), "format", $submission->format, "");
938                 helpbutton("textformat", get_string("helpformatting"));
939                 echo '</div>';
940             }
941         }
943         $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? 'checked="checked"' : '';
945         ///Print Buttons in Single View
946         echo '<input type="hidden" name="mailinfo" value="0" />';
947         echo '<input type="checkbox" id="mailinfo" name="mailinfo" value="1" '.$lastmailinfo.' /><label for="mailinfo">'.get_string('enableemailnotification','assignment').'</label>';
948         echo '<div class="buttons">';
949         echo '<input type="submit" name="submit" value="'.get_string('savechanges').'" onclick = "document.getElementById(\'submitform\').menuindex.value = document.getElementById(\'submitform\').grade.selectedIndex" />';
950         echo '<input type="submit" name="cancel" value="'.get_string('cancel').'" />';
951         //if there are more to be graded.
952         if ($nextid) {
953             echo '<input type="submit" name="saveandnext" value="'.get_string('saveandnext').'" onclick="saveNext()" />';
954             echo '<input type="submit" name="next" value="'.get_string('next').'" onclick="setNext();" />';
955         }
956         echo '</div>';
957         echo '</div></form>';
959         $customfeedback = $this->custom_feedbackform($submission, true);
960         if (!empty($customfeedback)) {
961             echo $customfeedback;
962         }
964         echo '</td></tr>';
966         ///End of teacher info row, Start of student info row
967         echo '<tr>';
968         echo '<td class="picture user">';
969         print_user_picture($user, $this->course->id, $user->picture);
970         echo '</td>';
971         echo '<td class="topic">';
972         echo '<div class="from">';
973         echo '<div class="fullname">'.fullname($user, true).'</div>';
974         if ($submission->timemodified) {
975             echo '<div class="time">'.userdate($submission->timemodified).
976                                      $this->display_lateness($submission->timemodified).'</div>';
977         }
978         echo '</div>';
979         $this->print_user_files($user->id);
980         echo '</td>';
981         echo '</tr>';
983         ///End of student info row
985         echo '</table>';
987         if (!$disabled and $this->usehtmleditor) {
988             use_html_editor();
989         }
991         print_footer('none');
992     }
994     /**
995      *  Preprocess submission before grading
996      *
997      * Called by display_submission()
998      * The default type does nothing here.
999      * @param $submission object The submission object
1000      */
1001     function preprocess_submission(&$submission) {
1002     }
1004     /**
1005      *  Display all the submissions ready for grading
1006      */
1007     function display_submissions($message='') {
1008         global $CFG, $DB, $USER;
1009         require_once($CFG->libdir.'/gradelib.php');
1011         /* first we check to see if the form has just been submitted
1012          * to request user_preference updates
1013          */
1015         if (isset($_POST['updatepref'])){
1016             $perpage = optional_param('perpage', 10, PARAM_INT);
1017             $perpage = ($perpage <= 0) ? 10 : $perpage ;
1018             set_user_preference('assignment_perpage', $perpage);
1019             set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
1020         }
1022         /* next we get perpage and quickgrade (allow quick grade) params
1023          * from database
1024          */
1025         $perpage    = get_user_preferences('assignment_perpage', 10);
1027         $quickgrade = get_user_preferences('assignment_quickgrade', 0);
1029         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);
1031         if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
1032             $uses_outcomes = true;
1033         } else {
1034             $uses_outcomes = false;
1035         }
1037         $page    = optional_param('page', 0, PARAM_INT);
1038         $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
1040     /// Some shortcuts to make the code read better
1042         $course     = $this->course;
1043         $assignment = $this->assignment;
1044         $cm         = $this->cm;
1046         $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->assignment->id, $this->assignment->id, $this->cm->id);
1050         $navigation = build_navigation($this->strsubmissions, $this->cm);
1051         print_header_simple(format_string($this->assignment->name,true), "", $navigation,
1052                 '', '', true, update_module_button($cm->id, $course->id, $this->strassignment), navmenu($course, $cm));
1054         $course_context = get_context_instance(CONTEXT_COURSE, $course->id);
1055         if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
1056             echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">'
1057                 . get_string('seeallcoursegrades', 'grades') . '</a></div>';
1058         }
1060         if (!empty($message)) {
1061             echo $message;   // display messages here if any
1062         }
1064         $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1066     /// Check to see if groups are being used in this assignment
1068         /// find out current groups mode
1069         $groupmode = groups_get_activity_groupmode($cm);
1070         $currentgroup = groups_get_activity_group($cm, true);
1071         groups_print_activity_menu($cm, 'submissions.php?id=' . $this->cm->id);
1073         /// Get all ppl that are allowed to submit assignments
1074         if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $currentgroup, '', false)) {
1075             $users = array_keys($users);
1076         }
1078         // if groupmembersonly used, remove users who are not in any group
1079         if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
1080             if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1081                 $users = array_intersect($users, array_keys($groupingusers));
1082             }
1083         }
1085         $tablecolumns = array('picture', 'fullname', 'grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade');
1086         if ($uses_outcomes) {
1087             $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
1088         }
1090         $tableheaders = array('',
1091                               get_string('fullname'),
1092                               get_string('grade'),
1093                               get_string('comment', 'assignment'),
1094                               get_string('lastmodified').' ('.$course->student.')',
1095                               get_string('lastmodified').' ('.$course->teacher.')',
1096                               get_string('status'),
1097                               get_string('finalgrade', 'grades'));
1098         if ($uses_outcomes) {
1099             $tableheaders[] = get_string('outcome', 'grades');
1100         }
1102         require_once($CFG->libdir.'/tablelib.php');
1103         $table = new flexible_table('mod-assignment-submissions');
1105         $table->define_columns($tablecolumns);
1106         $table->define_headers($tableheaders);
1107         $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;currentgroup='.$currentgroup);
1109         $table->sortable(true, 'lastname');//sorted by lastname by default
1110         $table->collapsible(true);
1111         $table->initialbars(true);
1113         $table->column_suppress('picture');
1114         $table->column_suppress('fullname');
1116         $table->column_class('picture', 'picture');
1117         $table->column_class('fullname', 'fullname');
1118         $table->column_class('grade', 'grade');
1119         $table->column_class('submissioncomment', 'comment');
1120         $table->column_class('timemodified', 'timemodified');
1121         $table->column_class('timemarked', 'timemarked');
1122         $table->column_class('status', 'status');
1123         $table->column_class('finalgrade', 'finalgrade');
1124         if ($uses_outcomes) {
1125             $table->column_class('outcome', 'outcome');
1126         }
1128         $table->set_attribute('cellspacing', '0');
1129         $table->set_attribute('id', 'attempts');
1130         $table->set_attribute('class', 'submissions');
1131         $table->set_attribute('width', '100%');
1132         //$table->set_attribute('align', 'center');
1134         $table->no_sorting('finalgrade');
1135         $table->no_sorting('outcome');
1137         // Start working -- this is necessary as soon as the niceties are over
1138         $table->setup();
1140         if (empty($users)) {
1141             print_heading(get_string('nosubmitusers','assignment'));
1142             return true;
1143         }
1145     /// Construct the SQL
1147         if ($where = $table->get_sql_where()) {
1148             $where .= ' AND ';
1149         }
1151         if ($sort = $table->get_sql_sort()) {
1152             $sort = ' ORDER BY '.$sort;
1153         }
1155         $select = 'SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt,
1156                           s.id AS submissionid, s.grade, s.submissioncomment,
1157                           s.timemodified, s.timemarked,
1158                           COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ';
1159         $sql = 'FROM '.$CFG->prefix.'user u '.
1160                'LEFT JOIN '.$CFG->prefix.'assignment_submissions s ON u.id = s.userid
1161                                                                   AND s.assignment = '.$this->assignment->id.' '.
1162                'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1164         $table->pagesize($perpage, count($users));
1166         ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1167         $offset = $page * $perpage;
1169         $strupdate = get_string('update');
1170         $strgrade  = get_string('grade');
1171         $grademenu = make_grades_menu($this->assignment->grade);
1173         if (($ausers = get_records_sql($select.$sql.$sort, $table->get_page_start(), $table->get_page_size())) !== false) {
1174             $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
1175             foreach ($ausers as $auser) {
1176                 $final_grade = $grading_info->items[0]->grades[$auser->id];
1177                 $grademax = $grading_info->items[0]->grademax;
1178                 $final_grade->formatted_grade = round($final_grade->grade,2) .' / ' . round($grademax,2);
1179                 $locked_overridden = 'locked';
1180                 if ($final_grade->overridden) {
1181                     $locked_overridden = 'overridden';
1182                 }
1184             /// Calculate user status
1185                 $auser->status = ($auser->timemarked > 0) && ($auser->timemarked >= $auser->timemodified);
1186                 $picture = print_user_picture($auser, $course->id, $auser->picture, false, true);
1188                 if (empty($auser->submissionid)) {
1189                     $auser->grade = -1; //no submission yet
1190                 }
1192                 if (!empty($auser->submissionid)) {
1193                 ///Prints student answer and student modified date
1194                 ///attach file or print link to student answer, depending on the type of the assignment.
1195                 ///Refer to print_student_answer in inherited classes.
1196                     if ($auser->timemodified > 0) {
1197                         $studentmodified = '<div id="ts'.$auser->id.'">'.$this->print_student_answer($auser->id)
1198                                          . userdate($auser->timemodified).'</div>';
1199                     } else {
1200                         $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1201                     }
1202                 ///Print grade, dropdown or text
1203                     if ($auser->timemarked > 0) {
1204                         $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
1206                         if ($final_grade->locked or $final_grade->overridden) {
1207                             $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1208                         } else if ($quickgrade) {
1209                             $menu = choose_from_menu(make_grades_menu($this->assignment->grade),
1210                                                      'menu['.$auser->id.']', $auser->grade,
1211                                                      get_string('nograde'),'',-1,true,false,$tabindex++);
1212                             $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
1213                         } else {
1214                             $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1215                         }
1217                     } else {
1218                         $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1219                         if ($final_grade->locked or $final_grade->overridden) {
1220                             $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1221                         } else if ($quickgrade) {
1222                             $menu = choose_from_menu(make_grades_menu($this->assignment->grade),
1223                                                      'menu['.$auser->id.']', $auser->grade,
1224                                                      get_string('nograde'),'',-1,true,false,$tabindex++);
1225                             $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1226                         } else {
1227                             $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1228                         }
1229                     }
1230                 ///Print Comment
1231                     if ($final_grade->locked or $final_grade->overridden) {
1232                         $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';
1234                     } else if ($quickgrade) {
1235                         $comment = '<div id="com'.$auser->id.'">'
1236                                  . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1237                                  . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1238                     } else {
1239                         $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
1240                     }
1241                 } else {
1242                     $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1243                     $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1244                     $status          = '<div id="st'.$auser->id.'">&nbsp;</div>';
1246                     if ($final_grade->locked or $final_grade->overridden) {
1247                         $grade = '<div id="g'.$auser->id.'">'.$final_grade->formatted_grade . '</div>';
1248                     } else if ($quickgrade) {   // allow editing
1249                         $menu = choose_from_menu(make_grades_menu($this->assignment->grade),
1250                                                  'menu['.$auser->id.']', $auser->grade,
1251                                                  get_string('nograde'),'',-1,true,false,$tabindex++);
1252                         $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1253                     } else {
1254                         $grade = '<div id="g'.$auser->id.'">-</div>';
1255                     }
1257                     if ($final_grade->locked or $final_grade->overridden) {
1258                         $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
1259                     } else if ($quickgrade) {
1260                         $comment = '<div id="com'.$auser->id.'">'
1261                                  . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1262                                  . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1263                     } else {
1264                         $comment = '<div id="com'.$auser->id.'">&nbsp;</div>';
1265                     }
1266                 }
1268                 if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
1269                     $auser->status = 0;
1270                 } else {
1271                     $auser->status = 1;
1272                 }
1274                 $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
1276                 ///No more buttons, we use popups ;-).
1277                 $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1278                            . '&amp;userid='.$auser->id.'&amp;mode=single'.'&amp;offset='.$offset++;
1279                 $button = link_to_popup_window ($popup_url, 'grade'.$auser->id, $buttontext, 600, 780,
1280                                                 $buttontext, 'none', true, 'button'.$auser->id);
1282                 $status  = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
1284                 $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';
1286                 $outcomes = '';
1288                 if ($uses_outcomes) {
1290                     foreach($grading_info->outcomes as $n=>$outcome) {
1291                         $outcomes .= '<div class="outcome"><label>'.$outcome->name.'</label>';
1292                         $options = make_grades_menu(-$outcome->scaleid);
1294                         if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
1295                             $options[0] = get_string('nooutcome', 'grades');
1296                             $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
1297                         } else {
1298                             $outcomes .= ' ';
1299                             $outcomes .= choose_from_menu($options, 'outcome_'.$n.'['.$auser->id.']',
1300                                         $outcome->grades[$auser->id]->grade, get_string('nooutcome', 'grades'), '', 0, true, false, 0, 'outcome_'.$n.'_'.$auser->id);
1301                         }
1302                         $outcomes .= '</div>';
1303                     }
1304                 }
1306                                 $userlink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $auser->id . '&amp;course=' . $course->id . '">' . fullname($auser) . '</a>';
1307                 $row = array($picture, $userlink, $grade, $comment, $studentmodified, $teachermodified, $status, $finalgrade);
1308                 if ($uses_outcomes) {
1309                     $row[] = $outcomes;
1310                 }
1312                 $table->add_data($row);
1313             }
1314         }
1316         /// Print quickgrade form around the table
1317         if ($quickgrade){
1318             echo '<form action="submissions.php" id="fastg" method="post">';
1319             echo '<div>';
1320             echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
1321             echo '<input type="hidden" name="mode" value="fastgrade" />';
1322             echo '<input type="hidden" name="page" value="'.$page.'" />';
1323             echo '</div>';
1324         }
1326         $table->print_html();  /// Print the whole table
1328         if ($quickgrade){
1329             $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? 'checked="checked"' : '';
1330             echo '<div class="fgcontrols">';
1331             echo '<div class="emailnotification">';
1332             echo '<label for="mailinfo">'.get_string('enableemailnotification','assignment').'</label>';
1333             echo '<input type="hidden" name="mailinfo" value="0" />';
1334             echo '<input type="checkbox" id="mailinfo" name="mailinfo" value="1" '.$lastmailinfo.' />';
1335             helpbutton('emailnotification', get_string('enableemailnotification', 'assignment'), 'assignment').'</p></div>';
1336             echo '</div>';
1337             echo '<div class="fastgbutton"><input type="submit" name="fastg" value="'.get_string('saveallfeedback', 'assignment').'" /></div>';
1338             echo '</div>';
1339             echo '</form>';
1340         }
1341         /// End of fast grading form
1343         /// Mini form for setting user preference
1344         echo '<div class="qgprefs">';
1345         echo '<form id="options" action="submissions.php?id='.$this->cm->id.'" method="post"><div>';
1346         echo '<input type="hidden" name="updatepref" value="1" />';
1347         echo '<table id="optiontable">';
1348         echo '<tr><td>';
1349         echo '<label for="perpage">'.get_string('pagesize','assignment').'</label>';
1350         echo '</td>';
1351         echo '<td>';
1352         echo '<input type="text" id="perpage" name="perpage" size="1" value="'.$perpage.'" />';
1353         helpbutton('pagesize', get_string('pagesize','assignment'), 'assignment');
1354         echo '</td></tr>';
1355         echo '<tr><td>';
1356         echo '<label for="quickgrade">'.get_string('quickgrade','assignment').'</label>';
1357         echo '</td>';
1358         echo '<td>';
1359         $checked = $quickgrade ? 'checked="checked"' : '';
1360         echo '<input type="checkbox" id="quickgrade" name="quickgrade" value="1" '.$checked.' />';
1361         helpbutton('quickgrade', get_string('quickgrade', 'assignment'), 'assignment').'</p></div>';
1362         echo '</td></tr>';
1363         echo '<tr><td colspan="2">';
1364         echo '<input type="submit" value="'.get_string('savepreferences').'" />';
1365         echo '</td></tr></table>';
1366         echo '</div></form></div>';
1367         ///End of mini form
1368         print_footer($this->course);
1369     }
1371     /**
1372      *  Process teacher feedback submission
1373      *
1374      * This is called by submissions() when a grading even has taken place.
1375      * It gets its data from the submitted form.
1376      * @return object The updated submission object
1377      */
1378     function process_feedback() {
1379         global $CFG, $USER;
1380         require_once($CFG->libdir.'/gradelib.php');
1382         if (!$feedback = data_submitted()) {      // No incoming data?
1383             return false;
1384         }
1386         ///For save and next, we need to know the userid to save, and the userid to go
1387         ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1388         ///as the userid to store
1389         if ((int)$feedback->saveuserid !== -1){
1390             $feedback->userid = $feedback->saveuserid;
1391         }
1393         if (!empty($feedback->cancel)) {          // User hit cancel button
1394             return false;
1395         }
1397         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);
1399         // store outcomes if needed
1400         $this->process_outcomes($feedback->userid);
1402         $submission = $this->get_submission($feedback->userid, true);  // Get or make one
1404         if (!$grading_info->items[0]->grades[$feedback->userid]->locked and
1405             !$grading_info->items[0]->grades[$feedback->userid]->overridden) {
1407             $submission->grade      = $feedback->grade;
1408             $submission->submissioncomment    = $feedback->submissioncomment;
1409             $submission->format     = $feedback->format;
1410             $submission->teacher    = $USER->id;
1411             $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1412             if (!$mailinfo) {
1413                 $submission->mailed = 1;       // treat as already mailed
1414             } else {
1415                 $submission->mailed = 0;       // Make sure mail goes out (again, even)
1416             }
1417             $submission->timemarked = time();
1419             unset($submission->data1);  // Don't need to update this.
1420             unset($submission->data2);  // Don't need to update this.
1422             if (empty($submission->timemodified)) {   // eg for offline assignments
1423                 // $submission->timemodified = time();
1424             }
1426             if (! update_record('assignment_submissions', $submission)) {
1427                 return false;
1428             }
1430             // triger grade event
1431             $this->update_grade($submission);
1433             add_to_log($this->course->id, 'assignment', 'update grades',
1434                        'submissions.php?id='.$this->assignment->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
1435         }
1437         return $submission;
1439     }
1441     function process_outcomes($userid) {
1442         global $CFG, $USER;
1444         if (empty($CFG->enableoutcomes)) {
1445             return;
1446         }
1448         require_once($CFG->libdir.'/gradelib.php');
1450         if (!$formdata = data_submitted()) {
1451             return;
1452         }
1454         $data = array();
1455         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
1457         if (!empty($grading_info->outcomes)) {
1458             foreach($grading_info->outcomes as $n=>$old) {
1459                 $name = 'outcome_'.$n;
1460                 if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
1461                     $data[$n] = $formdata->{$name}[$userid];
1462                 }
1463             }
1464         }
1465         if (count($data) > 0) {
1466             grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1467         }
1469     }
1471     /**
1472      * Load the submission object for a particular user
1473      *
1474      * @param $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1475      * @param $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1476      * @param bool $teachermodified student submission set if false
1477      * @return object The submission
1478      */
1479     function get_submission($userid=0, $createnew=false, $teachermodified=false) {
1480         global $USER;
1482         if (empty($userid)) {
1483             $userid = $USER->id;
1484         }
1486         $submission = get_record('assignment_submissions', 'assignment', $this->assignment->id, 'userid', $userid);
1488         if ($submission || !$createnew) {
1489             return $submission;
1490         }
1491         $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
1492         if (!insert_record("assignment_submissions", $newsubmission)) {
1493             print_error('cannotinsertempty', 'assignment');
1494         }
1496         return get_record('assignment_submissions', 'assignment', $this->assignment->id, 'userid', $userid);
1497     }
1499     /**
1500      * Instantiates a new submission object for a given user
1501      *
1502      * Sets the assignment, userid and times, everything else is set to default values.
1503      * @param $userid int The userid for which we want a submission object
1504      * @param bool $teachermodified student submission set if false
1505      * @return object The submission
1506      */
1507     function prepare_new_submission($userid, $teachermodified=false) {
1508         $submission = new Object;
1509         $submission->assignment   = $this->assignment->id;
1510         $submission->userid       = $userid;
1511         //$submission->timecreated  = time();
1512         $submission->timecreated = '';
1513         // teachers should not be modifying modified date, except offline assignments
1514         if ($teachermodified) {
1515             $submission->timemodified = 0;
1516         } else {
1517             $submission->timemodified = $submission->timecreated;
1518         }
1519         $submission->numfiles     = 0;
1520         $submission->data1        = '';
1521         $submission->data2        = '';
1522         $submission->grade        = -1;
1523         $submission->submissioncomment      = '';
1524         $submission->format       = 0;
1525         $submission->teacher      = 0;
1526         $submission->timemarked   = 0;
1527         $submission->mailed       = 0;
1528         return $submission;
1529     }
1531     /**
1532      * Return all assignment submissions by ENROLLED students (even empty)
1533      *
1534      * @param $sort string optional field names for the ORDER BY in the sql query
1535      * @param $dir string optional specifying the sort direction, defaults to DESC
1536      * @return array The submission objects indexed by id
1537      */
1538     function get_submissions($sort='', $dir='DESC') {
1539         return assignment_get_all_submissions($this->assignment, $sort, $dir);
1540     }
1542     /**
1543      * Counts all real assignment submissions by ENROLLED students (not empty ones)
1544      *
1545      * @param $groupid int optional If nonzero then count is restricted to this group
1546      * @return int The number of submissions
1547      */
1548     function count_real_submissions($groupid=0) {
1549         return assignment_count_real_submissions($this->cm, $groupid);
1550     }
1552     /**
1553      * Alerts teachers by email of new or changed assignments that need grading
1554      *
1555      * First checks whether the option to email teachers is set for this assignment.
1556      * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1557      * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1558      * @param $submission object The submission that has changed
1559      */
1560     function email_teachers($submission) {
1561         global $CFG;
1563         if (empty($this->assignment->emailteachers)) {          // No need to do anything
1564             return;
1565         }
1567         $user = get_record('user', 'id', $submission->userid);
1569         if ($teachers = $this->get_graders($user)) {
1571             $strassignments = get_string('modulenameplural', 'assignment');
1572             $strassignment  = get_string('modulename', 'assignment');
1573             $strsubmitted  = get_string('submitted', 'assignment');
1575             foreach ($teachers as $teacher) {
1576                 $info = new object();
1577                 $info->username = fullname($user, true);
1578                 $info->assignment = format_string($this->assignment->name,true);
1579                 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
1581                 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1582                 $posttext = $this->email_teachers_text($info);
1583                 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
1585                 @email_to_user($teacher, $user, $postsubject, $posttext, $posthtml);  // If it fails, oh well, too bad.
1586             }
1587         }
1588     }
1590     /**
1591      * Returns a list of teachers that should be grading given submission
1592      */
1593     function get_graders($user) {
1594         //potential graders
1595         $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false);
1597         $graders = array();
1598         if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) {   // Separate groups are being used
1599             if ($groups = groups_get_all_groups($this->course->id, $user->id)) {  // Try to find all groups
1600                 foreach ($groups as $group) {
1601                     foreach ($potgraders as $t) {
1602                         if ($t->id == $user->id) {
1603                             continue; // do not send self
1604                         }
1605                         if (groups_is_member($group->id, $t->id)) {
1606                             $graders[$t->id] = $t;
1607                         }
1608                     }
1609                 }
1610             } else {
1611                 // user not in group, try to find graders without group
1612                 foreach ($potgraders as $t) {
1613                     if ($t->id == $user->id) {
1614                         continue; // do not send self
1615                     }
1616                     if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
1617                         $graders[$t->id] = $t;
1618                     }
1619                 }
1620             }
1621         } else {
1622             foreach ($potgraders as $t) {
1623                 if ($t->id == $user->id) {
1624                     continue; // do not send self
1625                 }
1626                 $graders[$t->id] = $t;
1627             }
1628         }
1629         return $graders;
1630     }
1632     /**
1633      * Creates the text content for emails to teachers
1634      *
1635      * @param $info object The info used by the 'emailteachermail' language string
1636      * @return string
1637      */
1638     function email_teachers_text($info) {
1639         $posttext  = format_string($this->course->shortname).' -> '.$this->strassignments.' -> '.
1640                      format_string($this->assignment->name)."\n";
1641         $posttext .= '---------------------------------------------------------------------'."\n";
1642         $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
1643         $posttext .= "\n---------------------------------------------------------------------\n";
1644         return $posttext;
1645     }
1647      /**
1648      * Creates the html content for emails to teachers
1649      *
1650      * @param $info object The info used by the 'emailteachermailhtml' language string
1651      * @return string
1652      */
1653     function email_teachers_html($info) {
1654         global $CFG;
1655         $posthtml  = '<p><font face="sans-serif">'.
1656                      '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname).'</a> ->'.
1657                      '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
1658                      '<a href="'.$CFG->wwwroot.'/mod/assignment/view.php?id='.$this->cm->id.'">'.format_string($this->assignment->name).'</a></font></p>';
1659         $posthtml .= '<hr /><font face="sans-serif">';
1660         $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
1661         $posthtml .= '</font><hr />';
1662         return $posthtml;
1663     }
1665     /**
1666      * Produces a list of links to the files uploaded by a user
1667      *
1668      * @param $userid int optional id of the user. If 0 then $USER->id is used.
1669      * @param $return boolean optional defaults to false. If true the list is returned rather than printed
1670      * @return string optional
1671      */
1672     function print_user_files($userid=0, $return=false) {
1673         global $CFG, $USER;
1675         if (!$userid) {
1676             if (!isloggedin()) {
1677                 return '';
1678             }
1679             $userid = $USER->id;
1680         }
1682         $filearea = $this->file_area_name($userid);
1684         $output = '';
1686         if ($basedir = $this->file_area($userid)) {
1687             if ($files = get_directory_list($basedir)) {
1688                 require_once($CFG->libdir.'/filelib.php');
1689                 foreach ($files as $key => $file) {
1691                     $icon = mimeinfo('icon', $file);
1692                     $ffurl = get_file_url("$filearea/$file", array('forcedownload'=>1));
1694                     $output .= '<img src="'.$CFG->pixpath.'/f/'.$icon.'" class="icon" alt="'.$icon.'" />'.
1695                             '<a href="'.$ffurl.'" >'.$file.'</a><br />';
1696                 }
1697             }
1698         }
1700         $output = '<div class="files">'.$output.'</div>';
1702         if ($return) {
1703             return $output;
1704         }
1705         echo $output;
1706     }
1708     /**
1709      * Count the files uploaded by a given user
1710      *
1711      * @param $userid int The user id
1712      * @return int
1713      */
1714     function count_user_files($userid) {
1715         global $CFG;
1717         $filearea = $this->file_area_name($userid);
1719         if ( is_dir($CFG->dataroot.'/'.$filearea) && $basedir = $this->file_area($userid)) {
1720             if ($files = get_directory_list($basedir)) {
1721                 return count($files);
1722             }
1723         }
1724         return 0;
1725     }
1727     /**
1728      * Creates a directory file name, suitable for make_upload_directory()
1729      *
1730      * @param $userid int The user id
1731      * @return string path to file area
1732      */
1733     function file_area_name($userid) {
1734         global $CFG;
1736         return $this->course->id.'/'.$CFG->moddata.'/assignment/'.$this->assignment->id.'/'.$userid;
1737     }
1739     /**
1740      * Makes an upload directory
1741      *
1742      * @param $userid int The user id
1743      * @return string path to file area.
1744      */
1745     function file_area($userid) {
1746         return make_upload_directory( $this->file_area_name($userid) );
1747     }
1749     /**
1750      * Returns true if the student is allowed to submit
1751      *
1752      * Checks that the assignment has started and, if the option to prevent late
1753      * submissions is set, also checks that the assignment has not yet closed.
1754      * @return boolean
1755      */
1756     function isopen() {
1757         $time = time();
1758         if ($this->assignment->preventlate && $this->assignment->timedue) {
1759             return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
1760         } else {
1761             return ($this->assignment->timeavailable <= $time);
1762         }
1763     }
1766     /**
1767      * Return true if is set description is hidden till available date
1768      *
1769      * This is needed by calendar so that hidden descriptions do not
1770      * come up in upcoming events.
1771      *
1772      * Check that description is hidden till available date
1773      * By default return false
1774      * Assignments types should implement this method if needed
1775      * @return boolen
1776      */
1777     function description_is_hidden() {
1778         return false;
1779     }
1781     /**
1782      * Return an outline of the user's interaction with the assignment
1783      *
1784      * The default method prints the grade and timemodified
1785      * @param $user object
1786      * @return object with properties ->info and ->time
1787      */
1788     function user_outline($user) {
1789         if ($submission = $this->get_submission($user->id)) {
1791             $result = new object();
1792             $result->info = get_string('grade').': '.$this->display_grade($submission->grade);
1793             $result->time = $submission->timemodified;
1794             return $result;
1795         }
1796         return NULL;
1797     }
1799     /**
1800      * Print complete information about the user's interaction with the assignment
1801      *
1802      * @param $user object
1803      */
1804     function user_complete($user) {
1805         if ($submission = $this->get_submission($user->id)) {
1806             if ($basedir = $this->file_area($user->id)) {
1807                 if ($files = get_directory_list($basedir)) {
1808                     $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
1809                     foreach ($files as $file) {
1810                         $countfiles .= "; $file";
1811                     }
1812                 }
1813             }
1815             print_simple_box_start();
1816             echo get_string("lastmodified").": ";
1817             echo userdate($submission->timemodified);
1818             echo $this->display_lateness($submission->timemodified);
1820             $this->print_user_files($user->id);
1822             echo '<br />';
1824             if (empty($submission->timemarked)) {
1825                 print_string("notgradedyet", "assignment");
1826             } else {
1827                 $this->view_feedback($submission);
1828             }
1830             print_simple_box_end();
1832         } else {
1833             print_string("notsubmittedyet", "assignment");
1834         }
1835     }
1837     /**
1838      * Return a string indicating how late a submission is
1839      *
1840      * @param $timesubmitted int
1841      * @return string
1842      */
1843     function display_lateness($timesubmitted) {
1844         return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
1845     }
1847     /**
1848      * Empty method stub for all delete actions.
1849      */
1850     function delete() {
1851         //nothing by default
1852         redirect('view.php?id='.$this->cm->id);
1853     }
1855     /**
1856      * Empty custom feedback grading form.
1857      */
1858     function custom_feedbackform($submission, $return=false) {
1859         //nothing by default
1860         return '';
1861     }
1863     /**
1864      * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
1865      * for the course (see resource).
1866      *
1867      * Given a course_module object, this function returns any "extra" information that may be needed
1868      * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
1869      *
1870      * @param $coursemodule object The coursemodule object (record).
1871      * @return object An object on information that the coures will know about (most noticeably, an icon).
1872      *
1873      */
1874     function get_coursemodule_info($coursemodule) {
1875         return false;
1876     }
1878     /**
1879      * Plugin cron method - do not use $this here, create new assignment instances if needed.
1880      * @return void
1881      */
1882     function cron() {
1883         //no plugin cron by default - override if needed
1884     }
1886     /**
1887      * Reset all submissions
1888      */
1889     function reset_userdata($data) {
1890         global $CFG;
1891         require_once($CFG->libdir.'/filelib.php');
1893         if (!count_records('assignment', 'course', $data->courseid, 'assignmenttype', $this->type)) {
1894             return array(); // no assignments of this type present
1895         }
1897         $componentstr = get_string('modulenameplural', 'assignment');
1898         $status = array();
1900         $typestr = get_string('type'.$this->type, 'assignment');
1902         if (!empty($data->reset_assignment_submissions)) {
1903             $assignmentssql = "SELECT a.id
1904                                  FROM {$CFG->prefix}assignment a
1905                                 WHERE a.course={$data->courseid} AND a.assignmenttype='{$this->type}'";
1907             delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)");
1909             if ($assignments = get_records_sql($assignmentssql)) {
1910                 foreach ($assignments as $assignmentid=>$unused) {
1911                     fulldelete($CFG->dataroot.'/'.$data->courseid.'/moddata/assignment/'.$assignmentid);
1912                 }
1913             }
1915             $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
1917             if (empty($data->reset_gradebook_grades)) {
1918                 // remove all grades from gradebook
1919                 assignment_reset_gradebook($data->courseid, $this->type);
1920             }
1921         }
1923         /// updating dates - shift may be negative too
1924         if ($data->timeshift) {
1925             shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
1926             $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
1927         }
1929         return $status;
1930     }
1931 } ////// End of the assignment_base class
1935 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
1937 /**
1938  * Deletes an assignment instance
1939  *
1940  * This is done by calling the delete_instance() method of the assignment type class
1941  */
1942 function assignment_delete_instance($id){
1943     global $CFG;
1945     if (! $assignment = get_record('assignment', 'id', $id)) {
1946         return false;
1947     }
1949     // fall back to base class if plugin missing
1950     $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
1951     if (file_exists($classfile)) {
1952         require_once($classfile);
1953         $assignmentclass = "assignment_$assignment->assignmenttype";
1955     } else {
1956         debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
1957         $assignmentclass = "assignment_base";
1958     }
1960     $ass = new $assignmentclass();
1961     return $ass->delete_instance($assignment);
1965 /**
1966  * Updates an assignment instance
1967  *
1968  * This is done by calling the update_instance() method of the assignment type class
1969  */
1970 function assignment_update_instance($assignment){
1971     global $CFG;
1973     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
1975     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
1976     $assignmentclass = "assignment_$assignment->assignmenttype";
1977     $ass = new $assignmentclass();
1978     return $ass->update_instance($assignment);
1982 /**
1983  * Adds an assignment instance
1984  *
1985  * This is done by calling the add_instance() method of the assignment type class
1986  */
1987 function assignment_add_instance($assignment) {
1988     global $CFG;
1990     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
1992     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
1993     $assignmentclass = "assignment_$assignment->assignmenttype";
1994     $ass = new $assignmentclass();
1995     return $ass->add_instance($assignment);
1999 /**
2000  * Returns an outline of a user interaction with an assignment
2001  *
2002  * This is done by calling the user_outline() method of the assignment type class
2003  */
2004 function assignment_user_outline($course, $user, $mod, $assignment) {
2005     global $CFG;
2007     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2008     $assignmentclass = "assignment_$assignment->assignmenttype";
2009     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2010     return $ass->user_outline($user);
2013 /**
2014  * Prints the complete info about a user's interaction with an assignment
2015  *
2016  * This is done by calling the user_complete() method of the assignment type class
2017  */
2018 function assignment_user_complete($course, $user, $mod, $assignment) {
2019     global $CFG;
2021     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2022     $assignmentclass = "assignment_$assignment->assignmenttype";
2023     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2024     return $ass->user_complete($user);
2027 /**
2028  * Function to be run periodically according to the moodle cron
2029  *
2030  * Finds all assignment notifications that have yet to be mailed out, and mails them
2031  */
2032 function assignment_cron () {
2034     global $CFG, $USER;
2036     /// first execute all crons in plugins
2037     if ($plugins = get_list_of_plugins('mod/assignment/type')) {
2038         foreach ($plugins as $plugin) {
2039             require_once("$CFG->dirroot/mod/assignment/type/$plugin/assignment.class.php");
2040             $assignmentclass = "assignment_$plugin";
2041             $ass = new $assignmentclass();
2042             $ass->cron();
2043         }
2044     }
2046     /// Notices older than 1 day will not be mailed.  This is to avoid the problem where
2047     /// cron has not been running for a long time, and then suddenly people are flooded
2048     /// with mail from the past few weeks or months
2050     $timenow   = time();
2051     $endtime   = $timenow - $CFG->maxeditingtime;
2052     $starttime = $endtime - 24 * 3600;   /// One day earlier
2054     if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2056         $realuser = clone($USER);
2058         foreach ($submissions as $key => $submission) {
2059             if (! set_field("assignment_submissions", "mailed", "1", "id", "$submission->id")) {
2060                 echo "Could not update the mailed field for id $submission->id.  Not mailed.\n";
2061                 unset($submissions[$key]);
2062             }
2063         }
2065         $timenow = time();
2067         foreach ($submissions as $submission) {
2069             echo "Processing assignment submission $submission->id\n";
2071             if (! $user = get_record("user", "id", "$submission->userid")) {
2072                 echo "Could not find user $post->userid\n";
2073                 continue;
2074             }
2076             if (! $course = get_record("course", "id", "$submission->course")) {
2077                 echo "Could not find course $submission->course\n";
2078                 continue;
2079             }
2081             /// Override the language and timezone of the "current" user, so that
2082             /// mail is customised for the receiver.
2083             $USER = $user;
2084             course_setup($course);
2086             if (!has_capability('moodle/course:view', get_context_instance(CONTEXT_COURSE, $submission->course), $user->id)) {
2087                 echo fullname($user)." not an active participant in " . format_string($course->shortname) . "\n";
2088                 continue;
2089             }
2091             if (! $teacher = get_record("user", "id", "$submission->teacher")) {
2092                 echo "Could not find teacher $submission->teacher\n";
2093                 continue;
2094             }
2096             if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2097                 echo "Could not find course module for assignment id $submission->assignment\n";
2098                 continue;
2099             }
2101             if (! $mod->visible) {    /// Hold mail notification for hidden assignments until later
2102                 continue;
2103             }
2105             $strassignments = get_string("modulenameplural", "assignment");
2106             $strassignment  = get_string("modulename", "assignment");
2108             $assignmentinfo = new object();
2109             $assignmentinfo->teacher = fullname($teacher);
2110             $assignmentinfo->assignment = format_string($submission->name,true);
2111             $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2113             $postsubject = "$course->shortname: $strassignments: ".format_string($submission->name,true);
2114             $posttext  = "$course->shortname -> $strassignments -> ".format_string($submission->name,true)."\n";
2115             $posttext .= "---------------------------------------------------------------------\n";
2116             $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2117             $posttext .= "---------------------------------------------------------------------\n";
2119             if ($user->mailformat == 1) {  // HTML
2120                 $posthtml = "<p><font face=\"sans-serif\">".
2121                 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> ->".
2122                 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2123                 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2124                 $posthtml .= "<hr /><font face=\"sans-serif\">";
2125                 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2126                 $posthtml .= "</font><hr />";
2127             } else {
2128                 $posthtml = "";
2129             }
2131             if (! email_to_user($user, $teacher, $postsubject, $posttext, $posthtml)) {
2132                 echo "Error: assignment cron: Could not send out mail for id $submission->id to user $user->id ($user->email)\n";
2133             }
2134         }
2136         $USER = $realuser;
2137         course_setup(SITEID); // reset cron user language, theme and timezone settings
2139     }
2141     return true;
2144 /**
2145  * Return grade for given user or all users.
2146  *
2147  * @param int $assignmentid id of assignment
2148  * @param int $userid optional user id, 0 means all users
2149  * @return array array of grades, false if none
2150  */
2151 function assignment_get_user_grades($assignment, $userid=0) {
2152     global $CFG;
2154     $user = $userid ? "AND u.id = $userid" : "";
2156     $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2157                    s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2158               FROM {$CFG->prefix}user u, {$CFG->prefix}assignment_submissions s
2159              WHERE u.id = s.userid AND s.assignment = $assignment->id
2160                    $user";
2162     return get_records_sql($sql);
2165 /**
2166  * Update grades by firing grade_updated event
2167  *
2168  * @param object $assignment null means all assignments
2169  * @param int $userid specific user only, 0 mean all
2170  */
2171 function assignment_update_grades($assignment=null, $userid=0, $nullifnone=true) {
2172     global $CFG;
2173     if (!function_exists('grade_update')) { //workaround for buggy PHP versions
2174         require_once($CFG->libdir.'/gradelib.php');
2175     }
2177     if ($assignment != null) {
2178         if ($grades = assignment_get_user_grades($assignment, $userid)) {
2179             foreach($grades as $k=>$v) {
2180                 if ($v->rawgrade == -1) {
2181                     $grades[$k]->rawgrade = null;
2182                 }
2183             }
2184             assignment_grade_item_update($assignment, $grades);
2185         } else {
2186             assignment_grade_item_update($assignment);
2187         }
2189     } else {
2190         $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
2191                   FROM {$CFG->prefix}assignment a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
2192                  WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2193         if ($rs = get_recordset_sql($sql)) {
2194             while ($assignment = rs_fetch_next_record($rs)) {
2195                 if ($assignment->grade != 0) {
2196                     assignment_update_grades($assignment);
2197                 } else {
2198                     assignment_grade_item_update($assignment);
2199                 }
2200             }
2201             rs_close($rs);
2202         }
2203     }
2206 /**
2207  * Create grade item for given assignment
2208  *
2209  * @param object $assignment object with extra cmidnumber
2210  * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
2211  * @return int 0 if ok, error code otherwise
2212  */
2213 function assignment_grade_item_update($assignment, $grades=NULL) {
2214     global $CFG;
2215     if (!function_exists('grade_update')) { //workaround for buggy PHP versions
2216         require_once($CFG->libdir.'/gradelib.php');
2217     }
2219     if (!isset($assignment->courseid)) {
2220         $assignment->courseid = $assignment->course;
2221     }
2223     $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
2225     if ($assignment->grade > 0) {
2226         $params['gradetype'] = GRADE_TYPE_VALUE;
2227         $params['grademax']  = $assignment->grade;
2228         $params['grademin']  = 0;
2230     } else if ($assignment->grade < 0) {
2231         $params['gradetype'] = GRADE_TYPE_SCALE;
2232         $params['scaleid']   = -$assignment->grade;
2234     } else {
2235         $params['gradetype'] = GRADE_TYPE_TEXT; // allow text comments only
2236     }
2238     if ($grades  === 'reset') {
2239         $params['reset'] = true;
2240         $grades = NULL;
2241     }
2243     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades, $params);
2246 /**
2247  * Delete grade item for given assignment
2248  *
2249  * @param object $assignment object
2250  * @return object assignment
2251  */
2252 function assignment_grade_item_delete($assignment) {
2253     global $CFG;
2254     require_once($CFG->libdir.'/gradelib.php');
2256     if (!isset($assignment->courseid)) {
2257         $assignment->courseid = $assignment->course;
2258     }
2260     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
2263 /**
2264  * Returns the users with data in one assignment (students and teachers)
2265  *
2266  * @param $assignmentid int
2267  * @return array of user objects
2268  */
2269 function assignment_get_participants($assignmentid) {
2271     global $CFG;
2273     //Get students
2274     $students = get_records_sql("SELECT DISTINCT u.id, u.id
2275                                  FROM {$CFG->prefix}user u,
2276                                       {$CFG->prefix}assignment_submissions a
2277                                  WHERE a.assignment = '$assignmentid' and
2278                                        u.id = a.userid");
2279     //Get teachers
2280     $teachers = get_records_sql("SELECT DISTINCT u.id, u.id
2281                                  FROM {$CFG->prefix}user u,
2282                                       {$CFG->prefix}assignment_submissions a
2283                                  WHERE a.assignment = '$assignmentid' and
2284                                        u.id = a.teacher");
2286     //Add teachers to students
2287     if ($teachers) {
2288         foreach ($teachers as $teacher) {
2289             $students[$teacher->id] = $teacher;
2290         }
2291     }
2292     //Return students array (it contains an array of unique users)
2293     return ($students);
2296 /**
2297  * Checks if a scale is being used by an assignment
2298  *
2299  * This is used by the backup code to decide whether to back up a scale
2300  * @param $assignmentid int
2301  * @param $scaleid int
2302  * @return boolean True if the scale is used by the assignment
2303  */
2304 function assignment_scale_used($assignmentid, $scaleid) {
2306     $return = false;
2308     $rec = get_record('assignment','id',$assignmentid,'grade',-$scaleid);
2310     if (!empty($rec) && !empty($scaleid)) {
2311         $return = true;
2312     }
2314     return $return;
2317 /**
2318  * Checks if scale is being used by any instance of assignment
2319  *
2320  * This is used to find out if scale used anywhere
2321  * @param $scaleid int
2322  * @return boolean True if the scale is used by any assignment
2323  */
2324 function assignment_scale_used_anywhere($scaleid) {
2325     if ($scaleid and record_exists('assignment', 'grade', -$scaleid)) {
2326         return true;
2327     } else {
2328         return false;
2329     }
2332 /**
2333  * Make sure up-to-date events are created for all assignment instances
2334  *
2335  * This standard function will check all instances of this module
2336  * and make sure there are up-to-date events created for each of them.
2337  * If courseid = 0, then every assignment event in the site is checked, else
2338  * only assignment events belonging to the course specified are checked.
2339  * This function is used, in its new format, by restore_refresh_events()
2340  *
2341  * @param $courseid int optional If zero then all assignments for all courses are covered
2342  * @return boolean Always returns true
2343  */
2344 function assignment_refresh_events($courseid = 0) {
2346     if ($courseid == 0) {
2347         if (! $assignments = get_records("assignment")) {
2348             return true;
2349         }
2350     } else {
2351         if (! $assignments = get_records("assignment", "course", $courseid)) {
2352             return true;
2353         }
2354     }
2355     $moduleid = get_field('modules', 'id', 'name', 'assignment');
2357     foreach ($assignments as $assignment) {
2358         $event = NULL;
2359         $event->name        = addslashes($assignment->name);
2360         $event->description = addslashes($assignment->description);
2361         $event->timestart   = $assignment->timedue;
2363         if ($event->id = get_field('event', 'id', 'modulename', 'assignment', 'instance', $assignment->id)) {
2364             update_event($event);
2366         } else {
2367             $event->courseid    = $assignment->course;
2368             $event->groupid     = 0;
2369             $event->userid      = 0;
2370             $event->modulename  = 'assignment';
2371             $event->instance    = $assignment->id;
2372             $event->eventtype   = 'due';
2373             $event->timeduration = 0;
2374             $event->visible     = get_field('course_modules', 'visible', 'module', $moduleid, 'instance', $assignment->id);
2375             add_event($event);
2376         }
2378     }
2379     return true;
2382 /**
2383  * Print recent activity from all assignments in a given course
2384  *
2385  * This is used by the recent activity block
2386  */
2387 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
2388     global $CFG, $USER;
2390     // do not use log table if possible, it may be huge
2392     if (!$submissions = get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
2393                                                 u.firstname, u.lastname, u.email, u.picture
2394                                            FROM {$CFG->prefix}assignment_submissions asb
2395                                                 JOIN {$CFG->prefix}assignment a      ON a.id = asb.assignment
2396                                                 JOIN {$CFG->prefix}course_modules cm ON cm.instance = a.id
2397                                                 JOIN {$CFG->prefix}modules md        ON md.id = cm.module
2398                                                 JOIN {$CFG->prefix}user u            ON u.id = asb.userid
2399                                           WHERE asb.timemodified > $timestart AND
2400                                                 a.course = {$course->id} AND
2401                                                 md.name = 'assignment'
2402                                        ORDER BY asb.timemodified ASC")) {
2403          return false;
2404     }
2406     $modinfo =& get_fast_modinfo($course); // reference needed because we might load the groups
2407     $show    = array();
2408     $grader  = array();
2410     foreach($submissions as $submission) {
2411         if (!array_key_exists($submission->cmid, $modinfo->cms)) {
2412             continue;
2413         }
2414         $cm = $modinfo->cms[$submission->cmid];
2415         if (!$cm->uservisible) {
2416             continue;
2417         }
2418         if ($submission->userid == $USER->id) {
2419             $show[] = $submission;
2420             continue;
2421         }
2423         // the act of sumitting of assignemnt may be considered private - only graders will see it if specified
2424         if (empty($CFG->assignment_showrecentsubmissions)) {
2425             if (!array_key_exists($cm->id, $grader)) {
2426                 $grader[$cm->id] = has_capability('moodle/grade:viewall', get_context_instance(CONTEXT_MODULE, $cm->id));
2427             }
2428             if (!$grader[$cm->id]) {
2429                 continue;
2430             }
2431         }
2433         $groupmode = groups_get_activity_groupmode($cm, $course);
2435         if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2436             if (isguestuser()) {
2437                 // shortcut - guest user does not belong into any group
2438                 continue;
2439             }
2441             if (is_null($modinfo->groups)) {
2442                 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2443             }
2445             // this will be slow - show only users that share group with me in this cm
2446             if (empty($modinfo->groups[$cm->id])) {
2447                 continue;
2448             }
2449             $usersgroups =  groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
2450             if (is_array($usersgroups)) {
2451                 $usersgroups = array_keys($usersgroups);
2452                 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2453                 if (empty($intersect)) {
2454                     continue;
2455                 }
2456             }
2457         }
2458         $show[] = $submission;
2459     }
2461     if (empty($show)) {
2462         return false;
2463     }
2465     print_headline(get_string('newsubmissions', 'assignment').':');
2467     foreach ($show as $submission) {
2468         $cm = $modinfo->cms[$submission->cmid];
2469         $link = $CFG->wwwroot.'/mod/assignment/view.php?id='.$cm->id;
2470         print_recent_activity_note($submission->timemodified, $submission, $cm->name, $link, false, $viewfullnames);
2471     }
2473     return true;
2477 /**
2478  * Returns all assignments since a given time in specified forum.
2479  */
2480 function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0)  {
2482     global $CFG, $COURSE, $USER;
2484     if ($COURSE->id == $courseid) {
2485         $course = $COURSE;
2486     } else {
2487         $course = get_record('course', 'id', $courseid);
2488     }
2490     $modinfo =& get_fast_modinfo($course);
2492     $cm = $modinfo->cms[$cmid];
2494     if ($userid) {
2495         $userselect = "AND u.id = $userid";
2496     } else {
2497         $userselect = "";
2498     }
2500     if ($groupid) {
2501         $groupselect = "AND gm.groupid = $groupid";
2502         $groupjoin   = "JOIN {$CFG->prefix}groups_members gm ON  gm.userid=u.id";
2503     } else {
2504         $groupselect = "";
2505         $groupjoin   = "";
2506     }
2508     if (!$submissions = get_records_sql("SELECT asb.id, asb.timemodified, asb.userid,
2509                                                 u.firstname, u.lastname, u.email, u.picture
2510                                            FROM {$CFG->prefix}assignment_submissions asb
2511                                                 JOIN {$CFG->prefix}assignment a      ON a.id = asb.assignment
2512                                                 JOIN {$CFG->prefix}user u            ON u.id = asb.userid
2513                                                 $groupjoin
2514                                           WHERE asb.timemodified > $timestart AND a.id = $cm->instance
2515                                                 $userselect $groupselect
2516                                        ORDER BY asb.timemodified ASC")) {
2517          return;
2518     }
2520     $groupmode       = groups_get_activity_groupmode($cm, $course);
2521     $cm_context      = get_context_instance(CONTEXT_MODULE, $cm->id);
2522     $grader          = has_capability('moodle/grade:viewall', $cm_context);
2523     $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
2524     $viewfullnames   = has_capability('moodle/site:viewfullnames', $cm_context);
2526     if (is_null($modinfo->groups)) {
2527         $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2528     }
2530     $show = array();
2532     foreach($submissions as $submission) {
2533         if ($submission->userid == $USER->id) {
2534             $show[] = $submission;
2535             continue;
2536         }
2538         // the act of sumitting of assignemnt may be considered private - only graders will see it if specified
2539         if (!empty($CFG->assignment_showrecentsubmissions)) {
2540             if (!$grader) {
2541                 continue;
2542             }
2543         }
2545         if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
2546             if (isguestuser()) {
2547                 // shortcut - guest user does not belong into any group
2548                 continue;
2549             }
2551             // this will be slow - show only users that share group with me in this cm
2552             if (empty($modinfo->groups[$cm->id])) {
2553                 continue;
2554             }
2555             $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
2556             if (is_array($usersgroups)) {
2557                 $usersgroups = array_keys($usersgroups);
2558                 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2559                 if (empty($intersect)) {
2560                     continue;
2561                 }
2562             }
2563         }
2564         $show[] = $submission;
2565     }
2567     if (empty($show)) {
2568         return;
2569     }
2571     if ($grader) {
2572         require_once($CFG->libdir.'/gradelib.php');
2573         $userids = array();
2574         foreach ($show as $id=>$submission) {
2575             $userids[] = $submission->userid;
2577         }
2578         $grades = grade_get_grades($courseid, 'mod', 'assignment', $cm->instance, $userids);
2579     }
2581     $aname = format_string($cm->name,true);
2582     foreach ($show as $submission) {
2583         $tmpactivity = new object();
2585         $tmpactivity->type         = 'assignment';
2586         $tmpactivity->cmid         = $cm->id;
2587         $tmpactivity->name         = $aname;
2588         $tmpactivity->sectionnum   = $cm->sectionnum;
2589         $tmpactivity->timestamp    = $submission->timemodified;
2591         if ($grader) {
2592             $tmpactivity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
2593         }
2595         $tmpactivity->user->userid   = $submission->userid;
2596         $tmpactivity->user->fullname = fullname($submission, $viewfullnames);
2597         $tmpactivity->user->picture  = $submission->picture;
2599         $activities[$index++] = $tmpactivity;
2600     }
2602     return;
2605 /**
2606  * Print recent activity from all assignments in a given course
2607  *
2608  * This is used by course/recent.php
2609  */
2610 function assignment_print_recent_mod_activity($activity, $courseid, $detail, $modnames)  {
2611     global $CFG;
2613     echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
2615     echo "<tr><td class=\"userpicture\" valign=\"top\">";
2616     print_user_picture($activity->user->userid, $courseid, $activity->user->picture);
2617     echo "</td><td>";
2619     if ($detail) {
2620         $modname = $modnames[$activity->type];
2621         echo '<div class="title">';
2622         echo "<img src=\"$CFG->modpixpath/assignment/icon.gif\" ".
2623              "class=\"icon\" alt=\"$modname\">";
2624         echo "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id={$activity->cmid}\">{$activity->name}</a>";
2625         echo '</div>';
2626     }
2628     if (isset($activity->grade)) {
2629         echo '<div class="grade">';
2630         echo get_string('grade').': ';
2631         echo $activity->grade;
2632         echo '</div>';
2633     }
2635     echo '<div class="user">';
2636     echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->userid}&amp;course=$courseid\">"
2637          ."{$activity->user->fullname}</a>  - ".userdate($activity->timestamp);
2638     echo '</div>';
2640     echo "</td></tr></table>";
2643 /// GENERIC SQL FUNCTIONS
2645 /**
2646  * Fetch info from logs
2647  *
2648  * @param $log object with properties ->info (the assignment id) and ->userid
2649  * @return array with assignment name and user firstname and lastname
2650  */
2651 function assignment_log_info($log) {
2652     global $CFG;
2653     return get_record_sql("SELECT a.name, u.firstname, u.lastname
2654                              FROM {$CFG->prefix}assignment a,
2655                                   {$CFG->prefix}user u
2656                             WHERE a.id = '$log->info'
2657                               AND u.id = '$log->userid'");
2660 /**
2661  * Return list of marked submissions that have not been mailed out for currently enrolled students
2662  *
2663  * @return array
2664  */
2665 function assignment_get_unmailed_submissions($starttime, $endtime) {
2667     global $CFG;
2669     return get_records_sql("SELECT s.*, a.course, a.name
2670                               FROM {$CFG->prefix}assignment_submissions s,
2671                                    {$CFG->prefix}assignment a
2672                              WHERE s.mailed = 0
2673                                AND s.timemarked <= $endtime
2674                                AND s.timemarked >= $starttime
2675                                AND s.assignment = a.id");
2677     /* return get_records_sql("SELECT s.*, a.course, a.name
2678                               FROM {$CFG->prefix}assignment_submissions s,
2679                                    {$CFG->prefix}assignment a,
2680                                    {$CFG->prefix}user_students us
2681                              WHERE s.mailed = 0
2682                                AND s.timemarked <= $endtime
2683                                AND s.timemarked >= $starttime
2684                                AND s.assignment = a.id
2685                                AND s.userid = us.userid
2686                                AND a.course = us.course");
2687     */
2690 /**
2691  * Counts all real assignment submissions by ENROLLED students (not empty ones)
2692  *
2693  * There are also assignment type methods count_real_submissions() wich in the default
2694  * implementation simply call this function.
2695  * @param $groupid int optional If nonzero then count is restricted to this group
2696  * @return int The number of submissions
2697  */
2698 function assignment_count_real_submissions($cm, $groupid=0) {
2699     global $CFG;
2701     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2703     // this is all the users with this capability set, in this context or higher
2704     if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $groupid, '', false)) {
2705         $users = array_keys($users);
2706     }
2708     // if groupmembersonly used, remove users who are not in any group
2709     if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
2710         if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
2711             $users = array_intersect($users, array_keys($groupingusers));
2712         }
2713     }
2715     if (empty($users)) {
2716         return 0;
2717     }
2719     $userlists = implode(',', $users);
2721     return count_records_sql("SELECT COUNT('x')
2722                                 FROM {$CFG->prefix}assignment_submissions
2723                                WHERE assignment = $cm->instance AND
2724                                      timemodified > 0 AND
2725                                      userid IN ($userlists)");
2729 /**
2730  * Return all assignment submissions by ENROLLED students (even empty)
2731  *
2732  * There are also assignment type methods get_submissions() wich in the default
2733  * implementation simply call this function.
2734  * @param $sort string optional field names for the ORDER BY in the sql query
2735  * @param $dir string optional specifying the sort direction, defaults to DESC
2736  * @return array The submission objects indexed by id
2737  */
2738 function assignment_get_all_submissions($assignment, $sort="", $dir="DESC") {
2739 /// Return all assignment submissions by ENROLLED students (even empty)
2740     global $CFG;
2742     if ($sort == "lastname" or $sort == "firstname") {
2743         $sort = "u.$sort $dir";
2744     } else if (empty($sort)) {
2745         $sort = "a.timemodified DESC";
2746     } else {
2747         $sort = "a.$sort $dir";
2748     }
2750     /* not sure this is needed at all since assignmenet already has a course define, so this join?
2751     $select = "s.course = '$assignment->course' AND";
2752     if ($assignment->course == SITEID) {
2753         $select = '';
2754     }*/
2756     return get_records_sql("SELECT a.*
2757                               FROM {$CFG->prefix}assignment_submissions a,
2758                                    {$CFG->prefix}user u
2759                              WHERE u.id = a.userid
2760                                AND a.assignment = '$assignment->id'
2761                           ORDER BY $sort");
2763     /* return get_records_sql("SELECT a.*
2764                               FROM {$CFG->prefix}assignment_submissions a,
2765                                    {$CFG->prefix}user_students s,
2766                                    {$CFG->prefix}user u
2767                              WHERE a.userid = s.userid
2768                                AND u.id = a.userid
2769                                AND $select a.assignment = '$assignment->id'
2770                           ORDER BY $sort");
2771     */
2774 /**
2775  * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
2776  * for the course (see resource).
2777  *
2778  * Given a course_module object, this function returns any "extra" information that may be needed
2779  * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
2780  *
2781  * @param $coursemodule object The coursemodule object (record).
2782  * @return object An object on information that the coures will know about (most noticeably, an icon).
2783  *
2784  */
2785 function assignment_get_coursemodule_info($coursemodule) {
2786     global $CFG;
2788     if (! $assignment = get_record('assignment', 'id', $coursemodule->instance, '', '', '', '', 'id, assignmenttype, name')) {
2789         return false;
2790     }
2792     $libfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2794     if (file_exists($libfile)) {
2795         require_once($libfile);
2796         $assignmentclass = "assignment_$assignment->assignmenttype";
2797         $ass = new $assignmentclass('staticonly');
2798         if ($result = $ass->get_coursemodule_info($coursemodule)) {
2799             return $result;
2800         } else {
2801             $info = new object();
2802             $info->name = $assignment->name;
2803             return $info;
2804         }
2806     } else {
2807         debugging('Incorrect assignment type: '.$assignment->assignmenttype);
2808         return false;
2809     }
2814 /// OTHER GENERAL FUNCTIONS FOR ASSIGNMENTS  ///////////////////////////////////////
2816 /**
2817  * Returns an array of installed assignment types indexed and sorted by name
2818  *
2819  * @return array The index is the name of the assignment type, the value its full name from the language strings
2820  */
2821 function assignment_types() {
2822     $types = array();
2823     $names = get_list_of_plugins('mod/assignment/type');
2824     foreach ($names as $name) {
2825         $types[$name] = get_string('type'.$name, 'assignment');
2826     }
2827     asort($types);
2828     return $types;
2831 /**
2832  * Executes upgrade scripts for assignment types when necessary
2833  */
2834 function assignment_upgrade_submodules() {
2836     global $CFG;
2838 /// Install/upgrade assignment types (it uses, simply, the standard plugin architecture)
2839     upgrade_plugins('assignment_type', 'mod/assignment/type', "$CFG->wwwroot/$CFG->admin/index.php");
2843 function assignment_print_overview($courses, &$htmlarray) {
2845     global $USER, $CFG;
2847     if (empty($courses) || !is_array($courses) || count($courses) == 0) {
2848         return array();
2849     }
2851     if (!$assignments = get_all_instances_in_courses('assignment',$courses)) {
2852         return;
2853     }
2855     // Do assignment_base::isopen() here without loading the whole thing for speed
2856     foreach ($assignments as $key => $assignment) {
2857         $time = time();
2858         if ($assignment->timedue) {
2859             if ($assignment->preventlate) {
2860                 $isopen = ($assignment->timeavailable <= $time && $time <= $assignment->timedue);
2861             } else {
2862                 $isopen = ($assignment->timeavailable <= $time);
2863             }
2864         }
2865         if (empty($isopen) || empty($assignment->timedue)) {
2866             unset($assignments[$key]);
2867         }
2868     }
2870     $strduedate = get_string('duedate', 'assignment');
2871     $strduedateno = get_string('duedateno', 'assignment');
2872     $strgraded = get_string('graded', 'assignment');
2873     $strnotgradedyet = get_string('notgradedyet', 'assignment');
2874     $strnotsubmittedyet = get_string('notsubmittedyet', 'assignment');
2875     $strsubmitted = get_string('submitted', 'assignment');
2876     $strassignment = get_string('modulename', 'assignment');
2877     $strreviewed = get_string('reviewed','assignment');
2879     foreach ($assignments as $assignment) {
2880         $str = '<div class="assignment overview"><div class="name">'.$strassignment. ': '.
2881                '<a '.($assignment->visible ? '':' class="dimmed"').
2882                'title="'.$strassignment.'" href="'.$CFG->wwwroot.
2883                '/mod/assignment/view.php?id='.$assignment->coursemodule.'">'.
2884                $assignment->name.'</a></div>';
2885         if ($assignment->timedue) {
2886             $str .= '<div class="info">'.$strduedate.': '.userdate($assignment->timedue).'</div>';
2887         } else {
2888             $str .= '<div class="info">'.$strduedateno.'</div>';
2889         }
2890         $context = get_context_instance(CONTEXT_MODULE, $assignment->coursemodule);
2891         if (has_capability('mod/assignment:grade', $context)) {
2893             // count how many people can submit
2894             $submissions = 0; // init
2895             if ($students = get_users_by_capability($context, 'mod/assignment:submit', '', '', '', '', 0, '', false)) {
2896                  foreach ($students as $student) {
2897                     if (record_exists_sql("SELECT id FROM {$CFG->prefix}assignment_submissions
2898                                            WHERE assignment = $assignment->id AND
2899                                                userid = $student->id AND
2900                                                teacher = 0 AND
2901                                                timemarked = 0")) {
2902                         $submissions++;
2903                     }
2904                 }
2905             }
2907             if ($submissions) {
2908                 $str .= get_string('submissionsnotgraded', 'assignment', $submissions);
2909             }
2910         } else {
2911             $sql = "SELECT *
2912                       FROM {$CFG->prefix}assignment_submissions
2913                      WHERE userid = '$USER->id'
2914                        AND assignment = '{$assignment->id}'";
2915             if ($submission = get_record_sql($sql)) {
2916                 if ($submission->teacher == 0 && $submission->timemarked == 0) {
2917                     $str .= $strsubmitted . ', ' . $strnotgradedyet;
2918                 } else if ($submission->grade <= 0) {
2919                     $str .= $strsubmitted . ', ' . $strreviewed;
2920                 } else {
2921                     $str .= $strsubmitted . ', ' . $strgraded;
2922                 }
2923             } else {
2924                 $str .= $strnotsubmittedyet . ' ' . assignment_display_lateness(time(), $assignment->timedue);
2925             }
2926         }
2927         $str .= '</div>';
2928         if (empty($htmlarray[$assignment->course]['assignment'])) {
2929             $htmlarray[$assignment->course]['assignment'] = $str;
2930         } else {
2931             $htmlarray[$assignment->course]['assignment'] .= $str;
2932         }
2933     }
2936 function assignment_display_lateness($timesubmitted, $timedue) {
2937     if (!$timedue) {
2938         return '';
2939     }
2940     $time = $timedue - $timesubmitted;
2941     if ($time < 0) {
2942         $timetext = get_string('late', 'assignment', format_time($time));
2943         return ' (<span class="late">'.$timetext.'</span>)';
2944     } else {
2945         $timetext = get_string('early', 'assignment', format_time($time));
2946         return ' (<span class="early">'.$timetext.'</span>)';
2947     }
2950 function assignment_get_view_actions() {
2951     return array('view');
2954 function assignment_get_post_actions() {
2955     return array('upload');
2958 function assignment_get_types() {
2959     global $CFG;
2960     $types = array();
2962     $type = new object();
2963     $type->modclass = MOD_CLASS_ACTIVITY;
2964     $type->type = "assignment_group_start";
2965     $type->typestr = '--'.get_string('modulenameplural', 'assignment');
2966     $types[] = $type;
2968     $standardassignments = array('upload','online','uploadsingle','offline');
2969     foreach ($standardassignments as $assignmenttype) {
2970         $type = new object();
2971         $type->modclass = MOD_CLASS_ACTIVITY;
2972         $type->type = "assignment&amp;type=$assignmenttype";
2973         $type->typestr = get_string("type$assignmenttype", 'assignment');
2974         $types[] = $type;
2975     }
2977     /// Drop-in extra assignment types
2978     $assignmenttypes = get_list_of_plugins('mod/assignment/type');
2979     foreach ($assignmenttypes as $assignmenttype) {
2980         if (!empty($CFG->{'assignment_hide_'.$assignmenttype})) {  // Not wanted
2981             continue;
2982         }
2983         if (!in_array($assignmenttype, $standardassignments)) {
2984             $type = new object();
2985             $type->modclass = MOD_CLASS_ACTIVITY;
2986             $type->type = "assignment&amp;type=$assignmenttype";
2987             $type->typestr = get_string("type$assignmenttype", 'assignment');
2988             $types[] = $type;
2989         }
2990     }
2992     $type = new object();
2993     $type->modclass = MOD_CLASS_ACTIVITY;
2994     $type->type = "assignment_group_end";
2995     $type->typestr = '--';
2996     $types[] = $type;
2998     return $types;
3001 /**
3002  * Removes all grades from gradebook
3003  * @param int $courseid
3004  * @param string optional type
3005  */
3006 function assignment_reset_gradebook($courseid, $type='') {
3007     global $CFG;
3009     $type = $type ? "AND a.assignmenttype='$type'" : '';
3011     $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
3012               FROM {$CFG->prefix}assignment a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
3013              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id AND a.course=$courseid $type";
3015     if ($assignments = get_records_sql($sql)) {
3016         foreach ($assignments as $assignment) {
3017             assignment_grade_item_update($assignment, 'reset');
3018         }
3019     }
3022 /**
3023  * This function is used by the reset_course_userdata function in moodlelib.
3024  * This function will remove all posts from the specified assignment
3025  * and clean up any related data.
3026  * @param $data the data submitted from the reset course.
3027  * @return array status array
3028  */
3029 function assignment_reset_userdata($data) {
3030     global $CFG;
3032     $status = array();
3034     foreach (get_list_of_plugins('mod/assignment/type') as $type) {
3035         require_once("$CFG->dirroot/mod/assignment/type/$type/assignment.class.php");
3036         $assignmentclass = "assignment_$type";
3037         $ass = new $assignmentclass();
3038         $status = array_merge($status, $ass->reset_userdata($data));
3039     }
3041     return $status;
3044 /**
3045  * Implementation of the function for printing the form elements that control
3046  * whether the course reset functionality affects the assignment.
3047  * @param $mform form passed by reference
3048  */
3049 function assignment_reset_course_form_definition(&$mform) {
3050     $mform->addElement('header', 'assignmentheader', get_string('modulenameplural', 'assignment'));
3051     $mform->addElement('advcheckbox', 'reset_assignment_submissions', get_string('deleteallsubmissions','assignment'));
3054 /**
3055  * Course reset form defaults.
3056  */
3057 function assignment_reset_course_form_defaults($course) {
3058     return array('reset_assignment_submissions'=>1);
3061 ?>