MDL-14589 initial file storage implementation, temporary file manager, migration...
[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 require_once($CFG->libdir.'/eventslib.php');
9 require_once($CFG->libdir.'/formslib.php');
11 DEFINE ('ASSIGNMENT_COUNT_WORDS', 1);
12 DEFINE ('ASSIGNMENT_COUNT_LETTERS', 2);
14 /**
15  * Standard base class for all assignment submodules (assignment types).
16  */
17 class assignment_base {
19     var $cm;
20     var $course;
21     var $assignment;
22     var $strassignment;
23     var $strassignments;
24     var $strsubmissions;
25     var $strlastmodified;
26     var $pagetitle;
27     var $usehtmleditor;
28     var $defaultformat;
29     var $context;
30     var $type;
32     /**
33      * Constructor for the base assignment class
34      *
35      * Constructor for the base assignment class.
36      * If cmid is set create the cm, course, assignment objects.
37      * If the assignment is hidden and the user is not a teacher then
38      * this prints a page header and notice.
39      *
40      * @param cmid   integer, the current course module id - not set for new assignments
41      * @param assignment   object, usually null, but if we have it we pass it to save db access
42      * @param cm   object, usually null, but if we have it we pass it to save db access
43      * @param course   object, usually null, but if we have it we pass it to save db access
44      */
45     function assignment_base($cmid='staticonly', $assignment=NULL, $cm=NULL, $course=NULL) {
46         global $COURSE, $DB;
48         if ($cmid == 'staticonly') {
49             //use static functions only!
50             return;
51         }
53         global $CFG;
55         if ($cm) {
56             $this->cm = $cm;
57         } else if (! $this->cm = get_coursemodule_from_id('assignment', $cmid)) {
58             print_error('invalidcoursemodule');
59         }
61         $this->context = get_context_instance(CONTEXT_MODULE, $this->cm->id);
63         if ($course) {
64             $this->course = $course;
65         } else if ($this->cm->course == $COURSE->id) {
66             $this->course = $COURSE;
67         } else if (! $this->course = $DB->get_record('course', array('id'=>$this->cm->course))) {
68             print_error('invalidid', 'assignment');
69         }
71         if ($assignment) {
72             $this->assignment = $assignment;
73         } else if (! $this->assignment = $DB->get_record('assignment', array('id'=>$this->cm->instance))) {
74             print_error('invalidid', 'assignment');
75         }
77         $this->assignment->cmidnumber = $this->cm->id;     // compatibility with modedit assignment obj
78         $this->assignment->courseid   = $this->course->id; // compatibility with modedit assignment obj
80         $this->strassignment = get_string('modulename', 'assignment');
81         $this->strassignments = get_string('modulenameplural', 'assignment');
82         $this->strsubmissions = get_string('submissions', 'assignment');
83         $this->strlastmodified = get_string('lastmodified');
84         $this->pagetitle = strip_tags($this->course->shortname.': '.$this->strassignment.': '.format_string($this->assignment->name,true));
86         // visibility handled by require_login() with $cm parameter
87         // get current group only when really needed
89     /// Set up things for a HTML editor if it's needed
90         if ($this->usehtmleditor = can_use_html_editor()) {
91             $this->defaultformat = FORMAT_HTML;
92         } else {
93             $this->defaultformat = FORMAT_MOODLE;
94         }
95     }
97     /**
98      * Display the assignment, used by view.php
99      *
100      * This in turn calls the methods producing individual parts of the page
101      */
102     function view() {
104         $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
105         require_capability('mod/assignment:view', $context);
107         add_to_log($this->course->id, "assignment", "view", "view.php?id={$this->cm->id}",
108                    $this->assignment->id, $this->cm->id);
110         $this->view_header();
112         $this->view_intro();
114         $this->view_dates();
116         $this->view_feedback();
118         $this->view_footer();
119     }
121     /**
122      * Display the header and top of a page
123      *
124      * (this doesn't change much for assignment types)
125      * This is used by the view() method to print the header of view.php but
126      * it can be used on other pages in which case the string to denote the
127      * page in the navigation trail should be passed as an argument
128      *
129      * @param $subpage string Description of subpage to be used in navigation trail
130      */
131     function view_header($subpage='') {
133         global $CFG;
136         if ($subpage) {
137             $navigation = build_navigation($subpage, $this->cm);
138         } else {
139             $navigation = build_navigation('', $this->cm);
140         }
142         print_header($this->pagetitle, $this->course->fullname, $navigation, '', '',
143                      true, update_module_button($this->cm->id, $this->course->id, $this->strassignment),
144                      navmenu($this->course, $this->cm));
146         groups_print_activity_menu($this->cm, 'view.php?id=' . $this->cm->id);
148         echo '<div class="reportlink">'.$this->submittedlink().'</div>';
149         echo '<div class="clearer"></div>';
150     }
153     /**
154      * Display the assignment intro
155      *
156      * This will most likely be extended by assignment type plug-ins
157      * The default implementation prints the assignment description in a box
158      */
159     function view_intro() {
160         print_simple_box_start('center', '', '', 0, 'generalbox', 'intro');
161         $formatoptions = new stdClass;
162         $formatoptions->noclean = true;
163         echo format_text($this->assignment->description, $this->assignment->format, $formatoptions);
164         print_simple_box_end();
165     }
167     /**
168      * Display the assignment dates
169      *
170      * Prints the assignment start and end dates in a box.
171      * This will be suitable for most assignment types
172      */
173     function view_dates() {
174         if (!$this->assignment->timeavailable && !$this->assignment->timedue) {
175             return;
176         }
178         print_simple_box_start('center', '', '', 0, 'generalbox', 'dates');
179         echo '<table>';
180         if ($this->assignment->timeavailable) {
181             echo '<tr><td class="c0">'.get_string('availabledate','assignment').':</td>';
182             echo '    <td class="c1">'.userdate($this->assignment->timeavailable).'</td></tr>';
183         }
184         if ($this->assignment->timedue) {
185             echo '<tr><td class="c0">'.get_string('duedate','assignment').':</td>';
186             echo '    <td class="c1">'.userdate($this->assignment->timedue).'</td></tr>';
187         }
188         echo '</table>';
189         print_simple_box_end();
190     }
193     /**
194      * Display the bottom and footer of a page
195      *
196      * This default method just prints the footer.
197      * This will be suitable for most assignment types
198      */
199     function view_footer() {
200         print_footer($this->course);
201     }
203     /**
204      * Display the feedback to the student
205      *
206      * This default method prints the teacher picture and name, date when marked,
207      * grade and teacher submissioncomment.
208      *
209      * @param $submission object The submission object or NULL in which case it will be loaded
210      */
211     function view_feedback($submission=NULL) {
212         global $USER, $CFG, $DB;
213         require_once($CFG->libdir.'/gradelib.php');
215         if (!has_capability('mod/assignment:submit', $this->context, $USER->id, false)) {
216             // can not submit assignments -> no feedback
217             return;
218         }
220         if (!$submission) { /// Get submission for this assignment
221             $submission = $this->get_submission($USER->id);
222         }
224         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $USER->id);
225         $item = $grading_info->items[0];
226         $grade = $item->grades[$USER->id];
228         if ($grade->hidden or $grade->grade === false) { // hidden or error
229             return;
230         }
232         if ($grade->grade === null and empty($grade->str_feedback)) {   /// Nothing to show yet
233             return;
234         }
236         $graded_date = $grade->dategraded;
237         $graded_by   = $grade->usermodified;
239     /// We need the teacher info
240         if (!$teacher = $DB->get_record('user', array('id'=>$graded_by))) {
241             print_error('cannotfindteacher');
242         }
244     /// Print the feedback
245         print_heading(get_string('feedbackfromteacher', 'assignment', $this->course->teacher)); // TODO: fix teacher string
247         echo '<table cellspacing="0" class="feedback">';
249         echo '<tr>';
250         echo '<td class="left picture">';
251         if ($teacher) {
252             print_user_picture($teacher, $this->course->id, $teacher->picture);
253         }
254         echo '</td>';
255         echo '<td class="topic">';
256         echo '<div class="from">';
257         if ($teacher) {
258             echo '<div class="fullname">'.fullname($teacher).'</div>';
259         }
260         echo '<div class="time">'.userdate($graded_date).'</div>';
261         echo '</div>';
262         echo '</td>';
263         echo '</tr>';
265         echo '<tr>';
266         echo '<td class="left side">&nbsp;</td>';
267         echo '<td class="content">';
268         echo '<div class="grade">';
269         echo get_string("grade").': '.$grade->str_long_grade;
270         echo '</div>';
271         echo '<div class="clearer"></div>';
273         echo '<div class="comment">';
274         echo $grade->str_feedback;
275         echo '</div>';
276         echo '</tr>';
278         echo '</table>';
279     }
281     /**
282      * Returns a link with info about the state of the assignment submissions
283      *
284      * This is used by view_header to put this link at the top right of the page.
285      * For teachers it gives the number of submitted assignments with a link
286      * For students it gives the time of their submission.
287      * This will be suitable for most assignment types.
288      * @param bool $allgroup print all groups info if user can access all groups, suitable for index.php
289      * @return string
290      */
291     function submittedlink($allgroups=false) {
292         global $USER;
293         global $CFG;
295         $submitted = '';
296         $urlbase = "{$CFG->wwwroot}/mod/assignment/";
298         $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
299         if (has_capability('mod/assignment:grade', $context)) {
300             if ($allgroups and has_capability('moodle/site:accessallgroups', $context)) {
301                 $group = 0;
302             } else {
303                 $group = groups_get_activity_group($this->cm);
304             }
305             if ($count = $this->count_real_submissions($group)) {
306                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
307                              get_string('viewsubmissions', 'assignment', $count).'</a>';
308             } else {
309                 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
310                              get_string('noattempts', 'assignment').'</a>';
311             }
312         } else {
313             if (!empty($USER->id)) {
314                 if ($submission = $this->get_submission($USER->id)) {
315                     if ($submission->timemodified) {
316                         if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
317                             $submitted = '<span class="early">'.userdate($submission->timemodified).'</span>';
318                         } else {
319                             $submitted = '<span class="late">'.userdate($submission->timemodified).'</span>';
320                         }
321                     }
322                 }
323             }
324         }
326         return $submitted;
327     }
330     function setup_elements(&$mform) {
332     }
334     /**
335      * Create a new assignment activity
336      *
337      * Given an object containing all the necessary data,
338      * (defined by the form in mod_form.php) this function
339      * will create a new instance and return the id number
340      * of the new instance.
341      * The due data is added to the calendar
342      * This is common to all assignment types.
343      *
344      * @param $assignment object The data from the form on mod_form.php
345      * @return int The id of the assignment
346      */
347     function add_instance($assignment) {
348         global $COURSE, $DB;
350         $assignment->timemodified = time();
351         $assignment->courseid = $assignment->course;
353         if ($returnid = $DB->insert_record("assignment", $assignment)) {
354             $assignment->id = $returnid;
356             if ($assignment->timedue) {
357                 $event = new object();
358                 $event->name        = $assignment->name;
359                 $event->description = $assignment->description;
360                 $event->courseid    = $assignment->course;
361                 $event->groupid     = 0;
362                 $event->userid      = 0;
363                 $event->modulename  = 'assignment';
364                 $event->instance    = $returnid;
365                 $event->eventtype   = 'due';
366                 $event->timestart   = $assignment->timedue;
367                 $event->timeduration = 0;
369                 add_event($event);
370             }
372             assignment_grade_item_update($assignment);
374         }
377         return $returnid;
378     }
380     /**
381      * Deletes an assignment activity
382      *
383      * Deletes all database records, files and calendar events for this assignment.
384      * @param $assignment object The assignment to be deleted
385      * @return boolean False indicates error
386      */
387     function delete_instance($assignment) {
388         global $CFG, $DB;
390         $assignment->courseid = $assignment->course;
392         $result = true;
394         if (! $DB->delete_records('assignment_submissions', array('assignment'=>$assignment->id))) {
395             $result = false;
396         }
398         if (! $DB->delete_records('assignment', array('id'=>$assignment->id))) {
399             $result = false;
400         }
402         if (! $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
403             $result = false;
404         }
406         // delete file area with all attachments - ignore errors
407         require_once($CFG->libdir.'/filelib.php');
408         fulldelete($CFG->dataroot.'/'.$assignment->course.'/'.$CFG->moddata.'/assignment/'.$assignment->id);
410         assignment_grade_item_delete($assignment);
412         return $result;
413     }
415     /**
416      * Updates a new assignment activity
417      *
418      * Given an object containing all the necessary data,
419      * (defined by the form in mod_form.php) this function
420      * will update the assignment instance and return the id number
421      * The due date is updated in the calendar
422      * This is common to all assignment types.
423      *
424      * @param $assignment object The data from the form on mod_form.php
425      * @return int The assignment id
426      */
427     function update_instance($assignment) {
428         global $COURSE, $DB;
430         $assignment->timemodified = time();
432         $assignment->id = $assignment->instance;
433         $assignment->courseid = $assignment->course;
435         if (!$DB->update_record('assignment', $assignment)) {
436             return false;
437         }
439         if ($assignment->timedue) {
440             $event = new object();
442             if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
444                 $event->name        = $assignment->name;
445                 $event->description = $assignment->description;
446                 $event->timestart   = $assignment->timedue;
448                 update_event($event);
449             } else {
450                 $event = new object();
451                 $event->name        = $assignment->name;
452                 $event->description = $assignment->description;
453                 $event->courseid    = $assignment->course;
454                 $event->groupid     = 0;
455                 $event->userid      = 0;
456                 $event->modulename  = 'assignment';
457                 $event->instance    = $assignment->id;
458                 $event->eventtype   = 'due';
459                 $event->timestart   = $assignment->timedue;
460                 $event->timeduration = 0;
462                 add_event($event);
463             }
464         } else {
465             $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id));
466         }
468         // get existing grade item
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 != $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 = $DB->insert_record('assignment_submissions', $submission)) {
595                                 return false;
596                             }
597                             $submission->id = $sid;
598                         } else {
599                             if (!$DB->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) {
744         global $DB;
746         static $scalegrades = array();   // Cache scales for each assignment - they might have different scales!!
748         if ($this->assignment->grade >= 0) {    // Normal number
749             if ($grade == -1) {
750                 return '-';
751             } else {
752                 return $grade.' / '.$this->assignment->grade;
753             }
755         } else {                                // Scale
756             if (empty($scalegrades[$this->assignment->id])) {
757                 if ($scale = $DB->get_record('scale', array('id'=>-($this->assignment->grade)))) {
758                     $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
759                 } else {
760                     return '-';
761                 }
762             }
763             if (isset($scalegrades[$this->assignment->id][$grade])) {
764                 return $scalegrades[$this->assignment->id][$grade];
765             }
766             return '-';
767         }
768     }
770     /**
771      *  Display a single submission, ready for grading on a popup window
772      *
773      * This default method prints the teacher info and submissioncomment box at the top and
774      * the student info and submission at the bottom.
775      * This method also fetches the necessary data in order to be able to
776      * provide a "Next submission" button.
777      * Calls preprocess_submission() to give assignment type plug-ins a chance
778      * to process submissions before they are graded
779      * This method gets its arguments from the page parameters userid and offset
780      */
781     function display_submission($extra_javascript = '') {
782         global $CFG, $DB;
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 = $DB->get_record('user', array('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 {user} u '.
833                    'LEFT JOIN {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 = $DB->get_records_sql($select.$sql.$sort, null, $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 = $DB->get_record('user', array('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, $DB;
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 {user} u '.
1160                'LEFT JOIN {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 = $DB->get_records_sql($select.$sql.$sort, null, $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 (! $DB->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, $DB;
1482         if (empty($userid)) {
1483             $userid = $USER->id;
1484         }
1486         $submission = $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1488         if ($submission || !$createnew) {
1489             return $submission;
1490         }
1491         $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
1492         if (!$DB->insert_record("assignment_submissions", $newsubmission)) {
1493             print_error('cannotinsertempty', 'assignment');
1494         }
1496         return $DB->get_record('assignment_submissions', array('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, $DB;
1563         if (empty($this->assignment->emailteachers)) {          // No need to do anything
1564             return;
1565         }
1567         $user = $DB->get_record('user', array('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                 $eventdata = new object();
1586                 $eventdata->modulename       = 'assignment';
1587                 $eventdata->userfrom         = $user;
1588                 $eventdata->userto           = $teacher;
1589                 $eventdata->subject          = $postsubject;
1590                 $eventdata->fullmessage      = $posttext;
1591                 $eventdata->fullmessageformat = FORMAT_PLAIN;
1592                 $eventdata->fullmessagehtml  = $posthtml;
1593                 $eventdata->smallmessage     = '';
1594                 if ( events_trigger('message_send', $eventdata) > 0 ){
1595                 }
1597                 /*
1598                 @email_to_user($teacher, $user, $postsubject, $posttext, $posthtml);  // If it fails, oh well, too bad.
1599                 */
1600             }
1601         }
1602     }
1604     function send_file($filearea, $args) {
1605         debugging('plugin does not implement file sending', DEBUG_DEVELOPER);
1606         return false;
1607     }
1609     /**
1610      * Returns a list of teachers that should be grading given submission
1611      */
1612     function get_graders($user) {
1613         //potential graders
1614         $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false);
1616         $graders = array();
1617         if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) {   // Separate groups are being used
1618             if ($groups = groups_get_all_groups($this->course->id, $user->id)) {  // Try to find all groups
1619                 foreach ($groups as $group) {
1620                     foreach ($potgraders as $t) {
1621                         if ($t->id == $user->id) {
1622                             continue; // do not send self
1623                         }
1624                         if (groups_is_member($group->id, $t->id)) {
1625                             $graders[$t->id] = $t;
1626                         }
1627                     }
1628                 }
1629             } else {
1630                 // user not in group, try to find graders without group
1631                 foreach ($potgraders as $t) {
1632                     if ($t->id == $user->id) {
1633                         continue; // do not send self
1634                     }
1635                     if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
1636                         $graders[$t->id] = $t;
1637                     }
1638                 }
1639             }
1640         } else {
1641             foreach ($potgraders as $t) {
1642                 if ($t->id == $user->id) {
1643                     continue; // do not send self
1644                 }
1645                 $graders[$t->id] = $t;
1646             }
1647         }
1648         return $graders;
1649     }
1651     /**
1652      * Creates the text content for emails to teachers
1653      *
1654      * @param $info object The info used by the 'emailteachermail' language string
1655      * @return string
1656      */
1657     function email_teachers_text($info) {
1658         $posttext  = format_string($this->course->shortname).' -> '.$this->strassignments.' -> '.
1659                      format_string($this->assignment->name)."\n";
1660         $posttext .= '---------------------------------------------------------------------'."\n";
1661         $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
1662         $posttext .= "\n---------------------------------------------------------------------\n";
1663         return $posttext;
1664     }
1666      /**
1667      * Creates the html content for emails to teachers
1668      *
1669      * @param $info object The info used by the 'emailteachermailhtml' language string
1670      * @return string
1671      */
1672     function email_teachers_html($info) {
1673         global $CFG;
1674         $posthtml  = '<p><font face="sans-serif">'.
1675                      '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname).'</a> ->'.
1676                      '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
1677                      '<a href="'.$CFG->wwwroot.'/mod/assignment/view.php?id='.$this->cm->id.'">'.format_string($this->assignment->name).'</a></font></p>';
1678         $posthtml .= '<hr /><font face="sans-serif">';
1679         $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
1680         $posthtml .= '</font><hr />';
1681         return $posthtml;
1682     }
1684     /**
1685      * Produces a list of links to the files uploaded by a user
1686      *
1687      * @param $userid int optional id of the user. If 0 then $USER->id is used.
1688      * @param $return boolean optional defaults to false. If true the list is returned rather than printed
1689      * @return string optional
1690      */
1691     function print_user_files($userid=0, $return=false) {
1692         global $CFG, $USER;
1694         if (!$userid) {
1695             if (!isloggedin()) {
1696                 return '';
1697             }
1698             $userid = $USER->id;
1699         }
1701         $output = '';
1703         $fs = get_file_storage();
1704         $browser = get_file_browser();
1706         $found = false;
1708         if ($files = $fs->get_area_files($this->context->id, 'assignment_submission', $userid, "timemodified", false)) {
1709             $p = array(
1710                 'userid' => $userid,
1711                 'assignmentid' => $this->cm->id,
1712             );
1713             foreach ($files as $file) {
1714                 $filename = $file->get_filename();
1715                 $found = true;
1716                 $mimetype = $file->get_mimetype();
1717                 $icon = mimeinfo_from_type('icon', $mimetype);
1718                 $path = $browser->encodepath($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/assignment_submission/'.$userid.'/'.$filename);
1719                 $output .= '<a href="'.$path.'" ><img src="'.$CFG->pixpath.'/f/'.$icon.'" class="icon" alt="'.$icon.'" />'.s($filename).'</a>';
1720                 if ($this->portfolio_exportable() && true) { // @todo replace with capability check
1721                     $p['file'] = $file;
1722                     $output .= portfolio_add_button('assignment_portfolio_caller', $p, null, false, true);
1723                 }
1724                 $output .= '<br />';
1725             }
1726             if ($this->portfolio_exportable() && true) { //@todo replace with check capability
1727                 unset($p['file']);// for all files
1728                 $output .= '<br />' . portfolio_add_button('assignment_portfolio_caller', $p, null, true, true);
1729             }
1730         }
1732         $output = '<div class="files">'.$output.'</div>';
1734         if ($return) {
1735             return $output;
1736         }
1737         echo $output;
1738     }
1740     /**
1741      * Count the files uploaded by a given user
1742      *
1743      * @param $userid int The user id
1744      * @return int
1745      */
1746     function count_user_files($userid) {
1747         $fs = get_file_storage();
1748         $files = $fs->get_area_files($this->context->id, 'assignment_submission', $userid, "id", false);
1749         return count($files);
1750     }
1752     /**
1753      * Returns true if the student is allowed to submit
1754      *
1755      * Checks that the assignment has started and, if the option to prevent late
1756      * submissions is set, also checks that the assignment has not yet closed.
1757      * @return boolean
1758      */
1759     function isopen() {
1760         $time = time();
1761         if ($this->assignment->preventlate && $this->assignment->timedue) {
1762             return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
1763         } else {
1764             return ($this->assignment->timeavailable <= $time);
1765         }
1766     }
1769     /**
1770      * Return true if is set description is hidden till available date
1771      *
1772      * This is needed by calendar so that hidden descriptions do not
1773      * come up in upcoming events.
1774      *
1775      * Check that description is hidden till available date
1776      * By default return false
1777      * Assignments types should implement this method if needed
1778      * @return boolen
1779      */
1780     function description_is_hidden() {
1781         return false;
1782     }
1784     /**
1785      * Return an outline of the user's interaction with the assignment
1786      *
1787      * The default method prints the grade and timemodified
1788      * @param $user object
1789      * @return object with properties ->info and ->time
1790      */
1791     function user_outline($user) {
1792         if ($submission = $this->get_submission($user->id)) {
1794             $result = new object();
1795             $result->info = get_string('grade').': '.$this->display_grade($submission->grade);
1796             $result->time = $submission->timemodified;
1797             return $result;
1798         }
1799         return NULL;
1800     }
1802     /**
1803      * Print complete information about the user's interaction with the assignment
1804      *
1805      * @param $user object
1806      */
1807     function user_complete($user) {
1808         if ($submission = $this->get_submission($user->id)) {
1810             $fs = get_file_storage();
1811             $browser = get_file_browser();
1812     
1813             if ($files = $fs->get_area_files($this->context->id, 'assignment_submission', $user->id, "timemodified", false)) {
1814                 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
1815                 foreach ($files as $file) {
1816                     $countfiles .= "; ".$file->get_filename();
1817                 }
1818             }
1820             print_simple_box_start();
1821             echo get_string("lastmodified").": ";
1822             echo userdate($submission->timemodified);
1823             echo $this->display_lateness($submission->timemodified);
1825             $this->print_user_files($user->id);
1827             echo '<br />';
1829             if (empty($submission->timemarked)) {
1830                 print_string("notgradedyet", "assignment");
1831             } else {
1832                 $this->view_feedback($submission);
1833             }
1835             print_simple_box_end();
1837         } else {
1838             print_string("notsubmittedyet", "assignment");
1839         }
1840     }
1842     /**
1843      * Return a string indicating how late a submission is
1844      *
1845      * @param $timesubmitted int
1846      * @return string
1847      */
1848     function display_lateness($timesubmitted) {
1849         return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
1850     }
1852     /**
1853      * Empty method stub for all delete actions.
1854      */
1855     function delete() {
1856         //nothing by default
1857         redirect('view.php?id='.$this->cm->id);
1858     }
1860     /**
1861      * Empty custom feedback grading form.
1862      */
1863     function custom_feedbackform($submission, $return=false) {
1864         //nothing by default
1865         return '';
1866     }
1868     /**
1869      * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
1870      * for the course (see resource).
1871      *
1872      * Given a course_module object, this function returns any "extra" information that may be needed
1873      * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
1874      *
1875      * @param $coursemodule object The coursemodule object (record).
1876      * @return object An object on information that the coures will know about (most noticeably, an icon).
1877      *
1878      */
1879     function get_coursemodule_info($coursemodule) {
1880         return false;
1881     }
1883     /**
1884      * Plugin cron method - do not use $this here, create new assignment instances if needed.
1885      * @return void
1886      */
1887     function cron() {
1888         //no plugin cron by default - override if needed
1889     }
1891     /**
1892      * Reset all submissions
1893      */
1894     function reset_userdata($data) {
1895         global $CFG, $DB;
1896         require_once($CFG->libdir.'/filelib.php');
1898         if (!$DB->count_records('assignment', array('course'=>$data->courseid, 'assignmenttype'=>$this->type))) {
1899             return array(); // no assignments of this type present
1900         }
1902         $componentstr = get_string('modulenameplural', 'assignment');
1903         $status = array();
1905         $typestr = get_string('type'.$this->type, 'assignment');
1907         if (!empty($data->reset_assignment_submissions)) {
1908             $assignmentssql = "SELECT a.id
1909                                  FROM {assignment} a
1910                                 WHERE a.course=? AND a.assignmenttype=?";
1911             $params = array($data->courseid, $this->type);
1913             $DB->delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)", $params);
1915             if ($assignments = $DB->get_records_sql($assignmentssql, $params)) {
1916                 foreach ($assignments as $assignmentid=>$unused) {
1917                     fulldelete($CFG->dataroot.'/'.$data->courseid.'/moddata/assignment/'.$assignmentid);
1918                 }
1919             }
1921             $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
1923             if (empty($data->reset_gradebook_grades)) {
1924                 // remove all grades from gradebook
1925                 assignment_reset_gradebook($data->courseid, $this->type);
1926             }
1927         }
1929         /// updating dates - shift may be negative too
1930         if ($data->timeshift) {
1931             shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
1932             $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
1933         }
1935         return $status;
1936     }
1939     function portfolio_exportable() {
1940         return false;
1941     }
1942 } ////// End of the assignment_base class
1944 class mod_assignment_upload_file_form extends moodleform {
1945     function definition() {
1946         $mform = $this->_form;
1947         $instance = $this->_customdata;
1949         //TODO: improve upload size checking
1950         $mform->setMaxFileSize($instance->assignment->maxbytes);
1952         // visible elements
1953         $mform->addElement('file', 'newfile', get_string('uploadafile'));
1955         // hidden params
1956         $mform->addElement('hidden', 'id', $instance->cm->id);
1957         $mform->setType('id', PARAM_INT);
1958         $mform->addElement('hidden', 'action', 'uploadfile');
1959         $mform->setType('action', PARAM_ALPHA);
1961         // buttons
1962         $this->add_action_buttons(false, get_string('uploadthisfile'));
1963     }
1967 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
1969 /** 
1970  * Code to be executed when a module is installed
1971  */ 
1972 function assignment_install() {
1973     return true; 
1976 /**
1977  * Deletes an assignment instance
1978  *
1979  * This is done by calling the delete_instance() method of the assignment type class
1980  */
1981 function assignment_delete_instance($id){
1982     global $CFG, $DB;
1984     if (! $assignment = $DB->get_record('assignment', array('id'=>$id))) {
1985         return false;
1986     }
1988     // fall back to base class if plugin missing
1989     $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
1990     if (file_exists($classfile)) {
1991         require_once($classfile);
1992         $assignmentclass = "assignment_$assignment->assignmenttype";
1994     } else {
1995         debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
1996         $assignmentclass = "assignment_base";
1997     }
1999     $ass = new $assignmentclass();
2000     return $ass->delete_instance($assignment);
2004 /**
2005  * Updates an assignment instance
2006  *
2007  * This is done by calling the update_instance() method of the assignment type class
2008  */
2009 function assignment_update_instance($assignment){
2010     global $CFG;
2012     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2014     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2015     $assignmentclass = "assignment_$assignment->assignmenttype";
2016     $ass = new $assignmentclass();
2017     return $ass->update_instance($assignment);
2021 /**
2022  * Adds an assignment instance
2023  *
2024  * This is done by calling the add_instance() method of the assignment type class
2025  */
2026 function assignment_add_instance($assignment) {
2027     global $CFG;
2029     $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2031     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2032     $assignmentclass = "assignment_$assignment->assignmenttype";
2033     $ass = new $assignmentclass();
2034     return $ass->add_instance($assignment);
2038 /**
2039  * Returns an outline of a user interaction with an assignment
2040  *
2041  * This is done by calling the user_outline() method of the assignment type class
2042  */
2043 function assignment_user_outline($course, $user, $mod, $assignment) {
2044     global $CFG;
2046     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2047     $assignmentclass = "assignment_$assignment->assignmenttype";
2048     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2049     return $ass->user_outline($user);
2052 /**
2053  * Prints the complete info about a user's interaction with an assignment
2054  *
2055  * This is done by calling the user_complete() method of the assignment type class
2056  */
2057 function assignment_user_complete($course, $user, $mod, $assignment) {
2058     global $CFG;
2060     require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2061     $assignmentclass = "assignment_$assignment->assignmenttype";
2062     $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2063     return $ass->user_complete($user);
2066 /**
2067  * Function to be run periodically according to the moodle cron
2068  *
2069  * Finds all assignment notifications that have yet to be mailed out, and mails them
2070  */
2071 function assignment_cron () {
2072     global $CFG, $USER, $DB;
2074     /// first execute all crons in plugins
2075     if ($plugins = get_list_of_plugins('mod/assignment/type')) {
2076         foreach ($plugins as $plugin) {
2077             require_once("$CFG->dirroot/mod/assignment/type/$plugin/assignment.class.php");
2078             $assignmentclass = "assignment_$plugin";
2079             $ass = new $assignmentclass();
2080             $ass->cron();
2081         }
2082     }
2084     /// Notices older than 1 day will not be mailed.  This is to avoid the problem where
2085     /// cron has not been running for a long time, and then suddenly people are flooded
2086     /// with mail from the past few weeks or months
2088     $timenow   = time();
2089     $endtime   = $timenow - $CFG->maxeditingtime;
2090     $starttime = $endtime - 24 * 3600;   /// One day earlier
2092     if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2094         $realuser = clone($USER);
2096         foreach ($submissions as $key => $submission) {
2097             if (! $DB->set_field("assignment_submissions", "mailed", "1", array("id"=>$submission->id))) {
2098                 echo "Could not update the mailed field for id $submission->id.  Not mailed.\n";
2099                 unset($submissions[$key]);
2100             }
2101         }
2103         $timenow = time();
2105         foreach ($submissions as $submission) {
2107             echo "Processing assignment submission $submission->id\n";
2109             if (! $user = $DB->get_record("user", array("id"=>$submission->userid))) {
2110                 echo "Could not find user $post->userid\n";
2111                 continue;
2112             }
2114             if (! $course = $DB->get_record("course", array("id"=>$submission->course))) {
2115                 echo "Could not find course $submission->course\n";
2116                 continue;
2117             }
2119             /// Override the language and timezone of the "current" user, so that
2120             /// mail is customised for the receiver.
2121             $USER = $user;
2122             course_setup($course);
2124             if (!has_capability('moodle/course:view', get_context_instance(CONTEXT_COURSE, $submission->course), $user->id)) {
2125                 echo fullname($user)." not an active participant in " . format_string($course->shortname) . "\n";
2126                 continue;
2127             }
2129             if (! $teacher = $DB->get_record("user", array("id"=>$submission->teacher))) {
2130                 echo "Could not find teacher $submission->teacher\n";
2131                 continue;
2132             }
2134             if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2135                 echo "Could not find course module for assignment id $submission->assignment\n";
2136                 continue;
2137             }
2139             if (! $mod->visible) {    /// Hold mail notification for hidden assignments until later
2140                 continue;
2141             }
2143             $strassignments = get_string("modulenameplural", "assignment");
2144             $strassignment  = get_string("modulename", "assignment");
2146             $assignmentinfo = new object();
2147             $assignmentinfo->teacher = fullname($teacher);
2148             $assignmentinfo->assignment = format_string($submission->name,true);
2149             $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2151             $postsubject = "$course->shortname: $strassignments: ".format_string($submission->name,true);
2152             $posttext  = "$course->shortname -> $strassignments -> ".format_string($submission->name,true)."\n";
2153             $posttext .= "---------------------------------------------------------------------\n";
2154             $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2155             $posttext .= "---------------------------------------------------------------------\n";
2157             if ($user->mailformat == 1) {  // HTML
2158                 $posthtml = "<p><font face=\"sans-serif\">".
2159                 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> ->".
2160                 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2161                 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2162                 $posthtml .= "<hr /><font face=\"sans-serif\">";
2163                 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2164                 $posthtml .= "</font><hr />";
2165             } else {
2166                 $posthtml = "";
2167             }
2169             $eventdata = new object();
2170             $eventdata->modulename       = 'assignment';
2171             $eventdata->userfrom         = $teacher;
2172             $eventdata->userto           = $user;
2173             $eventdata->subject          = $postsubject;
2174             $eventdata->fullmessage      = $posttext;
2175             $eventdata->fullmessageformat = FORMAT_PLAIN;
2176             $eventdata->fullmessagehtml  = $posthtml;
2177             $eventdata->smallmessage     = '';
2178             if ( events_trigger('message_send', $eventdata) > 0 ){
2179                 echo "Error: assignment cron: Could not send out mail for id $submission->id to user $user->id ($user->email)\n";
2180             }
2182             /*
2183             if (! email_to_user($user, $teacher, $postsubject, $posttext, $posthtml)) {
2184                 echo "Error: assignment cron: Could not send out mail for id $submission->id to user $user->id ($user->email)\n";
2185             }
2186             */
2187         }
2189         $USER = $realuser;
2190         course_setup(SITEID); // reset cron user language, theme and timezone settings
2192     }
2194     return true;
2197 /**
2198  * Return grade for given user or all users.
2199  *
2200  * @param int $assignmentid id of assignment
2201  * @param int $userid optional user id, 0 means all users
2202  * @return array array of grades, false if none
2203  */
2204 function assignment_get_user_grades($assignment, $userid=0) {
2205     global $CFG, $DB;
2207     if ($userid) {
2208         $user = "AND u.id = :userid";
2209         $params = array('userid'=>$userid);
2210     } else {
2211         $user = "";
2212     }
2213     $params['aid'] = $assignment->id;
2215     $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2216                    s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2217               FROM {user} u, {assignment_submissions} s
2218              WHERE u.id = s.userid AND s.assignment = :aid
2219                    $user";
2221     return $DB->get_records_sql($sql, $params);
2224 /**
2225  * Update grades by firing grade_updated event
2226  *
2227  * @param object $assignment null means all assignments
2228  * @param int $userid specific user only, 0 mean all
2229  */
2230 function assignment_update_grades($assignment=null, $userid=0, $nullifnone=true) {
2231     global $CFG, $DB;
2232     require_once($CFG->libdir.'/gradelib.php');
2234     if ($assignment != null) {
2235         if ($grades = assignment_get_user_grades($assignment, $userid)) {
2236             foreach($grades as $k=>$v) {
2237                 if ($v->rawgrade == -1) {
2238                     $grades[$k]->rawgrade = null;
2239                 }
2240             }
2241             assignment_grade_item_update($assignment, $grades);
2242         } else {
2243             assignment_grade_item_update($assignment);
2244         }
2246     } else {
2247         $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
2248                   FROM {assignment} a, {course_modules} cm, {modules} m
2249                  WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2250         if ($rs = $DB->get_recordset_sql($sql)) {
2251             foreach ($rs as $assignment) {
2252                 if ($assignment->grade != 0) {
2253                     assignment_update_grades($assignment);
2254                 } else {
2255                     assignment_grade_item_update($assignment);
2256                 }
2257             }
2258             $rs->close();
2259         }
2260     }
2263 /**
2264  * Create grade item for given assignment
2265  *
2266  * @param object $assignment object with extra cmidnumber
2267  * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
2268  * @return int 0 if ok, error code otherwise
2269  */
2270 function assignment_grade_item_update($assignment, $grades=NULL) {
2271     global $CFG;
2272     require_once($CFG->libdir.'/gradelib.php');
2274     if (!isset($assignment->courseid)) {
2275         $assignment->courseid = $assignment->course;
2276     }
2278     $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
2280     if ($assignment->grade > 0) {
2281         $params['gradetype'] = GRADE_TYPE_VALUE;
2282         $params['grademax']  = $assignment->grade;
2283         $params['grademin']  = 0;
2285     } else if ($assignment->grade < 0) {
2286         $params['gradetype'] = GRADE_TYPE_SCALE;
2287         $params['scaleid']   = -$assignment->grade;
2289     } else {
2290         $params['gradetype'] = GRADE_TYPE_TEXT; // allow text comments only
2291     }
2293     if ($grades  === 'reset') {
2294         $params['reset'] = true;
2295         $grades = NULL;
2296     }
2298     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades, $params);
2301 /**
2302  * Delete grade item for given assignment
2303  *
2304  * @param object $assignment object
2305  * @return object assignment
2306  */
2307 function assignment_grade_item_delete($assignment) {
2308     global $CFG;
2309     require_once($CFG->libdir.'/gradelib.php');
2311     if (!isset($assignment->courseid)) {
2312         $assignment->courseid = $assignment->course;
2313     }
2315     return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
2318 /**
2319  * Returns the users with data in one assignment (students and teachers)
2320  *
2321  * @param $assignmentid int
2322  * @return array of user objects
2323  */
2324 function assignment_get_participants($assignmentid) {
2325     global $CFG, $DB;
2327     //Get students
2328     $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2329                                         FROM {user} u,
2330                                              {assignment_submissions} a
2331                                        WHERE a.assignment = ? and
2332                                              u.id = a.userid", array($assignmentid));
2333     //Get teachers
2334     $teachers = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2335                                         FROM {user} u,
2336                                              {assignment_submissions} a
2337                                        WHERE a.assignment = ? and
2338                                              u.id = a.teacher", array($assignmentid));
2340     //Add teachers to students
2341     if ($teachers) {
2342         foreach ($teachers as $teacher) {
2343             $students[$teacher->id] = $teacher;
2344         }
2345     }
2346     //Return students array (it contains an array of unique users)
2347     return ($students);
2350 function assignment_pluginfile($course, $cminfo, $context, $filearea, $args) {
2351     global $CFG, $DB;
2353     if (!$assignment = $DB->get_record('assignment', array('id'=>$cminfo->instance))) {
2354         return false;
2355     }
2356     if (!$cm = get_coursemodule_from_instance('assignment', $assignment->id, $course->id)) {
2357         return false;
2358     }
2360     require_once($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
2361     $assignmentclass = 'assignment_'.$assignment->assignmenttype;
2362     $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm, $course);
2364     return $assignmentinstance->send_file($filearea, $args);
2366 /**
2367  * Checks if a scale is being used by an assignment
2368  *
2369  * This is used by the backup code to decide whether to back up a scale
2370  * @param $assignmentid int
2371  * @param $scaleid int
2372  * @return boolean True if the scale is used by the assignment
2373  */
2374 function assignment_scale_used($assignmentid, $scaleid) {
2375     global $DB;
2377     $return = false;
2379     $rec = $DB->get_record('assignment', array('id'=>$assignmentid,'grade'=>-$scaleid));
2381     if (!empty($rec) && !empty($scaleid)) {
2382         $return = true;
2383     }
2385     return $return;
2388 /**
2389  * Checks if scale is being used by any instance of assignment
2390  *
2391  * This is used to find out if scale used anywhere
2392  * @param $scaleid int
2393  * @return boolean True if the scale is used by any assignment
2394  */
2395 function assignment_scale_used_anywhere($scaleid) {
2396     global $DB;
2398     if ($scaleid and $DB->record_exists('assignment', array('grade'=>-$scaleid))) {
2399         return true;
2400     } else {
2401         return false;
2402     }
2405 /**
2406  * Make sure up-to-date events are created for all assignment instances
2407  *
2408  * This standard function will check all instances of this module
2409  * and make sure there are up-to-date events created for each of them.
2410  * If courseid = 0, then every assignment event in the site is checked, else
2411  * only assignment events belonging to the course specified are checked.
2412  * This function is used, in its new format, by restore_refresh_events()
2413  *
2414  * @param $courseid int optional If zero then all assignments for all courses are covered
2415  * @return boolean Always returns true
2416  */
2417 function assignment_refresh_events($courseid = 0) {
2418     global $DB;
2420     if ($courseid == 0) {
2421         if (! $assignments = $DB->get_records("assignment")) {
2422             return true;
2423         }
2424     } else {
2425         if (! $assignments = $DB->get_records("assignment", array("course"=>$courseid))) {
2426             return true;
2427         }
2428     }
2429     $moduleid = $DB->get_field('modules', 'id', array('name'=>'assignment'));
2431     foreach ($assignments as $assignment) {
2432         $event = NULL;
2433         $event->name        = $assignment->name;
2434         $event->description = $assignment->description;
2435         $event->timestart   = $assignment->timedue;
2437         if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
2438             update_event($event);
2440         } else {
2441             $event->courseid    = $assignment->course;
2442             $event->groupid     = 0;
2443             $event->userid      = 0;
2444             $event->modulename  = 'assignment';
2445             $event->instance    = $assignment->id;
2446             $event->eventtype   = 'due';
2447             $event->timeduration = 0;
2448             $event->visible     = $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$assignment->id));
2449             add_event($event);
2450         }
2452     }
2453     return true;
2456 /**
2457  * Print recent activity from all assignments in a given course
2458  *
2459  * This is used by the recent activity block
2460  */
2461 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
2462     global $CFG, $USER, $DB;
2464     // do not use log table if possible, it may be huge
2466     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
2467                                                      u.firstname, u.lastname, u.email, u.picture
2468                                                 FROM {assignment_submissions} asb
2469                                                      JOIN {assignment} a      ON a.id = asb.assignment
2470                                                      JOIN {course_modules} cm ON cm.instance = a.id
2471                                                      JOIN {modules} md        ON md.id = cm.module
2472                                                      JOIN {user} u            ON u.id = asb.userid
2473                                                WHERE asb.timemodified > ? AND
2474                                                      a.course = ? AND
2475                                                      md.name = 'assignment'
2476                                             ORDER BY asb.timemodified ASC", array($timestart, $course->id))) {
2477          return false;
2478     }
2480     $modinfo =& get_fast_modinfo($course); // reference needed because we might load the groups
2481     $show    = array();
2482     $grader  = array();
2484     foreach($submissions as $submission) {
2485         if (!array_key_exists($submission->cmid, $modinfo->cms)) {
2486             continue;
2487         }
2488         $cm = $modinfo->cms[$submission->cmid];
2489         if (!$cm->uservisible) {
2490             continue;
2491         }
2492         if ($submission->userid == $USER->id) {
2493             $show[] = $submission;
2494             continue;
2495         }
2497         // the act of sumitting of assignemnt may be considered private - only graders will see it if specified
2498         if (empty($CFG->assignment_showrecentsubmissions)) {
2499             if (!array_key_exists($cm->id, $grader)) {
2500                 $grader[$cm->id] = has_capability('moodle/grade:viewall', get_context_instance(CONTEXT_MODULE, $cm->id));
2501             }
2502             if (!$grader[$cm->id]) {
2503                 continue;
2504             }
2505         }
2507         $groupmode = groups_get_activity_groupmode($cm, $course);
2509         if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2510             if (isguestuser()) {
2511                 // shortcut - guest user does not belong into any group
2512                 continue;
2513             }
2515             if (is_null($modinfo->groups)) {
2516                 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2517             }
2519             // this will be slow - show only users that share group with me in this cm
2520             if (empty($modinfo->groups[$cm->id])) {
2521                 continue;
2522             }
2523             $usersgroups =  groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
2524             if (is_array($usersgroups)) {
2525                 $usersgroups = array_keys($usersgroups);
2526                 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2527                 if (empty($intersect)) {
2528                     continue;
2529                 }
2530             }
2531         }
2532         $show[] = $submission;
2533     }
2535     if (empty($show)) {
2536         return false;
2537     }
2539     print_headline(get_string('newsubmissions', 'assignment').':');
2541     foreach ($show as $submission) {
2542         $cm = $modinfo->cms[$submission->cmid];
2543         $link = $CFG->wwwroot.'/mod/assignment/view.php?id='.$cm->id;
2544         print_recent_activity_note($submission->timemodified, $submission, $cm->name, $link, false, $viewfullnames);
2545     }
2547     return true;
2551 /**
2552  * Returns all assignments since a given time in specified forum.
2553  */
2554 function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0)  {
2555     global $CFG, $COURSE, $USER, $DB;
2557     if ($COURSE->id == $courseid) {
2558         $course = $COURSE;
2559     } else {
2560         $course = $DB->get_record('course', array('id'=>$courseid));
2561     }
2563     $modinfo =& get_fast_modinfo($course);
2565     $cm = $modinfo->cms[$cmid];
2567     $params = array();
2568     if ($userid) {
2569         $userselect = "AND u.id = :userid";
2570         $params['userid'] = $userid;
2571     } else {
2572         $userselect = "";
2573     }
2575     if ($groupid) {
2576         $groupselect = "AND gm.groupid = :groupid";
2577         $groupjoin   = "JOIN {groups_members} gm ON  gm.userid=u.id";
2578         $params['groupid'] = $groupid;
2579     } else {
2580         $groupselect = "";
2581         $groupjoin   = "";
2582     }
2584     $params['cminstance'] = $cm->instance;
2585     $params['timestart'] = $timestart;
2587     if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, asb.userid,
2588                                                      u.firstname, u.lastname, u.email, u.picture
2589                                                 FROM {assignment_submissions} asb
2590                                                 JOIN {assignment} a      ON a.id = asb.assignment
2591                                                 JOIN {user} u            ON u.id = asb.userid
2592                                           $groupjoin
2593                                                WHERE asb.timemodified > :timestart AND a.id = :cminstance
2594                                                      $userselect $groupselect
2595                                             ORDER BY asb.timemodified ASC", $params)) {
2596          return;
2597     }
2599     $groupmode       = groups_get_activity_groupmode($cm, $course);
2600     $cm_context      = get_context_instance(CONTEXT_MODULE, $cm->id);
2601     $grader          = has_capability('moodle/grade:viewall', $cm_context);
2602     $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
2603     $viewfullnames   = has_capability('moodle/site:viewfullnames', $cm_context);
2605     if (is_null($modinfo->groups)) {
2606         $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2607     }
2609     $show = array();
2611     foreach($submissions as $submission) {
2612         if ($submission->userid == $USER->id) {
2613             $show[] = $submission;
2614             continue;
2615         }
2617         // the act of sumitting of assignemnt may be considered private - only graders will see it if specified
2618         if (!empty($CFG->assignment_showrecentsubmissions)) {
2619             if (!$grader) {
2620                 continue;
2621             }
2622         }
2624         if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
2625             if (isguestuser()) {
2626                 // shortcut - guest user does not belong into any group
2627                 continue;
2628             }
2630             // this will be slow - show only users that share group with me in this cm
2631             if (empty($modinfo->groups[$cm->id])) {
2632                 continue;
2633             }
2634             $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
2635             if (is_array($usersgroups)) {
2636                 $usersgroups = array_keys($usersgroups);
2637                 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2638                 if (empty($intersect)) {
2639                     continue;
2640                 }
2641             }
2642         }
2643         $show[] = $submission;
2644     }
2646     if (empty($show)) {
2647         return;
2648     }
2650     if ($grader) {
2651         require_once($CFG->libdir.'/gradelib.php');
2652         $userids = array();
2653         foreach ($show as $id=>$submission) {
2654             $userids[] = $submission->userid;
2656         }
2657         $grades = grade_get_grades($courseid, 'mod', 'assignment', $cm->instance, $userids);
2658     }
2660     $aname = format_string($cm->name,true);
2661     foreach ($show as $submission) {
2662         $tmpactivity = new object();
2664         $tmpactivity->type         = 'assignment';
2665         $tmpactivity->cmid         = $cm->id;
2666         $tmpactivity->name         = $aname;
2667         $tmpactivity->sectionnum   = $cm->sectionnum;
2668         $tmpactivity->timestamp    = $submission->timemodified;
2670         if ($grader) {
2671             $tmpactivity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
2672         }
2674         $tmpactivity->user->userid   = $submission->userid;
2675         $tmpactivity->user->fullname = fullname($submission, $viewfullnames);
2676         $tmpactivity->user->picture  = $submission->picture;
2678         $activities[$index++] = $tmpactivity;
2679     }
2681     return;
2684 /**
2685  * Print recent activity from all assignments in a given course
2686  *
2687  * This is used by course/recent.php
2688  */
2689 function assignment_print_recent_mod_activity($activity, $courseid, $detail, $modnames)  {
2690     global $CFG;
2692     echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
2694     echo "<tr><td class=\"userpicture\" valign=\"top\">";
2695     print_user_picture($activity->user->userid, $courseid, $activity->user->picture);
2696     echo "</td><td>";
2698     if ($detail) {
2699         $modname = $modnames[$activity->type];
2700         echo '<div class="title">';
2701         echo "<img src=\"$CFG->modpixpath/assignment/icon.gif\" ".
2702              "class=\"icon\" alt=\"$modname\">";
2703         echo "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id={$activity->cmid}\">{$activity->name}</a>";
2704         echo '</div>';
2705     }
2707     if (isset($activity->grade)) {
2708         echo '<div class="grade">';
2709         echo get_string('grade').': ';
2710         echo $activity->grade;
2711         echo '</div>';
2712     }
2714     echo '<div class="user">';
2715     echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->userid}&amp;course=$courseid\">"
2716          ."{$activity->user->fullname}</a>  - ".userdate($activity->timestamp);
2717     echo '</div>';
2719     echo "</td></tr></table>";
2722 /// GENERIC SQL FUNCTIONS
2724 /**
2725  * Fetch info from logs
2726  *
2727  * @param $log object with properties ->info (the assignment id) and ->userid
2728  * @return array with assignment name and user firstname and lastname
2729  */
2730 function assignment_log_info($log) {
2731     global $CFG, $DB;
2733     return $DB->get_record_sql("SELECT a.name, u.firstname, u.lastname
2734                                   FROM {assignment} a, {user} u
2735                                  WHERE a.id = ? AND u.id = ?", array($log->info, $log->userid));
2738 /**
2739  * Return list of marked submissions that have not been mailed out for currently enrolled students
2740  *
2741  * @return array
2742  */
2743 function assignment_get_unmailed_submissions($starttime, $endtime) {
2744     global $CFG, $DB;
2746     return $DB->get_records_sql("SELECT s.*, a.course, a.name
2747                                    FROM {assignment_submissions} s,
2748                                         {assignment} a
2749                                   WHERE s.mailed = 0
2750                                         AND s.timemarked <= ?
2751                                         AND s.timemarked >= ?
2752                                         AND s.assignment = a.id", array($endtime, $starttime));
2755 /**
2756  * Counts all real assignment submissions by ENROLLED students (not empty ones)
2757  *
2758  * There are also assignment type methods count_real_submissions() wich in the default
2759  * implementation simply call this function.
2760  * @param $groupid int optional If nonzero then count is restricted to this group
2761  * @return int The number of submissions
2762  */
2763 function assignment_count_real_submissions($cm, $groupid=0) {
2764     global $CFG, $DB;
2766     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2768     // this is all the users with this capability set, in this context or higher
2769     if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $groupid, '', false)) {
2770         $users = array_keys($users);
2771     }
2773     // if groupmembersonly used, remove users who are not in any group
2774     if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
2775         if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
2776             $users = array_intersect($users, array_keys($groupingusers));
2777         }
2778     }
2780     if (empty($users)) {
2781         return 0;
2782     }
2784     $userlists = implode(',', $users);
2786     return $DB->count_records_sql("SELECT COUNT('x')
2787                                      FROM {assignment_submissions}
2788                                     WHERE assignment = ? AND
2789                                           timemodified > 0 AND
2790                                           userid IN ($userlists)", array($cm->instance));
2794 /**
2795  * Return all assignment submissions by ENROLLED students (even empty)
2796  *
2797  * There are also assignment type methods get_submissions() wich in the default
2798  * implementation simply call this function.
2799  * @param $sort string optional field names for the ORDER BY in the sql query
2800  * @param $dir string optional specifying the sort direction, defaults to DESC
2801  * @return array The submission objects indexed by id
2802  */
2803 function assignment_get_all_submissions($assignment, $sort="", $dir="DESC") {
2804 /// Return all assignment submissions by ENROLLED students (even empty)
2805     global $CFG, $DB;
2807     if ($sort == "lastname" or $sort == "firstname") {
2808         $sort = "u.$sort $dir";
2809     } else if (empty($sort)) {
2810         $sort = "a.timemodified DESC";
2811     } else {
2812         $sort = "a.$sort $dir";
2813     }
2815     /* not sure this is needed at all since assignmenet already has a course define, so this join?
2816     $select = "s.course = '$assignment->course' AND";
2817     if ($assignment->course == SITEID) {
2818         $select = '';
2819     }*/
2821     return $DB->get_records_sql("SELECT a.*
2822                                    FROM {assignment_submissions} a, {user} u
2823                                   WHERE u.id = a.userid
2824                                         AND a.assignment = ?
2825                                ORDER BY $sort", array($assignment->id));
2829 /**
2830  * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
2831  * for the course (see resource).
2832  *
2833  * Given a course_module object, this function returns any "extra" information that may be needed
2834  * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
2835  *
2836  * @param $coursemodule object The coursemodule object (record).
2837  * @return object An object on information that the coures will know about (most noticeably, an icon).
2838  *
2839  */
2840 function assignment_get_coursemodule_info($coursemodule) {
2841     global $CFG, $DB;
2843     if (! $assignment = $DB->get_record('assignment', array('id'=>$coursemodule->instance), 'id, assignmenttype, name')) {
2844         return false;
2845     }
2847     $libfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2849     if (file_exists($libfile)) {
2850         require_once($libfile);
2851         $assignmentclass = "assignment_$assignment->assignmenttype";
2852         $ass = new $assignmentclass('staticonly');
2853         if ($result = $ass->get_coursemodule_info($coursemodule)) {
2854             return $result;
2855         } else {
2856             $info = new object();
2857             $info->name = $assignment->name;
2858             return $info;
2859         }
2861     } else {
2862         debugging('Incorrect assignment type: '.$assignment->assignmenttype);
2863         return false;
2864     }
2869 /// OTHER GENERAL FUNCTIONS FOR ASSIGNMENTS  ///////////////////////////////////////
2871 /**
2872  * Returns an array of installed assignment types indexed and sorted by name
2873  *
2874  * @return array The index is the name of the assignment type, the value its full name from the language strings
2875  */
2876 function assignment_types() {
2877     $types = array();
2878     $names = get_list_of_plugins('mod/assignment/type');
2879     foreach ($names as $name) {
2880         $types[$name] = get_string('type'.$name, 'assignment');
2881     }
2882     asort($types);
2883     return $types;
2886 /**
2887  * Executes upgrade scripts for assignment types when necessary
2888  */
2889 function assignment_upgrade_submodules() {
2890     global $CFG;
2892 /// Install/upgrade assignment types (it uses, simply, the standard plugin architecture)
2893     upgrade_plugins('assignment_type', 'mod/assignment/type', "$CFG->wwwroot/$CFG->admin/index.php");
2897 function assignment_print_overview($courses, &$htmlarray) {
2898     global $USER, $CFG, $DB;
2900     if (empty($courses) || !is_array($courses) || count($courses) == 0) {
2901         return array();
2902     }
2904     if (!$assignments = get_all_instances_in_courses('assignment',$courses)) {
2905         return;
2906     }
2908     // Do assignment_base::isopen() here without loading the whole thing for speed
2909     foreach ($assignments as $key => $assignment) {
2910         $time = time();
2911         if ($assignment->timedue) {
2912             if ($assignment->preventlate) {
2913                 $isopen = ($assignment->timeavailable <= $time && $time <= $assignment->timedue);
2914             } else {
2915                 $isopen = ($assignment->timeavailable <= $time);
2916             }
2917         }
2918         if (empty($isopen) || empty($assignment->timedue)) {
2919             unset($assignments[$key]);
2920         }
2921     }
2923     $strduedate = get_string('duedate', 'assignment');
2924     $strduedateno = get_string('duedateno', 'assignment');
2925     $strgraded = get_string('graded', 'assignment');
2926     $strnotgradedyet = get_string('notgradedyet', 'assignment');
2927     $strnotsubmittedyet = get_string('notsubmittedyet', 'assignment');
2928     $strsubmitted = get_string('submitted', 'assignment');
2929     $strassignment = get_string('modulename', 'assignment');
2930     $strreviewed = get_string('reviewed','assignment');
2932     foreach ($assignments as $assignment) {
2933         $str = '<div class="assignment overview"><div class="name">'.$strassignment. ': '.
2934                '<a '.($assignment->visible ? '':' class="dimmed"').
2935                'title="'.$strassignment.'" href="'.$CFG->wwwroot.
2936                '/mod/assignment/view.php?id='.$assignment->coursemodule.'">'.
2937                $assignment->name.'</a></div>';
2938         if ($assignment->timedue) {
2939             $str .= '<div class="info">'.$strduedate.': '.userdate($assignment->timedue).'</div>';
2940         } else {
2941             $str .= '<div class="info">'.$strduedateno.'</div>';
2942         }
2943         $context = get_context_instance(CONTEXT_MODULE, $assignment->coursemodule);
2944         if (has_capability('mod/assignment:grade', $context)) {
2946             // count how many people can submit
2947             $submissions = 0; // init
2948             if ($students = get_users_by_capability($context, 'mod/assignment:submit', '', '', '', '', 0, '', false)) {
2949                  foreach ($students as $student) {
2950                     if ($DB->record_exists_sql("SELECT id
2951                                                   FROM {assignment_submissions}
2952                                                  WHERE assignment = ? AND
2953                                                        userid = ? AND
2954                                                        teacher = 0 AND
2955                                                        timemarked = 0", array($assignment->id, $student->id))) {
2956                         $submissions++;
2957                     }
2958                 }
2959             }
2961             if ($submissions) {
2962                 $str .= get_string('submissionsnotgraded', 'assignment', $submissions);
2963             }
2964         } else {
2965             $sql = "SELECT *
2966                       FROM {assignment_submissions}
2967                      WHERE userid = ?
2968                        AND assignment = ?";
2969             $params = array($USER->id, $assignment->id);
2970             if ($submission = $DB->get_record_sql($sql, $params)) {
2971                 if ($submission->teacher == 0 && $submission->timemarked == 0) {
2972                     $str .= $strsubmitted . ', ' . $strnotgradedyet;
2973                 } else if ($submission->grade <= 0) {
2974                     $str .= $strsubmitted . ', ' . $strreviewed;
2975                 } else {
2976                     $str .= $strsubmitted . ', ' . $strgraded;
2977                 }
2978             } else {
2979                 $str .= $strnotsubmittedyet . ' ' . assignment_display_lateness(time(), $assignment->timedue);
2980             }
2981         }
2982         $str .= '</div>';
2983         if (empty($htmlarray[$assignment->course]['assignment'])) {
2984             $htmlarray[$assignment->course]['assignment'] = $str;
2985         } else {
2986             $htmlarray[$assignment->course]['assignment'] .= $str;
2987         }
2988     }
2991 function assignment_display_lateness($timesubmitted, $timedue) {
2992     if (!$timedue) {
2993         return '';
2994     }
2995     $time = $timedue - $timesubmitted;
2996     if ($time < 0) {
2997         $timetext = get_string('late', 'assignment', format_time($time));
2998         return ' (<span class="late">'.$timetext.'</span>)';
2999     } else {
3000         $timetext = get_string('early', 'assignment', format_time($time));
3001         return ' (<span class="early">'.$timetext.'</span>)';
3002     }
3005 function assignment_get_view_actions() {
3006     return array('view');
3009 function assignment_get_post_actions() {
3010     return array('upload');
3013 function assignment_get_types() {
3014     global $CFG;
3015     $types = array();
3017     $type = new object();
3018     $type->modclass = MOD_CLASS_ACTIVITY;
3019     $type->type = "assignment_group_start";
3020     $type->typestr = '--'.get_string('modulenameplural', 'assignment');
3021     $types[] = $type;
3023     $standardassignments = array('upload','online','uploadsingle','offline');
3024     foreach ($standardassignments as $assignmenttype) {
3025         $type = new object();
3026         $type->modclass = MOD_CLASS_ACTIVITY;
3027         $type->type = "assignment&amp;type=$assignmenttype";
3028         $type->typestr = get_string("type$assignmenttype", 'assignment');
3029         $types[] = $type;
3030     }
3032     /// Drop-in extra assignment types
3033     $assignmenttypes = get_list_of_plugins('mod/assignment/type');
3034     foreach ($assignmenttypes as $assignmenttype) {
3035         if (!empty($CFG->{'assignment_hide_'.$assignmenttype})) {  // Not wanted
3036             continue;
3037         }
3038         if (!in_array($assignmenttype, $standardassignments)) {
3039             $type = new object();
3040             $type->modclass = MOD_CLASS_ACTIVITY;
3041             $type->type = "assignment&amp;type=$assignmenttype";
3042             $type->typestr = get_string("type$assignmenttype", 'assignment');
3043             $types[] = $type;
3044         }
3045     }
3047     $type = new object();
3048     $type->modclass = MOD_CLASS_ACTIVITY;
3049     $type->type = "assignment_group_end";
3050     $type->typestr = '--';
3051     $types[] = $type;
3053     return $types;
3056 /**
3057  * Removes all grades from gradebook
3058  * @param int $courseid
3059  * @param string optional type
3060  */
3061 function assignment_reset_gradebook($courseid, $type='') {
3062     global $CFG, $DB;
3064     $params = array('courseid'=>$courseid);
3065     if ($type) {
3066         $type = "AND a.assignmenttype= :type";
3067         $params['type'] = $type;
3068     }
3070     $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
3071               FROM {assignment} a, {course_modules} cm, {modules} m
3072              WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id AND a.course=:courseid $type";
3074     if ($assignments = $DB->get_records_sql($sql, $params)) {
3075         foreach ($assignments as $assignment) {
3076             assignment_grade_item_update($assignment, 'reset');
3077         }
3078     }
3081 /**
3082  * This function is used by the reset_course_userdata function in moodlelib.
3083  * This function will remove all posts from the specified assignment
3084  * and clean up any related data.
3085  * @param $data the data submitted from the reset course.
3086  * @return array status array
3087  */
3088 function assignment_reset_userdata($data) {
3089     global $CFG;
3091     $status = array();
3093     foreach (get_list_of_plugins('mod/assignment/type') as $type) {
3094         require_once("$CFG->dirroot/mod/assignment/type/$type/assignment.class.php");
3095         $assignmentclass = "assignment_$type";
3096         $ass = new $assignmentclass();
3097         $status = array_merge($status, $ass->reset_userdata($data));
3098     }
3100     return $status;
3103 /**
3104  * Implementation of the function for printing the form elements that control
3105  * whether the course reset functionality affects the assignment.
3106  * @param $mform form passed by reference
3107  */
3108 function assignment_reset_course_form_definition(&$mform) {
3109     $mform->addElement('header', 'assignmentheader', get_string('modulenameplural', 'assignment'));
3110     $mform->addElement('advcheckbox', 'reset_assignment_submissions', get_string('deleteallsubmissions','assignment'));
3113 /**
3114  * Course reset form defaults.
3115  */
3116 function assignment_reset_course_form_defaults($course) {
3117     return array('reset_assignment_submissions'=>1);
3120 /**
3121  * Returns all other caps used in module
3122  */
3123 function assignment_get_extra_capabilities() {
3124     return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames');
3127 require_once($CFG->libdir . '/portfoliolib.php');
3128 class assignment_portfolio_caller extends portfolio_module_caller_base {
3130     private $assignment;
3131     private $assignmentfile;
3132     private $userid;
3133     private $file;
3135     public function __construct($callbackargs) {
3136         global $DB, $CFG;
3138         if (! $this->cm = get_coursemodule_from_id('assignment', $callbackargs['assignmentid'])) {
3139             print_error('invalidcoursemodule');
3140         }
3142         if (! $assignment = $DB->get_record("assignment", array("id"=>$this->cm->instance))) {
3143             print_error('invalidid', 'assignment');
3144         }
3146         $this->assignmentfile = $CFG->dirroot . '/mod/assignment/type/' . $assignment->assignmenttype . '/assignment.class.php';
3147         require_once($this->assignmentfile);
3148         $assignmentclass = "assignment_$assignment->assignmenttype";
3149         $this->assignment= new $assignmentclass($this->cm->id, $assignment, $this->cm);
3150         if (!$this->assignment->portfolio_exportable()) {
3151             print_error('notexportable', 'portfolio', $this->get_return_url());
3152         }
3153         $this->userid = $callbackargs['userid'];
3154         $this->file = (array_key_exists('file', $callbackargs)) ? $callbackargs['file'] : null;
3155     }
3157     public function prepare_package($tempdir) {
3158         global $CFG;
3159         if (is_callable(array($this->assignment, 'portfolio_prepare_package'))) {
3160             return $this->assignment->portfolio_prepare_package($tempdir);
3161         }
3162 error('TODO: covert');
3163         // default...
3164         $filearea = $CFG->dataroot . '/' . $this->assignment->file_area_name($this->userid);
3165         //@todo  penny this is a dreadful thing to have to call (replace with files api anyway)
3166         require_once($CFG->dirroot . '/backup/lib.php');
3167         if ($this->file) {
3168             return backup_copy_file($filearea . '/' . $this->file, $tempdir . '/' . $this->file);
3169         }
3170         return backup_copy_file($filearea, $tempdir);
3171     }
3173     public function get_sha1() {
3174         global $CFG;
3175         if (is_callable(array($this->assignment, 'portfolio_get_sha1'))) {
3176             return $this->assignment->portfolio_get_sha1();
3177         }
3179 error('TODO: covert');
3180         // default ...
3181         $filearea = $CFG->dataroot . '/' . $this->assignment->file_area_name($this->userid);
3182         if ($this->file) {
3183             return sha1_file($filearea . '/' . $this->file);
3184         }
3185         $sha1s = array();
3186         foreach (get_directory_list($filearea) as $file) {
3187             $sha1s[] = sha1_file($filearea . '/' . $file);
3188         }
3189         asort($sha1s);
3190         return sha1(implode('', $sha1s));
3192     }
3194     public function expected_time() {
3195         return PORTFOLIO_TIME_MODERATE; // @TODO check uploaded file size
3196     }
3198     public function check_permissions() {
3199         return has_capability('mod/assignment:export-upload-files', get_context_instance(CONTEXT_MODULE, $this->assignment->cm->id));
3200     }
3202     public function __wakeup() {
3203         global $CFG;
3204         if (empty($CFG)) {
3205             return true; // too early yet
3206         }
3207         require_once($this->assignmentfile);
3208         $this->assignment = unserialize(serialize($this->assignment));
3209     }
3211     public static function display_name() {
3212         return get_string('modulename', 'assignment');
3213     }
3216 /**
3217  * @param string $feature FEATURE_xx constant for requested feature
3218  * @return mixed True if module supports feature, null if doesn't know
3219  */
3220 function assignment_supports($feature) {
3221     switch($feature) {
3222         case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
3223         case FEATURE_GRADE_HAS_GRADE: return true;
3224         default: return null;
3225     }
3227 ?>