Assignment MDL-7206 - download all submissions as a zip - finally pushing this into...
[moodle.git] / mod / assignment / type / upload / assignment.class.php
1 <?php
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, $OUTPUT;
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             echo $OUTPUT->box_start('generalbox boxaligncenter', 'intro');
32             print_string('notavailableyet', 'assignment');
33             echo $OUTPUT->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                 echo $OUTPUT->heading(get_string('submission', 'assignment'), 3);
48             } else {
49                 echo $OUTPUT->heading(get_string('submissiondraft', 'assignment'), 3);
50             }
52             if ($filecount and $submission) {
53                 echo $OUTPUT->box($this->print_user_files($USER->id, true), 'generalbox boxaligncenter');
54             } else {
55                 if (!$this->isopen() or $this->is_finalized($submission)) {
56                     echo $OUTPUT->box(get_string('nofiles', 'assignment'), 'generalbox boxaligncenter');
57                 } else {
58                     echo $OUTPUT->box(get_string('nofilesyet', 'assignment'), 'generalbox boxaligncenter');
59                 }
60             }
62             $this->view_upload_form();
64             if ($this->notes_allowed()) {
65                 echo $OUTPUT->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, $OUTPUT;
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                 echo $OUTPUT->heading(get_string('responsefiles', 'assignment'), 3);
86                 $responsefiles = $this->print_responsefiles($USER->id, true);
87                 echo $OUTPUT->box($responsefiles, 'generalbox boxaligncenter');
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         echo $OUTPUT->heading(get_string('submissionfeedback', 'assignment'), 3);
115         echo '<table cellspacing="0" class="feedback">';
117         echo '<tr>';
118         echo '<td class="left picture">';
119         echo $OUTPUT->user_picture($teacher);
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, $OUTPUT;
174         if ($submission = $this->get_submission($USER->id)
175           and !empty($submission->data1)) {
176             echo $OUTPUT->box(format_text($submission->data1, FORMAT_HTML), 'generalbox boxaligncenter boxwidthwide');
177         } else {
178             echo $OUTPUT->box(get_string('notesempty', 'assignment'), 'generalbox boxaligncenter');
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             echo $OUTPUT->single_button(new moodle_url('upload.php', $options), get_string('edit'));
184             echo '</div>';
185         }
186     }
188     function view_final_submission() {
189         global $CFG, $USER, $OUTPUT;
191         $submission = $this->get_submission($USER->id);
193         if ($this->isopen() and $this->can_finalize($submission)) {
194             //print final submit button
195             echo $OUTPUT->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="sesskey" value="'.sesskey().'" />';
201             echo '<input type="hidden" name="action" value="finalize" />';
202             echo '<input type="submit" name="formarking" value="'.get_string('sendformarking', 'assignment').'" />';
203             echo '</fieldset>';
204             echo '</form>';
205             echo '</div>';
206         } else if (!$this->isopen()) {
207             echo $OUTPUT->heading(get_string('nomoresubmissions','assignment'), 3);
209         } else if ($this->drafts_tracked() and $state = $this->is_finalized($submission)) {
210             if ($state == ASSIGNMENT_STATUS_SUBMITTED) {
211                 echo $OUTPUT->heading(get_string('submitedformarking','assignment'), 3);
212             } else {
213                 echo $OUTPUT->heading(get_string('nomoresubmissions','assignment'), 3);
214             }
215         } else {
216             //no submission yet
217         }
218     }
221     /**
222      * Return true if var3 == hide description till available day
223      *
224      *@return boolean
225      */
226     function description_is_hidden() {
227         return ($this->assignment->var3 && (time() <= $this->assignment->timeavailable));
228     }
230     function custom_feedbackform($submission, $return=false) {
231         global $CFG;
233         $mode         = optional_param('mode', '', PARAM_ALPHA);
234         $offset       = optional_param('offset', 0, PARAM_INT);
235         $forcerefresh = optional_param('forcerefresh', 0, PARAM_BOOL);
237         $mform = new mod_assignment_upload_response_form("$CFG->wwwroot/mod/assignment/upload.php", $this);
239         $mform->set_data(array('id'=>$this->cm->id, 'offset'=>$offset, 'forcerefresh'=>$forcerefresh, 'userid'=>$submission->userid, 'mode'=>$mode));
241         $output = get_string('responsefiles', 'assignment').': ';
243         ob_start();
244         $mform->display();
245         $output = ob_get_clean();
247         if ($forcerefresh) {
248             $output .= $this->update_main_listing($submission);
249         }
251         $responsefiles = $this->print_responsefiles($submission->userid, true);
252         if (!empty($responsefiles)) {
253             $output .= $responsefiles;
254         }
256         if ($return) {
257             return $output;
258         }
259         echo $output;
260         return;
261     }
264     function print_student_answer($userid, $return=false){
265         global $CFG, $OUTPUT;
267         $submission = $this->get_submission($userid);
269         $output = '';
271         if ($this->drafts_tracked() and $this->isopen() and !$this->is_finalized($submission)) {
272             $output .= '<strong>'.get_string('draft', 'assignment').':</strong> ';
273         }
275         if ($this->notes_allowed() and !empty($submission->data1)) {
276             $link = new moodle_url("/mod/assignment/type/upload/notes.php", array('id'=>$this->cm->id, 'userid'=>$userid));
277             $action = new popup_action('click', $link, 'notes', array('height' => 500, 'width' => 780));
278             $output .= $OUTPUT->action_link($link, get_string('notes', 'assignment'), $action, array('title'=>get_string('notes', 'assignment')));
280             $output .= '&nbsp;';
281         }
283         $fs = get_file_storage();
284         $browser = get_file_browser();
286         if ($files = $fs->get_area_files($this->context->id, 'assignment_submission', $userid, "timemodified", false)) {
288             foreach ($files as $file) {
289                 $filename = $file->get_filename();
290                 $found = true;
291                 $mimetype = $file->get_mimetype();
292                 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/assignment_submission/'.$userid.'/'.$filename);
293                 $output .= '<a href="'.$path.'" ><img class="icon" src="'.$OUTPUT->pix_url(file_mimetype_icon($mimetype)).'" alt="'.$mimetype.'" />'.s($filename).'</a>&nbsp;';
295             }
297         }
298         $output = '<div class="files">'.$output.'</div>';
299         $output .= '<br />';
301         return $output;
302     }
305     /**
306      * Produces a list of links to the files uploaded by a user
307      *
308      * @param $userid int optional id of the user. If 0 then $USER->id is used.
309      * @param $return boolean optional defaults to false. If true the list is returned rather than printed
310      * @return string optional
311      */
312     function print_user_files($userid=0, $return=false) {
313         global $CFG, $USER, $OUTPUT;
315         $mode    = optional_param('mode', '', PARAM_ALPHA);
316         $offset  = optional_param('offset', 0, PARAM_INT);
318         if (!$userid) {
319             if (!isloggedin()) {
320                 return '';
321             }
322             $userid = $USER->id;
323         }
325         $output = '';
327         $submission = $this->get_submission($userid);
329         $candelete = $this->can_delete_files($submission);
330         $strdelete   = get_string('delete');
332         if ($this->drafts_tracked() and $this->isopen() and !$this->is_finalized($submission) and !empty($mode)) {                 // only during grading
333             $output .= '<strong>'.get_string('draft', 'assignment').':</strong><br />';
334         }
336         if ($this->notes_allowed() and !empty($submission->data1) and !empty($mode)) { // only during grading
338             $npurl = $CFG->wwwroot."/mod/assignment/type/upload/notes.php?id={$this->cm->id}&amp;userid=$userid&amp;offset=$offset&amp;mode=single";
339             $output .= '<a href="'.$npurl.'">'.get_string('notes', 'assignment').'</a><br />';
341         }
343         $fs = get_file_storage();
344         $browser = get_file_browser();
346         if ($files = $fs->get_area_files($this->context->id, 'assignment_submission', $userid, "timemodified", false)) {
347             $button = new portfolio_add_button();
348             foreach ($files as $file) {
349                 $filename = $file->get_filename();
350                 $mimetype = $file->get_mimetype();
351                 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/assignment_submission/'.$userid.'/'.$filename);
352                 $output .= '<a href="'.$path.'" ><img src="'.$OUTPUT->pix_url(file_mimetype_icon($mimetype)).'" class="icon" alt="'.$mimetype.'" />'.s($filename).'</a>';
354                 if ($candelete) {
355                     $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";
357                     $output .= '<a href="'.$delurl.'">&nbsp;'
358                               .'<img title="'.$strdelete.'" src="'.$OUTPUT->pix_url('t/delete') . '" class="iconsmall" alt="" /></a> ';
359                 }
361                 if (has_capability('mod/assignment:exportownsubmission', $this->context)) {
362                     $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id, 'fileid' => $file->get_id()), '/mod/assignment/locallib.php');
363                     $button->set_format_by_file($file);
364                     $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
365                 }
366                 $output .= '<br />';
367             }
368             if (count($files) > 1 && has_capability('mod/assignment:exportownsubmission', $this->context)) {
369                 $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id), '/mod/assignment/locallib.php');
370                 $button->reset_formats(); // reset what we set before, since it's multi-file
371                 $output .= $button->to_html();
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 .= $OUTPUT->single_button(new moodle_url('upload.php', $options), get_string('unfinalize', 'assignment'));
379             } else if ($this->can_finalize($submission)) {
380                 $options = array ('id'=>$this->cm->id, 'userid'=>$userid, 'action'=>'finalizeclose', 'mode'=>$mode, 'offset'=>$offset);
381                 $output .= $OUTPUT->single_button(new moodle_url('upload.php', $options), get_string('finalize', 'assignment'));
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, $OUTPUT;
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                 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/assignment_response/'.$userid.'/'.$filename);
414                 $output .= '<a href="'.$path.'" ><img src="'.$OUTPUT->pix_url(file_mimetype_icon($mimetype)).'" alt="'.$mimetype.'" />'.$filename.'</a>';
416                 if ($candelete) {
417                     $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";
419                     $output .= '<a href="'.$delurl.'">&nbsp;'
420                               .'<img title="'.$strdelete.'" src="'.$OUTPUT->pix_url('t/delete') . '" class="iconsmall" alt=""/></a> ';
421                 }
423                 $output .= '&nbsp;';
424             }
426             $output = '<div class="responsefiles">'.$output.'</div>';
427         }
429         if ($return) {
430             return $output;
431         }
432         echo $output;
433     }
436     function upload() {
437         $action = required_param('action', PARAM_ALPHA);
439         switch ($action) {
440             case 'finalize':
441                 $this->finalize();
442                 break;
443             case 'finalizeclose':
444                 $this->finalizeclose();
445                 break;
446             case 'unfinalize':
447                 $this->unfinalize();
448                 break;
449             case 'uploadresponse':
450                 $this->upload_responsefile();
451                 break;
452             case 'uploadfile':
453                 $this->upload_file();
454             case 'savenotes':
455             case 'editnotes':
456                 $this->upload_notes();
457             default:
458                 print_error('unknowuploadaction', '', '', $action);
459         }
460     }
462     function upload_notes() {
463         global $CFG, $USER, $OUTPUT, $DB;
465         $action = required_param('action', PARAM_ALPHA);
467         $returnurl = 'view.php?id='.$this->cm->id;
469         $mform = new mod_assignment_upload_notes_form();
471         $defaults = new object();
472         $defaults->id = $this->cm->id;
474         if ($submission = $this->get_submission($USER->id)) {
475             $defaults->text = clean_text($submission->data1);
476         } else {
477             $defaults->text = '';
478         }
480         $mform->set_data($defaults);
482         if ($mform->is_cancelled()) {
483             redirect('view.php?id='.$this->cm->id);
484         }
486         if (!$this->can_update_notes($submission)) {
487             $this->view_header(get_string('upload'));
488             echo $OUTPUT->notification(get_string('uploaderror', 'assignment'));
489             echo $OUTPUT->continue_button($returnurl);
490             $this->view_footer();
491             die;
492         }
494         if ($data = $mform->get_data() and $action == 'savenotes') {
495             $submission = $this->get_submission($USER->id, true); // get or create submission
496             $updated = new object();
497             $updated->id           = $submission->id;
498             $updated->timemodified = time();
499             $updated->data1        = $data->text;
501             if ($DB->update_record('assignment_submissions', $updated)) {
502                 add_to_log($this->course->id, 'assignment', 'upload', 'view.php?a='.$this->assignment->id, $this->assignment->id, $this->cm->id);
503                 redirect($returnurl);
504                 $submission = $this->get_submission($USER->id);
505                 $this->update_grade($submission);
507             } else {
508                 $this->view_header(get_string('notes', 'assignment'));
509                 echo $OUTPUT->notification(get_string('notesupdateerror', 'assignment'));
510                 echo $OUTPUT->continue_button($returnurl);
511                 $this->view_footer();
512                 die;
513             }
514         }
516         /// show notes edit form
517         $this->view_header(get_string('notes', 'assignment'));
519         echo $OUTPUT->heading(get_string('notes', 'assignment'));
521         $mform->display();
523         $this->view_footer();
524         die;
525     }
527     function upload_responsefile() {
528         global $CFG, $USER, $OUTPUT, $PAGE;
530         $userid = required_param('userid', PARAM_INT);
531         $mode   = required_param('mode', PARAM_ALPHA);
532         $offset = required_param('offset', PARAM_INT);
534         $returnurl = "submissions.php?id={$this->cm->id}&amp;userid=$userid&amp;mode=$mode&amp;offset=$offset";
536         $mform = new mod_assignment_upload_response_form(null, $this);
537         if ($mform->get_data() and $this->can_manage_responsefiles()) {
538             $fs = get_file_storage();
539             $filename = $mform->get_new_filename('newfile');
540             if ($filename !== false) {
541                 if (!$fs->file_exists($this->context->id, 'assignment_response', $userid, '/', $filename)) {
542                     if ($file = $mform->save_stored_file('newfile', $this->context->id, 'assignment_response', $userid, '/', $filename, false, $USER->id)) {
543                         redirect($returnurl);
544                     }
545                 }
546             }
547         }
548         $PAGE->set_title(get_string('upload'));
549         echo $OUTPUT->header();
550         echo $OUTPUT->notification(get_string('uploaderror', 'assignment'));
551         echo $OUTPUT->continue_button($returnurl);
552         echo $OUTPUT->footer();
553         die;
554     }
556     function upload_file() {
557         global $CFG, $USER, $DB, $OUTPUT;
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             echo $OUTPUT->notification(get_string('uploaderror', 'assignment'));
567             echo $OUTPUT->continue_button($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                             //trigger event with information about this file.
589                             $eventdata = new object();
590                             $eventdata->component  = 'mod/assignment';
591                             $eventdata->course     = $this->course;
592                             $eventdata->assignment = $this->assignment;
593                             $eventdata->cm         = $this->cm;
594                             $eventdata->user       = $USER;
595                             $eventdata->file       = $file;
596                             events_trigger('assignment_file_sent', $eventdata);
598                             redirect('view.php?id='.$this->cm->id);
599                         } else {
600                             $file->delete();
601                         }
602                     }
603                 }
604             }
605         }
607         $this->view_header(get_string('upload'));
608         echo $OUTPUT->notification(get_string('uploaderror', 'assignment'));
609         echo $OUTPUT->continue_button($returnurl);
610         $this->view_footer();
611         die;
612     }
614     function send_file($filearea, $args) {
615         global $CFG, $DB, $USER;
616         require_once($CFG->libdir.'/filelib.php');
618         require_login($this->course, false, $this->cm);
620         $userid = (int)array_shift($args);
621         $relativepath = '/'.implode('/', $args);
622         $fullpath = $this->context->id.$filearea.$userid.$relativepath;
624         $fs = get_file_storage();
626         if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
627             return false;
628         }
630         if ($filearea === 'assignment_submission') {
631             if ($USER->id != $userid and !has_capability('mod/assignment:grade', $this->context)) {
632                 return false;
633             }
635         } else if ($filearea === 'assignment_response') {
636             if ($USER->id != $userid and !has_capability('mod/assignment:grade', $this->context)) {
637                 return false;
638             }
640         } else {
641             return false;
642         }
644         send_stored_file($file, 0, 0, true); // download MUST be forced - security!
645     }
647     function finalize() {
648         global $USER, $DB, $OUTPUT;
650         $confirm    = optional_param('confirm', 0, PARAM_BOOL);
651         $returnurl  = 'view.php?id='.$this->cm->id;
652         $submission = $this->get_submission($USER->id);
654         if (!$this->can_finalize($submission)) {
655             redirect($returnurl); // probably already graded, redirect to assignment page, the reason should be obvious
656         }
658         if (!data_submitted() or !$confirm or !confirm_sesskey()) {
659             $optionsno = array('id'=>$this->cm->id);
660             $optionsyes = array ('id'=>$this->cm->id, 'confirm'=>1, 'action'=>'finalize', 'sesskey'=>sesskey());
661             $this->view_header(get_string('submitformarking', 'assignment'));
662             echo $OUTPUT->heading(get_string('submitformarking', 'assignment'));
663             echo $OUTPUT->confirm(get_string('onceassignmentsent', 'assignment'), new moodle_url('upload.php', $optionsyes),new moodle_url( 'view.php', $optionsno));
664             $this->view_footer();
665             die;
667         }
668         $updated = new object();
669         $updated->id           = $submission->id;
670         $updated->data2        = ASSIGNMENT_STATUS_SUBMITTED;
671         $updated->timemodified = time();
673         if ($DB->update_record('assignment_submissions', $updated)) {
674             add_to_log($this->course->id, 'assignment', 'upload', //TODO: add finalize action to log
675                     'view.php?a='.$this->assignment->id, $this->assignment->id, $this->cm->id);
676             $submission = $this->get_submission($USER->id);
677             $this->update_grade($submission);
678             $this->email_teachers($submission);
679         } else {
680             $this->view_header(get_string('submitformarking', 'assignment'));
681             echo $OUTPUT->notification(get_string('finalizeerror', 'assignment'));
682             echo $OUTPUT->continue_button($returnurl);
683             $this->view_footer();
684             die;
685         }
686         //trigger event with information about this file.
687         $eventdata = new object();
688         $eventdata->component  = 'mod/assignment';
689         $eventdata->course     = $this->course;
690         $eventdata->assignment = $this->assignment;
691         $eventdata->cm         = $this->cm;
692         $eventdata->user       = $USER;
693         events_trigger('assignment_finalize_sent', $eventdata);
695         redirect($returnurl);
696     }
698     function finalizeclose() {
699         global $DB;
701         $userid    = optional_param('userid', 0, PARAM_INT);
702         $mode      = required_param('mode', PARAM_ALPHA);
703         $offset    = required_param('offset', PARAM_INT);
704         $returnurl = "submissions.php?id={$this->cm->id}&amp;userid=$userid&amp;mode=$mode&amp;offset=$offset&amp;forcerefresh=1";
706         // create but do not add student submission date
707         $submission = $this->get_submission($userid, true, true);
709         if (!data_submitted() or !$this->can_finalize($submission) or !confirm_sesskey()) {
710             redirect($returnurl); // probably closed already
711         }
713         $updated = new object();
714         $updated->id    = $submission->id;
715         $updated->data2 = ASSIGNMENT_STATUS_CLOSED;
717         if ($DB->update_record('assignment_submissions', $updated)) {
718             add_to_log($this->course->id, 'assignment', 'upload', //TODO: add finalize action to log
719                     'view.php?a='.$this->assignment->id, $this->assignment->id, $this->cm->id);
720             $submission = $this->get_submission($userid, false, true);
721             $this->update_grade($submission);
722         }
723         redirect($returnurl);
724     }
726     function unfinalize() {
727         global $DB;
729         $userid = required_param('userid', PARAM_INT);
730         $mode   = required_param('mode', PARAM_ALPHA);
731         $offset = required_param('offset', PARAM_INT);
733         $returnurl = "submissions.php?id={$this->cm->id}&amp;userid=$userid&amp;mode=$mode&amp;offset=$offset&amp;forcerefresh=1";
735         if (data_submitted()
736           and $submission = $this->get_submission($userid)
737           and $this->can_unfinalize($submission)
738           and confirm_sesskey()) {
740             $updated = new object();
741             $updated->id = $submission->id;
742             $updated->data2 = '';
743             if ($DB->update_record('assignment_submissions', $updated)) {
744                 //TODO: add unfinalize action to log
745                 add_to_log($this->course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->assignment->id, $this->assignment->id, $this->cm->id);
746                 $submission = $this->get_submission($userid);
747                 $this->update_grade($submission);
748             } else {
749                 $this->view_header(get_string('submitformarking', 'assignment'));
750                 echo $OUTPUT->notification(get_string('unfinalizeerror', 'assignment'));
751                 echo $OUTPUT->continue_button($returnurl);
752                 $this->view_footer();
753                 die;
754             }
755         }
756         redirect($returnurl);
757     }
760     function delete() {
761         $action   = optional_param('action', '', PARAM_ALPHA);
763         switch ($action) {
764             case 'response':
765                 $this->delete_responsefile();
766                 break;
767             default:
768                 $this->delete_file();
769         }
770         die;
771     }
774     function delete_responsefile() {
775         global $CFG, $OUTPUT,$PAGE;
777         $file     = required_param('file', PARAM_FILE);
778         $userid   = required_param('userid', PARAM_INT);
779         $mode     = required_param('mode', PARAM_ALPHA);
780         $offset   = required_param('offset', PARAM_INT);
781         $confirm  = optional_param('confirm', 0, PARAM_BOOL);
783         $returnurl = "submissions.php?id={$this->cm->id}&userid=$userid&mode=$mode&offset=$offset";
785         if (!$this->can_manage_responsefiles()) {
786            redirect($returnurl);
787         }
789         $urlreturn = 'submissions.php';
790         $optionsreturn = array('id'=>$this->cm->id, 'offset'=>$offset, 'mode'=>$mode, 'userid'=>$userid);
792         if (!data_submitted() or !$confirm or !confirm_sesskey()) {
793             $optionsyes = array ('id'=>$this->cm->id, 'file'=>$file, 'userid'=>$userid, 'confirm'=>1, 'action'=>'response', 'mode'=>$mode, 'offset'=>$offset, 'sesskey'=>sesskey());
794             $PAGE->set_title(get_string('delete'));
795             echo $OUTPUT->header();
796             echo $OUTPUT->heading(get_string('delete'));
797             echo $OUTPUT->confirm(get_string('confirmdeletefile', 'assignment', $file), new moodle_url('delete.php', $optionsyes), new moodle_url($urlreturn, $optionsreturn));
798             echo $OUTPUT->footer();
799             die;
800         }
802         $fs = get_file_storage();
803         if ($file = $fs->get_file($this->context->id, 'assignment_submission', $userid, '/', $file)) {
804             if ($file->delete()) {
805                 redirect($returnurl);
806             }
807         }
809         // print delete error
810         $PAGE->set_title(get_string('delete'));
811         echo $OUTPUT->header();
812         echo $OUTPUT->notification(get_string('deletefilefailed', 'assignment'));
813         echo $OUTPUT->continue_button($returnurl);
814         echo $OUTPUT->footer();
815         die;
817     }
820     function delete_file() {
821         global $CFG, $DB, $OUTPUT, $PAGE;
823         $file     = required_param('file', PARAM_FILE);
824         $userid   = required_param('userid', PARAM_INT);
825         $confirm  = optional_param('confirm', 0, PARAM_BOOL);
826         $mode     = optional_param('mode', '', PARAM_ALPHA);
827         $offset   = optional_param('offset', 0, PARAM_INT);
829         require_login($this->course->id, false, $this->cm);
831         if (empty($mode)) {
832             $urlreturn = 'view.php';
833             $optionsreturn = array('id'=>$this->cm->id);
834             $returnurl = 'view.php?id='.$this->cm->id;
835         } else {
836             $urlreturn = 'submissions.php';
837             $optionsreturn = array('id'=>$this->cm->id, 'offset'=>$offset, 'mode'=>$mode, 'userid'=>$userid);
838             $returnurl = "submissions.php?id={$this->cm->id}&offset=$offset&mode=$mode&userid=$userid";
839         }
841         if (!$submission = $this->get_submission($userid) // incorrect submission
842           or !$this->can_delete_files($submission)) {     // can not delete
843             $this->view_header(get_string('delete'));
844             echo $OUTPUT->notification(get_string('cannotdeletefiles', 'assignment'));
845             echo $OUTPUT->continue_button($returnurl);
846             $this->view_footer();
847             die;
848         }
850         if (!data_submitted() or !$confirm or !confirm_sesskey()) {
851             $optionsyes = array ('id'=>$this->cm->id, 'file'=>$file, 'userid'=>$userid, 'confirm'=>1, 'sesskey'=>sesskey(), 'mode'=>$mode, 'offset'=>$offset, 'sesskey'=>sesskey());
852             if (empty($mode)) {
853                 $this->view_header(get_string('delete'));
854             } else {
855                 $PAGE->set_title(get_string('delete'));
856                 echo $OUTPUT->header();
857             }
858             echo $OUTPUT->heading(get_string('delete'));
859             echo $OUTPUT->confirm(get_string('confirmdeletefile', 'assignment', $file), new moodle_url('delete.php', $optionsyes), new moodle_url($urlreturn, $optionsreturn));
860             if (empty($mode)) {
861                 $this->view_footer();
862             } else {
863                 echo $OUTPUT->footer();
864             }
865             die;
866         }
868         $fs = get_file_storage();
869         if ($file = $fs->get_file($this->context->id, 'assignment_submission', $userid, '/', $file)) {
870             if ($file->delete()) {
871                 $submission->timemodified = time();
872                 if ($DB->update_record('assignment_submissions', $submission)) {
873                     add_to_log($this->course->id, 'assignment', 'upload', //TODO: add delete action to log
874                             'view.php?a='.$this->assignment->id, $this->assignment->id, $this->cm->id);
875                     $this->update_grade($submission);
876                 }
877                 redirect($returnurl);
878             }
879         }
881         // print delete error
882         if (empty($mode)) {
883             $this->view_header(get_string('delete'));
884         } else {
885             $PAGE->set_title(get_string('delete'));
886             echo $OUTPUT->header();
887         }
888         echo $OUTPUT->notification(get_string('deletefilefailed', 'assignment'));
889         echo $OUTPUT->continue_button($returnurl);
890         if (empty($mode)) {
891             $this->view_footer();
892         } else {
893             echo $OUTPUT->footer();
894         }
895         die;
896     }
899     function can_upload_file($submission) {
900         global $USER;
902         if (has_capability('mod/assignment:submit', $this->context)           // can submit
903           and $this->isopen()                                                 // assignment not closed yet
904           and (empty($submission) or $submission->userid == $USER->id)        // his/her own submission
905           and $this->count_user_files($USER->id) < $this->assignment->var1    // file limit not reached
906           and !$this->is_finalized($submission)) {                            // no uploading after final submission
907             return true;
908         } else {
909             return false;
910         }
911     }
913     function can_manage_responsefiles() {
914         if (has_capability('mod/assignment:grade', $this->context)) {
915             return true;
916         } else {
917             return false;
918         }
919     }
921     function can_delete_files($submission) {
922         global $USER;
924         if (has_capability('mod/assignment:grade', $this->context)) {
925             return true;
926         }
928         if (has_capability('mod/assignment:submit', $this->context)
929           and $this->isopen()                                      // assignment not closed yet
930           and $this->assignment->resubmit                          // deleting allowed
931           and $USER->id == $submission->userid                     // his/her own submission
932           and !$this->is_finalized($submission)) {                 // no deleting after final submission
933             return true;
934         } else {
935             return false;
936         }
937     }
939     function drafts_tracked() {
940         return !empty($this->assignment->var4);
941     }
943     /**
944      * Returns submission status
945      * @param object $submission - may be empty
946      * @return string submission state - empty, ASSIGNMENT_STATUS_SUBMITTED or ASSIGNMENT_STATUS_CLOSED
947      */
948     function is_finalized($submission) {
949         if (!$this->drafts_tracked()) {
950             return '';
952         } else if (empty($submission)) {
953             return '';
955         } else if ($submission->data2 == ASSIGNMENT_STATUS_SUBMITTED or $submission->data2 == ASSIGNMENT_STATUS_CLOSED) {
956             return $submission->data2;
958         } else {
959             return '';
960         }
961     }
963     function can_unfinalize($submission) {
964         if (!$this->drafts_tracked()) {
965             return false;
966         }
967         if (has_capability('mod/assignment:grade', $this->context)
968           and $this->isopen()
969           and $this->is_finalized($submission)) {
970             return true;
971         } else {
972             return false;
973         }
974     }
976     function can_finalize($submission) {
977         global $USER;
978         if (!$this->drafts_tracked()) {
979             return false;
980         }
982         if ($this->is_finalized($submission)) {
983             return false;
984         }
986         if (has_capability('mod/assignment:grade', $this->context)) {
987             return true;
989         } else if (has_capability('mod/assignment:submit', $this->context)    // can submit
990           and $this->isopen()                                                 // assignment not closed yet
991           and !empty($submission)                                             // submission must exist
992           and $submission->userid == $USER->id                                // his/her own submission
993           and ($this->count_user_files($USER->id)
994             or ($this->notes_allowed() and !empty($submission->data1)))) {    // something must be submitted
996             return true;
997         } else {
998             return false;
999         }
1000     }
1002     function can_update_notes($submission) {
1003         global $USER;
1005         if (has_capability('mod/assignment:submit', $this->context)
1006           and $this->notes_allowed()                                          // notesd must be allowed
1007           and $this->isopen()                                                 // assignment not closed yet
1008           and (empty($submission) or $USER->id == $submission->userid)        // his/her own submission
1009           and !$this->is_finalized($submission)) {                            // no updateingafter final submission
1010             return true;
1011         } else {
1012             return false;
1013         }
1014     }
1016     function notes_allowed() {
1017         return (boolean)$this->assignment->var2;
1018     }
1020     function count_responsefiles($userid) {
1021         $fs = get_file_storage();
1022         $files = $fs->get_area_files($this->context->id, 'assignment_response', $userid, "id", false);
1023         return count($files);
1024     }
1026     function setup_elements(&$mform) {
1027         global $CFG, $COURSE;
1029         $ynoptions = array( 0 => get_string('no'), 1 => get_string('yes'));
1031         $choices = get_max_upload_sizes($CFG->maxbytes, $COURSE->maxbytes);
1032         $choices[0] = get_string('courseuploadlimit') . ' ('.display_size($COURSE->maxbytes).')';
1033         $mform->addElement('select', 'maxbytes', get_string('maximumsize', 'assignment'), $choices);
1034         $mform->setDefault('maxbytes', $CFG->assignment_maxbytes);
1036         $mform->addElement('select', 'resubmit', get_string("allowdeleting", "assignment"), $ynoptions);
1037         $mform->setHelpButton('resubmit', array('allowdeleting', get_string('allowdeleting', 'assignment'), 'assignment'));
1038         $mform->setDefault('resubmit', 1);
1040         $options = array();
1041         for($i = 1; $i <= 20; $i++) {
1042             $options[$i] = $i;
1043         }
1044         $mform->addElement('select', 'var1', get_string("allowmaxfiles", "assignment"), $options);
1045         $mform->setHelpButton('var1', array('allowmaxfiles', get_string('allowmaxfiles', 'assignment'), 'assignment'));
1046         $mform->setDefault('var1', 3);
1048         $mform->addElement('select', 'var2', get_string("allownotes", "assignment"), $ynoptions);
1049         $mform->setHelpButton('var2', array('allownotes', get_string('allownotes', 'assignment'), 'assignment'));
1050         $mform->setDefault('var2', 0);
1052         $mform->addElement('select', 'var3', get_string("hideintro", "assignment"), $ynoptions);
1053         $mform->setHelpButton('var3', array('hideintro', get_string('hideintro', 'assignment'), 'assignment'));
1054         $mform->setDefault('var3', 0);
1056         $mform->addElement('select', 'emailteachers', get_string("emailteachers", "assignment"), $ynoptions);
1057         $mform->setHelpButton('emailteachers', array('emailteachers', get_string('emailteachers', 'assignment'), 'assignment'));
1058         $mform->setDefault('emailteachers', 0);
1060         $mform->addElement('select', 'var4', get_string("trackdrafts", "assignment"), $ynoptions);
1061         $mform->setHelpButton('var4', array('trackdrafts', get_string('trackdrafts', 'assignment'), 'assignment'));
1062         $mform->setDefault('var4', 1);
1064     }
1066     function portfolio_exportable() {
1067         return true;
1068     }
1070     function extend_settings_navigation($node) {
1071         global $CFG, $USER, $OUTPUT;
1073         // get users submission if there is one
1074         $submission = $this->get_submission();
1075         if (has_capability('mod/assignment:submit', get_context_instance(CONTEXT_MODULE, $this->cm->id))) {
1076             $editable = $this->isopen() && (!$submission || $this->assignment->resubmit || !$submission->timemarked);
1077         } else {
1078             $editable = false;
1079         }
1081         // If the user has submitted something add a bit more stuff
1082         if ($submission) {
1083             // Add a view link to the settings nav
1084             $link = new moodle_url('/mod/assignment/view.php', array('id'=>$this->cm->id));
1085             $node->add(get_string('viewmysubmission', 'assignment'), $link, navigation_node::TYPE_SETTING);
1086             if (!empty($submission->timemodified)) {
1087                 $submittednode = $node->add(get_string('submitted', 'assignment') . ' ' . userdate($submission->timemodified));
1088                 $submittednode->text = preg_replace('#([^,])\s#', '$1&nbsp;', $submittednode->text);
1089                 $submittednode->add_class('note');
1090                 if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
1091                     $submittednode->add_class('early');
1092                 } else {
1093                     $submittednode->add_class('late');
1094                 }
1095             }
1096         }
1098         // Check if the user has uploaded any files, if so we can add some more stuff to the settings nav
1099         if ($submission && has_capability('mod/assignment:submit', $this->context) && $this->count_user_files($USER->id)) {
1100             $fs = get_file_storage();
1101             if ($files = $fs->get_area_files($this->context->id, 'assignment_submission', $USER->id, "timemodified", false)) {
1102                 if (!$this->drafts_tracked() or !$this->isopen() or $this->is_finalized($submission)) {
1103                     $filenode = $node->add(get_string('submission', 'assignment'));
1104                 } else {
1105                     $filenode = $node->add(get_string('submissiondraft', 'assignment'));
1106                 }
1107                 foreach ($files as $file) {
1108                     $filename = $file->get_filename();
1109                     $mimetype = $file->get_mimetype();
1110                     $link = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/assignment_submission/'.$USER->id.'/'.$filename);
1111                     $filenode->add($filename, $link, navigation_node::TYPE_SETTING, null, null, new pix_icon(file_mimetype_icon($mimetype),''));
1112                 }
1113             }
1114         }
1116         // Show a notes link if they are enabled
1117         if ($this->notes_allowed()) {
1118             $link = new moodle_url('/mod/assignment/upload.php', array('id'=>$this->cm->id, 'action'=>'editnotes', 'sesskey'=>sesskey()));
1119             $node->add(get_string('notes', 'assignment'), $link);
1120         }
1121     }
1123     /**
1124      * creates a zip of all assignment submissions and sends a zip to the browser
1125      */
1126     public function download_submissions() {
1127         global $CFG,$DB;
1128         require_once($CFG->libdir.'/filelib.php');
1130         $submissions = $this->get_submissions('','');
1131         if (empty($submissions)) {
1132             error("there are no submissions to download");
1133         }
1134         $filesforzipping = array();
1135         $filenewname = clean_filename($this->assignment->name); //create prefix of individual files
1136         $tempdir = assignment_create_temp_dir($CFG->dataroot."/temp/", "assignment".$this->assignment->id); //location for temp files.
1137         $fs = get_file_storage();
1139         $groupmode = groupmode($this->course,$this->cm);
1140         $groupid = 0;   // All users
1141         $groupname = '';
1142         if($groupmode) {
1143             $group = get_current_group($this->course->id, true);
1144             $groupid = $group->id;
1145             $groupname = $group->name.'-';
1146         }
1147         $filename = str_replace(' ', '_', clean_filename($this->course->shortname.'-'.$this->assignment->name.'-'.$groupname.$this->assignment->id.".zip")); //name of new zip file.
1148         foreach ($submissions as $submission) {
1149             $a_userid = $submission->userid; //get userid
1150             if ((groups_is_member($groupid,$a_userid)or !$groupmode or !$groupid)) {
1151                 $a_assignid = $submission->assignment; //get name of this assignment for use in the file names.
1152                 $a_user = $DB->get_record("user", array("id"=>$a_userid),'id,username,firstname,lastname'); //get user firstname/lastname
1153                 
1154                 $files = $fs->get_area_files($this->context->id, 'assignment_submission', $a_userid, "timemodified", false);
1155                 foreach ($files as $file) {
1156                     //get files new name.
1157                     $fileforzipname =  $a_user->username . "_" . $filenewname . "_" . $file->get_filename();
1158                     //get files old name
1159                     if (!$file->copy_content_to($tempdir . $fileforzipname)) {
1160                         error ("failed to copy file<br>" .$tempdir. $fileforzipname);
1161                     }
1162                     //save file name to array for zipping.
1163                     $filesforzipping[$fileforzipname] = $tempdir.$fileforzipname;
1164                 }
1165             }
1166         } // end of foreach loop
1167         if ($zipfile = assignment_pack_files($filesforzipping)) {
1168             remove_dir($tempdir); //remove old tempdir with individual files.
1169             send_temp_file($zipfile, $filename); //send file and delete after sending.
1170         }
1171     }
1174 class mod_assignment_upload_notes_form extends moodleform {
1176     function get_data() {
1177         $data = parent::get_data();
1178         if ($data) {
1179             $data->format = $data->text['format'];
1180             $data->text = $data->text['text'];
1181         }
1182         return $data;
1183     }
1185     function set_data($data) {
1186         if (!isset($data->format)) {
1187             $data->format = FORMAT_HTML;
1188         }
1189         if (isset($data->text)) {
1190             $data->text = array('text'=>$data->text, 'format'=>$data->format);
1191         }
1192         parent::set_data($data);
1193     }
1195     function definition() {
1196         $mform = $this->_form;
1198         // visible elements
1199         $mform->addElement('editor', 'text', get_string('notes', 'assignment'), null, null);
1200         $mform->setType('text', PARAM_RAW); // to be cleaned before display
1201         $mform->setHelpButton('text', array('reading', 'writing'), false, 'editorhelpbutton');
1203         // hidden params
1204         $mform->addElement('hidden', 'id', 0);
1205         $mform->setType('id', PARAM_INT);
1206         $mform->addElement('hidden', 'action', 'savenotes');
1207         $mform->setType('action', PARAM_ALPHA);
1209         // buttons
1210         $this->add_action_buttons();
1211     }
1214 class mod_assignment_upload_response_form extends moodleform {
1215     function definition() {
1216         $mform = $this->_form;
1217         $instance = $this->_customdata;
1219         // visible elements
1220         $mform->addElement('file', 'newfile', get_string('uploadafile'));
1222         // hidden params
1223         $mform->addElement('hidden', 'id', $instance->cm->id);
1224         $mform->setType('id', PARAM_INT);
1225         $mform->addElement('hidden', 'action', 'uploadresponse');
1226         $mform->setType('action', PARAM_ALPHA);
1227         $mform->addElement('hidden', 'mode');
1228         $mform->setType('mode', PARAM_ALPHA);
1229         $mform->addElement('hidden', 'offset');
1230         $mform->setType('offset', PARAM_INT);
1231         $mform->addElement('hidden', 'forcerefresh');
1232         $mform->setType('forcerefresh', PARAM_INT);
1233         $mform->addElement('hidden', 'userid');
1234         $mform->setType('userid', PARAM_INT);
1236         // buttons
1237         $this->add_action_buttons(false, get_string('uploadthisfile'));
1238     }