MDL-14589 initial file storage implementation, temporary file manager, migration...
[moodle.git] / mod / assignment / type / upload / assignment.class.php
1 <?php // $Id$
2 require_once($CFG->libdir . '/portfoliolib.php');
3 require_once($CFG->dirroot . '/mod/assignment/lib.php');
5 define('ASSIGNMENT_STATUS_SUBMITTED', 'submitted'); // student thinks it is finished
6 define('ASSIGNMENT_STATUS_CLOSED', 'closed');       // teacher prevents more submissions
8 /**
9  * Extend the base assignment class for assignments where you upload a single file
10  *
11  */
12 class assignment_upload extends assignment_base {
14     function assignment_upload($cmid='staticonly', $assignment=NULL, $cm=NULL, $course=NULL) {
15         parent::assignment_base($cmid, $assignment, $cm, $course);
16         $this->type = 'upload';
17     }
19     function view() {
20         global $USER;
22         require_capability('mod/assignment:view', $this->context);
24         add_to_log($this->course->id, 'assignment', 'view', "view.php?id={$this->cm->id}", $this->assignment->id, $this->cm->id);
26         $this->view_header();
28         if ($this->assignment->timeavailable > time()
29           and !has_capability('mod/assignment:grade', $this->context)      // grading user can see it anytime
30           and $this->assignment->var3) {                                   // force hiding before available date
31             print_simple_box_start('center', '', '', 0, 'generalbox', 'intro');
32             print_string('notavailableyet', 'assignment');
33             print_simple_box_end();
34         } else {
35             $this->view_intro();
36         }
38         $this->view_dates();
40         if (has_capability('mod/assignment:submit', $this->context)) {
41             $filecount = $this->count_user_files($USER->id);
42             $submission = $this->get_submission($USER->id);
44             $this->view_feedback();
46             if (!$this->drafts_tracked() or !$this->isopen() or $this->is_finalized($submission)) {
47                 print_heading(get_string('submission', 'assignment'), '', 3);
48             } else {
49                 print_heading(get_string('submissiondraft', 'assignment'), '', 3);
50             }
52             if ($filecount and $submission) {
53                 print_simple_box($this->print_user_files($USER->id, true), 'center');
54             } else {
55                 if (!$this->isopen() or $this->is_finalized($submission)) {
56                     print_simple_box(get_string('nofiles', 'assignment'), 'center');
57                 } else {
58                     print_simple_box(get_string('nofilesyet', 'assignment'), 'center');
59                 }
60             }
62             $this->view_upload_form();
64             if ($this->notes_allowed()) {
65                 print_heading(get_string('notes', 'assignment'), '', 3);
66                 $this->view_notes();
67             }
69             $this->view_final_submission();
70         }
71         $this->view_footer();
72     }
75     function view_feedback($submission=NULL) {
76         global $USER, $CFG, $DB;
77         require_once($CFG->libdir.'/gradelib.php');
79         if (!$submission) { /// Get submission for this assignment
80             $submission = $this->get_submission($USER->id);
81         }
83         if (empty($submission->timemarked)) {   /// Nothing to show, so print nothing
84             if ($this->count_responsefiles($USER->id)) {
85                 print_heading(get_string('responsefiles', 'assignment', $this->course->teacher), '', 3);
86                 $responsefiles = $this->print_responsefiles($USER->id, true);
87                 print_simple_box($responsefiles, 'center');
88             }
89             return;
90         }
92         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $USER->id);
93         $item = $grading_info->items[0];
94         $grade = $item->grades[$USER->id];
96         if ($grade->hidden or $grade->grade === false) { // hidden or error
97             return;
98         }
100         if ($grade->grade === null and empty($grade->str_feedback)) {   /// Nothing to show yet
101             return;
102         }
104         $graded_date = $grade->dategraded;
105         $graded_by   = $grade->usermodified;
107     /// We need the teacher info
108         if (!$teacher = $DB->get_record('user', array('id'=>$graded_by))) {
109             print_error('cannotfindteacher');
110         }
112     /// Print the feedback
113         print_heading(get_string('submissionfeedback', 'assignment'), '', 3);
115         echo '<table cellspacing="0" class="feedback">';
117         echo '<tr>';
118         echo '<td class="left picture">';
119         print_user_picture($teacher, $this->course->id, $teacher->picture);
120         echo '</td>';
121         echo '<td class="topic">';
122         echo '<div class="from">';
123         echo '<div class="fullname">'.fullname($teacher).'</div>';
124         echo '<div class="time">'.userdate($graded_date).'</div>';
125         echo '</div>';
126         echo '</td>';
127         echo '</tr>';
129         echo '<tr>';
130         echo '<td class="left side">&nbsp;</td>';
131         echo '<td class="content">';
132         if ($this->assignment->grade) {
133             echo '<div class="grade">';
134             echo get_string("grade").': '.$grade->str_long_grade;
135             echo '</div>';
136             echo '<div class="clearer"></div>';
137         }
139         echo '<div class="comment">';
140         echo $grade->str_feedback;
141         echo '</div>';
142         echo '</tr>';
144         echo '<tr>';
145         echo '<td class="left side">&nbsp;</td>';
146         echo '<td class="content">';
147         echo $this->print_responsefiles($USER->id, true);
148         echo '</tr>';
150         echo '</table>';
151     }
154     function view_upload_form() {
155         global $CFG, $USER;
157         $submission = $this->get_submission($USER->id);
159         if ($this->is_finalized($submission)) {
160             // no uploading
161             return;
162         }
164         if ($this->can_upload_file($submission)) {
165             $mform = new mod_assignment_upload_file_form('upload.php', $this);
166             $mform->display();
167         }
169     }
171     function view_notes() {
172         global $USER;
174         if ($submission = $this->get_submission($USER->id)
175           and !empty($submission->data1)) {
176             print_simple_box(format_text($submission->data1, FORMAT_HTML), 'center', '630px');
177         } else {
178             print_simple_box(get_string('notesempty', 'assignment'), 'center');
179         }
180         if ($this->can_update_notes($submission)) {
181             $options = array ('id'=>$this->cm->id, 'action'=>'editnotes');
182             echo '<div style="text-align:center">';
183             print_single_button('upload.php', $options, get_string('edit'), 'post', '_self', false);
184             echo '</div>';
185         }
186     }
188     function view_final_submission() {
189         global $CFG, $USER;
191         $submission = $this->get_submission($USER->id);
193         if ($this->isopen() and $this->can_finalize($submission)) {
194             //print final submit button
195             print_heading(get_string('submitformarking','assignment'), '', 3);
196             echo '<div style="text-align:center">';
197             echo '<form method="post" action="upload.php">';
198             echo '<fieldset class="invisiblefieldset">';
199             echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
200             echo '<input type="hidden" name="action" value="finalize" />';
201             echo '<input type="submit" name="formarking" value="'.get_string('sendformarking', 'assignment').'" />';
202             echo '</fieldset>';
203             echo '</form>';
204             echo '</div>';
205         } else if (!$this->isopen()) {
206             print_heading(get_string('nomoresubmissions','assignment'), '', 3);
208         } else if ($this->drafts_tracked() and $state = $this->is_finalized($submission)) {
209             if ($state == ASSIGNMENT_STATUS_SUBMITTED) {
210                 print_heading(get_string('submitedformarking','assignment'), '', 3);
211             } else {
212                 print_heading(get_string('nomoresubmissions','assignment'), '', 3);
213             }
214         } else {
215             //no submission yet
216         }
217     }
220     /**
221      * Return true if var3 == hide description till available day
222      *
223      *@return boolean
224      */
225     function description_is_hidden() {
226         return ($this->assignment->var3 && (time() <= $this->assignment->timeavailable));
227     }
229     function custom_feedbackform($submission, $return=false) {
230         global $CFG;
232         $mode         = optional_param('mode', '', PARAM_ALPHA);
233         $offset       = optional_param('offset', 0, PARAM_INT);
234         $forcerefresh = optional_param('forcerefresh', 0, PARAM_BOOL);
236         $mform = new mod_assignment_upload_response_form("$CFG->wwwroot/mod/assignment/upload.php", $this);
238         $mform->set_data(array('id'=>$this->cm->id, 'offset'=>$offset, 'forcerefresh'=>$forcerefresh, 'userid'=>$submission->userid, 'mode'=>$mode));
240         $output = get_string('responsefiles', 'assignment').': ';
242         ob_start();
243         $mform->display();
244         $output = ob_get_clean();
246         if ($forcerefresh) {
247             $output .= $this->update_main_listing($submission);
248         }
250         $responsefiles = $this->print_responsefiles($submission->userid, true);
251         if (!empty($responsefiles)) {
252             $output .= $responsefiles;
253         }
255         if ($return) {
256             return $output;
257         }
258         echo $output;
259         return;
260     }
263     function print_student_answer($userid, $return=false){
264         global $CFG;
266         $submission = $this->get_submission($userid);
268         $output = '';
270         if ($this->drafts_tracked() and $this->isopen() and !$this->is_finalized($submission)) {
271             $output .= '<strong>'.get_string('draft', 'assignment').':</strong> ';
272         }
274         if ($this->notes_allowed() and !empty($submission->data1)) {
275             $output .= link_to_popup_window ('/mod/assignment/type/upload/notes.php?id='.$this->cm->id.'&amp;userid='.$userid,
276                                             'notes'.$userid, get_string('notes', 'assignment'), 500, 780, get_string('notes', 'assignment'), 'none', true, 'notesbutton'.$userid);
277             $output .= '&nbsp;';
278         }
280         $fs = get_file_storage();
281         $browser = get_file_browser();
283         if ($files = $fs->get_area_files($this->context->id, 'assignment_submission', $userid, "timemodified", false)) {
285             foreach ($files as $file) {
286                 $filename = $file->get_filename();
287                 $found = true;
288                 $mimetype = $file->get_mimetype();
289                 $icon = mimeinfo_from_type('icon', $mimetype);
290                 $path = $browser->encodepath($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/assignment_submission/'.$userid.'/'.$filename);
291                 $output .= '<a href="'.$path.'" ><img class="icon" src="'.$CFG->pixpath.'/f/'.$icon.'" alt="'.$icon.'" />'.s($filename).'</a>&nbsp;';
292     
293             }
295         }
296         $output = '<div class="files">'.$output.'</div>';
297         $output .= '<br />';
299         return $output;
300     }
303     /**
304      * Produces a list of links to the files uploaded by a user
305      *
306      * @param $userid int optional id of the user. If 0 then $USER->id is used.
307      * @param $return boolean optional defaults to false. If true the list is returned rather than printed
308      * @return string optional
309      */
310     function print_user_files($userid=0, $return=false) {
311         global $CFG, $USER;
313         $mode    = optional_param('mode', '', PARAM_ALPHA);
314         $offset  = optional_param('offset', 0, PARAM_INT);
316         if (!$userid) {
317             if (!isloggedin()) {
318                 return '';
319             }
320             $userid = $USER->id;
321         }
323         $output = '';
325         $submission = $this->get_submission($userid);
327         $candelete = $this->can_delete_files($submission);
328         $strdelete   = get_string('delete');
330         if ($this->drafts_tracked() and $this->isopen() and !$this->is_finalized($submission) and !empty($mode)) {                 // only during grading
331             $output .= '<strong>'.get_string('draft', 'assignment').':</strong><br />';
332         }
334         if ($this->notes_allowed() and !empty($submission->data1) and !empty($mode)) { // only during grading
336             $npurl = $CFG->wwwroot."/mod/assignment/type/upload/notes.php?id={$this->cm->id}&amp;userid=$userid&amp;offset=$offset&amp;mode=single";
337             $output .= '<a href="'.$npurl.'">'.get_string('notes', 'assignment').'</a><br />';
339         }
341         $fs = get_file_storage();
342         $browser = get_file_browser();
344         if ($files = $fs->get_area_files($this->context->id, 'assignment_submission', $userid, "timemodified", false)) {
345             $p = array(
346                 'userid' => $userid,
347                 'assignmentid' => $this->cm->id,
348             );
349             foreach ($files as $file) {
350                 $filename = $file->get_filename();
351                 $mimetype = $file->get_mimetype();
352                 $icon = mimeinfo_from_type('icon', $mimetype);
353                 $path = $browser->encodepath($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/assignment_submission/'.$userid.'/'.$filename);
354                 $output .= '<a href="'.$path.'" ><img src="'.$CFG->pixpath.'/f/'.$icon.'" class="icon" alt="'.$icon.'" />'.s($filename).'</a>';
355     
356                 if ($candelete) {
357                     $delurl  = "$CFG->wwwroot/mod/assignment/delete.php?id={$this->cm->id}&amp;file=".rawurlencode($filename)."&amp;userid={$submission->userid}&amp;mode=$mode&amp;offset=$offset";
358     
359                     $output .= '<a href="'.$delurl.'">&nbsp;'
360                               .'<img title="'.$strdelete.'" src="'.$CFG->pixpath.'/t/delete.gif" class="iconsmall" alt="" /></a> ';
361                 }
362     
363                 if (true) { // @todo penny replace with capability check
364                     $p['file'] = $filename;
365                     $output .= portfolio_add_button('assignment_portfolio_caller', $p, '/mod/assignment/lib.php', false, true);
366                 }
367                 $output .= '<br />';
368             }
369             if (true) { //@todo penny replace with check capability
370                 unset($p['file']);// for all files
371                 $output .= '<br />' . portfolio_add_button('assignment_portfolio_caller', $p, '/mod/assignment/lib.php', true, true);
372             }
373         }
375         if ($this->drafts_tracked() and $this->isopen() and has_capability('mod/assignment:grade', $this->context) and $mode != '') { // we do not want it on view.php page
376             if ($this->can_unfinalize($submission)) {
377                 $options = array ('id'=>$this->cm->id, 'userid'=>$userid, 'action'=>'unfinalize', 'mode'=>$mode, 'offset'=>$offset);
378                 $output .= print_single_button('upload.php', $options, get_string('unfinalize', 'assignment'), 'post', '_self', true);
379             } else if ($this->can_finalize($submission)) {
380                 $options = array ('id'=>$this->cm->id, 'userid'=>$userid, 'action'=>'finalizeclose', 'mode'=>$mode, 'offset'=>$offset);
381                 $output .= print_single_button('upload.php', $options, get_string('finalize', 'assignment'), 'post', '_self', true);
382             }
383         }
385         $output = '<div class="files">'.$output.'</div>';
387         if ($return) {
388             return $output;
389         }
390         echo $output;
391     }
393     function print_responsefiles($userid, $return=false) {
394         global $CFG, $USER;
396         $mode    = optional_param('mode', '', PARAM_ALPHA);
397         $offset  = optional_param('offset', 0, PARAM_INT);
399         $output = '';
401         $candelete = $this->can_manage_responsefiles();
402         $strdelete   = get_string('delete');
404         $fs = get_file_storage();
405         $browser = get_file_browser();
407         if ($files = $fs->get_area_files($this->context->id, 'assignment_response', $userid, "timemodified", false)) {
408             foreach ($files as $file) {
409                 $filename = $file->get_filename();
410                 $found = true;
411                 $mimetype = $file->get_mimetype();
412                 $icon = mimeinfo_from_type('icon', $mimetype);
413                 $path = $browser->encodepath($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/assignment_response/'.$userid.'/'.$filename);
415                 $output .= '<a href="'.$path.'" ><img src="'.$CFG->pixpath.'/f/'.$icon.'" alt="'.$icon.'" />'.$filename.'</a>';
417                 if ($candelete) {
418                     $delurl  = "$CFG->wwwroot/mod/assignment/delete.php?id={$this->cm->id}&amp;file=".rawurlencode($filename)."&amp;userid=$userid&amp;mode=$mode&amp;offset=$offset&amp;action=response";
420                     $output .= '<a href="'.$delurl.'">&nbsp;'
421                               .'<img title="'.$strdelete.'" src="'.$CFG->pixpath.'/t/delete.gif" class="iconsmall" alt=""/></a> ';
422                 }
424                 $output .= '&nbsp;';
425             }
427             $output = '<div class="responsefiles">'.$output.'</div>';
428         }
430         if ($return) {
431             return $output;
432         }
433         echo $output;
434     }
437     function upload() {
438         $action = required_param('action', PARAM_ALPHA);
440         switch ($action) {
441             case 'finalize':
442                 $this->finalize();
443                 break;
444             case 'finalizeclose':
445                 $this->finalizeclose();
446                 break;
447             case 'unfinalize':
448                 $this->unfinalize();
449                 break;
450             case 'uploadresponse':
451                 $this->upload_responsefile();
452                 break;
453             case 'uploadfile':
454                 $this->upload_file();
455             case 'savenotes':
456             case 'editnotes':
457                 $this->upload_notes();
458             default:
459                 print_error('unknowuploadaction', '', '', $action);
460         }
461     }
463     function upload_notes() {
464         global $CFG, $USER;
466         $action = required_param('action', PARAM_ALPHA);
468         $returnurl = 'view.php?id='.$this->cm->id;
470         $mform = new mod_assignment_upload_notes_form();
472         $defaults = new object();
473         $defaults->id = $this->cm->id;
475         if ($submission = $this->get_submission($USER->id)) {
476             $defaults->text = $submission->data1;
477         } else {
478             $defaults->text = '';
479         }
481         $mform->set_data($defaults);
483         if ($mform->is_cancelled()) {
484             redirect('view.php?id='.$this->cm->id);
485         }
487         if (!$this->can_update_notes($submission)) {
488             $this->view_header(get_string('upload'));
489             notify(get_string('uploaderror', 'assignment'));
490             print_continue($returnurl);
491             $this->view_footer();
492             die;
493         }
495         if ($data = $mform->get_data() and $action == 'savenotes') {
496             $submission = $this->get_submission($USER->id, true); // get or create submission
497             $updated = new object();
498             $updated->id           = $submission->id;
499             $updated->timemodified = time();
500             $updated->data1        = $data->text;
502             if ($DB->update_record('assignment_submissions', $updated)) {
503                 add_to_log($this->course->id, 'assignment', 'upload', 'view.php?a='.$this->assignment->id, $this->assignment->id, $this->cm->id);
504                 redirect($returnurl);
505                 $submission = $this->get_submission($USER->id);
506                 $this->update_grade($submission);
508             } else {
509                 $this->view_header(get_string('notes', 'assignment'));
510                 notify(get_string('notesupdateerror', 'assignment'));
511                 print_continue($returnurl);
512                 $this->view_footer();
513                 die;
514             }
515         }
517         /// show notes edit form
518         $this->view_header(get_string('notes', 'assignment'));
520         print_heading(get_string('notes', 'assignment'), '');
522         $mform->display();
524         $this->view_footer();
525         die;
526     }
528     function upload_responsefile() {
529         global $CFG, $USER;
531         $userid = required_param('userid', PARAM_INT);
532         $mode   = required_param('mode', PARAM_ALPHA);
533         $offset = required_param('offset', PARAM_INT);
535         $returnurl = "submissions.php?id={$this->cm->id}&amp;userid=$userid&amp;mode=$mode&amp;offset=$offset";
537         $mform = new mod_assignment_upload_response_form(null, $this);
538         if ($mform->get_data() and $this->can_manage_responsefiles()) {
539             $fs = get_file_storage();
540             $filename = $mform->get_new_filename('newfile');
541             if ($filename !== false) {
542                 if (!$fs->file_exists($this->context->id, 'assignment_response', $userid, '/', $filename)) {
543                     if ($file = $mform->save_stored_file('newfile', $this->context->id, 'assignment_response', $userid, '/', $filename, false, $USER->id)) {
544                         redirect($returnurl);
545                     }
546                 }
547             }
548         }
549         print_header(get_string('upload'));
550         notify(get_string('uploaderror', 'assignment'));
551         print_continue($returnurl);
552         print_footer('none');
553         die;
554     }
556     function upload_file() {
557         global $CFG, $USER, $DB;
559         $returnurl = 'view.php?id='.$this->cm->id;
561         $filecount = $this->count_user_files($USER->id);
562         $submission = $this->get_submission($USER->id);
564         if (!$this->can_upload_file($submission)) {
565             $this->view_header(get_string('upload'));
566             notify(get_string('uploaderror', 'assignment'));
567             print_continue($returnurl);
568             $this->view_footer();
569             die;
570         }
572         $mform = new mod_assignment_upload_file_form('upload.php', $this);
573         if ($mform->get_data()) {
574             $fs = get_file_storage();
575             $filename = $mform->get_new_filename('newfile');
576             if ($filename !== false) {
577                 if (!$fs->file_exists($this->context->id, 'assignment_submission', $USER->id, '/', $filename)) {
578                     if ($file = $mform->save_stored_file('newfile', $this->context->id, 'assignment_submission', $USER->id, '/', $filename, false, $USER->id)) {
579                         $submission = $this->get_submission($USER->id, true); //create new submission if needed
580                         $submission->timemodified = time();
581                         if ($DB->update_record('assignment_submissions', $submission)) {
582                             add_to_log($this->course->id, 'assignment', 'upload',
583                                     'view.php?a='.$this->assignment->id, $this->assignment->id, $this->cm->id);
584                             $this->update_grade($submission);
585                             if (!$this->drafts_tracked()) {
586                                 $this->email_teachers($submission);
587                             }
588                             redirect('view.php?id='.$this->cm->id);
589                         } else {
590                             $file->delete();
591                         }
592                     }
593                 }
594             }
595         }
597         $this->view_header(get_string('upload'));
598         notify(get_string('uploaderror', 'assignment'));
599         print_continue($returnurl);
600         $this->view_footer();
601         die;
602     }
604     function send_file($filearea, $args) {
605         global $CFG, $DB, $USER;
606         require_once($CFG->libdir.'/filelib.php');
608         require_login($this->course, false, $this->cm);
610         $userid = (int)array_shift($args);
611         $relativepath = '/'.implode('/', $args);
612         $fullpath = $this->context->id.$filearea.$userid.$relativepath;
614         $fs = get_file_storage();
616         if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
617             return false;
618         }
620         if ($filearea === 'assignment_submission') {
621             if ($USER->id != $userid and !has_capability('mod/assignment:grade', $this->context)) {
622                 return false;
623             }
625         } else if ($filearea === 'assignment_response') {
626             if ($USER->id != $userid and !has_capability('mod/assignment:grade', $this->context)) {
627                 return false;
628             }
630         } else {
631             return false;
632         }
634         send_stored_file($file, 0, 0, true); // downlaod MUST be forced - security!
635     }
637     function finalize() {
638         global $USER, $DB;
640         $confirm    = optional_param('confirm', 0, PARAM_BOOL);
641         $returnurl  = 'view.php?id='.$this->cm->id;
642         $submission = $this->get_submission($USER->id);
644         if (!$this->can_finalize($submission)) {
645             redirect($returnurl); // probably already graded, redirect to assignment page, the reason should be obvious
646         }
648         if (!data_submitted() or !$confirm) {
649             $optionsno = array('id'=>$this->cm->id);
650             $optionsyes = array ('id'=>$this->cm->id, 'confirm'=>1, 'action'=>'finalize');
651             $this->view_header(get_string('submitformarking', 'assignment'));
652             print_heading(get_string('submitformarking', 'assignment'));
653             notice_yesno(get_string('onceassignmentsent', 'assignment'), 'upload.php', 'view.php', $optionsyes, $optionsno, 'post', 'get');
654             $this->view_footer();
655             die;
657         }
658         $updated = new object();
659         $updated->id           = $submission->id;
660         $updated->data2        = ASSIGNMENT_STATUS_SUBMITTED;
661         $updated->timemodified = time();
663         if ($DB->update_record('assignment_submissions', $updated)) {
664             add_to_log($this->course->id, 'assignment', 'upload', //TODO: add finalize action to log
665                     'view.php?a='.$this->assignment->id, $this->assignment->id, $this->cm->id);
666             $submission = $this->get_submission($USER->id);
667             $this->update_grade($submission);
668             $this->email_teachers($submission);
669         } else {
670             $this->view_header(get_string('submitformarking', 'assignment'));
671             notify(get_string('finalizeerror', 'assignment'));
672             print_continue($returnurl);
673             $this->view_footer();
674             die;
675         }
676         redirect($returnurl);
677     }
679     function finalizeclose() {
680         global $DB;
682         $userid    = optional_param('userid', 0, PARAM_INT);
683         $mode      = required_param('mode', PARAM_ALPHA);
684         $offset    = required_param('offset', PARAM_INT);
685         $returnurl = "submissions.php?id={$this->cm->id}&amp;userid=$userid&amp;mode=$mode&amp;offset=$offset&amp;forcerefresh=1";
687         // create but do not add student submission date
688         $submission = $this->get_submission($userid, true, true);
690         if (!data_submitted() or !$this->can_finalize($submission)) {
691             redirect($returnurl); // probably closed already
692         }
694         $updated = new object();
695         $updated->id    = $submission->id;
696         $updated->data2 = ASSIGNMENT_STATUS_CLOSED;
698         if ($DB->update_record('assignment_submissions', $updated)) {
699             add_to_log($this->course->id, 'assignment', 'upload', //TODO: add finalize action to log
700                     'view.php?a='.$this->assignment->id, $this->assignment->id, $this->cm->id);
701             $submission = $this->get_submission($userid, false, true);
702             $this->update_grade($submission);
703         }
704         redirect($returnurl);
705     }
707     function unfinalize() {
708         global $DB;
710         $userid = required_param('userid', PARAM_INT);
711         $mode   = required_param('mode', PARAM_ALPHA);
712         $offset = required_param('offset', PARAM_INT);
714         $returnurl = "submissions.php?id={$this->cm->id}&amp;userid=$userid&amp;mode=$mode&amp;offset=$offset&amp;forcerefresh=1";
716         if (data_submitted()
717           and $submission = $this->get_submission($userid)
718           and $this->can_unfinalize($submission)) {
720             $updated = new object();
721             $updated->id = $submission->id;
722             $updated->data2 = '';
723             if ($DB->update_record('assignment_submissions', $updated)) {
724                 //TODO: add unfinalize action to log
725                 add_to_log($this->course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->assignment->id, $this->assignment->id, $this->cm->id);
726                 $submission = $this->get_submission($userid);
727                 $this->update_grade($submission);
728             } else {
729                 $this->view_header(get_string('submitformarking', 'assignment'));
730                 notify(get_string('unfinalizeerror', 'assignment'));
731                 print_continue($returnurl);
732                 $this->view_footer();
733                 die;
734             }
735         }
736         redirect($returnurl);
737     }
740     function delete() {
741         $action   = optional_param('action', '', PARAM_ALPHA);
743         switch ($action) {
744             case 'response':
745                 $this->delete_responsefile();
746                 break;
747             default:
748                 $this->delete_file();
749         }
750         die;
751     }
754     function delete_responsefile() {
755         global $CFG;
757         $file     = required_param('file', PARAM_FILE);
758         $userid   = required_param('userid', PARAM_INT);
759         $mode     = required_param('mode', PARAM_ALPHA);
760         $offset   = required_param('offset', PARAM_INT);
761         $confirm  = optional_param('confirm', 0, PARAM_BOOL);
763         $returnurl = "submissions.php?id={$this->cm->id}&amp;userid=$userid&amp;mode=$mode&amp;offset=$offset";
765         if (!$this->can_manage_responsefiles()) {
766            redirect($returnurl);
767         }
769         $urlreturn = 'submissions.php';
770         $optionsreturn = array('id'=>$this->cm->id, 'offset'=>$offset, 'mode'=>$mode, 'userid'=>$userid);
772         if (!data_submitted() or !$confirm) {
773             $optionsyes = array ('id'=>$this->cm->id, 'file'=>$file, 'userid'=>$userid, 'confirm'=>1, 'action'=>'response', 'mode'=>$mode, 'offset'=>$offset);
774             print_header(get_string('delete'));
775             print_heading(get_string('delete'));
776             notice_yesno(get_string('confirmdeletefile', 'assignment', $file), 'delete.php', $urlreturn, $optionsyes, $optionsreturn, 'post', 'get');
777             print_footer('none');
778             die;
779         }
781         $fs = get_file_storage();
782         if ($file = $fs->get_file($this->context->id, 'assignment_submission', $userid, '/', $file)) {
783             if ($file->delete()) {
784                 redirect($returnurl);
785             }
786         }
788         // print delete error
789         print_header(get_string('delete'));
790         notify(get_string('deletefilefailed', 'assignment'));
791         print_continue($returnurl);
792         print_footer('none');
793         die;
795     }
798     function delete_file() {
799         global $CFG, $DB;
801         $file     = required_param('file', PARAM_FILE);
802         $userid   = required_param('userid', PARAM_INT);
803         $confirm  = optional_param('confirm', 0, PARAM_BOOL);
804         $mode     = optional_param('mode', '', PARAM_ALPHA);
805         $offset   = optional_param('offset', 0, PARAM_INT);
807         require_login($this->course->id, false, $this->cm);
809         if (empty($mode)) {
810             $urlreturn = 'view.php';
811             $optionsreturn = array('id'=>$this->cm->id);
812             $returnurl = 'view.php?id='.$this->cm->id;
813         } else {
814             $urlreturn = 'submissions.php';
815             $optionsreturn = array('id'=>$this->cm->id, 'offset'=>$offset, 'mode'=>$mode, 'userid'=>$userid);
816             $returnurl = "submissions.php?id={$this->cm->id}&amp;offset=$offset&amp;mode=$mode&amp;userid=$userid";
817         }
819         if (!$submission = $this->get_submission($userid) // incorrect submission
820           or !$this->can_delete_files($submission)) {     // can not delete
821             $this->view_header(get_string('delete'));
822             notify(get_string('cannotdeletefiles', 'assignment'));
823             print_continue($returnurl);
824             $this->view_footer();
825             die;
826         }
828         if (!data_submitted() or !$confirm) {
829             $optionsyes = array ('id'=>$this->cm->id, 'file'=>$file, 'userid'=>$userid, 'confirm'=>1, 'sesskey'=>sesskey(), 'mode'=>$mode, 'offset'=>$offset);
830             if (empty($mode)) {
831                 $this->view_header(get_string('delete'));
832             } else {
833                 print_header(get_string('delete'));
834             }
835             print_heading(get_string('delete'));
836             notice_yesno(get_string('confirmdeletefile', 'assignment', $file), 'delete.php', $urlreturn, $optionsyes, $optionsreturn, 'post', 'get');
837             if (empty($mode)) {
838                 $this->view_footer();
839             } else {
840                 print_footer('none');
841             }
842             die;
843         }
845         $fs = get_file_storage();
846         if ($file = $fs->get_file($this->context->id, 'assignment_submission', $userid, '/', $file)) {
847             if ($file->delete()) {
848                 $submission->timemodified = time();
849                 if ($DB->update_record('assignment_submissions', $submission)) {
850                     add_to_log($this->course->id, 'assignment', 'upload', //TODO: add delete action to log
851                             'view.php?a='.$this->assignment->id, $this->assignment->id, $this->cm->id);
852                     $this->update_grade($submission);
853                 }
854                 redirect($returnurl);
855             }
856         }
858         // print delete error
859         if (empty($mode)) {
860             $this->view_header(get_string('delete'));
861         } else {
862             print_header(get_string('delete'));
863         }
864         notify(get_string('deletefilefailed', 'assignment'));
865         print_continue($returnurl);
866         if (empty($mode)) {
867             $this->view_footer();
868         } else {
869             print_footer('none');
870         }
871         die;
872     }
875     function can_upload_file($submission) {
876         global $USER;
878         if (has_capability('mod/assignment:submit', $this->context)           // can submit
879           and $this->isopen()                                                 // assignment not closed yet
880           and (empty($submission) or $submission->userid == $USER->id)        // his/her own submission
881           and $this->count_user_files($USER->id) < $this->assignment->var1    // file limit not reached
882           and !$this->is_finalized($submission)) {                            // no uploading after final submission
883             return true;
884         } else {
885             return false;
886         }
887     }
889     function can_manage_responsefiles() {
890         if (has_capability('mod/assignment:grade', $this->context)) {
891             return true;
892         } else {
893             return false;
894         }
895     }
897     function can_delete_files($submission) {
898         global $USER;
900         if (has_capability('mod/assignment:grade', $this->context)) {
901             return true;
902         }
904         if (has_capability('mod/assignment:submit', $this->context)
905           and $this->isopen()                                      // assignment not closed yet
906           and $this->assignment->resubmit                          // deleting allowed
907           and $USER->id == $submission->userid                     // his/her own submission
908           and !$this->is_finalized($submission)) {                 // no deleting after final submission
909             return true;
910         } else {
911             return false;
912         }
913     }
915     function drafts_tracked() {
916         return !empty($this->assignment->var4);
917     }
919     /**
920      * Returns submission status
921      * @param object $submission - may be empty
922      * @return string submission state - empty, ASSIGNMENT_STATUS_SUBMITTED or ASSIGNMENT_STATUS_CLOSED
923      */
924     function is_finalized($submission) {
925         if (!$this->drafts_tracked()) {
926             return '';
928         } else if (empty($submission)) {
929             return '';
931         } else if ($submission->data2 == ASSIGNMENT_STATUS_SUBMITTED or $submission->data2 == ASSIGNMENT_STATUS_CLOSED) {
932             return $submission->data2;
934         } else {
935             return '';
936         }
937     }
939     function can_unfinalize($submission) {
940         if (!$this->drafts_tracked()) {
941             return false;
942         }
943         if (has_capability('mod/assignment:grade', $this->context)
944           and $this->isopen()
945           and $this->is_finalized($submission)) {
946             return true;
947         } else {
948             return false;
949         }
950     }
952     function can_finalize($submission) {
953         global $USER;
954         if (!$this->drafts_tracked()) {
955             return false;
956         }
958                 if ($this->is_finalized($submission)) {
959                     return false;
960                 }
962         if (has_capability('mod/assignment:grade', $this->context)) {
963             return true;
965         } else if (has_capability('mod/assignment:submit', $this->context)    // can submit
966           and $this->isopen()                                                 // assignment not closed yet
967           and !empty($submission)                                             // submission must exist
968           and $submission->userid == $USER->id                                // his/her own submission
969           and ($this->count_user_files($USER->id)
970             or ($this->notes_allowed() and !empty($submission->data1)))) {    // something must be submitted
972             return true;
973         } else {
974             return false;
975         }
976     }
978     function can_update_notes($submission) {
979         global $USER;
981         if (has_capability('mod/assignment:submit', $this->context)
982           and $this->notes_allowed()                                          // notesd must be allowed
983           and $this->isopen()                                                 // assignment not closed yet
984           and (empty($submission) or $USER->id == $submission->userid)        // his/her own submission
985           and !$this->is_finalized($submission)) {                            // no updateingafter final submission
986             return true;
987         } else {
988             return false;
989         }
990     }
992     function notes_allowed() {
993         return (boolean)$this->assignment->var2;
994     }
996     function count_responsefiles($userid) {
997         $fs = get_file_storage();
998         $files = $fs->get_area_files($this->context->id, 'assignment_response', $userid, "id", false);
999         return count($files);
1000     }
1002     function setup_elements(&$mform) {
1003         global $CFG, $COURSE;
1005         $ynoptions = array( 0 => get_string('no'), 1 => get_string('yes'));
1007         $choices = get_max_upload_sizes($CFG->maxbytes, $COURSE->maxbytes);
1008         $choices[0] = get_string('courseuploadlimit') . ' ('.display_size($COURSE->maxbytes).')';
1009         $mform->addElement('select', 'maxbytes', get_string('maximumsize', 'assignment'), $choices);
1010         $mform->setDefault('maxbytes', $CFG->assignment_maxbytes);
1012         $mform->addElement('select', 'resubmit', get_string("allowdeleting", "assignment"), $ynoptions);
1013         $mform->setHelpButton('resubmit', array('allowdeleting', get_string('allowdeleting', 'assignment'), 'assignment'));
1014         $mform->setDefault('resubmit', 1);
1016         $options = array();
1017         for($i = 1; $i <= 20; $i++) {
1018             $options[$i] = $i;
1019         }
1020         $mform->addElement('select', 'var1', get_string("allowmaxfiles", "assignment"), $options);
1021         $mform->setHelpButton('var1', array('allowmaxfiles', get_string('allowmaxfiles', 'assignment'), 'assignment'));
1022         $mform->setDefault('var1', 3);
1024         $mform->addElement('select', 'var2', get_string("allownotes", "assignment"), $ynoptions);
1025         $mform->setHelpButton('var2', array('allownotes', get_string('allownotes', 'assignment'), 'assignment'));
1026         $mform->setDefault('var2', 0);
1028         $mform->addElement('select', 'var3', get_string("hideintro", "assignment"), $ynoptions);
1029         $mform->setHelpButton('var3', array('hideintro', get_string('hideintro', 'assignment'), 'assignment'));
1030         $mform->setDefault('var3', 0);
1032         $mform->addElement('select', 'emailteachers', get_string("emailteachers", "assignment"), $ynoptions);
1033         $mform->setHelpButton('emailteachers', array('emailteachers', get_string('emailteachers', 'assignment'), 'assignment'));
1034         $mform->setDefault('emailteachers', 0);
1036         $mform->addElement('select', 'var4', get_string("trackdrafts", "assignment"), $ynoptions);
1037         $mform->setHelpButton('var4', array('trackdrafts', get_string('trackdrafts', 'assignment'), 'assignment'));
1038         $mform->setDefault('trackdrafts', 1);
1040     }
1042     function portfolio_exportable() {
1043         return true;
1044     }
1048 class mod_assignment_upload_notes_form extends moodleform {
1049     function definition() {
1050         $mform = $this->_form;
1052         // visible elements
1053         $mform->addElement('htmleditor', 'text', get_string('notes', 'assignment'), array('cols'=>85, 'rows'=>30));
1054         $mform->setType('text', PARAM_RAW); // to be cleaned before display
1055         $mform->setHelpButton('text', array('reading', 'writing'), false, 'editorhelpbutton');
1057         // hidden params
1058         $mform->addElement('hidden', 'id', 0);
1059         $mform->setType('id', PARAM_INT);
1060         $mform->addElement('hidden', 'action', 'savenotes');
1061         $mform->setType('action', PARAM_ALPHA);
1063         // buttons
1064         $this->add_action_buttons();
1065     }
1068 class mod_assignment_upload_response_form extends moodleform {
1069     function definition() {
1070         $mform = $this->_form;
1071         $instance = $this->_customdata;
1073         // visible elements
1074         $mform->addElement('file', 'newfile', get_string('uploadafile'));
1076         // hidden params
1077         $mform->addElement('hidden', 'id', $instance->cm->id);
1078         $mform->setType('id', PARAM_INT);
1079         $mform->addElement('hidden', 'action', 'uploadresponse');
1080         $mform->setType('action', PARAM_ALPHA);
1081         $mform->addElement('hidden', 'mode');
1082         $mform->setType('mode', PARAM_ALPHA);
1083         $mform->addElement('hidden', 'offset');
1084         $mform->setType('offset', PARAM_INT);
1085         $mform->addElement('hidden', 'forcerefresh');
1086         $mform->setType('forcerefresh', PARAM_INT);
1087         $mform->addElement('hidden', 'userid');
1088         $mform->setType('userid', PARAM_INT);
1090         // buttons
1091         $this->add_action_buttons(false, get_string('uploadthisfile'));
1092     }
1097 ?>