MDL-38254 Assignment Module: add avaialble message to all assignment types
[moodle.git] / mod / assignment / type / online / assignment.class.php
1 <?php
2 require_once($CFG->libdir.'/formslib.php');
3 require_once($CFG->libdir . '/portfoliolib.php');
4 require_once($CFG->dirroot . '/mod/assignment/lib.php');
5 require_once($CFG->libdir . '/filelib.php');
7 /**
8  * Extend the base assignment class for assignments where you upload a single file
9  *
10  */
11 class assignment_online extends assignment_base {
13     var $filearea = 'submission';
15     function assignment_online($cmid='staticonly', $assignment=NULL, $cm=NULL, $course=NULL) {
16         parent::assignment_base($cmid, $assignment, $cm, $course);
17         $this->type = 'online';
18     }
20     function view() {
21         global $OUTPUT, $CFG, $USER, $PAGE;
23         $edit  = optional_param('edit', 0, PARAM_BOOL);
24         $saved = optional_param('saved', 0, PARAM_BOOL);
26         $context = context_module::instance($this->cm->id);
27         require_capability('mod/assignment:view', $context);
29         $submission = $this->get_submission($USER->id, false);
31         //Guest can not submit nor edit an assignment (bug: 4604)
32         if (!is_enrolled($this->context, $USER, 'mod/assignment:submit')) {
33             $editable = false;
34         } else {
35             $editable = $this->isopen() && (!$submission || $this->assignment->resubmit || !$submission->timemarked);
36         }
37         $editmode = ($editable and $edit);
39         if ($editmode) {
40             // prepare form and process submitted data
41             $editoroptions = array(
42                 'noclean'  => false,
43                 'maxfiles' => EDITOR_UNLIMITED_FILES,
44                 'maxbytes' => $this->course->maxbytes,
45                 'context'  => $this->context,
46                 'return_types' => FILE_INTERNAL | FILE_EXTERNAL
47             );
49             $data = new stdClass();
50             $data->id         = $this->cm->id;
51             $data->edit       = 1;
52             if ($submission) {
53                 $data->sid        = $submission->id;
54                 $data->text       = $submission->data1;
55                 $data->textformat = $submission->data2;
56             } else {
57                 $data->sid        = NULL;
58                 $data->text       = '';
59                 $data->textformat = NULL;
60             }
62             $data = file_prepare_standard_editor($data, 'text', $editoroptions, $this->context, 'mod_assignment', $this->filearea, $data->sid);
64             $mform = new mod_assignment_online_edit_form(null, array($data, $editoroptions));
66             if ($mform->is_cancelled()) {
67                 redirect($PAGE->url);
68             }
70             if ($data = $mform->get_data()) {
71                 $submission = $this->get_submission($USER->id, true); //create the submission if needed & its id
73                 $data = file_postupdate_standard_editor($data, 'text', $editoroptions, $this->context, 'mod_assignment', $this->filearea, $submission->id);
75                 $submission = $this->update_submission($data);
77                 //TODO fix log actions - needs db upgrade
78                 add_to_log($this->course->id, 'assignment', 'upload', 'view.php?a='.$this->assignment->id, $this->assignment->id, $this->cm->id);
79                 $this->email_teachers($submission);
81                 //redirect to get updated submission date and word count
82                 redirect(new moodle_url($PAGE->url, array('saved'=>1)));
83             }
84         }
86         add_to_log($this->course->id, "assignment", "view", "view.php?id={$this->cm->id}", $this->assignment->id, $this->cm->id);
88 /// print header, etc. and display form if needed
89         if ($editmode) {
90             $this->view_header(get_string('editmysubmission', 'assignment'));
91         } else {
92             $this->view_header();
93         }
95         $this->view_intro();
97         $this->view_dates();
99         if ($saved) {
100             echo $OUTPUT->notification(get_string('submissionsaved', 'assignment'), 'notifysuccess');
101         }
103         if (is_enrolled($this->context, $USER)) {
104             if ($editmode) {
105                 echo $OUTPUT->box_start('generalbox', 'onlineenter');
106                 $mform->display();
107             } else {
108                 echo $OUTPUT->box_start('generalbox boxwidthwide boxaligncenter', 'online');
109                 if ($submission && has_capability('mod/assignment:exportownsubmission', $this->context)) {
110                     echo plagiarism_get_links(array('userid' => $USER->id,
111                         'content' => trim(format_text($submission->data1, $submission->data2, array('context' => $context))),
112                         'cmid' => $this->cm->id,
113                         'course' => $this->course,
114                         'assignment' => $this->assignment));
115                     $text = file_rewrite_pluginfile_urls($submission->data1, 'pluginfile.php', $this->context->id, 'mod_assignment', $this->filearea, $submission->id);
116                     echo format_text($text, $submission->data2, array('overflowdiv'=>true));
117                     if ($CFG->enableportfolios) {
118                         require_once($CFG->libdir . '/portfoliolib.php');
119                         $button = new portfolio_add_button();
120                         $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id), 'mod_assignment');
121                         $fs = get_file_storage();
122                         if ($files = $fs->get_area_files($this->context->id, 'mod_assignment', $this->filearea, $submission->id, "timemodified", false)) {
123                             $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
124                         } else {
125                             $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
126                         }
127                         $button->render();
128                     }
129                 } else if ($this->isopen()){    //fix for #4206
130                     echo $OUTPUT->heading(get_string('emptysubmission','assignment'), 3);
131                 } else if ($this->assignment->timeavailable > time()) {
132                     echo $OUTPUT->heading(get_string('futureaassignment','assignment'), 3);
133                 }
134             }
135             echo $OUTPUT->box_end();
136             if (!$editmode && $editable) {
137                 if (!empty($submission)) {
138                     $submitbutton = "editmysubmission";
139                 } else {
140                     $submitbutton = "addsubmission";
141                 }
142                 echo "<div style='text-align:center'>";
143                 echo $OUTPUT->single_button(new moodle_url('view.php', array('id'=>$this->cm->id, 'edit'=>'1')), get_string($submitbutton, 'assignment'));
144                 echo "</div>";
145             }
147         }
149         $this->view_feedback();
151         $this->view_footer();
152     }
154     /*
155      * Display the assignment dates
156      */
157     function view_dates() {
158         global $USER, $CFG, $OUTPUT;
160         if (!$this->assignment->timeavailable && !$this->assignment->timedue) {
161             return;
162         }
164         echo $OUTPUT->box_start('generalbox boxaligncenter', 'dates');
165         echo '<table>';
166         if ($this->assignment->timeavailable) {
167             echo '<tr><td class="c0">'.get_string('availabledate','assignment').':</td>';
168             echo '    <td class="c1">'.userdate($this->assignment->timeavailable).'</td></tr>';
169         }
170         if ($this->assignment->timedue) {
171             echo '<tr><td class="c0">'.get_string('duedate','assignment').':</td>';
172             echo '    <td class="c1">'.userdate($this->assignment->timedue).'</td></tr>';
173         }
174         $submission = $this->get_submission($USER->id);
175         if ($submission) {
176             echo '<tr><td class="c0">'.get_string('lastedited').':</td>';
177             echo '    <td class="c1">'.userdate($submission->timemodified);
178         /// Decide what to count
179             if ($CFG->assignment_itemstocount == ASSIGNMENT_COUNT_WORDS) {
180                 echo ' ('.get_string('numwords', '', count_words(format_text($submission->data1, $submission->data2))).')</td></tr>';
181             } else if ($CFG->assignment_itemstocount == ASSIGNMENT_COUNT_LETTERS) {
182                 echo ' ('.get_string('numletters', '', count_letters(format_text($submission->data1, $submission->data2))).')</td></tr>';
183             }
184         }
185         echo '</table>';
186         echo $OUTPUT->box_end();
187     }
189     function update_submission($data) {
190         global $CFG, $USER, $DB;
192         $submission = $this->get_submission($USER->id, true);
194         $update = new stdClass();
195         $update->id           = $submission->id;
196         $update->data1        = $data->text;
197         $update->data2        = $data->textformat;
198         $update->timemodified = time();
200         $DB->update_record('assignment_submissions', $update);
202         $submission = $this->get_submission($USER->id);
203         $this->update_grade($submission);
204         $fs = get_file_storage();
205         $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id);
206         // Let Moodle know that an assessable content was uploaded (eg for plagiarism detection)
207         $eventdata = new stdClass();
208         $eventdata->modulename   = 'assignment';
209         $eventdata->name         = 'update_submission';
210         $eventdata->cmid         = $this->cm->id;
211         $eventdata->itemid       = $update->id;
212         $eventdata->courseid     = $this->course->id;
213         $eventdata->userid       = $USER->id;
214         $eventdata->content      = trim(format_text($update->data1, $update->data2));
215         if ($files) {
216             $eventdata->pathnamehashes = array_keys($files);
217         }
218         events_trigger('assessable_content_uploaded', $eventdata);
219         return $submission;
220     }
223     function print_student_answer($userid, $return=false){
224         global $OUTPUT;
225         if (!$submission = $this->get_submission($userid)) {
226             return '';
227         }
229         $link = new moodle_url("/mod/assignment/type/online/file.php?id={$this->cm->id}&userid={$submission->userid}");
230         $action = new popup_action('click', $link, 'file'.$userid, array('height' => 450, 'width' => 580));
231         $popup = $OUTPUT->action_link($link, shorten_text(trim(strip_tags(format_text($submission->data1,$submission->data2))), 15), $action, array('title'=>get_string('submission', 'assignment')));
233         $output = '<div class="files">'.
234                   $OUTPUT->pix_icon(file_extension_icon('.htm'), 'html', 'moodle', array('class' => 'icon')).
235                   $popup .
236                   plagiarism_get_links(array('userid' => $userid,
237                       'content' => trim(format_text($submission->data1, $submission->data2)),
238                       'cmid' => $this->cm->id,
239                       'course' => $this->course,
240                       'assignment' => $this->assignment)) .
241                   '</div>';
242                   return $output;
243     }
245     function print_user_files($userid=0, $return=false) {
246         global $OUTPUT, $CFG, $USER;
248         if (!$userid) {
249             if (!isloggedin()) {
250                 return '';
251             }
252             $userid = $USER->id;
253         }
255         if (!$submission = $this->get_submission($userid)) {
256             return '';
257         }
259         $link = new moodle_url("/mod/assignment/type/online/file.php?id={$this->cm->id}&userid={$submission->userid}");
260         $action = new popup_action('click', $link, 'file'.$userid, array('height' => 450, 'width' => 580));
261         $popup = $OUTPUT->action_link($link, get_string('popupinnewwindow','assignment'), $action, array('title'=>get_string('submission', 'assignment')));
263         $output = '<div class="files">'.
264                   $OUTPUT->pix_icon(file_extension_icon('.htm'), 'html', 'moodle', array('height' => 16, 'width' => 16)).
265                   $popup .
266                   '</div>';
268         $wordcount = '<p id="wordcount">'. $popup . '&nbsp;';
269     /// Decide what to count
270         if ($CFG->assignment_itemstocount == ASSIGNMENT_COUNT_WORDS) {
271             $wordcount .= '('.get_string('numwords', '', count_words(format_text($submission->data1, $submission->data2))).')';
272         } else if ($CFG->assignment_itemstocount == ASSIGNMENT_COUNT_LETTERS) {
273             $wordcount .= '('.get_string('numletters', '', count_letters(format_text($submission->data1, $submission->data2))).')';
274         }
275         $wordcount .= '</p>';
277         $text = file_rewrite_pluginfile_urls($submission->data1, 'pluginfile.php', $this->context->id, 'mod_assignment', $this->filearea, $submission->id);
278         return $wordcount . format_text($text, $submission->data2, array('overflowdiv'=>true));
281         }
283     function preprocess_submission(&$submission) {
284         if ($this->assignment->var1 && empty($submission->submissioncomment)) {  // comment inline
285             if ($this->usehtmleditor) {
286                 // Convert to html, clean & copy student data to teacher
287                 $submission->submissioncomment = format_text($submission->data1, $submission->data2);
288                 $submission->format = FORMAT_HTML;
289             } else {
290                 // Copy student data to teacher
291                 $submission->submissioncomment = $submission->data1;
292                 $submission->format = $submission->data2;
293             }
294         }
295     }
297     function setup_elements(&$mform) {
298         global $CFG, $COURSE;
300         $ynoptions = array( 0 => get_string('no'), 1 => get_string('yes'));
302         $mform->addElement('select', 'resubmit', get_string('allowresubmit', 'assignment'), $ynoptions);
303         $mform->addHelpButton('resubmit', 'allowresubmit', 'assignment');
304         $mform->setDefault('resubmit', 0);
306         $mform->addElement('select', 'emailteachers', get_string('emailteachers', 'assignment'), $ynoptions);
307         $mform->addHelpButton('emailteachers', 'emailteachers', 'assignment');
308         $mform->setDefault('emailteachers', 0);
310         $mform->addElement('select', 'var1', get_string('commentinline', 'assignment'), $ynoptions);
311         $mform->addHelpButton('var1', 'commentinline', 'assignment');
312         $mform->setDefault('var1', 0);
314         $coursecontext = context_course::instance($COURSE->id);
315         plagiarism_get_form_elements_module($mform, $coursecontext, 'mod_assignment');
317     }
319     function portfolio_exportable() {
320         return true;
321     }
323     function portfolio_load_data($caller) {
324         $submission = $this->get_submission();
325         $fs = get_file_storage();
326         if ($files = $fs->get_area_files($this->context->id, 'mod_assignment', $this->filearea, $submission->id, "timemodified", false)) {
327             $caller->set('multifiles', $files);
328         }
329     }
331     function portfolio_get_sha1($caller) {
332         $submission = $this->get_submission();
333         $textsha1 = sha1(format_text($submission->data1, $submission->data2));
334         $filesha1 = '';
335         try {
336             $filesha1 = $caller->get_sha1_file();
337         } catch (portfolio_caller_exception $e) {} // no files
338         return sha1($textsha1 . $filesha1);
339     }
341     function portfolio_prepare_package($exporter, $user) {
342         $submission = $this->get_submission($user->id);
343         $options = portfolio_format_text_options();
344         $html = format_text($submission->data1, $submission->data2, $options);
345         $html = portfolio_rewrite_pluginfile_urls($html, $this->context->id, 'mod_assignment', $this->filearea, $submission->id, $exporter->get('format'));
346         if (in_array($exporter->get('formatclass'), array(PORTFOLIO_FORMAT_PLAINHTML, PORTFOLIO_FORMAT_RICHHTML))) {
347             if ($files = $exporter->get('caller')->get('multifiles')) {
348                 foreach ($files as $f) {
349                     $exporter->copy_existing_file($f);
350                 }
351             }
352             return $exporter->write_new_file($html, 'assignment.html', !empty($files));
353         } else if ($exporter->get('formatclass') == PORTFOLIO_FORMAT_LEAP2A) {
354             $leapwriter = $exporter->get('format')->leap2a_writer();
355             $entry = new portfolio_format_leap2a_entry('assignmentonline' . $this->assignment->id, $this->assignment->name, 'resource', $html);
356             $entry->add_category('web', 'resource_type');
357             $entry->published = $submission->timecreated;
358             $entry->updated = $submission->timemodified;
359             $entry->author = $user;
360             $leapwriter->add_entry($entry);
361             if ($files = $exporter->get('caller')->get('multifiles')) {
362                 $leapwriter->link_files($entry, $files, 'assignmentonline' . $this->assignment->id . 'file');
363                 foreach ($files as $f) {
364                     $exporter->copy_existing_file($f);
365                 }
366             }
367             $exporter->write_new_file($leapwriter->to_xml(), $exporter->get('format')->manifest_name(), true);
368         } else {
369             debugging('invalid format class: ' . $exporter->get('formatclass'));
370         }
371     }
373     function extend_settings_navigation($node) {
374         global $PAGE, $CFG, $USER;
376         // get users submission if there is one
377         $submission = $this->get_submission();
378         if (is_enrolled($PAGE->cm->context, $USER, 'mod/assignment:submit')) {
379             $editable = $this->isopen() && (!$submission || $this->assignment->resubmit || !$submission->timemarked);
380         } else {
381             $editable = false;
382         }
384         // If the user has submitted something add a bit more stuff
385         if ($submission) {
386             // Add a view link to the settings nav
387             $link = new moodle_url('/mod/assignment/view.php', array('id'=>$PAGE->cm->id));
388             $node->add(get_string('viewmysubmission', 'assignment'), $link, navigation_node::TYPE_SETTING);
390             if (!empty($submission->timemodified)) {
391                 $submittednode = $node->add(get_string('submitted', 'assignment') . ' ' . userdate($submission->timemodified));
392                 $submittednode->text = preg_replace('#([^,])\s#', '$1&nbsp;', $submittednode->text);
393                 $submittednode->add_class('note');
394                 if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
395                     $submittednode->add_class('early');
396                 } else {
397                     $submittednode->add_class('late');
398                 }
399             }
400         }
402         if (!$submission || $editable) {
403             // If this assignment is editable once submitted add an edit link to the settings nav
404             $link = new moodle_url('/mod/assignment/view.php', array('id'=>$PAGE->cm->id, 'edit'=>1, 'sesskey'=>sesskey()));
405             $node->add(get_string('editmysubmission', 'assignment'), $link, navigation_node::TYPE_SETTING);
406         }
407     }
409     public function send_file($filearea, $args, $forcedownload, array $options=array()) {
410         global $USER;
411         require_capability('mod/assignment:view', $this->context);
413         $fullpath = "/{$this->context->id}/mod_assignment/$filearea/".implode('/', $args);
415         $fs = get_file_storage();
416         if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
417             send_file_not_found();
418         }
420         if (($USER->id != $file->get_userid()) && !has_capability('mod/assignment:grade', $this->context)) {
421             send_file_not_found();
422         }
424         session_get_instance()->write_close(); // unlock session during fileserving
426         send_stored_file($file, 60*60, 0, true, $options);
427     }
429     /**
430      * creates a zip of all assignment submissions and sends a zip to the browser
431      */
432     public function download_submissions() {
433         global $CFG, $DB;
435         raise_memory_limit(MEMORY_EXTRA);
437         $submissions = $this->get_submissions('','');
438         if (empty($submissions)) {
439             print_error('errornosubmissions', 'assignment');
440         }
441         $filesforzipping = array();
443         //NOTE: do not create any stuff in temp directories, we now support unicode file names and that would not work, sorry
445         //online assignment can use html
446         $filextn=".html";
448         $groupmode = groups_get_activity_groupmode($this->cm);
449         $groupid = 0;   // All users
450         $groupname = '';
451         if ($groupmode) {
452             $groupid = groups_get_activity_group($this->cm, true);
453             $groupname = groups_get_group_name($groupid).'-';
454         }
455         $filename = str_replace(' ', '_', clean_filename($this->course->shortname.'-'.$this->assignment->name.'-'.$groupname.$this->assignment->id.".zip")); //name of new zip file.
456         foreach ($submissions as $submission) {
457             $a_userid = $submission->userid; //get userid
458             if ((groups_is_member($groupid,$a_userid)or !$groupmode or !$groupid)) {
459                 $a_assignid = $submission->assignment; //get name of this assignment for use in the file names.
460                 $a_user = $DB->get_record("user", array("id"=>$a_userid),'id,username,firstname,lastname'); //get user firstname/lastname
461                 $submissioncontent = "<html><body>". format_text($submission->data1, $submission->data2). "</body></html>";      //fetched from database
462                 //get file name.html
463                 $fileforzipname =  clean_filename(fullname($a_user) . "_" .$a_userid.$filextn);
464                 $filesforzipping[$fileforzipname] = array($submissioncontent);
465             }
466         }      //end of foreach
468         if ($zipfile = assignment_pack_files($filesforzipping)) {
469             send_temp_file($zipfile, $filename); //send file and delete after sending.
470         }
471     }
474 class mod_assignment_online_edit_form extends moodleform {
475     function definition() {
476         $mform = $this->_form;
478         list($data, $editoroptions) = $this->_customdata;
480         // visible elements
481         $mform->addElement('editor', 'text_editor', get_string('submission', 'assignment'), null, $editoroptions);
482         $mform->setType('text_editor', PARAM_RAW); // to be cleaned before display
483         $mform->addRule('text_editor', get_string('required'), 'required', null, 'client');
485         // hidden params
486         $mform->addElement('hidden', 'id');
487         $mform->setType('id', PARAM_INT);
489         $mform->addElement('hidden', 'edit');
490         $mform->setType('edit', PARAM_INT);
492         // buttons
493         $this->add_action_buttons();
495         $this->set_data($data);
496     }