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