f4dce79828ac253b14b24cb77d269ad0a30e26ad
[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 /**
6  * Extend the base assignment class for assignments where you upload a single file
7  *
8  */
9 class assignment_online extends assignment_base {
11     var $filearea = 'submission';
13     function assignment_online($cmid='staticonly', $assignment=NULL, $cm=NULL, $course=NULL) {
14         parent::assignment_base($cmid, $assignment, $cm, $course);
15         $this->type = 'online';
16     }
18     function view() {
19         global $OUTPUT, $CFG, $USER, $PAGE;
21         $edit  = optional_param('edit', 0, PARAM_BOOL);
22         $saved = optional_param('saved', 0, PARAM_BOOL);
24         $context = get_context_instance(CONTEXT_MODULE, $this->cm->id);
25         require_capability('mod/assignment:view', $context);
27         $submission = $this->get_submission($USER->id, false);
29         //Guest can not submit nor edit an assignment (bug: 4604)
30         if (!is_enrolled($this->context, $USER, 'mod/assignment:submit')) {
31             $editable = false;
32         } else {
33             $editable = $this->isopen() && (!$submission || $this->assignment->resubmit || !$submission->timemarked);
34         }
35         $editmode = ($editable and $edit);
37         if ($editmode) {
38             // prepare form and process submitted data
39             $editoroptions = array('noclean'=>false, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$this->course->maxbytes);
41             $data = new stdClass();
42             $data->id         = $this->cm->id;
43             $data->edit       = 1;
44             if ($submission) {
45                 $data->sid        = $submission->id;
46                 $data->text       = $submission->data1;
47                 $data->textformat = $submission->data2;
48             } else {
49                 $data->sid        = NULL;
50                 $data->text       = '';
51                 $data->textformat = NULL;
52             }
54             $data = file_prepare_standard_editor($data, 'text', $editoroptions, $this->context, 'mod_assignment', $this->filearea, $data->sid);
56             $mform = new mod_assignment_online_edit_form(null, array($data, $editoroptions));
58             if ($mform->is_cancelled()) {
59                 redirect($PAGE->url);
60             }
62             if ($data = $mform->get_data()) {
63                 $submission = $this->get_submission($USER->id, true); //create the submission if needed & its id
65                 $data = file_postupdate_standard_editor($data, 'text', $editoroptions, $this->context, 'mod_assignment', $this->filearea, $submission->id);
67                 $submission = $this->update_submission($data);
69                 //TODO fix log actions - needs db upgrade
70                 add_to_log($this->course->id, 'assignment', 'upload', 'view.php?a='.$this->assignment->id, $this->assignment->id, $this->cm->id);
71                 $this->email_teachers($submission);
73                 //redirect to get updated submission date and word count
74                 redirect(new moodle_url($PAGE->url, array('saved'=>1)));
75             }
76         }
78         add_to_log($this->course->id, "assignment", "view", "view.php?id={$this->cm->id}", $this->assignment->id, $this->cm->id);
80 /// print header, etc. and display form if needed
81         if ($editmode) {
82             $this->view_header(get_string('editmysubmission', 'assignment'));
83         } else {
84             $this->view_header();
85         }
87         $this->view_intro();
89         $this->view_dates();
91         if ($saved) {
92             echo $OUTPUT->notification(get_string('submissionsaved', 'assignment'), 'notifysuccess');
93         }
95         if (is_enrolled($this->context, $USER)) {
96             if ($editmode) {
97                 echo $OUTPUT->box_start('generalbox', 'onlineenter');
98                 $mform->display();
99             } else {
100                 echo $OUTPUT->box_start('generalbox boxwidthwide boxaligncenter', 'online');
101                 if ($submission && has_capability('mod/assignment:exportownsubmission', $this->context)) {
102                     $text = file_rewrite_pluginfile_urls($submission->data1, 'pluginfile.php', $this->context->id, 'mod_assignment', $this->filearea, $submission->id);
103                     echo format_text($text, $submission->data2, array('overflowdiv'=>true));
104                     if ($CFG->enableportfolios) {
105                         require_once($CFG->libdir . '/portfoliolib.php');
106                         $button = new portfolio_add_button();
107                         $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id), '/mod/assignment/locallib.php');
108                         $fs = get_file_storage();
109                         if ($files = $fs->get_area_files($this->context->id, 'mod_assignment', $this->filearea, $submission->id, "timemodified", false)) {
110                             $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
111                         } else {
112                             $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
113                         }
114                         $button->render();
115                     }
116                 } else if ($this->isopen()){    //fix for #4206
117                     echo '<div style="text-align:center">'.get_string('emptysubmission', 'assignment').'</div>';
118                 }
119             }
120             echo $OUTPUT->box_end();
121             if (!$editmode && $editable) {
122                 if (!empty($submission)) {
123                     $submitbutton = "editmysubmission";
124                 } else {
125                     $submitbutton = "addsubmission";
126                 }
127                 echo "<div style='text-align:center'>";
128                 echo $OUTPUT->single_button(new moodle_url('view.php', array('id'=>$this->cm->id, 'edit'=>'1')), get_string($submitbutton, 'assignment'));
129                 echo "</div>";
130             }
132         }
134         $this->view_feedback();
136         $this->view_footer();
137     }
139     /*
140      * Display the assignment dates
141      */
142     function view_dates() {
143         global $USER, $CFG, $OUTPUT;
145         if (!$this->assignment->timeavailable && !$this->assignment->timedue) {
146             return;
147         }
149         echo $OUTPUT->box_start('generalbox boxaligncenter', 'dates');
150         echo '<table>';
151         if ($this->assignment->timeavailable) {
152             echo '<tr><td class="c0">'.get_string('availabledate','assignment').':</td>';
153             echo '    <td class="c1">'.userdate($this->assignment->timeavailable).'</td></tr>';
154         }
155         if ($this->assignment->timedue) {
156             echo '<tr><td class="c0">'.get_string('duedate','assignment').':</td>';
157             echo '    <td class="c1">'.userdate($this->assignment->timedue).'</td></tr>';
158         }
159         $submission = $this->get_submission($USER->id);
160         if ($submission) {
161             echo '<tr><td class="c0">'.get_string('lastedited').':</td>';
162             echo '    <td class="c1">'.userdate($submission->timemodified);
163         /// Decide what to count
164             if ($CFG->assignment_itemstocount == ASSIGNMENT_COUNT_WORDS) {
165                 echo ' ('.get_string('numwords', '', count_words(format_text($submission->data1, $submission->data2))).')</td></tr>';
166             } else if ($CFG->assignment_itemstocount == ASSIGNMENT_COUNT_LETTERS) {
167                 echo ' ('.get_string('numletters', '', count_letters(format_text($submission->data1, $submission->data2))).')</td></tr>';
168             }
169         }
170         echo '</table>';
171         echo $OUTPUT->box_end();
172     }
174     function update_submission($data) {
175         global $CFG, $USER, $DB;
177         $submission = $this->get_submission($USER->id, true);
179         $update = new stdClass();
180         $update->id           = $submission->id;
181         $update->data1        = $data->text;
182         $update->data2        = $data->textformat;
183         $update->timemodified = time();
185         $DB->update_record('assignment_submissions', $update);
187         $submission = $this->get_submission($USER->id);
188         $this->update_grade($submission);
189         return $submission;
190     }
193     function print_student_answer($userid, $return=false){
194         global $OUTPUT;
195         if (!$submission = $this->get_submission($userid)) {
196             return '';
197         }
199         $link = new moodle_url("/mod/assignment/type/online/file.php?id={$this->cm->id}&userid={$submission->userid}");
200         $action = new popup_action('click', $link, 'file'.$userid, array('height' => 450, 'width' => 580));
201         $popup = $OUTPUT->action_link($link, shorten_text(trim(strip_tags(format_text($submission->data1,$submission->data2))), 15), $action, array('title'=>get_string('submission', 'assignment')));
203         $output = '<div class="files">'.
204                   '<img src="'.$OUTPUT->pix_url('f/html') . '" class="icon" alt="html" />'.
205                   $popup .
206                   '</div>';
207                   return $output;
208     }
210     function print_user_files($userid, $return=false) {
211         global $OUTPUT, $CFG;
213         if (!$submission = $this->get_submission($userid)) {
214             return '';
215         }
217         $link = new moodle_url("/mod/assignment/type/online/file.php?id={$this->cm->id}&userid={$submission->userid}");
218         $action = new popup_action('click', $link, 'file'.$userid, array('height' => 450, 'width' => 580));
219         $popup = $OUTPUT->action_link($link, get_string('popupinnewwindow','assignment'), $action, array('title'=>get_string('submission', 'assignment')));
221         $output = '<div class="files">'.
222                   '<img align="middle" src="'.$OUTPUT->pix_url('f/html') . '" height="16" width="16" alt="html" />'.
223                   $popup .
224                   '</div>';
226         $wordcount = '<p id="wordcount">'. $popup . '&nbsp;';
227     /// Decide what to count
228         if ($CFG->assignment_itemstocount == ASSIGNMENT_COUNT_WORDS) {
229             $wordcount .= '('.get_string('numwords', '', count_words(format_text($submission->data1, $submission->data2))).')';
230         } else if ($CFG->assignment_itemstocount == ASSIGNMENT_COUNT_LETTERS) {
231             $wordcount .= '('.get_string('numletters', '', count_letters(format_text($submission->data1, $submission->data2))).')';
232         }
233         $wordcount .= '</p>';
235         $text = file_rewrite_pluginfile_urls($submission->data1, 'pluginfile.php', $this->context->id, 'mod_assignment', $this->filearea, $submission->id);
236         return $wordcount . format_text($text, $submission->data2, array('overflowdiv'=>true));
239         }
241     function preprocess_submission(&$submission) {
242         if ($this->assignment->var1 && empty($submission->submissioncomment)) {  // comment inline
243             if ($this->usehtmleditor) {
244                 // Convert to html, clean & copy student data to teacher
245                 $submission->submissioncomment = format_text($submission->data1, $submission->data2);
246                 $submission->format = FORMAT_HTML;
247             } else {
248                 // Copy student data to teacher
249                 $submission->submissioncomment = $submission->data1;
250                 $submission->format = $submission->data2;
251             }
252         }
253     }
255     function setup_elements(&$mform) {
256         global $CFG, $COURSE;
258         $ynoptions = array( 0 => get_string('no'), 1 => get_string('yes'));
260         $mform->addElement('select', 'resubmit', get_string('allowresubmit', 'assignment'), $ynoptions);
261         $mform->addHelpButton('resubmit', 'allowresubmit', 'assignment');
262         $mform->setDefault('resubmit', 0);
264         $mform->addElement('select', 'emailteachers', get_string('emailteachers', 'assignment'), $ynoptions);
265         $mform->addHelpButton('emailteachers', 'emailteachers', 'assignment');
266         $mform->setDefault('emailteachers', 0);
268         $mform->addElement('select', 'var1', get_string('commentinline', 'assignment'), $ynoptions);
269         $mform->addHelpButton('var1', 'commentinline', 'assignment');
270         $mform->setDefault('var1', 0);
272     }
274     function portfolio_exportable() {
275         return true;
276     }
278     function portfolio_load_data($caller) {
279         $submission = $this->get_submission();
280         $fs = get_file_storage();
281         if ($files = $fs->get_area_files($this->context->id, 'mod_assignment', $this->filearea, $submission->id, "timemodified", false)) {
282             $caller->set('multifiles', $files);
283         }
284     }
286     function portfolio_get_sha1($caller) {
287         $submission = $this->get_submission();
288         $textsha1 = sha1(format_text($submission->data1, $submission->data2));
289         $filesha1 = '';
290         try {
291             $filesha1 = $caller->get_sha1_file();
292         } catch (portfolio_caller_exception $e) {} // no files
293         return sha1($textsha1 . $filesha1);
294     }
296     function portfolio_prepare_package($exporter, $user) {
297         $submission = $this->get_submission($user->id);
298         $options = new stdClass();
299         $options->para = false;
300         $options->filter = false;
301         $html = format_text($submission->data1, $submission->data2, $options);
302         $html = portfolio_rewrite_pluginfile_urls($html, $this->context->id, 'mod_assignment', $this->filearea, $submission->id, $exporter->get('format'));
303         if (in_array($exporter->get('formatclass'), array(PORTFOLIO_FORMAT_PLAINHTML, PORTFOLIO_FORMAT_RICHHTML))) {
304             if ($files = $exporter->get('caller')->get('multifiles')) {
305                 foreach ($files as $f) {
306                     $exporter->copy_existing_file($f);
307                 }
308             }
309             return $exporter->write_new_file($html, 'assignment.html', !empty($files));
310         } else if ($exporter->get('formatclass') == PORTFOLIO_FORMAT_LEAP2A) {
311             $leapwriter = $exporter->get('format')->leap2a_writer();
312             $entry = new portfolio_format_leap2a_entry('assignmentonline' . $this->assignment->id, $this->assignment->name, 'resource', $html);
313             $entry->add_category('web', 'resource_type');
314             $entry->published = $submission->timecreated;
315             $entry->updated = $submission->timemodified;
316             $entry->author = $user;
317             $leapwriter->add_entry($entry);
318             if ($files = $exporter->get('caller')->get('multifiles')) {
319                 $leapwriter->link_files($entry, $files, 'assignmentonline' . $this->assignment->id . 'file');
320                 foreach ($files as $f) {
321                     $exporter->copy_existing_file($f);
322                 }
323             }
324             $exporter->write_new_file($leapwriter->to_xml(), $exporter->get('format')->manifest_name(), true);
325         } else {
326             debugging('invalid format class: ' . $exporter->get('formatclass'));
327         }
328     }
330     function extend_settings_navigation($node) {
331         global $PAGE, $CFG, $USER;
333         // get users submission if there is one
334         $submission = $this->get_submission();
335         if (is_enrolled($PAGE->cm->context, $USER, 'mod/assignment:submit')) {
336             $editable = $this->isopen() && (!$submission || $this->assignment->resubmit || !$submission->timemarked);
337         } else {
338             $editable = false;
339         }
341         // If the user has submitted something add a bit more stuff
342         if ($submission) {
343             // Add a view link to the settings nav
344             $link = new moodle_url('/mod/assignment/view.php', array('id'=>$PAGE->cm->id));
345             $node->add(get_string('viewmysubmission', 'assignment'), $link, navigation_node::TYPE_SETTING);
347             if (!empty($submission->timemodified)) {
348                 $submittednode = $node->add(get_string('submitted', 'assignment') . ' ' . userdate($submission->timemodified));
349                 $submittednode->text = preg_replace('#([^,])\s#', '$1&nbsp;', $submittednode->text);
350                 $submittednode->add_class('note');
351                 if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
352                     $submittednode->add_class('early');
353                 } else {
354                     $submittednode->add_class('late');
355                 }
356             }
357         }
359         if (!$submission || $editable) {
360             // If this assignment is editable once submitted add an edit link to the settings nav
361             $link = new moodle_url('/mod/assignment/view.php', array('id'=>$PAGE->cm->id, 'edit'=>1, 'sesskey'=>sesskey()));
362             $node->add(get_string('editmysubmission', 'assignment'), $link, navigation_node::TYPE_SETTING);
363         }
364     }
366     public function send_file($filearea, $args) {
367         global $USER;
368         require_capability('mod/assignment:view', $this->context);
370         $fullpath = "/{$this->context->id}/mod_assignment/$filearea/".implode('/', $args);
372         $fs = get_file_storage();
373         if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
374             send_file_not_found();
375         }
377         if (($USER->id != $file->get_userid()) && !has_capability('mod/assignment:grade', $this->context)) {
378             send_file_not_found();
379         }
381         session_get_instance()->write_close(); // unlock session during fileserving
382         send_stored_file($file, 60*60, 0, true);
383     }
385     /**
386      * creates a zip of all assignment submissions and sends a zip to the browser
387      */
388     public function download_submissions() {
389         global $CFG, $DB;
391         raise_memory_limit(MEMORY_EXTRA);
393         $submissions = $this->get_submissions('','');
394         if (empty($submissions)) {
395             print_error('errornosubmissions', 'assignment');
396         }
397         $filesforzipping = array();
399         //NOTE: do not create any stuff in temp directories, we now support unicode file names and that would not work, sorry
401         //online assignment can use html
402         $filextn=".html";
404         $groupmode = groups_get_activity_groupmode($this->cm);
405         $groupid = 0;   // All users
406         $groupname = '';
407         if ($groupmode) {
408             $groupid = groups_get_activity_group($this->cm, true);
409             $groupname = groups_get_group_name($groupid).'-';
410         }
411         $filename = str_replace(' ', '_', clean_filename($this->course->shortname.'-'.$this->assignment->name.'-'.$groupname.$this->assignment->id.".zip")); //name of new zip file.
412         foreach ($submissions as $submission) {
413             $a_userid = $submission->userid; //get userid
414             if ((groups_is_member($groupid,$a_userid)or !$groupmode or !$groupid)) {
415                 $a_assignid = $submission->assignment; //get name of this assignment for use in the file names.
416                 $a_user = $DB->get_record("user", array("id"=>$a_userid),'id,username,firstname,lastname'); //get user firstname/lastname
417                 $submissioncontent = "<html><body>". format_text($submission->data1, $submission->data2). "</body></html>";      //fetched from database
418                 //get file name.html
419                 $fileforzipname =  clean_filename(fullname($a_user) . "_" .$a_userid.$filextn);
420                 $filesforzipping[$fileforzipname] = array($submissioncontent);
421             }
422         }      //end of foreach
424         if ($zipfile = assignment_pack_files($filesforzipping)) {
425             send_temp_file($zipfile, $filename); //send file and delete after sending.
426         }
427     }
430 class mod_assignment_online_edit_form extends moodleform {
431     function definition() {
432         $mform = $this->_form;
434         list($data, $editoroptions) = $this->_customdata;
436         // visible elements
437         $mform->addElement('editor', 'text_editor', get_string('submission', 'assignment'), null, $editoroptions);
438         $mform->setType('text_editor', PARAM_RAW); // to be cleaned before display
439         $mform->addRule('text_editor', get_string('required'), 'required', null, 'client');
441         // hidden params
442         $mform->addElement('hidden', 'id');
443         $mform->setType('id', PARAM_INT);
445         $mform->addElement('hidden', 'edit');
446         $mform->setType('edit', PARAM_INT);
448         // buttons
449         $this->add_action_buttons();
451         $this->set_data($data);
452     }