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