MDL-33547: Fix for mod_assign portfolio export for a list of files.
[moodle.git] / mod / assign / locallib.php
CommitLineData
bbd0e548
DW
1<?php
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * This file contains the definition for the class assignment
19 *
20 * This class provides all the functionality for the new assign module.
21 *
22 * @package mod_assign
23 * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 */
26
27defined('MOODLE_INTERNAL') || die();
28
29/**
30 * Assignment submission statuses
31 */
32define('ASSIGN_SUBMISSION_STATUS_DRAFT', 'draft'); // student thinks it is a draft
33define('ASSIGN_SUBMISSION_STATUS_SUBMITTED', 'submitted'); // student thinks it is finished
34
35/**
36 * Search filters for grading page
37 */
38define('ASSIGN_FILTER_SUBMITTED', 'submitted');
39define('ASSIGN_FILTER_SINGLE_USER', 'singleuser');
40define('ASSIGN_FILTER_REQUIRE_GRADING', 'require_grading');
41
bbd0e548
DW
42/** Include accesslib.php */
43require_once($CFG->libdir.'/accesslib.php');
44/** Include formslib.php */
45require_once($CFG->libdir.'/formslib.php');
46/** Include repository/lib.php */
47require_once($CFG->dirroot . '/repository/lib.php');
48/** Include local mod_form.php */
49require_once($CFG->dirroot.'/mod/assign/mod_form.php');
bbd0e548
DW
50/** gradelib.php */
51require_once($CFG->libdir.'/gradelib.php');
52/** grading lib.php */
53require_once($CFG->dirroot.'/grade/grading/lib.php');
54/** Include feedbackplugin.php */
55require_once($CFG->dirroot.'/mod/assign/feedbackplugin.php');
56/** Include submissionplugin.php */
57require_once($CFG->dirroot.'/mod/assign/submissionplugin.php');
58/** Include renderable.php */
59require_once($CFG->dirroot.'/mod/assign/renderable.php');
60/** Include gradingtable.php */
61require_once($CFG->dirroot.'/mod/assign/gradingtable.php');
62/** Include eventslib.php */
63require_once($CFG->libdir.'/eventslib.php');
64
65
66/**
67 * Standard base class for mod_assign (assignment types).
68 *
69 * @package mod_assign
70 * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
71 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
72 */
73class assign {
74
75
76 /** @var stdClass the assignment record that contains the global settings for this assign instance */
77 private $instance;
78
79 /** @var context the context of the course module for this assign instance (or just the course if we are
80 creating a new one) */
81 private $context;
82
83 /** @var stdClass the course this assign instance belongs to */
84 private $course;
bc5a657b 85
cfc81f03
DW
86 /** @var stdClass the admin config for all assign instances */
87 private $adminconfig;
88
bbd0e548
DW
89
90 /** @var assign_renderer the custom renderer for this module */
91 private $output;
92
93 /** @var stdClass the course module for this assign instance */
94 private $coursemodule;
95
96 /** @var array cache for things like the coursemodule name or the scale menu - only lives for a single
97 request */
98 private $cache;
99
100 /** @var array list of the installed submission plugins */
101 private $submissionplugins;
102
103 /** @var array list of the installed feedback plugins */
104 private $feedbackplugins;
105
106 /** @var string action to be used to return to this page (without repeating any form submissions etc.) */
107 private $returnaction = 'view';
108
109 /** @var array params to be used to return to this page */
110 private $returnparams = array();
111
112 /** @var string modulename prevents excessive calls to get_string */
f5b32abe 113 private static $modulename = null;
bbd0e548
DW
114
115 /** @var string modulenameplural prevents excessive calls to get_string */
f5b32abe 116 private static $modulenameplural = null;
bbd0e548
DW
117
118 /**
119 * Constructor for the base assign class
120 *
121 * @param mixed $coursemodulecontext context|null the course module context (or the course context if the coursemodule has not been created yet)
122 * @param mixed $coursemodule the current course module if it was already loaded - otherwise this class will load one from the context as required
123 * @param mixed $course the current course if it was already loaded - otherwise this class will load one from the context as required
124 */
125 public function __construct($coursemodulecontext, $coursemodule, $course) {
126 global $PAGE;
127
128 $this->context = $coursemodulecontext;
129 $this->coursemodule = $coursemodule;
130 $this->course = $course;
131 $this->cache = array(); // temporary cache only lives for a single request - used to reduce db lookups
132
133 $this->submissionplugins = $this->load_plugins('assignsubmission');
134 $this->feedbackplugins = $this->load_plugins('assignfeedback');
135 $this->output = $PAGE->get_renderer('mod_assign');
136 }
137
138 /**
139 * Set the action and parameters that can be used to return to the current page
140 *
141 * @param string $action The action for the current page
142 * @param array $params An array of name value pairs which form the parameters to return to the current page
143 * @return void
144 */
145 public function register_return_link($action, $params) {
146 $this->returnaction = $action;
147 $this->returnparams = $params;
148 }
149
150 /**
151 * Return an action that can be used to get back to the current page
152 * @return string action
153 */
154 public function get_return_action() {
155 return $this->returnaction;
156 }
157
158 /**
159 * Based on the current assignment settings should we display the intro
160 * @return bool showintro
161 */
162 private function show_intro() {
163 if ($this->get_instance()->alwaysshowdescription ||
164 time() > $this->get_instance()->allowsubmissionsfromdate) {
165 return true;
166 }
167 return false;
168 }
169
170 /**
171 * Return a list of parameters that can be used to get back to the current page
172 * @return array params
173 */
174 public function get_return_params() {
175 return $this->returnparams;
176 }
177
178 /**
179 * Set the submitted form data
180 * @param stdClass $data The form data (instance)
181 */
182 public function set_instance(stdClass $data) {
183 $this->instance = $data;
184 }
185
186 /**
187 * Set the context
188 * @param context $context The new context
189 */
190 public function set_context(context $context) {
191 $this->context = $context;
192 }
193
194 /**
195 * Set the course data
196 * @param stdClass $course The course data
197 */
198 public function set_course(stdClass $course) {
199 $this->course = $course;
200 }
201
202 /**
203 * get list of feedback plugins installed
204 * @return array
205 */
206 public function get_feedback_plugins() {
207 return $this->feedbackplugins;
208 }
209
210 /**
211 * get list of submission plugins installed
212 * @return array
213 */
214 public function get_submission_plugins() {
215 return $this->submissionplugins;
216 }
217
218
219 /**
220 * get a specific submission plugin by its type
221 * @param string $subtype assignsubmission | assignfeedback
222 * @param string $type
223 * @return mixed assign_plugin|null
224 */
225 private function get_plugin_by_type($subtype, $type) {
226 $shortsubtype = substr($subtype, strlen('assign'));
227 $name = $shortsubtype . 'plugins';
228 $pluginlist = $this->$name;
229 foreach ($pluginlist as $plugin) {
230 if ($plugin->get_type() == $type) {
231 return $plugin;
232 }
233 }
234 return null;
235 }
236
237 /**
238 * Get a feedback plugin by type
239 * @param string $type - The type of plugin e.g comments
240 * @return mixed assign_feedback_plugin|null
241 */
242 public function get_feedback_plugin_by_type($type) {
243 return $this->get_plugin_by_type('assignfeedback', $type);
244 }
245
246 /**
247 * Get a submission plugin by type
248 * @param string $type - The type of plugin e.g comments
249 * @return mixed assign_submission_plugin|null
250 */
251 public function get_submission_plugin_by_type($type) {
252 return $this->get_plugin_by_type('assignsubmission', $type);
253 }
254
255 /**
256 * Load the plugins from the sub folders under subtype
257 * @param string $subtype - either submission or feedback
258 * @return array - The sorted list of plugins
259 */
260 private function load_plugins($subtype) {
261 global $CFG;
262 $result = array();
263
264 $names = get_plugin_list($subtype);
265
266 foreach ($names as $name => $path) {
267 if (file_exists($path . '/locallib.php')) {
268 require_once($path . '/locallib.php');
269
270 $shortsubtype = substr($subtype, strlen('assign'));
271 $pluginclass = 'assign_' . $shortsubtype . '_' . $name;
272
273 $plugin = new $pluginclass($this, $name);
274
275 if ($plugin instanceof assign_plugin) {
276 $idx = $plugin->get_sort_order();
277 while (array_key_exists($idx, $result)) $idx +=1;
278 $result[$idx] = $plugin;
279 }
280 }
281 }
282 ksort($result);
283 return $result;
284 }
285
286
287 /**
288 * Display the assignment, used by view.php
289 *
290 * The assignment is displayed differently depending on your role,
291 * the settings for the assignment and the status of the assignment.
292 * @param string $action The current action if any.
293 * @return void
294 */
295 public function view($action='') {
296
297 $o = '';
298 $mform = null;
299
300 // handle form submissions first
301 if ($action == 'savesubmission') {
302 $action = 'editsubmission';
303 if ($this->process_save_submission($mform)) {
304 $action = 'view';
305 }
306 } else if ($action == 'lock') {
307 $this->process_lock();
308 $action = 'grading';
309 } else if ($action == 'reverttodraft') {
310 $this->process_revert_to_draft();
311 $action = 'grading';
312 } else if ($action == 'unlock') {
313 $this->process_unlock();
314 $action = 'grading';
315 } else if ($action == 'confirmsubmit') {
316 $this->process_submit_for_grading();
317 // save and show next button
318 } else if ($action == 'batchgradingoperation') {
319 $this->process_batch_grading_operation();
320 $action = 'grading';
321 } else if ($action == 'submitgrade') {
322 if (optional_param('saveandshownext', null, PARAM_ALPHA)) {
323 //save and show next
324 $action = 'grade';
325 if ($this->process_save_grade($mform)) {
326 $action = 'nextgrade';
327 }
328 } else if (optional_param('nosaveandprevious', null, PARAM_ALPHA)) {
329 $action = 'previousgrade';
330 } else if (optional_param('nosaveandnext', null, PARAM_ALPHA)) {
331 //show next button
332 $action = 'nextgrade';
333 } else if (optional_param('savegrade', null, PARAM_ALPHA)) {
334 //save changes button
335 $action = 'grade';
336 if ($this->process_save_grade($mform)) {
337 $action = 'grading';
338 }
339 } else {
340 //cancel button
341 $action = 'grading';
342 }
bf78ebd6
DW
343 }else if ($action == 'quickgrade') {
344 $message = $this->process_save_quick_grades();
345 $action = 'quickgradingresult';
bbd0e548
DW
346 }else if ($action == 'saveoptions') {
347 $this->process_save_grading_options();
348 $action = 'grading';
349 }
350
351 $returnparams = array('rownum'=>optional_param('rownum', 0, PARAM_INT));
352 $this->register_return_link($action, $returnparams);
353
354 // now show the right view page
355 if ($action == 'previousgrade') {
356 $mform = null;
357 $o .= $this->view_single_grade_page($mform, -1);
bf78ebd6
DW
358 } else if ($action == 'quickgradingresult') {
359 $mform = null;
360 $o .= $this->view_quickgrading_result($message);
bbd0e548
DW
361 } else if ($action == 'nextgrade') {
362 $mform = null;
363 $o .= $this->view_single_grade_page($mform, 1);
364 } else if ($action == 'redirect') {
365 redirect(required_param('url', PARAM_TEXT));
366 } else if ($action == 'grade') {
367 $o .= $this->view_single_grade_page($mform);
368 } else if ($action == 'viewpluginassignfeedback') {
369 $o .= $this->view_plugin_content('assignfeedback');
370 } else if ($action == 'viewpluginassignsubmission') {
371 $o .= $this->view_plugin_content('assignsubmission');
372 } else if ($action == 'editsubmission') {
373 $o .= $this->view_edit_submission_page($mform);
374 } else if ($action == 'grading') {
375 $o .= $this->view_grading_page();
376 } else if ($action == 'downloadall') {
377 $o .= $this->download_submissions();
378 } else if ($action == 'submit') {
379 $o .= $this->check_submit_for_grading();
380 } else {
381 $o .= $this->view_submission_page();
382 }
383
384 return $o;
385 }
386
387
388 /**
389 * Add this instance to the database
390 *
391 * @param stdClass $formdata The data submitted from the form
392 * @param bool $callplugins This is used to skip the plugin code
393 * when upgrading an old assignment to a new one (the plugins get called manually)
394 * @return mixed false if an error occurs or the int id of the new instance
395 */
396 public function add_instance(stdClass $formdata, $callplugins) {
397 global $DB;
398
399 $err = '';
400
401 // add the database record
402 $update = new stdClass();
403 $update->name = $formdata->name;
404 $update->timemodified = time();
405 $update->timecreated = time();
406 $update->course = $formdata->course;
407 $update->courseid = $formdata->course;
408 $update->intro = $formdata->intro;
409 $update->introformat = $formdata->introformat;
410 $update->alwaysshowdescription = $formdata->alwaysshowdescription;
411 $update->preventlatesubmissions = $formdata->preventlatesubmissions;
412 $update->submissiondrafts = $formdata->submissiondrafts;
413 $update->sendnotifications = $formdata->sendnotifications;
75f87a57 414 $update->sendlatenotifications = $formdata->sendlatenotifications;
bbd0e548
DW
415 $update->duedate = $formdata->duedate;
416 $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
417 $update->grade = $formdata->grade;
418 $returnid = $DB->insert_record('assign', $update);
419 $this->instance = $DB->get_record('assign', array('id'=>$returnid), '*', MUST_EXIST);
420 // cache the course record
421 $this->course = $DB->get_record('course', array('id'=>$formdata->course), '*', MUST_EXIST);
422
423 if ($callplugins) {
424 // call save_settings hook for submission plugins
425 foreach ($this->submissionplugins as $plugin) {
426 if (!$this->update_plugin_instance($plugin, $formdata)) {
427 print_error($plugin->get_error());
428 return false;
429 }
430 }
431 foreach ($this->feedbackplugins as $plugin) {
432 if (!$this->update_plugin_instance($plugin, $formdata)) {
433 print_error($plugin->get_error());
434 return false;
435 }
436 }
437
438 // in the case of upgrades the coursemodule has not been set so we need to wait before calling these two
439 // TODO: add event to the calendar
440 $this->update_calendar($formdata->coursemodule);
441 // TODO: add the item in the gradebook
442 $this->update_gradebook(false, $formdata->coursemodule);
443
444 }
445
446 $update = new stdClass();
447 $update->id = $this->get_instance()->id;
448 $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
449 $DB->update_record('assign', $update);
450
451 return $returnid;
452 }
453
454 /**
455 * Delete all grades from the gradebook for this assignment
456 *
457 * @return bool
458 */
459 private function delete_grades() {
460 global $CFG;
461
462 return grade_update('mod/assign', $this->get_course()->id, 'mod', 'assign', $this->get_instance()->id, 0, NULL, array('deleted'=>1)) == GRADE_UPDATE_OK;
463 }
464
465 /**
466 * Delete this instance from the database
467 *
468 * @return bool false if an error occurs
469 */
470 public function delete_instance() {
471 global $DB;
472 $result = true;
473
474 foreach ($this->submissionplugins as $plugin) {
475 if (!$plugin->delete_instance()) {
476 print_error($plugin->get_error());
477 $result = false;
478 }
479 }
480 foreach ($this->feedbackplugins as $plugin) {
481 if (!$plugin->delete_instance()) {
482 print_error($plugin->get_error());
483 $result = false;
484 }
485 }
486
487 // delete files associated with this assignment
488 $fs = get_file_storage();
489 if (! $fs->delete_area_files($this->context->id) ) {
490 $result = false;
491 }
492
493 // delete_records will throw an exception if it fails - so no need for error checking here
494
495 $DB->delete_records('assign_submission', array('assignment'=>$this->get_instance()->id));
496 $DB->delete_records('assign_grades', array('assignment'=>$this->get_instance()->id));
497 $DB->delete_records('assign_plugin_config', array('assignment'=>$this->get_instance()->id));
498
499 // delete items from the gradebook
500 if (! $this->delete_grades()) {
501 $result = false;
502 }
503
504 // delete the instance
505 $DB->delete_records('assign', array('id'=>$this->get_instance()->id));
506
507 return $result;
508 }
509
510 /**
511 * Update the settings for a single plugin
512 *
513 * @param assign_plugin $plugin The plugin to update
514 * @param stdClass $formdata The form data
515 * @return bool false if an error occurs
516 */
517 private function update_plugin_instance(assign_plugin $plugin, stdClass $formdata) {
518 if ($plugin->is_visible()) {
519 $enabledname = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
520 if ($formdata->$enabledname) {
521 $plugin->enable();
522 if (!$plugin->save_settings($formdata)) {
523 print_error($plugin->get_error());
524 return false;
525 }
526 } else {
527 $plugin->disable();
528 }
529 }
530 return true;
531 }
532
533 /**
534 * Update the gradebook information for this assignment
535 *
536 * @param bool $reset If true, will reset all grades in the gradbook for this assignment
537 * @param int $coursemoduleid This is required because it might not exist in the database yet
538 * @return bool
539 */
540 public function update_gradebook($reset, $coursemoduleid) {
541 global $CFG;
542 /** Include lib.php */
543 require_once($CFG->dirroot.'/mod/assign/lib.php');
544 $assign = clone $this->get_instance();
545 $assign->cmidnumber = $coursemoduleid;
546 $param = null;
547 if ($reset) {
548 $param = 'reset';
549 }
550
551 return assign_grade_item_update($assign, $param);
552 }
553
cfc81f03 554 /** Load and cache the admin config for this module
bc5a657b 555 *
cfc81f03
DW
556 * @return stdClass the plugin config
557 */
558 public function get_admin_config() {
559 if ($this->adminconfig) {
560 return $this->adminconfig;
561 }
b11808c7 562 $this->adminconfig = get_config('assign');
cfc81f03
DW
563 return $this->adminconfig;
564 }
565
bbd0e548
DW
566
567 /**
568 * Update the calendar entries for this assignment
569 *
570 * @param int $coursemoduleid - Required to pass this in because it might not exist in the database yet
571 * @return bool
572 */
573 public function update_calendar($coursemoduleid) {
574 global $DB, $CFG;
575 require_once($CFG->dirroot.'/calendar/lib.php');
576
577 // special case for add_instance as the coursemodule has not been set yet.
578
579 if ($this->get_instance()->duedate) {
580 $event = new stdClass();
581
582 if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assign', 'instance'=>$this->get_instance()->id))) {
583
584 $event->name = $this->get_instance()->name;
585
586 $event->description = format_module_intro('assign', $this->get_instance(), $coursemoduleid);
587 $event->timestart = $this->get_instance()->duedate;
588
589 $calendarevent = calendar_event::load($event->id);
590 $calendarevent->update($event);
591 } else {
592 $event = new stdClass();
593 $event->name = $this->get_instance()->name;
594 $event->description = format_module_intro('assign', $this->get_instance(), $coursemoduleid);
595 $event->courseid = $this->get_instance()->course;
596 $event->groupid = 0;
597 $event->userid = 0;
598 $event->modulename = 'assign';
599 $event->instance = $this->get_instance()->id;
600 $event->eventtype = 'due';
601 $event->timestart = $this->get_instance()->duedate;
602 $event->timeduration = 0;
603
604 calendar_event::create($event);
605 }
606 } else {
607 $DB->delete_records('event', array('modulename'=>'assign', 'instance'=>$this->get_instance()->id));
608 }
609 }
610
611
612 /**
613 * Update this instance in the database
614 *
615 * @param stdClass $formdata - the data submitted from the form
616 * @return bool false if an error occurs
617 */
618 public function update_instance($formdata) {
619 global $DB;
620
621 $update = new stdClass();
622 $update->id = $formdata->instance;
623 $update->name = $formdata->name;
624 $update->timemodified = time();
625 $update->course = $formdata->course;
626 $update->intro = $formdata->intro;
627 $update->introformat = $formdata->introformat;
628 $update->alwaysshowdescription = $formdata->alwaysshowdescription;
629 $update->preventlatesubmissions = $formdata->preventlatesubmissions;
630 $update->submissiondrafts = $formdata->submissiondrafts;
631 $update->sendnotifications = $formdata->sendnotifications;
75f87a57 632 $update->sendlatenotifications = $formdata->sendlatenotifications;
bbd0e548
DW
633 $update->duedate = $formdata->duedate;
634 $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
635 $update->grade = $formdata->grade;
636
637 $result = $DB->update_record('assign', $update);
638 $this->instance = $DB->get_record('assign', array('id'=>$update->id), '*', MUST_EXIST);
639
640 // load the assignment so the plugins have access to it
641
642 // call save_settings hook for submission plugins
643 foreach ($this->submissionplugins as $plugin) {
644 if (!$this->update_plugin_instance($plugin, $formdata)) {
645 print_error($plugin->get_error());
646 return false;
647 }
648 }
649 foreach ($this->feedbackplugins as $plugin) {
650 if (!$this->update_plugin_instance($plugin, $formdata)) {
651 print_error($plugin->get_error());
652 return false;
653 }
654 }
655
656
657 // update the database record
658
659
660 // update all the calendar events
661 $this->update_calendar($this->get_course_module()->id);
662
663 $this->update_gradebook(false, $this->get_course_module()->id);
664
665 $update = new stdClass();
666 $update->id = $this->get_instance()->id;
667 $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
668 $DB->update_record('assign', $update);
669
670
671
672
673
674 return $result;
675 }
676
677 /**
678 * add elements in grading plugin form
679 *
680 * @param mixed $grade stdClass|null
681 * @param MoodleQuickForm $mform
682 * @param stdClass $data
683 * @return void
684 */
685 private function add_plugin_grade_elements($grade, MoodleQuickForm $mform, stdClass $data) {
686 foreach ($this->feedbackplugins as $plugin) {
687 if ($plugin->is_enabled() && $plugin->is_visible()) {
688 $mform->addElement('header', 'header_' . $plugin->get_type(), $plugin->get_name());
689 if (!$plugin->get_form_elements($grade, $mform, $data)) {
690 $mform->removeElement('header_' . $plugin->get_type());
691 }
692 }
693 }
694 }
695
696
697
698 /**
699 * Add one plugins settings to edit plugin form
700 *
701 * @param assign_plugin $plugin The plugin to add the settings from
702 * @param MoodleQuickForm $mform The form to add the configuration settings to. This form is modified directly (not returned)
703 * @return void
704 */
705 private function add_plugin_settings(assign_plugin $plugin, MoodleQuickForm $mform) {
706 global $CFG;
707 if ($plugin->is_visible()) {
708 // enabled
709 //tied disableIf rule to this select element
710 $mform->addElement('selectyesno', $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $plugin->get_name());
711 $mform->addHelpButton($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', 'enabled', $plugin->get_subtype() . '_' . $plugin->get_type());
712
bbd0e548 713
cfc81f03 714 $default = get_config($plugin->get_subtype() . '_' . $plugin->get_type(), 'default');
bbd0e548
DW
715 if ($plugin->get_config('enabled') !== false) {
716 $default = $plugin->is_enabled();
717 }
718 $mform->setDefault($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $default);
719
720 $plugin->get_settings($mform);
721
722 }
723
724 }
725
726
727 /**
728 * Add settings to edit plugin form
729 *
730 * @param MoodleQuickForm $mform The form to add the configuration settings to. This form is modified directly (not returned)
731 * @return void
732 */
733 public function add_all_plugin_settings(MoodleQuickForm $mform) {
734 $mform->addElement('header', 'general', get_string('submissionsettings', 'assign'));
735
736 foreach ($this->submissionplugins as $plugin) {
737 $this->add_plugin_settings($plugin, $mform);
738
739 }
740 $mform->addElement('header', 'general', get_string('feedbacksettings', 'assign'));
741 foreach ($this->feedbackplugins as $plugin) {
742 $this->add_plugin_settings($plugin, $mform);
743 }
744 }
745
746 /**
747 * Allow each plugin an opportunity to update the defaultvalues
748 * passed in to the settings form (needed to set up draft areas for
749 * editor and filemanager elements)
750 * @param array $defaultvalues
751 */
752 public function plugin_data_preprocessing(&$defaultvalues) {
753 foreach ($this->submissionplugins as $plugin) {
754 if ($plugin->is_visible()) {
755 $plugin->data_preprocessing($defaultvalues);
756 }
757 }
758 foreach ($this->feedbackplugins as $plugin) {
759 if ($plugin->is_visible()) {
760 $plugin->data_preprocessing($defaultvalues);
761 }
762 }
763 }
764
765 /**
766 * Get the name of the current module.
767 *
768 * @return string the module name (Assignment)
769 */
770 protected function get_module_name() {
771 if (isset(self::$modulename)) {
772 return self::$modulename;
773 }
774 self::$modulename = get_string('modulename', 'assign');
775 return self::$modulename;
776 }
777
778 /**
779 * Get the plural name of the current module.
780 *
781 * @return string the module name plural (Assignments)
782 */
783 protected function get_module_name_plural() {
784 if (isset(self::$modulenameplural)) {
785 return self::$modulenameplural;
786 }
787 self::$modulenameplural = get_string('modulenameplural', 'assign');
788 return self::$modulenameplural;
789 }
790
791 /**
792 * Has this assignment been constructed from an instance?
793 *
794 * @return bool
795 */
796 public function has_instance() {
797 return $this->instance || $this->get_course_module();
798 }
799
800 /**
801 * Get the settings for the current instance of this assignment
802 *
803 * @return stdClass The settings
804 */
805 public function get_instance() {
806 global $DB;
807 if ($this->instance) {
808 return $this->instance;
809 }
810 if ($this->get_course_module()) {
811 $this->instance = $DB->get_record('assign', array('id' => $this->get_course_module()->instance), '*', MUST_EXIST);
812 }
813 if (!$this->instance) {
814 throw new coding_exception('Improper use of the assignment class. Cannot load the assignment record.');
815 }
816 return $this->instance;
817 }
818
819 /**
820 * Get the context of the current course
821 * @return mixed context|null The course context
822 */
823 public function get_course_context() {
824 if (!$this->context && !$this->course) {
825 throw new coding_exception('Improper use of the assignment class. Cannot load the course context.');
826 }
827 if ($this->context) {
828 return $this->context->get_course_context();
829 } else {
830 return context_course::instance($this->course->id);
831 }
832 }
833
834
835 /**
836 * Get the current course module
837 *
838 * @return mixed stdClass|null The course module
839 */
840 public function get_course_module() {
841 if ($this->coursemodule) {
842 return $this->coursemodule;
843 }
844 if (!$this->context) {
845 return null;
846 }
847
848 if ($this->context->contextlevel == CONTEXT_MODULE) {
849 $this->coursemodule = get_coursemodule_from_id('assign', $this->context->instanceid, 0, false, MUST_EXIST);
850 return $this->coursemodule;
851 }
852 return null;
853 }
854
855 /**
856 * Get context module
857 *
858 * @return context
859 */
860 public function get_context() {
861 return $this->context;
862 }
863
864 /**
865 * Get the current course
866 * @return mixed stdClass|null The course
867 */
868 public function get_course() {
869 global $DB;
870 if ($this->course) {
871 return $this->course;
872 }
873
874 if (!$this->context) {
875 return null;
876 }
877 $this->course = $DB->get_record('course', array('id' => $this->get_course_context()->instanceid), '*', MUST_EXIST);
878 return $this->course;
879 }
880
881 /**
882 * Return a grade in user-friendly form, whether it's a scale or not
883 *
9682626e 884 * @param mixed $grade int|null
bf78ebd6 885 * @param boolean $editing Are we allowing changes to this grade?
2a4fbc32
SH
886 * @param int $userid The user id the grade belongs to
887 * @param int $modified Timestamp from when the grade was last modified
bbd0e548
DW
888 * @return string User-friendly representation of grade
889 */
bf78ebd6 890 public function display_grade($grade, $editing, $userid=0, $modified=0) {
bbd0e548
DW
891 global $DB;
892
893 static $scalegrades = array();
894
2a4fbc32
SH
895 if ($this->get_instance()->grade >= 0) {
896 // Normal number
bf78ebd6
DW
897 if ($editing) {
898 $o = '<input type="text" name="quickgrade_' . $userid . '" value="' . $grade . '" size="6" maxlength="10" class="quickgrade"/>';
899 $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade,2);
2a4fbc32 900 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
bf78ebd6
DW
901 return $o;
902 } else if ($grade == -1 || $grade === null) {
bbd0e548
DW
903 return '-';
904 } else {
905 return format_float(($grade),2) .'&nbsp;/&nbsp;'. format_float($this->get_instance()->grade,2);
906 }
907
2a4fbc32
SH
908 } else {
909 // Scale
bbd0e548
DW
910 if (empty($this->cache['scale'])) {
911 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
912 $this->cache['scale'] = make_menu_from_list($scale->scale);
913 } else {
914 return '-';
915 }
916 }
bf78ebd6
DW
917 if ($editing) {
918 $o = '<select name="quickgrade_' . $userid . '" class="quickgrade">';
919 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
920 foreach ($this->cache['scale'] as $optionid => $option) {
921 $selected = '';
922 if ($grade == $optionid) {
923 $selected = 'selected="selected"';
924 }
925 $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
926 }
927 $o .= '</select>';
928 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
929 return $o;
930 } else {
931 $scaleid = (int)$grade;
932 if (isset($this->cache['scale'][$scaleid])) {
933 return $this->cache['scale'][$scaleid];
934 }
935 return '-';
bbd0e548 936 }
bbd0e548
DW
937 }
938 }
939
940 /**
941 * Load a list of users enrolled in the current course with the specified permission and group (0 for no group)
942 *
943 * @param int $currentgroup
944 * @param bool $idsonly
945 * @return array List of user records
946 */
947 public function list_participants($currentgroup, $idsonly) {
948 if ($idsonly) {
949 return get_enrolled_users($this->context, "mod/assign:submit", $currentgroup, 'u.id');
950 } else {
951 return get_enrolled_users($this->context, "mod/assign:submit", $currentgroup);
952 }
953 }
954
955 /**
956 * Load a count of users enrolled in the current course with the specified permission and group (0 for no group)
957 *
958 * @param int $currentgroup
959 * @return int number of matching users
960 */
961 public function count_participants($currentgroup) {
962 return count_enrolled_users($this->context, "mod/assign:submit", $currentgroup);
963 }
964
965 /**
966 * Load a count of users enrolled in the current course with the specified permission and group (optional)
967 *
968 * @param string $status The submission status - should match one of the constants
969 * @return int number of matching submissions
970 */
971 public function count_submissions_with_status($status) {
972 global $DB;
973 return $DB->count_records_sql("SELECT COUNT('x')
974 FROM {assign_submission}
975 WHERE assignment = ? AND
976 status = ?", array($this->get_course_module()->instance, $status));
977 }
978
979 /**
980 * Utility function to get the userid for every row in the grading table
981 * so the order can be frozen while we iterate it
982 *
983 * @return array An array of userids
984 */
985 private function get_grading_userid_list(){
986 $filter = get_user_preferences('assign_filter', '');
bf78ebd6 987 $table = new assign_grading_table($this, 0, $filter, 0, false);
bbd0e548
DW
988
989 $useridlist = $table->get_column_data('userid');
990
991 return $useridlist;
992 }
993
994
995 /**
996 * Utility function get the userid based on the row number of the grading table.
997 * This takes into account any active filters on the table.
998 *
999 * @param int $num The row number of the user
1000 * @param bool $last This is set to true if this is the last user in the table
1001 * @return mixed The user id of the matching user or false if there was an error
1002 */
1003 private function get_userid_for_row($num, $last){
1004 if (!array_key_exists('userid_for_row', $this->cache)) {
1005 $this->cache['userid_for_row'] = array();
1006 }
1007 if (array_key_exists($num, $this->cache['userid_for_row'])) {
1008 list($userid, $last) = $this->cache['userid_for_row'][$num];
1009 return $userid;
1010 }
1011
1012 $filter = get_user_preferences('assign_filter', '');
bf78ebd6 1013 $table = new assign_grading_table($this, 0, $filter, 0, false);
bbd0e548
DW
1014
1015 $userid = $table->get_cell_data($num, 'userid', $last);
1016
1017 $this->cache['userid_for_row'][$num] = array($userid, $last);
1018 return $userid;
1019 }
1020
1021 /**
1022 * Return all assignment submissions by ENROLLED students (even empty)
1023 *
1024 * @param string $sort optional field names for the ORDER BY in the sql query
1025 * @param string $dir optional specifying the sort direction, defaults to DESC
1026 * @return array The submission objects indexed by id
1027 */
1028 private function get_all_submissions( $sort="", $dir="DESC") {
1029 global $CFG, $DB;
1030
1031 if ($sort == "lastname" or $sort == "firstname") {
1032 $sort = "u.$sort $dir";
1033 } else if (empty($sort)) {
1034 $sort = "a.timemodified DESC";
1035 } else {
1036 $sort = "a.$sort $dir";
1037 }
1038
1039 return $DB->get_records_sql("SELECT a.*
1040 FROM {assign_submission} a, {user} u
1041 WHERE u.id = a.userid
1042 AND a.assignment = ?
1043 ORDER BY $sort", array($this->get_instance()->id));
1044
1045 }
1046
1047 /**
1048 * Generate zip file from array of given files
1049 *
1050 * @param array $filesforzipping - array of files to pass into archive_to_pathname - this array is indexed by the final file name and each element in the array is an instance of a stored_file object
1051 * @return path of temp file - note this returned file does not have a .zip extension - it is a temp file.
1052 */
1053 private function pack_files($filesforzipping) {
1054 global $CFG;
1055 //create path for new zip file.
1056 $tempzip = tempnam($CFG->tempdir.'/', 'assignment_');
1057 //zip files
1058 $zipper = new zip_packer();
1059 if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
1060 return $tempzip;
1061 }
1062 return false;
1063 }
1064
bbd0e548 1065 /**
3f7b501e
SH
1066 * Finds all assignment notifications that have yet to be mailed out, and mails them.
1067 *
1068 * Cron function to be run periodically according to the moodle cron
bbd0e548
DW
1069 *
1070 * @return bool
1071 */
1072 static function cron() {
3f7b501e 1073 global $DB;
75f87a57
DW
1074
1075 // only ever send a max of one days worth of updates
1076 $yesterday = time() - (24 * 3600);
1077 $timenow = time();
1078
3f7b501e
SH
1079 // Collect all submissions from the past 24 hours that require mailing.
1080 $sql = "SELECT s.*, a.course, a.name, g.*, g.id as gradeid, g.timemodified as lastmodified
1081 FROM {assign} a
1082 JOIN {assign_grades} g ON g.assignment = a.id
1083 LEFT JOIN {assign_submission} s ON s.assignment = a.id AND s.userid = g.userid
1084 WHERE g.timemodified >= :yesterday AND
1085 g.timemodified <= :today AND
1086 g.mailed = 0";
1087 $params = array('yesterday' => $yesterday, 'today' => $timenow);
1088 $submissions = $DB->get_records_sql($sql, $params);
75f87a57 1089
c8314005
SH
1090 if (empty($submissions)) {
1091 mtrace('done.');
1092 return true;
1093 }
1094
75f87a57
DW
1095 mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
1096
3f7b501e
SH
1097 // Preload courses we are going to need those.
1098 $courseids = array();
1099 foreach ($submissions as $submission) {
1100 $courseids[] = $submission->course;
1101 }
1102 // Filter out duplicates
1103 $courseids = array_unique($courseids);
1104 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1105 list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
1106 $sql = "SELECT c.*, {$ctxselect}
1107 FROM {course} c
1108 LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
1109 WHERE c.id {$courseidsql}";
1110 $params['contextlevel'] = CONTEXT_COURSE;
1111 $courses = $DB->get_records_sql($sql, $params);
1112 // Clean up... this could go on for a while.
1113 unset($courseids);
1114 unset($ctxselect);
1115 unset($courseidsql);
1116 unset($params);
1117
1118 // Simple array we'll use for caching modules.
1119 $modcache = array();
1120
1121 // Email students about new feedback
75f87a57
DW
1122 foreach ($submissions as $submission) {
1123
1124 mtrace("Processing assignment submission $submission->id ...");
1125
1126 // do not cache user lookups - could be too many
3f7b501e 1127 if (!$user = $DB->get_record("user", array("id"=>$submission->userid))) {
75f87a57
DW
1128 mtrace("Could not find user $submission->userid");
1129 continue;
1130 }
1131
1132 // use a cache to prevent the same DB queries happening over and over
3f7b501e
SH
1133 if (!array_key_exists($submission->course, $courses)) {
1134 mtrace("Could not find course $submission->course");
1135 continue;
1136 }
1137 $course = $courses[$submission->course];
1138 if (isset($course->ctxid)) {
1139 // Context has not yet been preloaded. Do so now.
1140 context_helper::preload_from_record($course);
75f87a57
DW
1141 }
1142
3f7b501e
SH
1143 // Override the language and timezone of the "current" user, so that
1144 // mail is customised for the receiver.
75f87a57
DW
1145 cron_setup_user($user, $course);
1146
1147 // context lookups are already cached
3f7b501e 1148 $coursecontext = context_course::instance($course->id);
75f87a57 1149 if (!is_enrolled($coursecontext, $user->id)) {
3f7b501e 1150 $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
75f87a57
DW
1151 mtrace(fullname($user)." not an active participant in " . $courseshortname);
1152 continue;
1153 }
1154
3f7b501e 1155 if (!$grader = $DB->get_record("user", array("id"=>$submission->grader))) {
75f87a57
DW
1156 mtrace("Could not find grader $submission->grader");
1157 continue;
1158 }
1159
3f7b501e 1160 if (!array_key_exists($submission->assignment, $modcache)) {
75f87a57
DW
1161 if (! $mod = get_coursemodule_from_instance("assign", $submission->assignment, $course->id)) {
1162 mtrace("Could not find course module for assignment id $submission->assignment");
1163 continue;
1164 }
3f7b501e
SH
1165 $modcache[$submission->assignment] = $mod;
1166 } else {
1167 $mod = $modcache[$submission->assignment];
75f87a57 1168 }
75f87a57
DW
1169 // context lookups are already cached
1170 $contextmodule = context_module::instance($mod->id);
bbd0e548 1171
3f7b501e
SH
1172 if (!$mod->visible) {
1173 // Hold mail notification for hidden assignments until later
75f87a57
DW
1174 continue;
1175 }
1176
1177 // need to send this to the student
3f7b501e
SH
1178 $messagetype = 'feedbackavailable';
1179 $eventtype = 'assign_student_notification';
1180 $updatetime = $submission->lastmodified;
1181 $modulename = get_string('modulename', 'assign');
1182 self::send_assignment_notification($grader, $user, $messagetype, $eventtype, $updatetime, $mod, $contextmodule, $course, $modulename, $submission->name);
75f87a57
DW
1183
1184 $grade = new stdClass();
1185 $grade->id = $submission->gradeid;
1186 $grade->mailed = 1;
1187 $DB->update_record('assign_grades', $grade);
1188
1189 mtrace('Done');
1190 }
1191 mtrace('Done processing ' . count($submissions) . ' assignment submissions');
1192
1193 cron_setup_user();
3f7b501e
SH
1194
1195 // Free up memory just to be sure
1196 unset($courses);
1197 unset($modcache);
bbd0e548
DW
1198
1199 return true;
1200 }
1201
1202 /**
1203 * Update a grade in the grade table for the assignment and in the gradebook
1204 *
1205 * @param stdClass $grade a grade record keyed on id
1206 * @return bool true for success
1207 */
1208 private function update_grade($grade) {
1209 global $DB;
1210
1211 $grade->timemodified = time();
1212
1213 if ($grade->grade && $grade->grade != -1) {
1214 if ($this->get_instance()->grade > 0) {
1215 if (!is_numeric($grade->grade)) {
1216 return false;
1217 } else if ($grade->grade > $this->get_instance()->grade) {
1218 return false;
1219 } else if ($grade->grade < 0) {
1220 return false;
1221 }
1222 } else {
1223 // this is a scale
1224 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
1225 $scaleoptions = make_menu_from_list($scale->scale);
1226 if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
1227 return false;
1228 }
1229 }
1230 }
1231 }
1232
1233 $result = $DB->update_record('assign_grades', $grade);
1234 if ($result) {
1235 $this->gradebook_item_update(null, $grade);
1236 }
1237 return $result;
1238 }
1239
1240 /**
1241 * display the submission that is used by a plugin
1242 * Uses url parameters 'sid', 'gid' and 'plugin'
1243 * @param string $pluginsubtype
1244 * @return string
1245 */
1246 private function view_plugin_content($pluginsubtype) {
1247 global $USER;
1248
1249 $o = '';
1250
1251 $submissionid = optional_param('sid', 0, PARAM_INT);
1252 $gradeid = optional_param('gid', 0, PARAM_INT);
1253 $plugintype = required_param('plugin', PARAM_TEXT);
1254 $item = null;
1255 if ($pluginsubtype == 'assignsubmission') {
1256 $plugin = $this->get_submission_plugin_by_type($plugintype);
1257 if ($submissionid <= 0) {
1258 throw new coding_exception('Submission id should not be 0');
1259 }
1260 $item = $this->get_submission($submissionid);
1261
1262 // permissions
1263 if ($item->userid != $USER->id) {
1264 require_capability('mod/assign:grade', $this->context);
1265 }
1266 $o .= $this->output->render(new assign_header($this->get_instance(),
1267 $this->get_context(),
1268 $this->show_intro(),
1269 $this->get_course_module()->id,
1270 $plugin->get_name()));
1271 $o .= $this->output->render(new assign_submission_plugin_submission($plugin,
1272 $item,
1273 assign_submission_plugin_submission::FULL,
1274 $this->get_course_module()->id,
1275 $this->get_return_action(),
1276 $this->get_return_params()));
1277
1278 $this->add_to_log('view submission', get_string('viewsubmissionforuser', 'assign', $item->userid));
1279 } else {
1280 $plugin = $this->get_feedback_plugin_by_type($plugintype);
1281 if ($gradeid <= 0) {
1282 throw new coding_exception('Grade id should not be 0');
1283 }
1284 $item = $this->get_grade($gradeid);
1285 // permissions
1286 if ($item->userid != $USER->id) {
1287 require_capability('mod/assign:grade', $this->context);
1288 }
1289 $o .= $this->output->render(new assign_header($this->get_instance(),
1290 $this->get_context(),
1291 $this->show_intro(),
1292 $this->get_course_module()->id,
1293 $plugin->get_name()));
1294 $o .= $this->output->render(new assign_feedback_plugin_feedback($plugin,
1295 $item,
1296 assign_feedback_plugin_feedback::FULL,
1297 $this->get_course_module()->id,
1298 $this->get_return_action(),
1299 $this->get_return_params()));
1300 $this->add_to_log('view feedback', get_string('viewfeedbackforuser', 'assign', $item->userid));
1301 }
1302
1303
1304 $o .= $this->view_return_links();
1305
1306 $o .= $this->view_footer();
1307 return $o;
1308 }
1309
1310 /**
1311 * render the content in editor that is often used by plugin
1312 *
1313 * @param string $filearea
1314 * @param int $submissionid
1315 * @param string $plugintype
1316 * @param string $editor
1317 * @param string $component
1318 * @return string
1319 */
1320 public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
1321 global $CFG;
1322
1323 $result = '';
1324
1325 $plugin = $this->get_submission_plugin_by_type($plugintype);
1326
1327 $text = $plugin->get_editor_text($editor, $submissionid);
1328 $format = $plugin->get_editor_format($editor, $submissionid);
1329
1330 $finaltext = file_rewrite_pluginfile_urls($text, 'pluginfile.php', $this->get_context()->id, $component, $filearea, $submissionid);
1331 $result .= format_text($finaltext, $format, array('overflowdiv' => true, 'context' => $this->get_context()));
1332
1333
1334
1335 if ($CFG->enableportfolios) {
1336 require_once($CFG->libdir . '/portfoliolib.php');
1337
1338 $button = new portfolio_add_button();
1339 $button->set_callback_options('assign_portfolio_caller', array('cmid' => $this->get_course_module()->id, 'sid' => $submissionid, 'plugin' => $plugintype, 'editor' => $editor, 'area'=>$filearea), '/mod/assign/portfolio_callback.php');
1340 $fs = get_file_storage();
1341
1342 if ($files = $fs->get_area_files($this->context->id, $component,$filearea, $submissionid, "timemodified", false)) {
1343 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
1344 } else {
1345 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
1346 }
1347 $result .= $button->to_html();
1348 }
1349 return $result;
1350 }
1351
bf78ebd6
DW
1352 /**
1353 * Display a grading error
1354 *
1355 * @param string $message - The description of the result
1356 * @return string
1357 */
1358 private function view_quickgrading_result($message) {
1359 $o = '';
1360 $o .= $this->output->render(new assign_header($this->get_instance(),
1361 $this->get_context(),
1362 $this->show_intro(),
1363 $this->get_course_module()->id,
1364 get_string('quickgradingresult', 'assign')));
1365 $o .= $this->output->render(new assign_quickgrading_result($message, $this->get_course_module()->id));
1366 $o .= $this->view_footer();
1367 return $o;
1368 }
bbd0e548
DW
1369
1370 /**
1371 * Display the page footer
1372 *
bf78ebd6 1373 * @return string
bbd0e548
DW
1374 */
1375 private function view_footer() {
1376 return $this->output->render_footer();
1377 }
1378
1379 /**
1380 * Does this user have grade permission for this assignment
1381 *
1382 * @return bool
1383 */
1384 private function can_grade() {
1385 // Permissions check
1386 if (!has_capability('mod/assign:grade', $this->context)) {
1387 return false;
1388 }
1389
1390 return true;
1391 }
1392
1393 /**
1394 * Download a zip file of all assignment submissions
1395 *
1396 * @return void
1397 */
1398 private function download_submissions() {
1399 global $CFG,$DB;
1400
1401 // more efficient to load this here
1402 require_once($CFG->libdir.'/filelib.php');
1403
1404 // load all submissions
1405 $submissions = $this->get_all_submissions('','');
1406
1407 if (empty($submissions)) {
1408 print_error('errornosubmissions', 'assign');
1409 return;
1410 }
1411
1412 // build a list of files to zip
1413 $filesforzipping = array();
1414 $fs = get_file_storage();
1415
1416 $groupmode = groups_get_activity_groupmode($this->get_course_module());
1417 $groupid = 0; // All users
1418 $groupname = '';
1419 if ($groupmode) {
1420 $groupid = groups_get_activity_group($this->get_course_module(), true);
1421 $groupname = groups_get_group_name($groupid).'-';
1422 }
1423
1424 // construct the zip file name
1425 $filename = str_replace(' ', '_', clean_filename($this->get_course()->shortname.'-'.$this->get_instance()->name.'-'.$groupname.$this->get_course_module()->id.".zip")); //name of new zip file.
1426
1427 // get all the files for each submission
1428 foreach ($submissions as $submission) {
1429 $userid = $submission->userid; //get userid
1430 if ((groups_is_member($groupid,$userid) or !$groupmode or !$groupid)) {
1431 // get the plugins to add their own files to the zip
1432
1433 $user = $DB->get_record("user", array("id"=>$userid),'id,username,firstname,lastname', MUST_EXIST);
1434
1435 $prefix = clean_filename(fullname($user) . "_" .$userid . "_");
1436
1437 foreach ($this->submissionplugins as $plugin) {
1438 if ($plugin->is_enabled() && $plugin->is_visible()) {
1439 $pluginfiles = $plugin->get_files($submission);
1440
1441
1442 foreach ($pluginfiles as $zipfilename => $file) {
1443 $filesforzipping[$prefix . $zipfilename] = $file;
1444 }
1445 }
1446 }
1447
1448 }
1449 } // end of foreach loop
1450 if ($zipfile = $this->pack_files($filesforzipping)) {
1451 $this->add_to_log('download all submissions', get_string('downloadall', 'assign'));
1452 send_temp_file($zipfile, $filename); //send file and delete after sending.
1453 }
1454 }
1455
1456 /**
1457 * Util function to add a message to the log
1458 *
1459 * @param string $action The current action
1460 * @param string $info A detailed description of the change. But no more than 255 characters.
1461 * @param string $url The url to the assign module instance.
1462 * @return void
1463 */
1464 public function add_to_log($action = '', $info = '', $url='') {
1465 global $USER;
1466
1467 $fullurl = 'view.php?id=' . $this->get_course_module()->id;
1468 if ($url != '') {
1469 $fullurl .= '&' . $url;
1470 }
1471
1472 add_to_log($this->get_course()->id, 'assign', $action, $fullurl, $info, $this->get_course_module()->id, $USER->id);
1473 }
1474
1475 /**
1476 * Load the submission object for a particular user, optionally creating it if required
1477 *
1478 * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
1479 * @param bool $create optional Defaults to false. If set to true a new submission object will be created in the database
1480 * @return stdClass The submission
1481 */
1482 private function get_user_submission($userid, $create) {
1483 global $DB, $USER;
1484
1485 if (!$userid) {
1486 $userid = $USER->id;
1487 }
1488 // if the userid is not null then use userid
1489 $submission = $DB->get_record('assign_submission', array('assignment'=>$this->get_instance()->id, 'userid'=>$userid));
1490
1491 if ($submission) {
1492 return $submission;
1493 }
1494 if ($create) {
1495 $submission = new stdClass();
1496 $submission->assignment = $this->get_instance()->id;
1497 $submission->userid = $userid;
1498 $submission->timecreated = time();
1499 $submission->timemodified = $submission->timecreated;
1500
1501 if ($this->get_instance()->submissiondrafts) {
1502 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
1503 } else {
1504 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1505 }
1506 $sid = $DB->insert_record('assign_submission', $submission);
1507 $submission->id = $sid;
1508 return $submission;
1509 }
1510 return false;
1511 }
1512
1513 /**
1514 * Load the submission object from it's id
1515 *
1516 * @param int $submissionid The id of the submission we want
1517 * @return stdClass The submission
1518 */
1519 private function get_submission($submissionid) {
1520 global $DB;
1521
1522 return $DB->get_record('assign_submission', array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid), '*', MUST_EXIST);
1523 }
1524
1525 /**
1526 * This will retrieve a grade object from the db, optionally creating it if required
1527 *
1528 * @param int $userid The user we are grading
1529 * @param bool $create If true the grade will be created if it does not exist
1530 * @return stdClass The grade record
1531 */
1532 private function get_user_grade($userid, $create) {
1533 global $DB, $USER;
1534
1535 if (!$userid) {
1536 $userid = $USER->id;
1537 }
1538
1539 // if the userid is not null then use userid
1540 $grade = $DB->get_record('assign_grades', array('assignment'=>$this->get_instance()->id, 'userid'=>$userid));
1541
1542 if ($grade) {
1543 return $grade;
1544 }
1545 if ($create) {
1546 $grade = new stdClass();
1547 $grade->assignment = $this->get_instance()->id;
1548 $grade->userid = $userid;
1549 $grade->timecreated = time();
1550 $grade->timemodified = $grade->timecreated;
1551 $grade->locked = 0;
1552 $grade->grade = -1;
1553 $grade->grader = $USER->id;
1554 $gid = $DB->insert_record('assign_grades', $grade);
1555 $grade->id = $gid;
1556 return $grade;
1557 }
1558 return false;
1559 }
1560
1561 /**
1562 * This will retrieve a grade object from the db
1563 *
1564 * @param int $gradeid The id of the grade
1565 * @return stdClass The grade record
1566 */
1567 private function get_grade($gradeid) {
1568 global $DB;
1569
1570 return $DB->get_record('assign_grades', array('assignment'=>$this->get_instance()->id, 'id'=>$gradeid), '*', MUST_EXIST);
1571 }
1572
1573 /**
1574 * Print the grading page for a single user submission
1575 *
1576 * @param moodleform $mform
1577 * @param int $offset
1578 * @return string
1579 */
1580 private function view_single_grade_page($mform, $offset=0) {
1581 global $DB, $CFG;
1582
1583 $o = '';
1584
1585 // Include grade form
1586 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
1587
1588 // Need submit permission to submit an assignment
1589 require_capability('mod/assign:grade', $this->context);
1590
1591 $o .= $this->output->render(new assign_header($this->get_instance(),
1592 $this->get_context(), false, $this->get_course_module()->id,get_string('grading', 'assign')));
1593
1594 $rownum = required_param('rownum', PARAM_INT) + $offset;
1595 $useridlist = optional_param('useridlist', '', PARAM_TEXT);
1596 if ($useridlist) {
1597 $useridlist = explode(',', $useridlist);
1598 } else {
1599 $useridlist = $this->get_grading_userid_list();
1600 }
1601 $last = false;
1602 $userid = $useridlist[$rownum];
1603 if ($rownum == count($useridlist) - 1) {
1604 $last = true;
1605 }
1606 // the placement of this is important so can pass the list of userids above
1607 if ($offset) {
1608 $_POST = array();
1609 }
1610 if(!$userid){
1611 throw new coding_exception('Row is out of bounds for the current grading table: ' . $rownum);
1612 }
1613 $user = $DB->get_record('user', array('id' => $userid));
1614 if ($user) {
1615 $o .= $this->output->render(new assign_user_summary($user, $this->get_course()->id, has_capability('moodle/site:viewfullnames', $this->get_course_context())));
1616 }
1617 $submission = $this->get_user_submission($userid, false);
1618 // get the current grade
1619 $grade = $this->get_user_grade($userid, false);
1620 if ($this->can_view_submission($userid)) {
1621 $gradelocked = ($grade && $grade->locked) || $this->grading_disabled($userid);
1622 $o .= $this->output->render(new assign_submission_status($this->get_instance()->allowsubmissionsfromdate,
1623 $this->get_instance()->alwaysshowdescription,
1624 $submission,
1625 $this->is_any_submission_plugin_enabled(),
1626 $gradelocked,
1627 $this->is_graded($userid),
1628 $this->get_instance()->duedate,
1629 $this->get_submission_plugins(),
1630 $this->get_return_action(),
1631 $this->get_return_params(),
1632 $this->get_course_module()->id,
1633 assign_submission_status::GRADER_VIEW,
1634 false,
1635 false));
1636 }
1637 if ($grade) {
1638 $data = new stdClass();
1639 if ($grade->grade >= 0) {
1640 $data->grade = format_float($grade->grade,2);
1641 }
1642 } else {
1643 $data = new stdClass();
1644 $data->grade = '';
1645 }
1646
1647 // now show the grading form
1648 if (!$mform) {
1649 $mform = new mod_assign_grade_form(null, array($this, $data, array('rownum'=>$rownum, 'useridlist'=>$useridlist, 'last'=>$last)), 'post', '', array('class'=>'gradeform'));
1650 }
1651 $o .= $this->output->render(new assign_form('gradingform',$mform));
1652
1653 $this->add_to_log('view grading form', get_string('viewgradingformforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user))));
1654
1655 $o .= $this->view_footer();
1656 return $o;
1657 }
1658
1659
1660
1661 /**
1662 * View a link to go back to the previous page. Uses url parameters returnaction and returnparams.
1663 *
1664 * @return string
1665 */
1666 private function view_return_links() {
1667
1668 $returnaction = optional_param('returnaction','', PARAM_ALPHA);
1669 $returnparams = optional_param('returnparams','', PARAM_TEXT);
1670
1671 $params = array();
1672 parse_str($returnparams, $params);
1673 $params = array_merge( array('id' => $this->get_course_module()->id, 'action' => $returnaction), $params);
1674
1675 return $this->output->single_button(new moodle_url('/mod/assign/view.php', $params), get_string('back'), 'get');
1676
1677 }
1678
1679 /**
1680 * View the grading table of all submissions for this assignment
1681 *
1682 * @return string
1683 */
1684 private function view_grading_table() {
1685 global $USER, $CFG;
1686 // Include grading options form
1687 require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
1688 require_once($CFG->dirroot . '/mod/assign/gradingactionsform.php');
bf78ebd6 1689 require_once($CFG->dirroot . '/mod/assign/quickgradingform.php');
bbd0e548
DW
1690 require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
1691 $o = '';
1692
1693 $links = array();
1694 $selecturl = (string)(new moodle_url('/mod/assign/view.php',
1695 array('action'=>'grading', 'id'=>$this->get_course_module()->id)));
1696 $links[$selecturl] = get_string('selectlink', 'assign');
1697 if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
1698 has_capability('moodle/grade:viewall', $this->get_course_context())) {
1699 $gradebookurl = (string) (new moodle_url('/grade/report/grader/index.php',
1700 array('id' => $this->get_course()->id)));
1701 $links[$gradebookurl] = get_string('viewgradebook', 'assign');
1702 }
1703 if ($this->is_any_submission_plugin_enabled()) {
1704 $downloadurl = (string) (new moodle_url('/mod/assign/view.php',
1705 array('id' => $this->get_course_module()->id,
1706 'action' => 'downloadall')));
1707 $links[$downloadurl] = get_string('downloadall', 'assign');
1708 }
1709 $gradingactionsform = new mod_assign_grading_actions_form(null,
1710 array('links'=>$links,
1711 'cm'=>$this->get_course_module()->id),
1712 'post', '',
1713 array('class'=>'gradingactionsform'));
1714
bf78ebd6
DW
1715 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
1716
bbd0e548
DW
1717 $perpage = get_user_preferences('assign_perpage', 10);
1718 $filter = get_user_preferences('assign_filter', '');
bf78ebd6
DW
1719 $controller = $gradingmanager->get_active_controller();
1720 $showquickgrading = empty($controller);
1721 if (optional_param('action', '', PARAM_ALPHA) == 'saveoptions') {
1722 $quickgrading = optional_param('quickgrading', false, PARAM_BOOL);
1723 set_user_preference('assign_quickgrading', $quickgrading);
1724 }
1725 $quickgrading = get_user_preferences('assign_quickgrading', false);
1726
bbd0e548
DW
1727 // print options for changing the filter and changing the number of results per page
1728 $gradingoptionsform = new mod_assign_grading_options_form(null,
1729 array('cm'=>$this->get_course_module()->id,
1730 'contextid'=>$this->context->id,
bf78ebd6
DW
1731 'userid'=>$USER->id,
1732 'showquickgrading'=>$showquickgrading,
1733 'quickgrading'=>$quickgrading),
bbd0e548
DW
1734 'post', '',
1735 array('class'=>'gradingoptionsform'));
1736
1737 $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
1738 array('cm'=>$this->get_course_module()->id,
1739 'submissiondrafts'=>$this->get_instance()->submissiondrafts),
1740 'post', '',
1741 array('class'=>'gradingbatchoperationsform'));
1742
1743 $gradingoptionsdata = new stdClass();
1744 $gradingoptionsdata->perpage = $perpage;
1745 $gradingoptionsdata->filter = $filter;
1746 $gradingoptionsform->set_data($gradingoptionsdata);
1747
1748 // plagiarism update status apearring in the grading book
1749 if (!empty($CFG->enableplagiarism)) {
1750 /** Include plagiarismlib.php */
1751 require_once($CFG->libdir . '/plagiarismlib.php');
1752 plagiarism_update_status($this->get_course(), $this->get_course_module());
1753 }
1754
1755 $o .= $this->output->render(new assign_form('gradingactionsform', $gradingactionsform));
bf78ebd6 1756 $o .= $this->output->render(new assign_form('gradingoptionsform', $gradingoptionsform, 'M.mod_assign.init_grading_options'));
bbd0e548
DW
1757
1758 // load and print the table of submissions
bf78ebd6
DW
1759 if ($showquickgrading && $quickgrading) {
1760 $table = $this->output->render(new assign_grading_table($this, $perpage, $filter, 0, true));
1761 $quickgradingform = new mod_assign_quick_grading_form(null,
1762 array('cm'=>$this->get_course_module()->id,
1763 'gradingtable'=>$table));
1764 $o .= $this->output->render(new assign_form('quickgradingform', $quickgradingform));
1765 } else {
1766 $o .= $this->output->render(new assign_grading_table($this, $perpage, $filter, 0, false));
1767 }
bbd0e548
DW
1768
1769 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1770 $users = array_keys($this->list_participants($currentgroup, true));
1771 if (count($users) != 0) {
1772 // if no enrolled user in a course then don't display the batch operations feature
1773 $o .= $this->output->render(new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform));
1774 }
1775 return $o;
1776 }
1777
1778 /**
1779 * View entire grading page.
1780 *
1781 * @return string
1782 */
1783 private function view_grading_page() {
1784 global $CFG;
1785
1786 $o = '';
1787 // Need submit permission to submit an assignment
1788 require_capability('mod/assign:grade', $this->context);
1789 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
1790
1791 // only load this if it is
1792
1793 $o .= $this->output->render(new assign_header($this->get_instance(),
1794 $this->get_context(), false, $this->get_course_module()->id, get_string('grading', 'assign')));
1795 $o .= groups_print_activity_menu($this->get_course_module(), $CFG->wwwroot . '/mod/assign/view.php?id=' . $this->get_course_module()->id.'&action=grading', true);
1796
1797
1798 $o .= $this->view_grading_table();
1799
1800 $o .= $this->view_footer();
1801 $this->add_to_log('view submission grading table', get_string('viewsubmissiongradingtable', 'assign'));
1802 return $o;
1803 }
1804
1805 /**
1806 * Capture the output of the plagiarism plugins disclosures and return it as a string
1807 *
1808 * @return void
1809 */
1810 private function plagiarism_print_disclosure() {
1811 global $CFG;
1812 $o = '';
1813
1814 if (!empty($CFG->enableplagiarism)) {
1815 /** Include plagiarismlib.php */
1816 require_once($CFG->libdir . '/plagiarismlib.php');
1817 ob_start();
1818
1819 plagiarism_print_disclosure($this->get_course_module()->id);
1820 $o = ob_get_contents();
1821 ob_end_clean();
1822 }
1823
1824 return $o;
1825 }
1826
1827 /**
1828 * message for students when assignment submissions have been closed
1829 *
1830 * @return string
1831 */
1832 private function view_student_error_message() {
1833 global $CFG;
1834
1835 $o = '';
1836 // Need submit permission to submit an assignment
1837 require_capability('mod/assign:submit', $this->context);
1838
1839 $o .= $this->output->render(new assign_header($this->get_instance(),
1840 $this->get_context(),
1841 $this->show_intro(),
1842 $this->get_course_module()->id,
1843 get_string('editsubmission', 'assign')));
1844
bf78ebd6 1845 $o .= $this->output->notification(get_string('submissionsclosed', 'assign'));
bbd0e548
DW
1846
1847 $o .= $this->view_footer();
1848
1849 return $o;
1850
1851 }
1852
1853 /**
1854 * View edit submissions page.
1855 *
1856 * @param moodleform $mform
1857 * @return void
1858 */
1859 private function view_edit_submission_page($mform) {
1860 global $CFG;
1861
1862 $o = '';
1863 // Include submission form
1864 require_once($CFG->dirroot . '/mod/assign/submission_form.php');
1865 // Need submit permission to submit an assignment
1866 require_capability('mod/assign:submit', $this->context);
1867
1868 if (!$this->submissions_open()) {
bf78ebd6 1869 return $this->view_student_error_message();
bbd0e548
DW
1870 }
1871 $o .= $this->output->render(new assign_header($this->get_instance(),
1872 $this->get_context(),
1873 $this->show_intro(),
1874 $this->get_course_module()->id,
1875 get_string('editsubmission', 'assign')));
1876 $o .= $this->plagiarism_print_disclosure();
1877 $data = new stdClass();
1878
1879 if (!$mform) {
1880 $mform = new mod_assign_submission_form(null, array($this, $data));
1881 }
1882
1883 $o .= $this->output->render(new assign_form('editsubmissionform',$mform));
1884
1885 $o .= $this->view_footer();
1886 $this->add_to_log('view submit assignment form', get_string('viewownsubmissionform', 'assign'));
1887
1888 return $o;
1889 }
1890
1891 /**
1892 * See if this assignment has a grade yet
1893 *
1894 * @param int $userid
1895 * @return bool
1896 */
1897 private function is_graded($userid) {
1898 $grade = $this->get_user_grade($userid, false);
1899 if ($grade) {
1900 return ($grade->grade != '');
1901 }
1902 return false;
1903 }
1904
1905
1906 /**
1907 * Perform an access check to see if the current $USER can view this users submission
1908 *
1909 * @param int $userid
1910 * @return bool
1911 */
1912 public function can_view_submission($userid) {
1913 global $USER;
1914
1915 if (!is_enrolled($this->get_course_context(), $userid)) {
1916 return false;
1917 }
1918 if ($userid == $USER->id && !has_capability('mod/assign:submit', $this->context)) {
1919 return false;
1920 }
1921 if ($userid != $USER->id && !has_capability('mod/assign:grade', $this->context)) {
1922 return false;
1923 }
1924 return true;
1925 }
1926
1927 /**
1928 * Ask the user to confirm they want to perform this batch operation
1929 * @return string
1930 */
1931 private function process_batch_grading_operation() {
1932 global $CFG;
1933 require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
1934 require_sesskey();
1935
1936 $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
1937 array('cm'=>$this->get_course_module()->id,
1938 'submissiondrafts'=>$this->get_instance()->submissiondrafts),
1939 'post', '',
1940 array('class'=>'gradingbatchoperationsform'));
1941
1942 if ($data = $gradingbatchoperationsform->get_data()) {
1943 // get the list of users
1944 $users = $data->selectedusers;
1945 $userlist = explode(',', $users);
1946
1947 foreach ($userlist as $userid) {
1948 if ($data->operation == 'lock') {
1949 $this->process_lock($userid);
1950 } else if ($data->operation == 'unlock') {
1951 $this->process_unlock($userid);
1952 } else if ($data->operation == 'reverttodraft') {
1953 $this->process_revert_to_draft($userid);
1954 }
1955 }
1956 }
1957
1958 return true;
1959 }
1960
1961 /**
1962 * Ask the user to confirm they want to submit their work for grading
1963 * @return string
1964 */
1965 private function check_submit_for_grading() {
1966 global $USER;
1967 // Check that all of the submission plugins are ready for this submission
1968 $notifications = array();
1969 $submission = $this->get_user_submission($USER->id, false);
1970 $plugins = $this->get_submission_plugins();
1971 foreach ($plugins as $plugin) {
1972 if ($plugin->is_enabled() && $plugin->is_visible()) {
1973 $check = $plugin->precheck_submission($submission);
1974 if ($check !== true) {
1975 $notifications[] = $check;
1976 }
1977 }
1978 }
1979
1980 $o = '';
1981 $o .= $this->output->header();
1982 $o .= $this->output->render(new assign_submit_for_grading_page($notifications, $this->get_course_module()->id));
1983 $o .= $this->view_footer();
1984 return $o;
1985 }
1986
1987 /**
1988 * Print 2 tables of information with no action links -
1989 * the submission summary and the grading summary
1990 *
1991 * @param stdClass $user the user to print the report for
1992 * @param bool $showlinks - Return plain text or links to the profile
1993 * @return string - the html summary
1994 */
1995 public function view_student_summary($user, $showlinks) {
1996 global $CFG, $DB, $PAGE;
1997
1998 $grade = $this->get_user_grade($user->id, false);
1999 $submission = $this->get_user_submission($user->id, false);
2000 $o = '';
2001
2002 if ($this->can_view_submission($user->id)) {
2003 $showedit = has_capability('mod/assign:submit', $this->context) &&
2004 $this->submissions_open() && ($this->is_any_submission_plugin_enabled()) && $showlinks;
2005 $showsubmit = $submission && ($submission->status == ASSIGN_SUBMISSION_STATUS_DRAFT) && $showlinks;
2006 $gradelocked = ($grade && $grade->locked) || $this->grading_disabled($user->id);
2007
2008 $o .= $this->output->render(new assign_submission_status($this->get_instance()->allowsubmissionsfromdate,
2009 $this->get_instance()->alwaysshowdescription,
2010 $submission,
2011 $this->is_any_submission_plugin_enabled(),
2012 $gradelocked,
2013 $this->is_graded($user->id),
2014 $this->get_instance()->duedate,
2015 $this->get_submission_plugins(),
2016 $this->get_return_action(),
2017 $this->get_return_params(),
2018 $this->get_course_module()->id,
2019 assign_submission_status::STUDENT_VIEW,
2020 $showedit,
2021 $showsubmit));
2022 require_once($CFG->libdir.'/gradelib.php');
2023 require_once($CFG->dirroot.'/grade/grading/lib.php');
2024
2025 $gradinginfo = grade_get_grades($this->get_course()->id,
2026 'mod',
2027 'assign',
2028 $this->get_instance()->id,
2029 $user->id);
2030
2031 $gradingitem = $gradinginfo->items[0];
2032 $gradebookgrade = $gradingitem->grades[$user->id];
2033
2034 // check to see if all feedback plugins are empty
2035 $emptyplugins = true;
2036 if ($grade) {
2037 foreach ($this->get_feedback_plugins() as $plugin) {
2038 if ($plugin->is_visible() && $plugin->is_enabled()) {
2039 if (!$plugin->is_empty($grade)) {
2040 $emptyplugins = false;
2041 }
2042 }
2043 }
2044 }
2045
2046
2047 if (!($gradebookgrade->hidden) && ($gradebookgrade->grade !== null || !$emptyplugins)) {
2048
2049 $gradefordisplay = '';
2050 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2051
2052 if ($controller = $gradingmanager->get_active_controller()) {
2053 $controller->set_grade_range(make_grades_menu($this->get_instance()->grade));
2054 $gradefordisplay = $controller->render_grade($PAGE,
2055 $grade->id,
2056 $gradingitem,
2057 $gradebookgrade->str_long_grade,
2058 has_capability('mod/assign:grade', $this->get_context()));
2059 } else {
bf78ebd6 2060 $gradefordisplay = $this->display_grade($gradebookgrade->grade, false);
bbd0e548
DW
2061 }
2062
2063 $gradeddate = $gradebookgrade->dategraded;
2064 $grader = $DB->get_record('user', array('id'=>$gradebookgrade->usermodified));
2065
2066 $feedbackstatus = new assign_feedback_status($gradefordisplay,
2067 $gradeddate,
2068 $grader,
2069 $this->get_feedback_plugins(),
2070 $grade,
2071 $this->get_course_module()->id,
2072 $this->get_return_action(),
2073 $this->get_return_params());
2074
2075 $o .= $this->output->render($feedbackstatus);
2076 }
2077
2078 }
2079 return $o;
2080 }
2081
2082 /**
2083 * View submissions page (contains details of current submission).
2084 *
2085 * @return string
2086 */
2087 private function view_submission_page() {
2088 global $CFG, $DB, $USER, $PAGE;
2089
2090 $o = '';
2091 $o .= $this->output->render(new assign_header($this->get_instance(),
2092 $this->get_context(),
2093 $this->show_intro(),
2094 $this->get_course_module()->id));
2095
2096 if ($this->can_grade()) {
2097 $o .= $this->output->render(new assign_grading_summary($this->count_participants(0),
2098 $this->get_instance()->submissiondrafts,
2099 $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_DRAFT),
2100 $this->is_any_submission_plugin_enabled(),
2101 $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED),
2102 $this->get_instance()->duedate,
2103 $this->get_course_module()->id
2104 ));
2105 }
2106 $grade = $this->get_user_grade($USER->id, false);
2107 $submission = $this->get_user_submission($USER->id, false);
2108
2109 if ($this->can_view_submission($USER->id)) {
2110 $o .= $this->view_student_summary($USER, true);
2111 }
2112
2113
2114 $o .= $this->view_footer();
2115 $this->add_to_log('view', get_string('viewownsubmissionstatus', 'assign'));
2116 return $o;
2117 }
2118
2119 /**
2120 * convert the final raw grade(s) in the grading table for the gradebook
2121 *
2122 * @param stdClass $grade
2123 * @return array
2124 */
2125 private function convert_grade_for_gradebook(stdClass $grade) {
2126 $gradebookgrade = array();
2127 // trying to match those array keys in grade update function in gradelib.php
2128 // with keys in th database table assign_grades
2129 // starting around line 262
2130 $gradebookgrade['rawgrade'] = $grade->grade;
2131 $gradebookgrade['userid'] = $grade->userid;
2132 $gradebookgrade['usermodified'] = $grade->grader;
2133 $gradebookgrade['datesubmitted'] = NULL;
2134 $gradebookgrade['dategraded'] = $grade->timemodified;
2135 if (isset($grade->feedbackformat)) {
2136 $gradebookgrade['feedbackformat'] = $grade->feedbackformat;
2137 }
2138 if (isset($grade->feedbacktext)) {
2139 $gradebookgrade['feedback'] = $grade->feedbacktext;
2140 }
2141
2142 return $gradebookgrade;
2143 }
2144
2145 /**
2146 * convert submission details for the gradebook
2147 *
2148 * @param stdClass $submission
2149 * @return array
2150 */
2151 private function convert_submission_for_gradebook(stdClass $submission) {
2152 $gradebookgrade = array();
2153
2154
2155 $gradebookgrade['userid'] = $submission->userid;
2156 $gradebookgrade['usermodified'] = $submission->userid;
2157 $gradebookgrade['datesubmitted'] = $submission->timemodified;
2158
2159 return $gradebookgrade;
2160 }
2161
2162 /**
2163 * update grades in the gradebook
2164 *
2165 * @param mixed $submission stdClass|null
2166 * @param mixed $grade stdClass|null
2167 * @return bool
2168 */
2169 private function gradebook_item_update($submission=NULL, $grade=NULL) {
2170
2171 if($submission != NULL){
2172
2173 $gradebookgrade = $this->convert_submission_for_gradebook($submission);
2174
2175
2176 }else{
2177
2178
2179 $gradebookgrade = $this->convert_grade_for_gradebook($grade);
2180 }
2181 $assign = clone $this->get_instance();
2182 $assign->cmidnumber = $this->get_course_module()->id;
2183
2184 return assign_grade_item_update($assign, $gradebookgrade);
2185 }
2186
2187 /**
2188 * update grades in the gradebook based on submission time
2189 *
2190 * @param stdClass $submission
2191 * @param bool $updatetime
2192 * @return bool
2193 */
2194 private function update_submission(stdClass $submission, $updatetime=true) {
2195 global $DB;
2196
2197 if ($updatetime) {
2198 $submission->timemodified = time();
2199 }
2200 $result= $DB->update_record('assign_submission', $submission);
2201 if ($result) {
2202 $this->gradebook_item_update($submission);
2203 }
2204 return $result;
2205 }
2206
2207 /**
2208 * Is this assignment open for submissions?
2209 *
2210 * Check the due date,
2211 * prevent late submissions,
2212 * has this person already submitted,
2213 * is the assignment locked?
2214 *
2215 * @return bool
2216 */
2217 private function submissions_open() {
2218 global $USER;
2219
2220 $time = time();
2221 $dateopen = true;
2222 if ($this->get_instance()->preventlatesubmissions && $this->get_instance()->duedate) {
2223 $dateopen = ($this->get_instance()->allowsubmissionsfromdate <= $time && $time <= $this->get_instance()->duedate);
2224 } else {
2225 $dateopen = ($this->get_instance()->allowsubmissionsfromdate <= $time);
2226 }
2227
2228 if (!$dateopen) {
2229 return false;
2230 }
2231
2232 // now check if this user has already submitted etc.
2233 if (!is_enrolled($this->get_course_context(), $USER)) {
2234 return false;
2235 }
2236 if ($submission = $this->get_user_submission($USER->id, false)) {
2237 if ($this->get_instance()->submissiondrafts && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
2238 // drafts are tracked and the student has submitted the assignment
2239 return false;
2240 }
2241 }
2242 if ($grade = $this->get_user_grade($USER->id, false)) {
2243 if ($grade->locked) {
2244 return false;
2245 }
2246 }
2247
2248 if ($this->grading_disabled($USER->id)) {
2249 return false;
2250 }
2251
2252 return true;
2253 }
2254
2255 /**
2256 * render the files in file area
2257 * @param string $component
2258 * @param string $area
2259 * @param int $submissionid
2260 * @return string
2261 */
2262 public function render_area_files($component, $area, $submissionid) {
2263 global $USER;
2264
2265 if (!$submissionid) {
2266 $submission = $this->get_user_submission($USER->id,false);
2267 $submissionid = $submission->id;
2268 }
2269
bbd0e548
DW
2270 $fs = get_file_storage();
2271 $browser = get_file_browser();
2272 $files = $fs->get_area_files($this->get_context()->id, $component, $area , $submissionid , "timemodified", false);
2273 return $this->output->assign_files($this->context, $submissionid, $area, $component);
2274
2275 }
2276
2277 /**
2278 * Returns a list of teachers that should be grading given submission
2279 *
75f87a57 2280 * @param int $userid
bbd0e548
DW
2281 * @return array
2282 */
75f87a57 2283 private function get_graders($userid) {
bbd0e548 2284 //potential graders
75f87a57 2285 $potentialgraders = get_enrolled_users($this->context, "mod/assign:grade");
bbd0e548
DW
2286
2287 $graders = array();
2288 if (groups_get_activity_groupmode($this->get_course_module()) == SEPARATEGROUPS) { // Separate groups are being used
75f87a57 2289 if ($groups = groups_get_all_groups($this->get_course()->id, $userid)) { // Try to find all groups
bbd0e548
DW
2290 foreach ($groups as $group) {
2291 foreach ($potentialgraders as $grader) {
75f87a57 2292 if ($grader->id == $userid) {
bbd0e548
DW
2293 continue; // do not send self
2294 }
2295 if (groups_is_member($group->id, $grader->id)) {
2296 $graders[$grader->id] = $grader;
2297 }
2298 }
2299 }
2300 } else {
2301 // user not in group, try to find graders without group
2302 foreach ($potentialgraders as $grader) {
75f87a57 2303 if ($grader->id == $userid) {
bbd0e548
DW
2304 continue; // do not send self
2305 }
2306 if (!groups_has_membership($this->get_course_module(), $grader->id)) {
2307 $graders[$grader->id] = $grader;
2308 }
2309 }
2310 }
2311 } else {
2312 foreach ($potentialgraders as $grader) {
75f87a57 2313 if ($grader->id == $userid) {
bbd0e548
DW
2314 continue; // do not send self
2315 }
2316 // must be enrolled
2317 if (is_enrolled($this->get_course_context(), $grader->id)) {
2318 $graders[$grader->id] = $grader;
2319 }
2320 }
2321 }
2322 return $graders;
2323 }
2324
2325 /**
3f7b501e 2326 * Format a notification for plain text
bbd0e548 2327 *
75f87a57
DW
2328 * @param string $messagetype
2329 * @param stdClass $info
2330 * @param stdClass $course
2331 * @param stdClass $context
2332 * @param string $modulename
2333 * @param string $assignmentname
bbd0e548 2334 */
75f87a57
DW
2335 private static function format_notification_message_text($messagetype, $info, $course, $context, $modulename, $assignmentname) {
2336 $posttext = format_string($course->shortname, true, array('context' => $context->get_course_context())).' -> '.
2337 $modulename.' -> '.
2338 format_string($assignmentname, true, array('context' => $context))."\n";
bbd0e548 2339 $posttext .= '---------------------------------------------------------------------'."\n";
75f87a57 2340 $posttext .= get_string($messagetype . 'text', "assign", $info)."\n";
bbd0e548
DW
2341 $posttext .= "\n---------------------------------------------------------------------\n";
2342 return $posttext;
2343 }
2344
75f87a57 2345 /**
3f7b501e 2346 * Format a notification for HTML
bbd0e548 2347 *
75f87a57
DW
2348 * @param string $messagetype
2349 * @param stdClass $info
3f7b501e
SH
2350 * @param stdClass $course
2351 * @param stdClass $context
2352 * @param string $modulename
2353 * @param stdClass $coursemodule
2354 * @param string $assignmentname
2355 * @param stdClass $info
bbd0e548 2356 */
75f87a57 2357 private static function format_notification_message_html($messagetype, $info, $course, $context, $modulename, $coursemodule, $assignmentname) {
bbd0e548
DW
2358 global $CFG;
2359 $posthtml = '<p><font face="sans-serif">'.
75f87a57 2360 '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.format_string($course->shortname, true, array('context' => $context->get_course_context())).'</a> ->'.
599f7a27
RK
2361 '<a href="'.$CFG->wwwroot.'/mod/assign/index.php?id='.$course->id.'">'.$modulename.'</a> ->'.
2362 '<a href="'.$CFG->wwwroot.'/mod/assign/view.php?id='.$coursemodule->id.'">'.format_string($assignmentname, true, array('context' => $context)).'</a></font></p>';
bbd0e548 2363 $posthtml .= '<hr /><font face="sans-serif">';
75f87a57 2364 $posthtml .= '<p>'.get_string($messagetype . 'html', 'assign', $info).'</p>';
bbd0e548
DW
2365 $posthtml .= '</font><hr />';
2366 return $posthtml;
2367 }
2368
75f87a57
DW
2369 /**
2370 * email someone about something (static so it can be called from cron)
2371 *
75f87a57
DW
2372 * @param stdClass $userfrom
2373 * @param stdClass $userto
2374 * @param string $messagetype
2375 * @param string $eventtype
2376 * @param int $updatetime
2377 * @param stdClass $coursemodule
2378 * @param stdClass $context
2379 * @param stdClass $course
2380 * @param string $modulename
75f87a57
DW
2381 * @param string $assignmentname
2382 * @return void
2383 */
2384 public static function send_assignment_notification($userfrom, $userto, $messagetype, $eventtype,
2385 $updatetime, $coursemodule, $context, $course,
2386 $modulename, $assignmentname) {
3f7b501e 2387 global $CFG;
75f87a57
DW
2388
2389 $info = new stdClass();
2390 $info->username = fullname($userfrom, true);
2391 $info->assignment = format_string($assignmentname,true, array('context'=>$context));
2392 $info->url = $CFG->wwwroot.'/mod/assign/view.php?id='.$coursemodule->id;
2393 $info->timeupdated = strftime('%c',$updatetime);
2394
2395 $postsubject = get_string($messagetype . 'small', 'assign', $info);
2396 $posttext = self::format_notification_message_text($messagetype, $info, $course, $context, $modulename, $assignmentname);
2397 $posthtml = ($userto->mailformat == 1) ? self::format_notification_message_html($messagetype, $info, $course, $context, $modulename, $coursemodule, $assignmentname) : '';
2398
2399 $eventdata = new stdClass();
2400 $eventdata->modulename = 'assign';
2401 $eventdata->userfrom = $userfrom;
2402 $eventdata->userto = $userto;
2403 $eventdata->subject = $postsubject;
2404 $eventdata->fullmessage = $posttext;
2405 $eventdata->fullmessageformat = FORMAT_PLAIN;
2406 $eventdata->fullmessagehtml = $posthtml;
2407 $eventdata->smallmessage = $postsubject;
2408
2409 $eventdata->name = $eventtype;
2410 $eventdata->component = 'mod_assign';
2411 $eventdata->notification = 1;
2412 $eventdata->contexturl = $info->url;
2413 $eventdata->contexturlname = $info->assignment;
2414
2415 message_send($eventdata);
75f87a57
DW
2416 }
2417
2418 /**
2419 * email someone about something
2420 *
3f7b501e
SH
2421 * @param stdClass $userfrom
2422 * @param stdClass $userto
2423 * @param string $messagetype
2424 * @param string $eventtype
2425 * @param int $updatetime
75f87a57
DW
2426 * @return void
2427 */
2428 public function send_notification($userfrom, $userto, $messagetype, $eventtype, $updatetime) {
2429 self::send_assignment_notification($userfrom, $userto, $messagetype, $eventtype, $updatetime, $this->get_course_module(), $this->get_context(), $this->get_course(), $this->get_module_name(), $this->get_instance()->name);
2430 }
2431
2432 /**
3f7b501e 2433 * Email student upon successful submission
75f87a57 2434 *
75f87a57
DW
2435 * @global moodle_database $DB
2436 * @param stdClass $submission
2437 * @return void
2438 */
2439 private function email_student_submission_receipt(stdClass $submission) {
2440 global $DB;
2441
2442 $adminconfig = $this->get_admin_config();
3f7b501e
SH
2443 if (!$adminconfig->submissionreceipts) {
2444 // No need to do anything
75f87a57
DW
2445 return;
2446 }
75f87a57 2447 $user = $DB->get_record('user', array('id'=>$submission->userid), '*', MUST_EXIST);
75f87a57
DW
2448 $this->send_notification($user, $user, 'submissionreceipt', 'assign_student_notification', $submission->timemodified);
2449 }
2450
bbd0e548 2451 /**
3f7b501e 2452 * Email graders upon student submissions
bbd0e548 2453 *
75f87a57 2454 * @global moodle_database $DB
bbd0e548
DW
2455 * @param stdClass $submission
2456 * @return void
2457 */
2458 private function email_graders(stdClass $submission) {
75f87a57
DW
2459 global $DB;
2460
2461 $late = $this->get_instance()->duedate && ($this->get_instance()->duedate < time());
bbd0e548 2462
75f87a57 2463 if (!$this->get_instance()->sendnotifications && !($late && $this->get_instance()->sendlatenotifications)) { // No need to do anything
bbd0e548
DW
2464 return;
2465 }
2466
2467 $user = $DB->get_record('user', array('id'=>$submission->userid), '*', MUST_EXIST);
75f87a57 2468 if ($teachers = $this->get_graders($user->id)) {
bbd0e548 2469 foreach ($teachers as $teacher) {
75f87a57 2470 $this->send_notification($user, $teacher, 'gradersubmissionupdated', 'assign_grader_notification', $submission->timemodified);
bbd0e548
DW
2471 }
2472 }
2473 }
2474
2475 /**
2476 * assignment submission is processed before grading
2477 *
2478 * @return void
2479 */
2480 private function process_submit_for_grading() {
2481 global $USER;
2482
2483 // Need submit permission to submit an assignment
2484 require_capability('mod/assign:submit', $this->context);
2485 require_sesskey();
2486
2487 $submission = $this->get_user_submission($USER->id,true);
2488 if ($submission->status != ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
2489 // Give each submission plugin a chance to process the submission
2490 $plugins = $this->get_submission_plugins();
2491 foreach ($plugins as $plugin) {
2492 $plugin->submit_for_grading();
2493 }
2494
2495 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
2496 $this->update_submission($submission);
2497 $this->add_to_log('submit for grading', $this->format_submission_for_log($submission));
2498 $this->email_graders($submission);
75f87a57 2499 $this->email_student_submission_receipt($submission);
bbd0e548
DW
2500 }
2501 }
2502
bf78ebd6
DW
2503 /**
2504 * save quick grades
2505 *
2a4fbc32
SH
2506 * @global moodle_database $DB
2507 * @return string The result of the save operation
bf78ebd6
DW
2508 */
2509 private function process_save_quick_grades() {
2510 global $USER, $DB, $CFG;
2511
2512 // Need grade permission
2513 require_capability('mod/assign:grade', $this->context);
2514
2515 // make sure advanced grading is disabled
2516 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2517 $controller = $gradingmanager->get_active_controller();
2518 if (!empty($controller)) {
2a4fbc32 2519 return get_string('errorquickgradingvsadvancedgrading', 'assign');
bf78ebd6
DW
2520 }
2521
2522 $users = array();
2523 // first check all the last modified values
2a4fbc32
SH
2524 // Using POST is really unfortunate. A better solution needs to be found here. As we are looking for grades students we could
2525 // gets a list of possible users and look for values based upon that.
bf78ebd6 2526 foreach ($_POST as $key => $value) {
2a4fbc32 2527 if (preg_match('#^grademodified_(\d+)$#', $key, $matches)) {
bf78ebd6
DW
2528 // gather the userid, updated grade and last modified value
2529 $record = new stdClass();
2a4fbc32 2530 $record->userid = (int)$matches[1];
bf78ebd6 2531 $record->grade = required_param('quickgrade_' . $record->userid, PARAM_INT);
2a4fbc32 2532 $record->lastmodified = clean_param($value, PARAM_INT);
bf78ebd6
DW
2533 $record->gradinginfo = grade_get_grades($this->get_course()->id, 'mod', 'assign', $this->get_instance()->id, array($record->userid));
2534 $users[$record->userid] = $record;
2535 }
2536 }
2a4fbc32
SH
2537 if (empty($users)) {
2538 // Quick check to see whether we have any users to update and we don't
2539 return get_string('quickgradingchangessaved', 'assign'); // Technical lie
2540 }
bf78ebd6 2541
2a4fbc32
SH
2542 list($userids, $params) = $DB->get_in_or_equal(array_keys($users), SQL_PARAMS_NAMED);
2543 $params['assignment'] = $this->get_instance()->id;
bf78ebd6 2544 // check them all for currency
2a4fbc32
SH
2545 $sql = 'SELECT u.id as userid, g.grade as grade, g.timemodified as lastmodified
2546 FROM {user} u
2547 LEFT JOIN {assign_grades} g ON u.id = g.userid AND g.assignment = :assignment
2548 WHERE u.id ' . $userids;
2549 $currentgrades = $DB->get_recordset_sql($sql, $params);
bf78ebd6
DW
2550
2551 $modifiedusers = array();
2552 foreach ($currentgrades as $current) {
2553 $modified = $users[(int)$current->userid];
2554
2555 // check to see if the outcomes were modified
2556 if ($CFG->enableoutcomes) {
2557 foreach ($modified->gradinginfo->outcomes as $outcomeid => $outcome) {
2558 $oldoutcome = $outcome->grades[$modified->userid]->grade;
2559 $newoutcome = optional_param('outcome_' . $outcomeid . '_' . $modified->userid, -1, PARAM_INT);
2560 if ($oldoutcome != $newoutcome) {
2561 // can't check modified time for outcomes because it is not reported
2562 $modifiedusers[$modified->userid] = $modified;
2563 continue;
2564 }
2565 }
2566 }
2567
2568
2569 if (($current->grade < 0 || $current->grade === NULL) &&
2570 ($modified->grade < 0 || $modified->grade === NULL)) {
2571 // different ways to indicate no grade
2572 continue;
2573 }
2574 if ($current->grade != $modified->grade) {
2575 // grade changed
2576 if ((int)$current->lastmodified > (int)$modified->lastmodified) {
2577 // error - record has been modified since viewing the page
2578 return get_string('errorrecordmodified', 'assign');
2579 } else {
2580 $modifiedusers[$modified->userid] = $modified;
2581 }
2582 }
2583
2584 }
2a4fbc32 2585 $currentgrades->close();
bf78ebd6
DW
2586
2587 // ok - ready to process the updates
2588 foreach ($modifiedusers as $userid => $modified) {
2589 $grade = $this->get_user_grade($userid, true);
2590 $grade->grade= grade_floatval($modified->grade);
2591 $grade->grader= $USER->id;
2592
2593 $this->update_grade($grade);
2594
2595 // save outcomes
2596 if ($CFG->enableoutcomes) {
2597 $data = array();
2598 foreach ($modified->gradinginfo->outcomes as $outcomeid => $outcome) {
2599 $oldoutcome = $outcome->grades[$modified->userid]->grade;
2600 $newoutcome = optional_param('outcome_' . $outcomeid . '_' . $modified->userid, -1, PARAM_INT);
2601 if ($oldoutcome != $newoutcome) {
2602 $data[$outcomeid] = $newoutcome;
2603 }
2604 }
2605 if (count($data) > 0) {
2606 grade_update_outcomes('mod/assign', $this->course->id, 'mod', 'assign', $this->get_instance()->id, $userid, $data);
2607 }
2608 }
2609
bf78ebd6
DW
2610 $this->add_to_log('grade submission', $this->format_grade_for_log($grade));
2611 }
2612
2613 return get_string('quickgradingchangessaved', 'assign');
2614 }
2615
bbd0e548
DW
2616 /**
2617 * save grading options
2618 *
2619 * @return void
2620 */
2621 private function process_save_grading_options() {
2622 global $USER, $CFG;
2623
2624 // Include grading options form
2625 require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
2626
2627 // Need submit permission to submit an assignment
2628 require_capability('mod/assign:grade', $this->context);
2629
bf78ebd6 2630 $mform = new mod_assign_grading_options_form(null, array('cm'=>$this->get_course_module()->id, 'contextid'=>$this->context->id, 'userid'=>$USER->id, 'showquickgrading'=>false));
bbd0e548
DW
2631 if ($formdata = $mform->get_data()) {
2632 set_user_preference('assign_perpage', $formdata->perpage);
2633 set_user_preference('assign_filter', $formdata->filter);
2634 }
2635 }
2636
2637 /**
2638 * Take a grade object and print a short summary for the log file.
2639 * The size limit for the log file is 255 characters, so be careful not
2640 * to include too much information.
2641 *
2642 * @param stdClass $grade
2643 * @return string
2644 */
2645 private function format_grade_for_log(stdClass $grade) {
2646 global $DB;
2647
2648 $user = $DB->get_record('user', array('id' => $grade->userid), '*', MUST_EXIST);
2649
2650 $info = get_string('gradestudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user)));
2651 if ($grade->grade != '') {
bf78ebd6 2652 $info .= get_string('grade') . ': ' . $this->display_grade($grade->grade, false) . '. ';
bbd0e548
DW
2653 } else {
2654 $info .= get_string('nograde', 'assign');
2655 }
2656 if ($grade->locked) {
2657 $info .= get_string('submissionslocked', 'assign') . '. ';
2658 }
2659 return $info;
2660 }
2661
2662 /**
2663 * Take a submission object and print a short summary for the log file.
2664 * The size limit for the log file is 255 characters, so be careful not
2665 * to include too much information.
2666 *
2667 * @param stdClass $submission
2668 * @return string
2669 */
2670 private function format_submission_for_log(stdClass $submission) {
2671 $info = '';
2672 $info .= get_string('submissionstatus', 'assign') . ': ' . get_string('submissionstatus_' . $submission->status, 'assign') . '. <br>';
2673 // format_for_log here iterating every single log INFO from either submission or grade in every assignment plugin
2674
2675 foreach ($this->submissionplugins as $plugin) {
2676 if ($plugin->is_enabled() && $plugin->is_visible()) {
2677
2678
2679 $info .= "<br>" . $plugin->format_for_log($submission);
2680 }
2681 }
2682
2683
2684 return $info;
2685 }
2686
2687 /**
2688 * save assignment submission
2689 *
2690 * @param moodleform $mform
2691 * @return bool
2692 */
2693 private function process_save_submission(&$mform) {
2694 global $USER, $CFG;
2695
2696 // Include submission form
2697 require_once($CFG->dirroot . '/mod/assign/submission_form.php');
2698
2699 // Need submit permission to submit an assignment
2700 require_capability('mod/assign:submit', $this->context);
2701 require_sesskey();
2702
2703 $data = new stdClass();
2704 $mform = new mod_assign_submission_form(null, array($this, $data));
2705 if ($mform->is_cancelled()) {
2706 return true;
2707 }
2708 if ($data = $mform->get_data()) {
2709 $submission = $this->get_user_submission($USER->id, true); //create the submission if needed & its id
2710 $grade = $this->get_user_grade($USER->id, false); // get the grade to check if it is locked
2711 if ($grade && $grade->locked) {
2712 print_error('submissionslocked', 'assign');
2713 return true;
2714 }
2715
2716
2717 foreach ($this->submissionplugins as $plugin) {
2718 if ($plugin->is_enabled()) {
2719 if (!$plugin->save($submission, $data)) {
2720 print_error($plugin->get_error());
2721 }
2722 }
2723 }
2724
2725 $this->update_submission($submission);
2726
2727 // Logging
2728 $this->add_to_log('submit', $this->format_submission_for_log($submission));
2729
2730 if (!$this->get_instance()->submissiondrafts) {
75f87a57 2731 $this->email_student_submission_receipt($submission);
bbd0e548
DW
2732 $this->email_graders($submission);
2733 }
2734 return true;
2735 }
2736 return false;
2737 }
2738
bbd0e548
DW
2739
2740 /**
2741 * Determine if this users grade is locked or overridden
2742 *
2743 * @param int $userid - The student userid
2744 * @return bool $gradingdisabled
2745 */
2746 private function grading_disabled($userid) {
2747 global $CFG;
2748
2749 $gradinginfo = grade_get_grades($this->get_course()->id, 'mod', 'assign', $this->get_instance()->id, array($userid));
2750 if (!$gradinginfo) {
2751 return false;
2752 }
2753
2754 if (!isset($gradinginfo->items[0]->grades[$userid])) {
2755 return false;
2756 }
2757 $gradingdisabled = $gradinginfo->items[0]->grades[$userid]->locked || $gradinginfo->items[0]->grades[$userid]->overridden;
2758 return $gradingdisabled;
2759 }
2760
2761
2762 /**
2763 * Get an instance of a grading form if advanced grading is enabled
2764 * This is specific to the assignment, marker and student
2765 *
2766 * @param int $userid - The student userid
2767 * @param bool $gradingdisabled
2768 * @return mixed gradingform_instance|null $gradinginstance
2769 */
2770 private function get_grading_instance($userid, $gradingdisabled) {
2771 global $CFG, $USER;
2772
2773 $grade = $this->get_user_grade($userid, false);
2774 $grademenu = make_grades_menu($this->get_instance()->grade);
2775
2776 $advancedgradingwarning = false;
2777 $gradingmanager = get_grading_manager($this->context, 'mod_assign', 'submissions');
2778 $gradinginstance = null;
2779 if ($gradingmethod = $gradingmanager->get_active_method()) {
2780 $controller = $gradingmanager->get_controller($gradingmethod);
2781 if ($controller->is_form_available()) {
2782 $itemid = null;
2783 if ($grade) {
2784 $itemid = $grade->id;
2785 }
2786 if ($gradingdisabled && $itemid) {
2787 $gradinginstance = ($controller->get_current_instance($USER->id, $itemid));
2788 } else if (!$gradingdisabled) {
2789 $instanceid = optional_param('advancedgradinginstanceid', 0, PARAM_INT);
2790 $gradinginstance = ($controller->get_or_create_instance($instanceid, $USER->id, $itemid));
2791 }
2792 } else {
2793 $advancedgradingwarning = $controller->form_unavailable_notification();
2794 }
2795 }
2796 if ($gradinginstance) {
2797 $gradinginstance->get_controller()->set_grade_range($grademenu);
2798 }
2799 return $gradinginstance;
2800 }
2801
2802 /**
2803 * add elements to grade form
2804 *
2805 * @param MoodleQuickForm $mform
2806 * @param stdClass $data
2807 * @param array $params
2808 * @return void
2809 */
2810 public function add_grade_form_elements(MoodleQuickForm $mform, stdClass $data, $params) {
2811 global $USER, $CFG;
2812 $settings = $this->get_instance();
2813
2814 $rownum = $params['rownum'];
2815 $last = $params['last'];
2816 $useridlist = $params['useridlist'];
2817 $userid = $useridlist[$rownum];
2818 $grade = $this->get_user_grade($userid, false);
2819
2820 // add advanced grading
2821 $gradingdisabled = $this->grading_disabled($userid);
2822 $gradinginstance = $this->get_grading_instance($userid, $gradingdisabled);
2823
2824 if ($gradinginstance) {
2825 $gradingelement = $mform->addElement('grading', 'advancedgrading', get_string('grade').':', array('gradinginstance' => $gradinginstance));
2826 if ($gradingdisabled) {
2827 $gradingelement->freeze();
2828 } else {
2829 $mform->addElement('hidden', 'advancedgradinginstanceid', $gradinginstance->get_id());
2830 }
2831 } else {
2832 // use simple direct grading
2833 if ($this->get_instance()->grade > 0) {
2834 $mform->addElement('text', 'grade', get_string('gradeoutof', 'assign',$this->get_instance()->grade));
2835 $mform->addHelpButton('grade', 'gradeoutofhelp', 'assign');
2836 $mform->setType('grade', PARAM_TEXT);
2837 } else {
2838 $grademenu = make_grades_menu($this->get_instance()->grade);
2839 if (count($grademenu) > 0) {
2840 $mform->addElement('select', 'grade', get_string('grade').':', $grademenu);
2841 $mform->setType('grade', PARAM_INT);
2842 }
2843 }
2844 }
bbd0e548 2845
c45261df
DW
2846 $gradinginfo = grade_get_grades($this->get_course()->id,
2847 'mod',
2848 'assign',
2849 $this->get_instance()->id,
2850 $userid);
2851 if (!empty($CFG->enableoutcomes)) {
2852 foreach($gradinginfo->outcomes as $index=>$outcome) {
2853 $options = make_grades_menu(-$outcome->scaleid);
2854 if ($outcome->grades[$userid]->locked) {
2855 $options[0] = get_string('nooutcome', 'grades');
2856 $mform->addElement('static', 'outcome_'.$index.'['.$userid.']', $outcome->name.':',
2857 $options[$outcome->grades[$userid]->grade]);
2858 } else {
2859 $options[''] = get_string('nooutcome', 'grades');
2860 $attributes = array('id' => 'menuoutcome_'.$index );
2861 $mform->addElement('select', 'outcome_'.$index.'['.$userid.']', $outcome->name.':', $options, $attributes );
2862 $mform->setType('outcome_'.$index.'['.$userid.']', PARAM_INT);
2863 $mform->setDefault('outcome_'.$index.'['.$userid.']', $outcome->grades[$userid]->grade );
2864 }
2865 }
2866 }
2867
2868 $mform->addElement('static', 'progress', '', get_string('gradingstudentprogress', 'assign', array('index'=>$rownum+1, 'count'=>count($useridlist))));
bbd0e548
DW
2869
2870 // plugins
2871 $this->add_plugin_grade_elements($grade, $mform, $data);
2872
2873 // hidden params
2874 $mform->addElement('hidden', 'id', $this->get_course_module()->id);
2875 $mform->setType('id', PARAM_INT);
2876 $mform->addElement('hidden', 'rownum', $rownum);
2877 $mform->setType('rownum', PARAM_INT);
2878 $mform->addElement('hidden', 'useridlist', implode(',', $useridlist));
2879 $mform->setType('useridlist', PARAM_TEXT);
2880 $mform->addElement('hidden', 'ajax', optional_param('ajax', 0, PARAM_INT));
2881 $mform->setType('ajax', PARAM_INT);
2882
2883 $mform->addElement('hidden', 'action', 'submitgrade');
2884 $mform->setType('action', PARAM_ALPHA);
2885
2886
2887 $buttonarray=array();
2888 $buttonarray[] = $mform->createElement('submit', 'savegrade', get_string('savechanges', 'assign'));
2889 if (!$last){
2890 $buttonarray[] = $mform->createElement('submit', 'saveandshownext', get_string('savenext','assign'));
2891 }
2892 $buttonarray[] = $mform->createElement('cancel', 'cancelbutton', get_string('cancel'));
2893 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
2894 $mform->closeHeaderBefore('buttonar');
2895 $buttonarray=array();
2896
2897 if ($rownum > 0) {
2898 $buttonarray[] = $mform->createElement('submit', 'nosaveandprevious', get_string('previous','assign'));
2899 }
2900
2901 if (!$last){
2902 $buttonarray[] = $mform->createElement('submit', 'nosaveandnext', get_string('nosavebutnext', 'assign'));
2903 }
2904 $mform->addGroup($buttonarray, 'navar', '', array(' '), false);
2905 }
2906
2907
2908 /**
2909 * add elements in submission plugin form
2910 *
2911 * @param mixed $submission stdClass|null
2912 * @param MoodleQuickForm $mform
2913 * @param stdClass $data
2914 * @return void
2915 */
2916 private function add_plugin_submission_elements($submission, MoodleQuickForm $mform, stdClass $data) {
2917 foreach ($this->submissionplugins as $plugin) {
2918 if ($plugin->is_enabled() && $plugin->is_visible() && $plugin->allow_submissions()) {
2919 $mform->addElement('header', 'header_' . $plugin->get_type(), $plugin->get_name());
2920 if (!$plugin->get_form_elements($submission, $mform, $data)) {
2921 $mform->removeElement('header_' . $plugin->get_type());
2922 }
2923 }
2924 }
2925 }
2926
2927 /**
2928 * check if feedback plugins installed are enabled
2929 *
2930 * @return bool
2931 */
2932 public function is_any_feedback_plugin_enabled() {
2933 if (!isset($this->cache['any_feedback_plugin_enabled'])) {
2934 $this->cache['any_feedback_plugin_enabled'] = false;
2935 foreach ($this->feedbackplugins as $plugin) {
2936 if ($plugin->is_enabled() && $plugin->is_visible()) {
2937 $this->cache['any_feedback_plugin_enabled'] = true;
2938 break;
2939 }
2940 }
2941 }
2942
2943 return $this->cache['any_feedback_plugin_enabled'];
2944
2945 }
2946
2947 /**
2948 * check if submission plugins installed are enabled
2949 *
2950 * @return bool
2951 */
2952 public function is_any_submission_plugin_enabled() {
2953 if (!isset($this->cache['any_submission_plugin_enabled'])) {
2954 $this->cache['any_submission_plugin_enabled'] = false;
2955 foreach ($this->submissionplugins as $plugin) {
2956 if ($plugin->is_enabled() && $plugin->is_visible() && $plugin->allow_submissions()) {
2957 $this->cache['any_submission_plugin_enabled'] = true;
2958 break;
2959 }
2960 }
2961 }
2962
2963 return $this->cache['any_submission_plugin_enabled'];
2964
2965 }
2966
2967 /**
2968 * add elements to submission form
2969 * @param MoodleQuickForm $mform
2970 * @param stdClass $data
2971 * @return void
2972 */
2973 public function add_submission_form_elements(MoodleQuickForm $mform, stdClass $data) {
2974 global $USER;
2975
2976 // online text submissions
2977
2978 $submission = $this->get_user_submission($USER->id, false);
2979
2980 $this->add_plugin_submission_elements($submission, $mform, $data);
2981
2982 // hidden params
2983 $mform->addElement('hidden', 'id', $this->get_course_module()->id);
2984 $mform->setType('id', PARAM_INT);
2985
2986 $mform->addElement('hidden', 'action', 'savesubmission');
2987 $mform->setType('action', PARAM_TEXT);
2988 // buttons
2989
2990 }
2991
2992 /**
2993 * revert to draft
2994 * Uses url parameter userid
9682626e 2995 *
bbd0e548
DW
2996 * @param int $userid
2997 * @return void
2998 */
2999 private function process_revert_to_draft($userid = 0) {
3000 global $USER, $DB;
3001
3002 // Need grade permission
3003 require_capability('mod/assign:grade', $this->context);
3004 require_sesskey();
3005
3006 if (!$userid) {
3007 $userid = required_param('userid', PARAM_INT);
3008 }
3009
3010 $submission = $this->get_user_submission($userid, false);
3011 if (!$submission) {
3012 return;
3013 }
3014 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
3015 $this->update_submission($submission, false);
3016
3017 // update the modified time on the grade (grader modified)
3018 $grade = $this->get_user_grade($userid, true);
3019 $this->update_grade($grade);
3020
3021 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
3022
3023 $this->add_to_log('revert submission to draft', get_string('reverttodraftforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user))));
3024
3025 }
3026
3027 /**
3028 * lock the process
3029 * Uses url parameter userid
3030 * @param int $userid
3031 * @return void
3032 */
3033 private function process_lock($userid = 0) {
3034 global $USER, $DB;
3035
3036 // Need grade permission
3037 require_capability('mod/assign:grade', $this->context);
3038 require_sesskey();
3039
3040 if (!$userid) {
3041 $userid = required_param('userid', PARAM_INT);
3042 }
3043
3044 $grade = $this->get_user_grade($userid, true);
3045 $grade->locked = 1;
3046 $grade->grader = $USER->id;
3047 $this->update_grade($grade);
3048
3049 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
3050
3051 $this->add_to_log('lock submission', get_string('locksubmissionforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user))));
3052 }
3053
3054 /**
3055 * unlock the process
3056 *
3057 * @param int $userid
3058 * @return void
3059 */
3060 private function process_unlock($userid = 0) {
3061 global $USER, $DB;
3062
3063 // Need grade permission
3064 require_capability('mod/assign:grade', $this->context);
3065 require_sesskey();
3066
3067 if (!$userid) {
3068 $userid = required_param('userid', PARAM_INT);
3069 }
3070
3071 $grade = $this->get_user_grade($userid, true);
3072 $grade->locked = 0;
3073 $grade->grader = $USER->id;
3074 $this->update_grade($grade);
3075
3076 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
3077
3078 $this->add_to_log('unlock submission', get_string('unlocksubmissionforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user))));
3079 }
3080
c45261df
DW
3081 /**
3082 * save outcomes submitted from grading form
3083 *
3084 * @param int $userid
3085 * @param stdClass $formdata
3086 */
3087 private function process_outcomes($userid, $formdata) {
3088 global $CFG, $USER;
3089
3090 if (empty($CFG->enableoutcomes)) {
3091 return;
3092 }
3093
3094 require_once($CFG->libdir.'/gradelib.php');
3095
3096 $data = array();
3097 $gradinginfo = grade_get_grades($this->get_course()->id,
3098 'mod',
3099 'assign',
3100 $this->get_instance()->id,
3101 $userid);
3102
3103 if (!empty($gradinginfo->outcomes)) {
3104 foreach($gradinginfo->outcomes as $index=>$oldoutcome) {
3105 $name = 'outcome_'.$index;
3106 if (isset($formdata->{$name}[$userid]) and $oldoutcome->grades[$userid]->grade != $formdata->{$name}[$userid]) {
3107 $data[$index] = $formdata->{$name}[$userid];
3108 }
3109 }
3110 }
3111 if (count($data) > 0) {
3112 grade_update_outcomes('mod/assign', $this->course->id, 'mod', 'assign', $this->get_instance()->id, $userid, $data);
3113 }
3114
3115 }
3116
3117
bbd0e548
DW
3118 /**
3119 * save grade
3120 *
3121 * @param moodleform $mform
3122 * @return bool - was the grade saved
3123 */
3124 private function process_save_grade(&$mform) {
3125 global $USER, $DB, $CFG;
3126 // Include grade form
3127 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
3128
3129 // Need submit permission to submit an assignment
3130 require_capability('mod/assign:grade', $this->context);
3131 require_sesskey();
3132
3133 $rownum = required_param('rownum', PARAM_INT);
3134 $useridlist = optional_param('useridlist', '', PARAM_TEXT);
3135 if ($useridlist) {
3136 $useridlist = explode(',', $useridlist);
3137 } else {
3138 $useridlist = $this->get_grading_userid_list();
3139 }
3140 $last = false;
3141 $userid = $useridlist[$rownum];
3142 if ($rownum == count($useridlist) - 1) {
3143 $last = true;
3144 }
3145
3146 $data = new stdClass();
3147 $mform = new mod_assign_grade_form(null, array($this, $data, array('rownum'=>$rownum, 'useridlist'=>$useridlist, 'last'=>false)), 'post', '', array('class'=>'gradeform'));
3148
3149 if ($formdata = $mform->get_data()) {
3150 $grade = $this->get_user_grade($userid, true);
3151 $gradingdisabled = $this->grading_disabled($userid);
3152 $gradinginstance = $this->get_grading_instance($userid, $gradingdisabled);
3153 if ($gradinginstance) {
3154 $grade->grade = $gradinginstance->submit_and_get_grade($formdata->advancedgrading, $grade->id);
3155 } else {
3156 // handle the case when grade is set to No Grade
3157 if (isset($formdata->grade)) {
3158 $grade->grade= grade_floatval($formdata->grade);
3159 }
3160 }
3161 $grade->grader= $USER->id;
3162
cfc81f03
DW
3163 $adminconfig = $this->get_admin_config();
3164 $gradebookplugin = $adminconfig->feedback_plugin_for_gradebook;
bbd0e548
DW
3165
3166 // call save in plugins
3167 foreach ($this->feedbackplugins as $plugin) {
3168 if ($plugin->is_enabled() && $plugin->is_visible()) {
3169 if (!$plugin->save($grade, $formdata)) {
3170 $result = false;
3171 print_error($plugin->get_error());
3172 }
3173 if (('assignfeedback_' . $plugin->get_type()) == $gradebookplugin) {
3174 // this is the feedback plugin chose to push comments to the gradebook
3175 $grade->feedbacktext = $plugin->text_for_gradebook($grade);
3176 $grade->feedbackformat = $plugin->format_for_gradebook($grade);
3177 }
3178 }
3179 }
c45261df 3180 $this->process_outcomes($userid, $formdata);
75f87a57
DW
3181
3182 $grade->mailed = 0;
3183
bbd0e548
DW
3184 $this->update_grade($grade);
3185
3186 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
3187
3188 $this->add_to_log('grade submission', $this->format_grade_for_log($grade));
3189
3190
3191 } else {
3192 return false;
3193 }
3194 return true;
3195 }
3196
3197 /**
3198 * This function is a static wrapper around can_upgrade
3199 *
3200 * @param string $type The plugin type
3201 * @param int $version The plugin version
3202 * @return bool
3203 */
3204 public static function can_upgrade_assignment($type, $version) {
3205 $assignment = new assign(null, null, null);
3206 return $assignment->can_upgrade($type, $version);
3207 }
3208
3209 /**
3210 * This function returns true if it can upgrade an assignment from the 2.2
3211 * module.
3212 * @param string $type The plugin type
3213 * @param int $version The plugin version
3214 * @return bool
3215 */
3216 public function can_upgrade($type, $version) {
3217 if ($type == 'offline' && $version >= 2011112900) {
3218 return true;
3219 }
3220 foreach ($this->submissionplugins as $plugin) {
3221 if ($plugin->can_upgrade($type, $version)) {
3222 return true;
3223 }
3224 }
3225 foreach ($this->feedbackplugins as $plugin) {
3226 if ($plugin->can_upgrade($type, $version)) {
3227 return true;
3228 }
3229 }
3230 return false;
3231 }
3232
3233 /**
3234 * Copy all the files from the old assignment files area to the new one.
3235 * This is used by the plugin upgrade code.
3236 *
3237 * @param int $oldcontextid The old assignment context id
3238 * @param int $oldcomponent The old assignment component ('assignment')
3239 * @param int $oldfilearea The old assignment filearea ('submissions')
3240 * @param int $olditemid The old submissionid (can be null e.g. intro)
3241 * @param int $newcontextid The new assignment context id
3242 * @param int $newcomponent The new assignment component ('assignment')
3243 * @param int $newfilearea The new assignment filearea ('submissions')
3244 * @param int $newitemid The new submissionid (can be null e.g. intro)
3245 * @return int The number of files copied
3246 */
3247 public function copy_area_files_for_upgrade($oldcontextid, $oldcomponent, $oldfilearea, $olditemid, $newcontextid, $newcomponent, $newfilearea, $newitemid) {
3248 // Note, this code is based on some code in filestorage - but that code
3249 // deleted the old files (which we don't want)
3250 $count = 0;
3251
3252 $fs = get_file_storage();
3253
3254 $oldfiles = $fs->get_area_files($oldcontextid, $oldcomponent, $oldfilearea, $olditemid, 'id', false);
3255 foreach ($oldfiles as $oldfile) {
3256 $filerecord = new stdClass();
3257 $filerecord->contextid = $newcontextid;
3258 $filerecord->component = $newcomponent;
3259 $filerecord->filearea = $newfilearea;
3260 $filerecord->itemid = $newitemid;
3261 $fs->create_file_from_storedfile($filerecord, $oldfile);
3262 $count += 1;
3263 }
3264
3265 return $count;
3266 }
3267
3268 /**
3269 * Get an upto date list of user grades and feedback for the gradebook
3270 *
3271 * @param int $userid int or 0 for all users
3272 * @return array of grade data formated for the gradebook api
3273 * The data required by the gradebook api is userid,
3274 * rawgrade,
3275 * feedback,
3276 * feedbackformat,
3277 * usermodified,
3278 * dategraded,
3279 * datesubmitted
3280 */
3281 public function get_user_grades_for_gradebook($userid) {
3282 global $DB, $CFG;
3283 $grades = array();
3284 $assignmentid = $this->get_instance()->id;
3285
b11808c7
DW
3286 $adminconfig = $this->get_admin_config();
3287 $gradebookpluginname = $adminconfig->feedback_plugin_for_gradebook;
bbd0e548
DW
3288 $gradebookplugin = null;
3289
3290 // find the gradebook plugin
3291 foreach ($this->feedbackplugins as $plugin) {
3292 if ($plugin->is_enabled() && $plugin->is_visible()) {
3293 if (('assignfeedback_' . $plugin->get_type()) == $gradebookpluginname) {
3294 $gradebookplugin = $plugin;
3295 }
3296 }
3297 }
3298 if ($userid) {
3299 $where = ' WHERE u.id = ? ';
3300 } else {
3301 $where = ' WHERE u.id != ? ';
3302 }
3303
3304 $graderesults = $DB->get_recordset_sql('SELECT u.id as userid, s.timemodified as datesubmitted, g.grade as rawgrade, g.timemodified as dategraded, g.grader as usermodified
3305 FROM {user} u
3306 LEFT JOIN {assign_submission} s ON u.id = s.userid and s.assignment = ?
3307 LEFT JOIN {assign_grades} g ON u.id = g.userid and g.assignment = ?
3308 ' . $where, array($assignmentid, $assignmentid, $userid));
3309
3310
3311 foreach ($graderesults as $result) {
3312 $gradebookgrade = clone $result;
3313 // now get the feedback
3314 if ($gradebookplugin) {
3315 $grade = $this->get_user_grade($result->userid, false);
3316 $gradebookgrade->feedbacktext = $gradebookplugin->text_for_gradebook($grade);
3317 $gradebookgrade->feedbackformat = $gradebookplugin->format_for_gradebook($grade);
3318 }
3319 $grades[$gradebookgrade->userid] = $gradebookgrade;
3320 }
3321
3322 $graderesults->close();
3323 return $grades;
3324 }
3325
3326}
3327