Merge branch 'MDL-35966-23' of git://github.com/damyon/moodle into MOODLE_23_STABLE
[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
2a4fbc32
SH
971 if ($this->get_instance()->grade >= 0) {
972 // Normal number
e7ade405 973 if ($editing && $this->get_instance()->grade > 0) {
2d8a9ce9
DW
974 if ($grade < 0) {
975 $displaygrade = '';
976 } else {
977 $displaygrade = format_float($grade);
978 }
502be9a0 979 $o = '<input type="text" name="quickgrade_' . $userid . '" value="' . $displaygrade . '" size="6" maxlength="10" class="quickgrade"/>';
bf78ebd6 980 $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade,2);
2a4fbc32 981 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
bf78ebd6 982 return $o;
bbd0e548 983 } else {
a1e54f4d
DW
984 if ($grade == -1 || $grade === null) {
985 return '-';
986 } else {
987 return format_float(($grade),2) .'&nbsp;/&nbsp;'. format_float($this->get_instance()->grade,2);
988 }
bbd0e548
DW
989 }
990
2a4fbc32
SH
991 } else {
992 // Scale
bbd0e548
DW
993 if (empty($this->cache['scale'])) {
994 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
995 $this->cache['scale'] = make_menu_from_list($scale->scale);
996 } else {
997 return '-';
998 }
999 }
bf78ebd6
DW
1000 if ($editing) {
1001 $o = '<select name="quickgrade_' . $userid . '" class="quickgrade">';
1002 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
1003 foreach ($this->cache['scale'] as $optionid => $option) {
1004 $selected = '';
1005 if ($grade == $optionid) {
1006 $selected = 'selected="selected"';
1007 }
1008 $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
1009 }
1010 $o .= '</select>';
1011 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
1012 return $o;
1013 } else {
1014 $scaleid = (int)$grade;
1015 if (isset($this->cache['scale'][$scaleid])) {
1016 return $this->cache['scale'][$scaleid];
1017 }
1018 return '-';
bbd0e548 1019 }
bbd0e548
DW
1020 }
1021 }
1022
1023 /**
1024 * Load a list of users enrolled in the current course with the specified permission and group (0 for no group)
1025 *
1026 * @param int $currentgroup
1027 * @param bool $idsonly
1028 * @return array List of user records
1029 */
1030 public function list_participants($currentgroup, $idsonly) {
1031 if ($idsonly) {
1032 return get_enrolled_users($this->context, "mod/assign:submit", $currentgroup, 'u.id');
1033 } else {
1034 return get_enrolled_users($this->context, "mod/assign:submit", $currentgroup);
1035 }
1036 }
1037
1038 /**
1039 * Load a count of users enrolled in the current course with the specified permission and group (0 for no group)
1040 *
1041 * @param int $currentgroup
1042 * @return int number of matching users
1043 */
1044 public function count_participants($currentgroup) {
1045 return count_enrolled_users($this->context, "mod/assign:submit", $currentgroup);
1046 }
1047
392ee02d
DW
1048 /**
1049 * Load a count of users submissions in the current module that require grading
1050 * This means the submission modification time is more recent than the
1051 * grading modification time.
1052 *
1053 * @return int number of matching submissions
1054 */
1055 public function count_submissions_need_grading() {
1056 global $DB;
1057
1058 $params = array($this->get_course_module()->instance);
1059
1060 return $DB->count_records_sql("SELECT COUNT('x')
1061 FROM {assign_submission} s
1062 LEFT JOIN {assign_grades} g ON s.assignment = g.assignment AND s.userid = g.userid
1063 WHERE s.assignment = ?
1064 AND s.timemodified IS NOT NULL
1065 AND (s.timemodified > g.timemodified OR g.timemodified IS NULL)",
1066 $params);
1067 }
1068
bbd0e548
DW
1069 /**
1070 * Load a count of users enrolled in the current course with the specified permission and group (optional)
1071 *
1072 * @param string $status The submission status - should match one of the constants
1073 * @return int number of matching submissions
1074 */
1075 public function count_submissions_with_status($status) {
1076 global $DB;
1077 return $DB->count_records_sql("SELECT COUNT('x')
1078 FROM {assign_submission}
1079 WHERE assignment = ? AND
1080 status = ?", array($this->get_course_module()->instance, $status));
1081 }
1082
1083 /**
1084 * Utility function to get the userid for every row in the grading table
1085 * so the order can be frozen while we iterate it
1086 *
1087 * @return array An array of userids
1088 */
1089 private function get_grading_userid_list(){
1090 $filter = get_user_preferences('assign_filter', '');
bf78ebd6 1091 $table = new assign_grading_table($this, 0, $filter, 0, false);
bbd0e548
DW
1092
1093 $useridlist = $table->get_column_data('userid');
1094
1095 return $useridlist;
1096 }
1097
1098
1099 /**
1100 * Utility function get the userid based on the row number of the grading table.
1101 * This takes into account any active filters on the table.
1102 *
1103 * @param int $num The row number of the user
1104 * @param bool $last This is set to true if this is the last user in the table
1105 * @return mixed The user id of the matching user or false if there was an error
1106 */
1107 private function get_userid_for_row($num, $last){
1108 if (!array_key_exists('userid_for_row', $this->cache)) {
1109 $this->cache['userid_for_row'] = array();
1110 }
1111 if (array_key_exists($num, $this->cache['userid_for_row'])) {
1112 list($userid, $last) = $this->cache['userid_for_row'][$num];
1113 return $userid;
1114 }
1115
1116 $filter = get_user_preferences('assign_filter', '');
bf78ebd6 1117 $table = new assign_grading_table($this, 0, $filter, 0, false);
bbd0e548
DW
1118
1119 $userid = $table->get_cell_data($num, 'userid', $last);
1120
1121 $this->cache['userid_for_row'][$num] = array($userid, $last);
1122 return $userid;
1123 }
1124
1125 /**
1126 * Return all assignment submissions by ENROLLED students (even empty)
1127 *
1128 * @param string $sort optional field names for the ORDER BY in the sql query
1129 * @param string $dir optional specifying the sort direction, defaults to DESC
1130 * @return array The submission objects indexed by id
1131 */
1132 private function get_all_submissions( $sort="", $dir="DESC") {
1133 global $CFG, $DB;
1134
1135 if ($sort == "lastname" or $sort == "firstname") {
1136 $sort = "u.$sort $dir";
1137 } else if (empty($sort)) {
1138 $sort = "a.timemodified DESC";
1139 } else {
1140 $sort = "a.$sort $dir";
1141 }
1142
1143 return $DB->get_records_sql("SELECT a.*
1144 FROM {assign_submission} a, {user} u
1145 WHERE u.id = a.userid
1146 AND a.assignment = ?
1147 ORDER BY $sort", array($this->get_instance()->id));
1148
1149 }
1150
1151 /**
1152 * Generate zip file from array of given files
1153 *
1154 * @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
1155 * @return path of temp file - note this returned file does not have a .zip extension - it is a temp file.
1156 */
1157 private function pack_files($filesforzipping) {
1158 global $CFG;
1159 //create path for new zip file.
1160 $tempzip = tempnam($CFG->tempdir.'/', 'assignment_');
1161 //zip files
1162 $zipper = new zip_packer();
1163 if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
1164 return $tempzip;
1165 }
1166 return false;
1167 }
1168
bbd0e548 1169 /**
3f7b501e
SH
1170 * Finds all assignment notifications that have yet to be mailed out, and mails them.
1171 *
1172 * Cron function to be run periodically according to the moodle cron
bbd0e548
DW
1173 *
1174 * @return bool
1175 */
1176 static function cron() {
3f7b501e 1177 global $DB;
75f87a57
DW
1178
1179 // only ever send a max of one days worth of updates
1180 $yesterday = time() - (24 * 3600);
1181 $timenow = time();
1182
3f7b501e
SH
1183 // Collect all submissions from the past 24 hours that require mailing.
1184 $sql = "SELECT s.*, a.course, a.name, g.*, g.id as gradeid, g.timemodified as lastmodified
1185 FROM {assign} a
1186 JOIN {assign_grades} g ON g.assignment = a.id
1187 LEFT JOIN {assign_submission} s ON s.assignment = a.id AND s.userid = g.userid
1188 WHERE g.timemodified >= :yesterday AND
1189 g.timemodified <= :today AND
1190 g.mailed = 0";
1191 $params = array('yesterday' => $yesterday, 'today' => $timenow);
1192 $submissions = $DB->get_records_sql($sql, $params);
75f87a57 1193
c8314005
SH
1194 if (empty($submissions)) {
1195 mtrace('done.');
1196 return true;
1197 }
1198
75f87a57
DW
1199 mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
1200
3f7b501e
SH
1201 // Preload courses we are going to need those.
1202 $courseids = array();
1203 foreach ($submissions as $submission) {
1204 $courseids[] = $submission->course;
1205 }
1206 // Filter out duplicates
1207 $courseids = array_unique($courseids);
1208 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1209 list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
1210 $sql = "SELECT c.*, {$ctxselect}
1211 FROM {course} c
1212 LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
1213 WHERE c.id {$courseidsql}";
1214 $params['contextlevel'] = CONTEXT_COURSE;
1215 $courses = $DB->get_records_sql($sql, $params);
1216 // Clean up... this could go on for a while.
1217 unset($courseids);
1218 unset($ctxselect);
1219 unset($courseidsql);
1220 unset($params);
1221
1222 // Simple array we'll use for caching modules.
1223 $modcache = array();
1224
c1d09c6f 1225 // Message students about new feedback
75f87a57
DW
1226 foreach ($submissions as $submission) {
1227
1228 mtrace("Processing assignment submission $submission->id ...");
1229
1230 // do not cache user lookups - could be too many
3f7b501e 1231 if (!$user = $DB->get_record("user", array("id"=>$submission->userid))) {
75f87a57
DW
1232 mtrace("Could not find user $submission->userid");
1233 continue;
1234 }
1235
1236 // use a cache to prevent the same DB queries happening over and over
3f7b501e
SH
1237 if (!array_key_exists($submission->course, $courses)) {
1238 mtrace("Could not find course $submission->course");
1239 continue;
1240 }
1241 $course = $courses[$submission->course];
1242 if (isset($course->ctxid)) {
1243 // Context has not yet been preloaded. Do so now.
1244 context_helper::preload_from_record($course);
75f87a57
DW
1245 }
1246
3f7b501e
SH
1247 // Override the language and timezone of the "current" user, so that
1248 // mail is customised for the receiver.
75f87a57
DW
1249 cron_setup_user($user, $course);
1250
1251 // context lookups are already cached
3f7b501e 1252 $coursecontext = context_course::instance($course->id);
75f87a57 1253 if (!is_enrolled($coursecontext, $user->id)) {
3f7b501e 1254 $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
75f87a57
DW
1255 mtrace(fullname($user)." not an active participant in " . $courseshortname);
1256 continue;
1257 }
1258
3f7b501e 1259 if (!$grader = $DB->get_record("user", array("id"=>$submission->grader))) {
75f87a57
DW
1260 mtrace("Could not find grader $submission->grader");
1261 continue;
1262 }
1263
3f7b501e 1264 if (!array_key_exists($submission->assignment, $modcache)) {
75f87a57
DW
1265 if (! $mod = get_coursemodule_from_instance("assign", $submission->assignment, $course->id)) {
1266 mtrace("Could not find course module for assignment id $submission->assignment");
1267 continue;
1268 }
3f7b501e
SH
1269 $modcache[$submission->assignment] = $mod;
1270 } else {
1271 $mod = $modcache[$submission->assignment];
75f87a57 1272 }
75f87a57
DW
1273 // context lookups are already cached
1274 $contextmodule = context_module::instance($mod->id);
bbd0e548 1275
3f7b501e
SH
1276 if (!$mod->visible) {
1277 // Hold mail notification for hidden assignments until later
75f87a57
DW
1278 continue;
1279 }
1280
1281 // need to send this to the student
3f7b501e 1282 $messagetype = 'feedbackavailable';
f750cf71 1283 $eventtype = 'assign_notification';
3f7b501e
SH
1284 $updatetime = $submission->lastmodified;
1285 $modulename = get_string('modulename', 'assign');
1286 self::send_assignment_notification($grader, $user, $messagetype, $eventtype, $updatetime, $mod, $contextmodule, $course, $modulename, $submission->name);
75f87a57
DW
1287
1288 $grade = new stdClass();
1289 $grade->id = $submission->gradeid;
1290 $grade->mailed = 1;
1291 $DB->update_record('assign_grades', $grade);
1292
1293 mtrace('Done');
1294 }
1295 mtrace('Done processing ' . count($submissions) . ' assignment submissions');
1296
1297 cron_setup_user();
3f7b501e
SH
1298
1299 // Free up memory just to be sure
1300 unset($courses);
1301 unset($modcache);
bbd0e548
DW
1302
1303 return true;
1304 }
1305
1306 /**
1307 * Update a grade in the grade table for the assignment and in the gradebook
1308 *
1309 * @param stdClass $grade a grade record keyed on id
1310 * @return bool true for success
1311 */
1312 private function update_grade($grade) {
1313 global $DB;
1314
1315 $grade->timemodified = time();
1316
1317 if ($grade->grade && $grade->grade != -1) {
1318 if ($this->get_instance()->grade > 0) {
1319 if (!is_numeric($grade->grade)) {
1320 return false;
1321 } else if ($grade->grade > $this->get_instance()->grade) {
1322 return false;
1323 } else if ($grade->grade < 0) {
1324 return false;
1325 }
1326 } else {
1327 // this is a scale
1328 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
1329 $scaleoptions = make_menu_from_list($scale->scale);
1330 if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
1331 return false;
1332 }
1333 }
1334 }
1335 }
1336
1337 $result = $DB->update_record('assign_grades', $grade);
1338 if ($result) {
1339 $this->gradebook_item_update(null, $grade);
1340 }
1341 return $result;
1342 }
1343
1344 /**
1345 * display the submission that is used by a plugin
1346 * Uses url parameters 'sid', 'gid' and 'plugin'
1347 * @param string $pluginsubtype
1348 * @return string
1349 */
1350 private function view_plugin_content($pluginsubtype) {
1351 global $USER;
1352
1353 $o = '';
1354
1355 $submissionid = optional_param('sid', 0, PARAM_INT);
1356 $gradeid = optional_param('gid', 0, PARAM_INT);
1357 $plugintype = required_param('plugin', PARAM_TEXT);
1358 $item = null;
1359 if ($pluginsubtype == 'assignsubmission') {
1360 $plugin = $this->get_submission_plugin_by_type($plugintype);
1361 if ($submissionid <= 0) {
1362 throw new coding_exception('Submission id should not be 0');
1363 }
1364 $item = $this->get_submission($submissionid);
1365
1366 // permissions
1367 if ($item->userid != $USER->id) {
1368 require_capability('mod/assign:grade', $this->context);
1369 }
1370 $o .= $this->output->render(new assign_header($this->get_instance(),
1371 $this->get_context(),
1372 $this->show_intro(),
1373 $this->get_course_module()->id,
1374 $plugin->get_name()));
1375 $o .= $this->output->render(new assign_submission_plugin_submission($plugin,
1376 $item,
1377 assign_submission_plugin_submission::FULL,
1378 $this->get_course_module()->id,
1379 $this->get_return_action(),
1380 $this->get_return_params()));
1381
1382 $this->add_to_log('view submission', get_string('viewsubmissionforuser', 'assign', $item->userid));
1383 } else {
1384 $plugin = $this->get_feedback_plugin_by_type($plugintype);
1385 if ($gradeid <= 0) {
1386 throw new coding_exception('Grade id should not be 0');
1387 }
1388 $item = $this->get_grade($gradeid);
1389 // permissions
1390 if ($item->userid != $USER->id) {
1391 require_capability('mod/assign:grade', $this->context);
1392 }
1393 $o .= $this->output->render(new assign_header($this->get_instance(),
1394 $this->get_context(),
1395 $this->show_intro(),
1396 $this->get_course_module()->id,
1397 $plugin->get_name()));
1398 $o .= $this->output->render(new assign_feedback_plugin_feedback($plugin,
1399 $item,
1400 assign_feedback_plugin_feedback::FULL,
1401 $this->get_course_module()->id,
1402 $this->get_return_action(),
1403 $this->get_return_params()));
1404 $this->add_to_log('view feedback', get_string('viewfeedbackforuser', 'assign', $item->userid));
1405 }
1406
1407
1408 $o .= $this->view_return_links();
1409
1410 $o .= $this->view_footer();
1411 return $o;
1412 }
1413
1414 /**
1415 * render the content in editor that is often used by plugin
1416 *
1417 * @param string $filearea
1418 * @param int $submissionid
1419 * @param string $plugintype
1420 * @param string $editor
1421 * @param string $component
1422 * @return string
1423 */
1424 public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
1425 global $CFG;
1426
1427 $result = '';
1428
1429 $plugin = $this->get_submission_plugin_by_type($plugintype);
1430
1431 $text = $plugin->get_editor_text($editor, $submissionid);
1432 $format = $plugin->get_editor_format($editor, $submissionid);
1433
1434 $finaltext = file_rewrite_pluginfile_urls($text, 'pluginfile.php', $this->get_context()->id, $component, $filearea, $submissionid);
1435 $result .= format_text($finaltext, $format, array('overflowdiv' => true, 'context' => $this->get_context()));
1436
1437
1438
1439 if ($CFG->enableportfolios) {
1440 require_once($CFG->libdir . '/portfoliolib.php');
1441
1442 $button = new portfolio_add_button();
1443 $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');
1444 $fs = get_file_storage();
1445
1446 if ($files = $fs->get_area_files($this->context->id, $component,$filearea, $submissionid, "timemodified", false)) {
1447 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
1448 } else {
1449 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
1450 }
1451 $result .= $button->to_html();
1452 }
1453 return $result;
1454 }
1455
bf78ebd6
DW
1456 /**
1457 * Display a grading error
1458 *
1459 * @param string $message - The description of the result
1460 * @return string
1461 */
1462 private function view_quickgrading_result($message) {
1463 $o = '';
1464 $o .= $this->output->render(new assign_header($this->get_instance(),
1465 $this->get_context(),
1466 $this->show_intro(),
1467 $this->get_course_module()->id,
1468 get_string('quickgradingresult', 'assign')));
1469 $o .= $this->output->render(new assign_quickgrading_result($message, $this->get_course_module()->id));
1470 $o .= $this->view_footer();
1471 return $o;
1472 }
bbd0e548
DW
1473
1474 /**
1475 * Display the page footer
1476 *
bf78ebd6 1477 * @return string
bbd0e548
DW
1478 */
1479 private function view_footer() {
1480 return $this->output->render_footer();
1481 }
1482
1483 /**
1484 * Does this user have grade permission for this assignment
1485 *
1486 * @return bool
1487 */
1488 private function can_grade() {
1489 // Permissions check
1490 if (!has_capability('mod/assign:grade', $this->context)) {
1491 return false;
1492 }
1493
1494 return true;
1495 }
1496
1497 /**
1498 * Download a zip file of all assignment submissions
1499 *
1500 * @return void
1501 */
1502 private function download_submissions() {
1503 global $CFG,$DB;
1504
1505 // more efficient to load this here
1506 require_once($CFG->libdir.'/filelib.php');
1507
1508 // load all submissions
1509 $submissions = $this->get_all_submissions('','');
1510
1511 if (empty($submissions)) {
1512 print_error('errornosubmissions', 'assign');
1513 return;
1514 }
1515
1516 // build a list of files to zip
1517 $filesforzipping = array();
1518 $fs = get_file_storage();
1519
1520 $groupmode = groups_get_activity_groupmode($this->get_course_module());
1521 $groupid = 0; // All users
1522 $groupname = '';
1523 if ($groupmode) {
1524 $groupid = groups_get_activity_group($this->get_course_module(), true);
1525 $groupname = groups_get_group_name($groupid).'-';
1526 }
1527
1528 // construct the zip file name
1529 $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.
1530
1531 // get all the files for each submission
1532 foreach ($submissions as $submission) {
1533 $userid = $submission->userid; //get userid
1534 if ((groups_is_member($groupid,$userid) or !$groupmode or !$groupid)) {
1535 // get the plugins to add their own files to the zip
1536
1537 $user = $DB->get_record("user", array("id"=>$userid),'id,username,firstname,lastname', MUST_EXIST);
1538
1539 $prefix = clean_filename(fullname($user) . "_" .$userid . "_");
1540
1541 foreach ($this->submissionplugins as $plugin) {
1542 if ($plugin->is_enabled() && $plugin->is_visible()) {
1543 $pluginfiles = $plugin->get_files($submission);
1544
1545
1546 foreach ($pluginfiles as $zipfilename => $file) {
1547 $filesforzipping[$prefix . $zipfilename] = $file;
1548 }
1549 }
1550 }
1551
1552 }
1553 } // end of foreach loop
1554 if ($zipfile = $this->pack_files($filesforzipping)) {
1555 $this->add_to_log('download all submissions', get_string('downloadall', 'assign'));
1556 send_temp_file($zipfile, $filename); //send file and delete after sending.
1557 }
1558 }
1559
1560 /**
1561 * Util function to add a message to the log
1562 *
1563 * @param string $action The current action
1564 * @param string $info A detailed description of the change. But no more than 255 characters.
1565 * @param string $url The url to the assign module instance.
1566 * @return void
1567 */
1568 public function add_to_log($action = '', $info = '', $url='') {
1569 global $USER;
1570
1571 $fullurl = 'view.php?id=' . $this->get_course_module()->id;
1572 if ($url != '') {
1573 $fullurl .= '&' . $url;
1574 }
1575
1576 add_to_log($this->get_course()->id, 'assign', $action, $fullurl, $info, $this->get_course_module()->id, $USER->id);
1577 }
1578
1579 /**
1580 * Load the submission object for a particular user, optionally creating it if required
1581 *
1582 * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
1583 * @param bool $create optional Defaults to false. If set to true a new submission object will be created in the database
1584 * @return stdClass The submission
1585 */
1586 private function get_user_submission($userid, $create) {
1587 global $DB, $USER;
1588
1589 if (!$userid) {
1590 $userid = $USER->id;
1591 }
1592 // if the userid is not null then use userid
1593 $submission = $DB->get_record('assign_submission', array('assignment'=>$this->get_instance()->id, 'userid'=>$userid));
1594
1595 if ($submission) {
1596 return $submission;
1597 }
1598 if ($create) {
1599 $submission = new stdClass();
1600 $submission->assignment = $this->get_instance()->id;
1601 $submission->userid = $userid;
1602 $submission->timecreated = time();
1603 $submission->timemodified = $submission->timecreated;
1604
1605 if ($this->get_instance()->submissiondrafts) {
1606 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
1607 } else {
1608 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1609 }
1610 $sid = $DB->insert_record('assign_submission', $submission);
1611 $submission->id = $sid;
1612 return $submission;
1613 }
1614 return false;
1615 }
1616
1617 /**
1618 * Load the submission object from it's id
1619 *
1620 * @param int $submissionid The id of the submission we want
1621 * @return stdClass The submission
1622 */
1623 private function get_submission($submissionid) {
1624 global $DB;
1625
1626 return $DB->get_record('assign_submission', array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid), '*', MUST_EXIST);
1627 }
1628
1629 /**
1630 * This will retrieve a grade object from the db, optionally creating it if required
1631 *
1632 * @param int $userid The user we are grading
1633 * @param bool $create If true the grade will be created if it does not exist
1634 * @return stdClass The grade record
1635 */
1636 private function get_user_grade($userid, $create) {
1637 global $DB, $USER;
1638
1639 if (!$userid) {
1640 $userid = $USER->id;
1641 }
1642
1643 // if the userid is not null then use userid
1644 $grade = $DB->get_record('assign_grades', array('assignment'=>$this->get_instance()->id, 'userid'=>$userid));
1645
1646 if ($grade) {
1647 return $grade;
1648 }
1649 if ($create) {
1650 $grade = new stdClass();
1651 $grade->assignment = $this->get_instance()->id;
1652 $grade->userid = $userid;
1653 $grade->timecreated = time();
1654 $grade->timemodified = $grade->timecreated;
1655 $grade->locked = 0;
1656 $grade->grade = -1;
1657 $grade->grader = $USER->id;
1658 $gid = $DB->insert_record('assign_grades', $grade);
1659 $grade->id = $gid;
1660 return $grade;
1661 }
1662 return false;
1663 }
1664
1665 /**
1666 * This will retrieve a grade object from the db
1667 *
1668 * @param int $gradeid The id of the grade
1669 * @return stdClass The grade record
1670 */
1671 private function get_grade($gradeid) {
1672 global $DB;
1673
1674 return $DB->get_record('assign_grades', array('assignment'=>$this->get_instance()->id, 'id'=>$gradeid), '*', MUST_EXIST);
1675 }
1676
1677 /**
1678 * Print the grading page for a single user submission
1679 *
1680 * @param moodleform $mform
1681 * @param int $offset
1682 * @return string
1683 */
1684 private function view_single_grade_page($mform, $offset=0) {
1685 global $DB, $CFG;
1686
1687 $o = '';
1688
1689 // Include grade form
1690 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
1691
1692 // Need submit permission to submit an assignment
1693 require_capability('mod/assign:grade', $this->context);
1694
1695 $o .= $this->output->render(new assign_header($this->get_instance(),
1696 $this->get_context(), false, $this->get_course_module()->id,get_string('grading', 'assign')));
1697
1698 $rownum = required_param('rownum', PARAM_INT) + $offset;
1699 $useridlist = optional_param('useridlist', '', PARAM_TEXT);
1700 if ($useridlist) {
1701 $useridlist = explode(',', $useridlist);
1702 } else {
1703 $useridlist = $this->get_grading_userid_list();
1704 }
1705 $last = false;
1706 $userid = $useridlist[$rownum];
1707 if ($rownum == count($useridlist) - 1) {
1708 $last = true;
1709 }
2b702484 1710 if (!$userid) {
bbd0e548
DW
1711 throw new coding_exception('Row is out of bounds for the current grading table: ' . $rownum);
1712 }
1713 $user = $DB->get_record('user', array('id' => $userid));
1714 if ($user) {
1715 $o .= $this->output->render(new assign_user_summary($user, $this->get_course()->id, has_capability('moodle/site:viewfullnames', $this->get_course_context())));
1716 }
1717 $submission = $this->get_user_submission($userid, false);
1718 // get the current grade
1719 $grade = $this->get_user_grade($userid, false);
1720 if ($this->can_view_submission($userid)) {
1721 $gradelocked = ($grade && $grade->locked) || $this->grading_disabled($userid);
1722 $o .= $this->output->render(new assign_submission_status($this->get_instance()->allowsubmissionsfromdate,
1723 $this->get_instance()->alwaysshowdescription,
1724 $submission,
1725 $this->is_any_submission_plugin_enabled(),
1726 $gradelocked,
1727 $this->is_graded($userid),
1728 $this->get_instance()->duedate,
1729 $this->get_submission_plugins(),
1730 $this->get_return_action(),
1731 $this->get_return_params(),
1732 $this->get_course_module()->id,
1733 assign_submission_status::GRADER_VIEW,
1734 false,
1735 false));
1736 }
1737 if ($grade) {
1738 $data = new stdClass();
2d8a9ce9 1739 if ($grade->grade !== NULL && $grade->grade >= 0) {
bbd0e548
DW
1740 $data->grade = format_float($grade->grade,2);
1741 }
1742 } else {
1743 $data = new stdClass();
1744 $data->grade = '';
1745 }
1746
1747 // now show the grading form
1748 if (!$mform) {
1749 $mform = new mod_assign_grade_form(null, array($this, $data, array('rownum'=>$rownum, 'useridlist'=>$useridlist, 'last'=>$last)), 'post', '', array('class'=>'gradeform'));
1750 }
1751 $o .= $this->output->render(new assign_form('gradingform',$mform));
1752
1753 $this->add_to_log('view grading form', get_string('viewgradingformforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user))));
1754
1755 $o .= $this->view_footer();
1756 return $o;
1757 }
1758
1759
1760
1761 /**
1762 * View a link to go back to the previous page. Uses url parameters returnaction and returnparams.
1763 *
1764 * @return string
1765 */
1766 private function view_return_links() {
1767
1768 $returnaction = optional_param('returnaction','', PARAM_ALPHA);
1769 $returnparams = optional_param('returnparams','', PARAM_TEXT);
1770
1771 $params = array();
1772 parse_str($returnparams, $params);
1773 $params = array_merge( array('id' => $this->get_course_module()->id, 'action' => $returnaction), $params);
1774
1775 return $this->output->single_button(new moodle_url('/mod/assign/view.php', $params), get_string('back'), 'get');
1776
1777 }
1778
1779 /**
1780 * View the grading table of all submissions for this assignment
1781 *
1782 * @return string
1783 */
1784 private function view_grading_table() {
1785 global $USER, $CFG;
1786 // Include grading options form
1787 require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
bf78ebd6 1788 require_once($CFG->dirroot . '/mod/assign/quickgradingform.php');
bbd0e548
DW
1789 require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
1790 $o = '';
1791
1792 $links = array();
bbd0e548
DW
1793 if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
1794 has_capability('moodle/grade:viewall', $this->get_course_context())) {
a1e54f4d 1795 $gradebookurl = '/grade/report/grader/index.php?id=' . $this->get_course()->id;
bbd0e548
DW
1796 $links[$gradebookurl] = get_string('viewgradebook', 'assign');
1797 }
1798 if ($this->is_any_submission_plugin_enabled()) {
a1e54f4d 1799 $downloadurl = '/mod/assign/view.php?id=' . $this->get_course_module()->id . '&action=downloadall';
bbd0e548
DW
1800 $links[$downloadurl] = get_string('downloadall', 'assign');
1801 }
a1e54f4d
DW
1802
1803 $gradingactions = new url_select($links);
bbd0e548 1804
bf78ebd6
DW
1805 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
1806
bbd0e548
DW
1807 $perpage = get_user_preferences('assign_perpage', 10);
1808 $filter = get_user_preferences('assign_filter', '');
bf78ebd6
DW
1809 $controller = $gradingmanager->get_active_controller();
1810 $showquickgrading = empty($controller);
1811 if (optional_param('action', '', PARAM_ALPHA) == 'saveoptions') {
1812 $quickgrading = optional_param('quickgrading', false, PARAM_BOOL);
1813 set_user_preference('assign_quickgrading', $quickgrading);
1814 }
1815 $quickgrading = get_user_preferences('assign_quickgrading', false);
1816
bbd0e548
DW
1817 // print options for changing the filter and changing the number of results per page
1818 $gradingoptionsform = new mod_assign_grading_options_form(null,
1819 array('cm'=>$this->get_course_module()->id,
1820 'contextid'=>$this->context->id,
bf78ebd6 1821 'userid'=>$USER->id,
145a300b 1822 'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
bf78ebd6
DW
1823 'showquickgrading'=>$showquickgrading,
1824 'quickgrading'=>$quickgrading),
bbd0e548
DW
1825 'post', '',
1826 array('class'=>'gradingoptionsform'));
1827
1828 $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
1829 array('cm'=>$this->get_course_module()->id,
1830 'submissiondrafts'=>$this->get_instance()->submissiondrafts),
1831 'post', '',
1832 array('class'=>'gradingbatchoperationsform'));
1833
1834 $gradingoptionsdata = new stdClass();
1835 $gradingoptionsdata->perpage = $perpage;
1836 $gradingoptionsdata->filter = $filter;
1837 $gradingoptionsform->set_data($gradingoptionsdata);
1838
4d48a651
DM
1839 $actionformtext = $this->output->render($gradingactions);
1840 $o .= $this->output->render(new assign_header($this->get_instance(),
1841 $this->get_context(), false, $this->get_course_module()->id, get_string('grading', 'assign'), $actionformtext));
1842 $o .= groups_print_activity_menu($this->get_course_module(), $CFG->wwwroot . '/mod/assign/view.php?id=' . $this->get_course_module()->id.'&action=grading', true);
1843
bbd0e548
DW
1844 // plagiarism update status apearring in the grading book
1845 if (!empty($CFG->enableplagiarism)) {
1846 /** Include plagiarismlib.php */
1847 require_once($CFG->libdir . '/plagiarismlib.php');
66681a51 1848 $o .= plagiarism_update_status($this->get_course(), $this->get_course_module());
bbd0e548
DW
1849 }
1850
bbd0e548 1851 // load and print the table of submissions
bf78ebd6
DW
1852 if ($showquickgrading && $quickgrading) {
1853 $table = $this->output->render(new assign_grading_table($this, $perpage, $filter, 0, true));
1854 $quickgradingform = new mod_assign_quick_grading_form(null,
1855 array('cm'=>$this->get_course_module()->id,
1856 'gradingtable'=>$table));
1857 $o .= $this->output->render(new assign_form('quickgradingform', $quickgradingform));
1858 } else {
1859 $o .= $this->output->render(new assign_grading_table($this, $perpage, $filter, 0, false));
1860 }
bbd0e548
DW
1861
1862 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1863 $users = array_keys($this->list_participants($currentgroup, true));
1864 if (count($users) != 0) {
1865 // if no enrolled user in a course then don't display the batch operations feature
1866 $o .= $this->output->render(new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform));
1867 }
a1e54f4d 1868 $o .= $this->output->render(new assign_form('gradingoptionsform', $gradingoptionsform, 'M.mod_assign.init_grading_options'));
bbd0e548
DW
1869 return $o;
1870 }
1871
1872 /**
1873 * View entire grading page.
1874 *
1875 * @return string
1876 */
1877 private function view_grading_page() {
1878 global $CFG;
1879
1880 $o = '';
1881 // Need submit permission to submit an assignment
1882 require_capability('mod/assign:grade', $this->context);
1883 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
1884
1885 // only load this if it is
1886
bbd0e548
DW
1887 $o .= $this->view_grading_table();
1888
1889 $o .= $this->view_footer();
1890 $this->add_to_log('view submission grading table', get_string('viewsubmissiongradingtable', 'assign'));
1891 return $o;
1892 }
1893
1894 /**
1895 * Capture the output of the plagiarism plugins disclosures and return it as a string
1896 *
1897 * @return void
1898 */
1899 private function plagiarism_print_disclosure() {
1900 global $CFG;
1901 $o = '';
1902
1903 if (!empty($CFG->enableplagiarism)) {
1904 /** Include plagiarismlib.php */
1905 require_once($CFG->libdir . '/plagiarismlib.php');
bbd0e548 1906
66681a51 1907 $o .= plagiarism_print_disclosure($this->get_course_module()->id);
bbd0e548
DW
1908 }
1909
1910 return $o;
1911 }
1912
1913 /**
1914 * message for students when assignment submissions have been closed
1915 *
1916 * @return string
1917 */
1918 private function view_student_error_message() {
1919 global $CFG;
1920
1921 $o = '';
1922 // Need submit permission to submit an assignment
1923 require_capability('mod/assign:submit', $this->context);
1924
1925 $o .= $this->output->render(new assign_header($this->get_instance(),
1926 $this->get_context(),
1927 $this->show_intro(),
1928 $this->get_course_module()->id,
1929 get_string('editsubmission', 'assign')));
1930
bf78ebd6 1931 $o .= $this->output->notification(get_string('submissionsclosed', 'assign'));
bbd0e548
DW
1932
1933 $o .= $this->view_footer();
1934
1935 return $o;
1936
1937 }
1938
1939 /**
1940 * View edit submissions page.
1941 *
1942 * @param moodleform $mform
85b5e20c 1943 * @param array $notices A list of notices to display at the top of the edit submission form (e.g. from plugins).
bbd0e548
DW
1944 * @return void
1945 */
85b5e20c 1946 private function view_edit_submission_page($mform, $notices) {
bbd0e548
DW
1947 global $CFG;
1948
1949 $o = '';
1950 // Include submission form
1951 require_once($CFG->dirroot . '/mod/assign/submission_form.php');
1952 // Need submit permission to submit an assignment
1953 require_capability('mod/assign:submit', $this->context);
1954
1955 if (!$this->submissions_open()) {
bf78ebd6 1956 return $this->view_student_error_message();
bbd0e548
DW
1957 }
1958 $o .= $this->output->render(new assign_header($this->get_instance(),
1959 $this->get_context(),
1960 $this->show_intro(),
1961 $this->get_course_module()->id,
1962 get_string('editsubmission', 'assign')));
1963 $o .= $this->plagiarism_print_disclosure();
1964 $data = new stdClass();
1965
1966 if (!$mform) {
1967 $mform = new mod_assign_submission_form(null, array($this, $data));
1968 }
1969
85b5e20c
DW
1970 foreach ($notices as $notice) {
1971 $o .= $this->output->notification($notice);
1972 }
1973
bbd0e548
DW
1974 $o .= $this->output->render(new assign_form('editsubmissionform',$mform));
1975
1976 $o .= $this->view_footer();
1977 $this->add_to_log('view submit assignment form', get_string('viewownsubmissionform', 'assign'));
1978
1979 return $o;
1980 }
1981
1982 /**
1983 * See if this assignment has a grade yet
1984 *
1985 * @param int $userid
1986 * @return bool
1987 */
1988 private function is_graded($userid) {
1989 $grade = $this->get_user_grade($userid, false);
1990 if ($grade) {
2d8a9ce9 1991 return ($grade->grade !== NULL && $grade->grade >= 0);
bbd0e548
DW
1992 }
1993 return false;
1994 }
1995
1996
1997 /**
1998 * Perform an access check to see if the current $USER can view this users submission
1999 *
2000 * @param int $userid
2001 * @return bool
2002 */
2003 public function can_view_submission($userid) {
2004 global $USER;
2005
2006 if (!is_enrolled($this->get_course_context(), $userid)) {
2007 return false;
2008 }
2009 if ($userid == $USER->id && !has_capability('mod/assign:submit', $this->context)) {
2010 return false;
2011 }
2012 if ($userid != $USER->id && !has_capability('mod/assign:grade', $this->context)) {
2013 return false;
2014 }
2015 return true;
2016 }
2017
2018 /**
2019 * Ask the user to confirm they want to perform this batch operation
2020 * @return string
2021 */
2022 private function process_batch_grading_operation() {
2023 global $CFG;
2024 require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
2025 require_sesskey();
2026
2027 $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
2028 array('cm'=>$this->get_course_module()->id,
2029 'submissiondrafts'=>$this->get_instance()->submissiondrafts),
2030 'post', '',
2031 array('class'=>'gradingbatchoperationsform'));
2032
2033 if ($data = $gradingbatchoperationsform->get_data()) {
2034 // get the list of users
2035 $users = $data->selectedusers;
2036 $userlist = explode(',', $users);
2037
2038 foreach ($userlist as $userid) {
2039 if ($data->operation == 'lock') {
2040 $this->process_lock($userid);
2041 } else if ($data->operation == 'unlock') {
2042 $this->process_unlock($userid);
2043 } else if ($data->operation == 'reverttodraft') {
2044 $this->process_revert_to_draft($userid);
2045 }
2046 }
2047 }
2048
2049 return true;
2050 }
2051
2052 /**
2053 * Ask the user to confirm they want to submit their work for grading
2054 * @return string
2055 */
2056 private function check_submit_for_grading() {
2057 global $USER;
2058 // Check that all of the submission plugins are ready for this submission
2059 $notifications = array();
2060 $submission = $this->get_user_submission($USER->id, false);
2061 $plugins = $this->get_submission_plugins();
2062 foreach ($plugins as $plugin) {
2063 if ($plugin->is_enabled() && $plugin->is_visible()) {
2064 $check = $plugin->precheck_submission($submission);
2065 if ($check !== true) {
2066 $notifications[] = $check;
2067 }
2068 }
2069 }
2070
2071 $o = '';
2072 $o .= $this->output->header();
2073 $o .= $this->output->render(new assign_submit_for_grading_page($notifications, $this->get_course_module()->id));
2074 $o .= $this->view_footer();
2075 return $o;
2076 }
2077
2078 /**
2079 * Print 2 tables of information with no action links -
2080 * the submission summary and the grading summary
2081 *
2082 * @param stdClass $user the user to print the report for
2083 * @param bool $showlinks - Return plain text or links to the profile
2084 * @return string - the html summary
2085 */
2086 public function view_student_summary($user, $showlinks) {
2087 global $CFG, $DB, $PAGE;
2088
2089 $grade = $this->get_user_grade($user->id, false);
2090 $submission = $this->get_user_submission($user->id, false);
2091 $o = '';
2092
2093 if ($this->can_view_submission($user->id)) {
2094 $showedit = has_capability('mod/assign:submit', $this->context) &&
2095 $this->submissions_open() && ($this->is_any_submission_plugin_enabled()) && $showlinks;
2096 $showsubmit = $submission && ($submission->status == ASSIGN_SUBMISSION_STATUS_DRAFT) && $showlinks;
2097 $gradelocked = ($grade && $grade->locked) || $this->grading_disabled($user->id);
2098
2099 $o .= $this->output->render(new assign_submission_status($this->get_instance()->allowsubmissionsfromdate,
2100 $this->get_instance()->alwaysshowdescription,
2101 $submission,
2102 $this->is_any_submission_plugin_enabled(),
2103 $gradelocked,
2104 $this->is_graded($user->id),
2105 $this->get_instance()->duedate,
2106 $this->get_submission_plugins(),
2107 $this->get_return_action(),
2108 $this->get_return_params(),
2109 $this->get_course_module()->id,
2110 assign_submission_status::STUDENT_VIEW,
2111 $showedit,
2112 $showsubmit));
2113 require_once($CFG->libdir.'/gradelib.php');
2114 require_once($CFG->dirroot.'/grade/grading/lib.php');
2115
2116 $gradinginfo = grade_get_grades($this->get_course()->id,
2117 'mod',
2118 'assign',
2119 $this->get_instance()->id,
2120 $user->id);
2121
2122 $gradingitem = $gradinginfo->items[0];
2123 $gradebookgrade = $gradingitem->grades[$user->id];
2124
2125 // check to see if all feedback plugins are empty
2126 $emptyplugins = true;
2127 if ($grade) {
2128 foreach ($this->get_feedback_plugins() as $plugin) {
2129 if ($plugin->is_visible() && $plugin->is_enabled()) {
2130 if (!$plugin->is_empty($grade)) {
2131 $emptyplugins = false;
2132 }
2133 }
2134 }
2135 }
2136
2137
2138 if (!($gradebookgrade->hidden) && ($gradebookgrade->grade !== null || !$emptyplugins)) {
2139
2140 $gradefordisplay = '';
2141 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2142
2143 if ($controller = $gradingmanager->get_active_controller()) {
2144 $controller->set_grade_range(make_grades_menu($this->get_instance()->grade));
2145 $gradefordisplay = $controller->render_grade($PAGE,
2146 $grade->id,
2147 $gradingitem,
2148 $gradebookgrade->str_long_grade,
2149 has_capability('mod/assign:grade', $this->get_context()));
2150 } else {
bf78ebd6 2151 $gradefordisplay = $this->display_grade($gradebookgrade->grade, false);
bbd0e548
DW
2152 }
2153
2154 $gradeddate = $gradebookgrade->dategraded;
2155 $grader = $DB->get_record('user', array('id'=>$gradebookgrade->usermodified));
2156
2157 $feedbackstatus = new assign_feedback_status($gradefordisplay,
2158 $gradeddate,
2159 $grader,
2160 $this->get_feedback_plugins(),
2161 $grade,
2162 $this->get_course_module()->id,
2163 $this->get_return_action(),
2164 $this->get_return_params());
2165
2166 $o .= $this->output->render($feedbackstatus);
2167 }
2168
2169 }
2170 return $o;
2171 }
2172
2173 /**
2174 * View submissions page (contains details of current submission).
2175 *
2176 * @return string
2177 */
2178 private function view_submission_page() {
2179 global $CFG, $DB, $USER, $PAGE;
2180
2181 $o = '';
2182 $o .= $this->output->render(new assign_header($this->get_instance(),
2183 $this->get_context(),
2184 $this->show_intro(),
2185 $this->get_course_module()->id));
2186
2187 if ($this->can_grade()) {
2188 $o .= $this->output->render(new assign_grading_summary($this->count_participants(0),
2189 $this->get_instance()->submissiondrafts,
2190 $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_DRAFT),
2191 $this->is_any_submission_plugin_enabled(),
2192 $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED),
2193 $this->get_instance()->duedate,
392ee02d
DW
2194 $this->get_course_module()->id,
2195 $this->count_submissions_need_grading()
bbd0e548
DW
2196 ));
2197 }
2198 $grade = $this->get_user_grade($USER->id, false);
2199 $submission = $this->get_user_submission($USER->id, false);
2200
2201 if ($this->can_view_submission($USER->id)) {
2202 $o .= $this->view_student_summary($USER, true);
2203 }
2204
2205
2206 $o .= $this->view_footer();
2207 $this->add_to_log('view', get_string('viewownsubmissionstatus', 'assign'));
2208 return $o;
2209 }
2210
2211 /**
2212 * convert the final raw grade(s) in the grading table for the gradebook
2213 *
2214 * @param stdClass $grade
2215 * @return array
2216 */
2217 private function convert_grade_for_gradebook(stdClass $grade) {
2218 $gradebookgrade = array();
2219 // trying to match those array keys in grade update function in gradelib.php
2220 // with keys in th database table assign_grades
2221 // starting around line 262
99467a9f
DW
2222 if ($grade->grade >= 0) {
2223 $gradebookgrade['rawgrade'] = $grade->grade;
2224 }
bbd0e548
DW
2225 $gradebookgrade['userid'] = $grade->userid;
2226 $gradebookgrade['usermodified'] = $grade->grader;
2227 $gradebookgrade['datesubmitted'] = NULL;
2228 $gradebookgrade['dategraded'] = $grade->timemodified;
2229 if (isset($grade->feedbackformat)) {
2230 $gradebookgrade['feedbackformat'] = $grade->feedbackformat;
2231 }
2232 if (isset($grade->feedbacktext)) {
2233 $gradebookgrade['feedback'] = $grade->feedbacktext;
2234 }
2235
2236 return $gradebookgrade;
2237 }
2238
2239 /**
2240 * convert submission details for the gradebook
2241 *
2242 * @param stdClass $submission
2243 * @return array
2244 */
2245 private function convert_submission_for_gradebook(stdClass $submission) {
2246 $gradebookgrade = array();
2247
2248
2249 $gradebookgrade['userid'] = $submission->userid;
2250 $gradebookgrade['usermodified'] = $submission->userid;
2251 $gradebookgrade['datesubmitted'] = $submission->timemodified;
2252
2253 return $gradebookgrade;
2254 }
2255
2256 /**
2257 * update grades in the gradebook
2258 *
2259 * @param mixed $submission stdClass|null
2260 * @param mixed $grade stdClass|null
2261 * @return bool
2262 */
2263 private function gradebook_item_update($submission=NULL, $grade=NULL) {
2264
2265 if($submission != NULL){
bbd0e548 2266 $gradebookgrade = $this->convert_submission_for_gradebook($submission);
bbd0e548 2267 }else{
bbd0e548
DW
2268 $gradebookgrade = $this->convert_grade_for_gradebook($grade);
2269 }
09b46f0e
AA
2270 // Grading is disabled, return.
2271 if ($this->grading_disabled($gradebookgrade['userid'])) {
2272 return false;
2273 }
bbd0e548
DW
2274 $assign = clone $this->get_instance();
2275 $assign->cmidnumber = $this->get_course_module()->id;
2276
2277 return assign_grade_item_update($assign, $gradebookgrade);
2278 }
2279
2280 /**
2281 * update grades in the gradebook based on submission time
2282 *
2283 * @param stdClass $submission
2284 * @param bool $updatetime
2285 * @return bool
2286 */
2287 private function update_submission(stdClass $submission, $updatetime=true) {
2288 global $DB;
2289
2290 if ($updatetime) {
2291 $submission->timemodified = time();
2292 }
2293 $result= $DB->update_record('assign_submission', $submission);
2294 if ($result) {
2295 $this->gradebook_item_update($submission);
2296 }
2297 return $result;
2298 }
2299
2300 /**
2301 * Is this assignment open for submissions?
2302 *
2303 * Check the due date,
2304 * prevent late submissions,
2305 * has this person already submitted,
2306 * is the assignment locked?
2307 *
2308 * @return bool
2309 */
2310 private function submissions_open() {
2311 global $USER;
2312
2313 $time = time();
2314 $dateopen = true;
2315 if ($this->get_instance()->preventlatesubmissions && $this->get_instance()->duedate) {
2316 $dateopen = ($this->get_instance()->allowsubmissionsfromdate <= $time && $time <= $this->get_instance()->duedate);
2317 } else {
2318 $dateopen = ($this->get_instance()->allowsubmissionsfromdate <= $time);
2319 }
2320
2321 if (!$dateopen) {
2322 return false;
2323 }
2324
2325 // now check if this user has already submitted etc.
2326 if (!is_enrolled($this->get_course_context(), $USER)) {
2327 return false;
2328 }
2329 if ($submission = $this->get_user_submission($USER->id, false)) {
2330 if ($this->get_instance()->submissiondrafts && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
2331 // drafts are tracked and the student has submitted the assignment
2332 return false;
2333 }
2334 }
2335 if ($grade = $this->get_user_grade($USER->id, false)) {
2336 if ($grade->locked) {
2337 return false;
2338 }
2339 }
2340
2341 if ($this->grading_disabled($USER->id)) {
2342 return false;
2343 }
2344
2345 return true;
2346 }
2347
2348 /**
2349 * render the files in file area
2350 * @param string $component
2351 * @param string $area
2352 * @param int $submissionid
2353 * @return string
2354 */
2355 public function render_area_files($component, $area, $submissionid) {
2356 global $USER;
2357
2358 if (!$submissionid) {
2359 $submission = $this->get_user_submission($USER->id,false);
2360 $submissionid = $submission->id;
2361 }
2362
bbd0e548
DW
2363 $fs = get_file_storage();
2364 $browser = get_file_browser();
2365 $files = $fs->get_area_files($this->get_context()->id, $component, $area , $submissionid , "timemodified", false);
2366 return $this->output->assign_files($this->context, $submissionid, $area, $component);
2367
2368 }
2369
2370 /**
2371 * Returns a list of teachers that should be grading given submission
2372 *
75f87a57 2373 * @param int $userid
bbd0e548
DW
2374 * @return array
2375 */
75f87a57 2376 private function get_graders($userid) {
bbd0e548 2377 //potential graders
75f87a57 2378 $potentialgraders = get_enrolled_users($this->context, "mod/assign:grade");
bbd0e548
DW
2379
2380 $graders = array();
2381 if (groups_get_activity_groupmode($this->get_course_module()) == SEPARATEGROUPS) { // Separate groups are being used
75f87a57 2382 if ($groups = groups_get_all_groups($this->get_course()->id, $userid)) { // Try to find all groups
bbd0e548
DW
2383 foreach ($groups as $group) {
2384 foreach ($potentialgraders as $grader) {
75f87a57 2385 if ($grader->id == $userid) {
bbd0e548
DW
2386 continue; // do not send self
2387 }
2388 if (groups_is_member($group->id, $grader->id)) {
2389 $graders[$grader->id] = $grader;
2390 }
2391 }
2392 }
2393 } else {
2394 // user not in group, try to find graders without group
2395 foreach ($potentialgraders as $grader) {
75f87a57 2396 if ($grader->id == $userid) {
bbd0e548
DW
2397 continue; // do not send self
2398 }
2399 if (!groups_has_membership($this->get_course_module(), $grader->id)) {
2400 $graders[$grader->id] = $grader;
2401 }
2402 }
2403 }
2404 } else {
2405 foreach ($potentialgraders as $grader) {
75f87a57 2406 if ($grader->id == $userid) {
bbd0e548
DW
2407 continue; // do not send self
2408 }
2409 // must be enrolled
2410 if (is_enrolled($this->get_course_context(), $grader->id)) {
2411 $graders[$grader->id] = $grader;
2412 }
2413 }
2414 }
2415 return $graders;
2416 }
2417
2418 /**
3f7b501e 2419 * Format a notification for plain text
bbd0e548 2420 *
75f87a57
DW
2421 * @param string $messagetype
2422 * @param stdClass $info
2423 * @param stdClass $course
2424 * @param stdClass $context
2425 * @param string $modulename
2426 * @param string $assignmentname
bbd0e548 2427 */
75f87a57
DW
2428 private static function format_notification_message_text($messagetype, $info, $course, $context, $modulename, $assignmentname) {
2429 $posttext = format_string($course->shortname, true, array('context' => $context->get_course_context())).' -> '.
2430 $modulename.' -> '.
2431 format_string($assignmentname, true, array('context' => $context))."\n";
bbd0e548 2432 $posttext .= '---------------------------------------------------------------------'."\n";
75f87a57 2433 $posttext .= get_string($messagetype . 'text', "assign", $info)."\n";
bbd0e548
DW
2434 $posttext .= "\n---------------------------------------------------------------------\n";
2435 return $posttext;
2436 }
2437
75f87a57 2438 /**
3f7b501e 2439 * Format a notification for HTML
bbd0e548 2440 *
75f87a57
DW
2441 * @param string $messagetype
2442 * @param stdClass $info
3f7b501e
SH
2443 * @param stdClass $course
2444 * @param stdClass $context
2445 * @param string $modulename
2446 * @param stdClass $coursemodule
2447 * @param string $assignmentname
2448 * @param stdClass $info
bbd0e548 2449 */
75f87a57 2450 private static function format_notification_message_html($messagetype, $info, $course, $context, $modulename, $coursemodule, $assignmentname) {
bbd0e548
DW
2451 global $CFG;
2452 $posthtml = '<p><font face="sans-serif">'.
75f87a57 2453 '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.format_string($course->shortname, true, array('context' => $context->get_course_context())).'</a> ->'.
599f7a27
RK
2454 '<a href="'.$CFG->wwwroot.'/mod/assign/index.php?id='.$course->id.'">'.$modulename.'</a> ->'.
2455 '<a href="'.$CFG->wwwroot.'/mod/assign/view.php?id='.$coursemodule->id.'">'.format_string($assignmentname, true, array('context' => $context)).'</a></font></p>';
bbd0e548 2456 $posthtml .= '<hr /><font face="sans-serif">';
75f87a57 2457 $posthtml .= '<p>'.get_string($messagetype . 'html', 'assign', $info).'</p>';
bbd0e548
DW
2458 $posthtml .= '</font><hr />';
2459 return $posthtml;
2460 }
2461
75f87a57 2462 /**
c1d09c6f 2463 * Message someone about something (static so it can be called from cron)
75f87a57 2464 *
75f87a57
DW
2465 * @param stdClass $userfrom
2466 * @param stdClass $userto
2467 * @param string $messagetype
2468 * @param string $eventtype
2469 * @param int $updatetime
2470 * @param stdClass $coursemodule
2471 * @param stdClass $context
2472 * @param stdClass $course
2473 * @param string $modulename
75f87a57
DW
2474 * @param string $assignmentname
2475 * @return void
2476 */
2477 public static function send_assignment_notification($userfrom, $userto, $messagetype, $eventtype,
2478 $updatetime, $coursemodule, $context, $course,
2479 $modulename, $assignmentname) {
3f7b501e 2480 global $CFG;
75f87a57
DW
2481
2482 $info = new stdClass();
2483 $info->username = fullname($userfrom, true);
2484 $info->assignment = format_string($assignmentname,true, array('context'=>$context));
2485 $info->url = $CFG->wwwroot.'/mod/assign/view.php?id='.$coursemodule->id;
2dd7131e 2486 $info->timeupdated = userdate($updatetime, get_string('strftimerecentfull'));
75f87a57
DW
2487
2488 $postsubject = get_string($messagetype . 'small', 'assign', $info);
2489 $posttext = self::format_notification_message_text($messagetype, $info, $course, $context, $modulename, $assignmentname);
2490 $posthtml = ($userto->mailformat == 1) ? self::format_notification_message_html($messagetype, $info, $course, $context, $modulename, $coursemodule, $assignmentname) : '';
2491
2492 $eventdata = new stdClass();
2493 $eventdata->modulename = 'assign';
2494 $eventdata->userfrom = $userfrom;
2495 $eventdata->userto = $userto;
2496 $eventdata->subject = $postsubject;
2497 $eventdata->fullmessage = $posttext;
2498 $eventdata->fullmessageformat = FORMAT_PLAIN;
2499 $eventdata->fullmessagehtml = $posthtml;
2500 $eventdata->smallmessage = $postsubject;
2501
2502 $eventdata->name = $eventtype;
2503 $eventdata->component = 'mod_assign';
2504 $eventdata->notification = 1;
2505 $eventdata->contexturl = $info->url;
2506 $eventdata->contexturlname = $info->assignment;
2507
2508 message_send($eventdata);
75f87a57
DW
2509 }
2510
2511 /**
c1d09c6f 2512 * Message someone about something
75f87a57 2513 *
3f7b501e
SH
2514 * @param stdClass $userfrom
2515 * @param stdClass $userto
2516 * @param string $messagetype
2517 * @param string $eventtype
2518 * @param int $updatetime
75f87a57
DW
2519 * @return void
2520 */
2521 public function send_notification($userfrom, $userto, $messagetype, $eventtype, $updatetime) {
2522 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);
2523 }
2524
2525 /**
c1d09c6f 2526 * Notify student upon successful submission
75f87a57 2527 *
75f87a57
DW
2528 * @global moodle_database $DB
2529 * @param stdClass $submission
2530 * @return void
2531 */
c1d09c6f 2532 private function notify_student_submission_receipt(stdClass $submission) {
75f87a57
DW
2533 global $DB;
2534
2535 $adminconfig = $this->get_admin_config();
3f7b501e
SH
2536 if (!$adminconfig->submissionreceipts) {
2537 // No need to do anything
75f87a57
DW
2538 return;
2539 }
75f87a57 2540 $user = $DB->get_record('user', array('id'=>$submission->userid), '*', MUST_EXIST);
f750cf71 2541 $this->send_notification($user, $user, 'submissionreceipt', 'assign_notification', $submission->timemodified);
75f87a57
DW
2542 }
2543
bbd0e548 2544 /**
c1d09c6f 2545 * Send notifications to graders upon student submissions
bbd0e548 2546 *
75f87a57 2547 * @global moodle_database $DB
bbd0e548
DW
2548 * @param stdClass $submission
2549 * @return void
2550 */
c1d09c6f 2551 private function notify_graders(stdClass $submission) {
75f87a57
DW
2552 global $DB;
2553
2554 $late = $this->get_instance()->duedate && ($this->get_instance()->duedate < time());
bbd0e548 2555
75f87a57 2556 if (!$this->get_instance()->sendnotifications && !($late && $this->get_instance()->sendlatenotifications)) { // No need to do anything
bbd0e548
DW
2557 return;
2558 }
2559
2560 $user = $DB->get_record('user', array('id'=>$submission->userid), '*', MUST_EXIST);
75f87a57 2561 if ($teachers = $this->get_graders($user->id)) {
bbd0e548 2562 foreach ($teachers as $teacher) {
f750cf71 2563 $this->send_notification($user, $teacher, 'gradersubmissionupdated', 'assign_notification', $submission->timemodified);
bbd0e548
DW
2564 }
2565 }
2566 }
2567
2568 /**
2569 * assignment submission is processed before grading
2570 *
2571 * @return void
2572 */
2573 private function process_submit_for_grading() {
2574 global $USER;
2575
2576 // Need submit permission to submit an assignment
2577 require_capability('mod/assign:submit', $this->context);
2578 require_sesskey();
2579
2580 $submission = $this->get_user_submission($USER->id,true);
2581 if ($submission->status != ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
2582 // Give each submission plugin a chance to process the submission
2583 $plugins = $this->get_submission_plugins();
2584 foreach ($plugins as $plugin) {
2585 $plugin->submit_for_grading();
2586 }
2587
2588 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
2589 $this->update_submission($submission);
2590 $this->add_to_log('submit for grading', $this->format_submission_for_log($submission));
c1d09c6f
RK
2591 $this->notify_graders($submission);
2592 $this->notify_student_submission_receipt($submission);
bbd0e548
DW
2593 }
2594 }
2595
bf78ebd6
DW
2596 /**
2597 * save quick grades
2598 *
2a4fbc32
SH
2599 * @global moodle_database $DB
2600 * @return string The result of the save operation
bf78ebd6
DW
2601 */
2602 private function process_save_quick_grades() {
2603 global $USER, $DB, $CFG;
2604
2605 // Need grade permission
2606 require_capability('mod/assign:grade', $this->context);
2607
2608 // make sure advanced grading is disabled
2609 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2610 $controller = $gradingmanager->get_active_controller();
2611 if (!empty($controller)) {
2a4fbc32 2612 return get_string('errorquickgradingvsadvancedgrading', 'assign');
bf78ebd6
DW
2613 }
2614
2615 $users = array();
2616 // first check all the last modified values
2c6a3dbf
DW
2617 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
2618 $participants = $this->list_participants($currentgroup, true);
2619
2a4fbc32 2620 // gets a list of possible users and look for values based upon that.
2c6a3dbf
DW
2621 foreach ($participants as $userid => $unused) {
2622 $modified = optional_param('grademodified_' . $userid, -1, PARAM_INT);
2623 if ($modified >= 0) {
bf78ebd6
DW
2624 // gather the userid, updated grade and last modified value
2625 $record = new stdClass();
2c6a3dbf 2626 $record->userid = $userid;
4913af93 2627 $record->grade = unformat_float(required_param('quickgrade_' . $record->userid, PARAM_TEXT));
2c6a3dbf
DW
2628 $record->lastmodified = $modified;
2629 $record->gradinginfo = grade_get_grades($this->get_course()->id, 'mod', 'assign', $this->get_instance()->id, array($userid));
2630 $users[$userid] = $record;
bf78ebd6
DW
2631 }
2632 }
2a4fbc32
SH
2633 if (empty($users)) {
2634 // Quick check to see whether we have any users to update and we don't
2635 return get_string('quickgradingchangessaved', 'assign'); // Technical lie
2636 }
bf78ebd6 2637
2a4fbc32
SH
2638 list($userids, $params) = $DB->get_in_or_equal(array_keys($users), SQL_PARAMS_NAMED);
2639 $params['assignment'] = $this->get_instance()->id;
bf78ebd6 2640 // check them all for currency
2a4fbc32
SH
2641 $sql = 'SELECT u.id as userid, g.grade as grade, g.timemodified as lastmodified
2642 FROM {user} u
2643 LEFT JOIN {assign_grades} g ON u.id = g.userid AND g.assignment = :assignment
2644 WHERE u.id ' . $userids;
2645 $currentgrades = $DB->get_recordset_sql($sql, $params);
bf78ebd6
DW
2646
2647 $modifiedusers = array();
2648 foreach ($currentgrades as $current) {
2649 $modified = $users[(int)$current->userid];
fbd336f8 2650 $grade = $this->get_user_grade($modified->userid, false);
bf78ebd6
DW
2651
2652 // check to see if the outcomes were modified
2653 if ($CFG->enableoutcomes) {
2654 foreach ($modified->gradinginfo->outcomes as $outcomeid => $outcome) {
2655 $oldoutcome = $outcome->grades[$modified->userid]->grade;
4913af93 2656 $newoutcome = optional_param('outcome_' . $outcomeid . '_' . $modified->userid, -1, PARAM_FLOAT);
bf78ebd6
DW
2657 if ($oldoutcome != $newoutcome) {
2658 // can't check modified time for outcomes because it is not reported
2659 $modifiedusers[$modified->userid] = $modified;
2660 continue;
2661 }
2662 }
2663 }
2664
2c6a3dbf
DW
2665 // let plugins participate
2666 foreach ($this->feedbackplugins as $plugin) {
2667 if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->supports_quickgrading()) {
2668 if ($plugin->is_quickgrading_modified($modified->userid, $grade)) {
2669 if ((int)$current->lastmodified > (int)$modified->lastmodified) {
2670 return get_string('errorrecordmodified', 'assign');
2671 } else {
2672 $modifiedusers[$modified->userid] = $modified;
2673 continue;
2674 }
2675 }
2676 }
2677 }
2678
bf78ebd6
DW
2679
2680 if (($current->grade < 0 || $current->grade === NULL) &&
2681 ($modified->grade < 0 || $modified->grade === NULL)) {
2682 // different ways to indicate no grade
2683 continue;
2684 }
a13edd49
DW
2685 // Treat 0 and null as different values
2686 if ($current->grade !== null) {
2687 $current->grade = floatval($current->grade);
2688 }
2689 if ($current->grade !== $modified->grade) {
bf78ebd6 2690 // grade changed
09b46f0e
AA
2691 if ($this->grading_disabled($modified->userid)) {
2692 continue;
2693 }
bf78ebd6
DW
2694 if ((int)$current->lastmodified > (int)$modified->lastmodified) {
2695 // error - record has been modified since viewing the page
2696 return get_string('errorrecordmodified', 'assign');
2697 } else {
2698 $modifiedusers[$modified->userid] = $modified;
2699 }
2700 }
2701
2702 }
2a4fbc32 2703 $currentgrades->close();
bf78ebd6 2704
97b53d6c
DW
2705 $adminconfig = $this->get_admin_config();
2706 $gradebookplugin = $adminconfig->feedback_plugin_for_gradebook;
2707
bf78ebd6
DW
2708 // ok - ready to process the updates
2709 foreach ($modifiedusers as $userid => $modified) {
2710 $grade = $this->get_user_grade($userid, true);
4913af93 2711 $grade->grade= grade_floatval(unformat_float($modified->grade));
bf78ebd6
DW
2712 $grade->grader= $USER->id;
2713
2c6a3dbf
DW
2714 // save plugins data
2715 foreach ($this->feedbackplugins as $plugin) {
2716 if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->supports_quickgrading()) {
2717 $plugin->save_quickgrading_changes($userid, $grade);
97b53d6c
DW
2718 if (('assignfeedback_' . $plugin->get_type()) == $gradebookplugin) {
2719 // This is the feedback plugin chose to push comments to the gradebook.
2720 $grade->feedbacktext = $plugin->text_for_gradebook($grade);
2721 $grade->feedbackformat = $plugin->format_for_gradebook($grade);
2722 }
2c6a3dbf
DW
2723 }
2724 }
2725
97b53d6c
DW
2726 $this->update_grade($grade);
2727
bf78ebd6
DW
2728 // save outcomes
2729 if ($CFG->enableoutcomes) {
2730 $data = array();
2731 foreach ($modified->gradinginfo->outcomes as $outcomeid => $outcome) {
2732 $oldoutcome = $outcome->grades[$modified->userid]->grade;
2733 $newoutcome = optional_param('outcome_' . $outcomeid . '_' . $modified->userid, -1, PARAM_INT);
2734 if ($oldoutcome != $newoutcome) {
2735 $data[$outcomeid] = $newoutcome;
2736 }
2737 }
2738 if (count($data) > 0) {
2739 grade_update_outcomes('mod/assign', $this->course->id, 'mod', 'assign', $this->get_instance()->id, $userid, $data);
2740 }
2741 }
2742
bf78ebd6
DW
2743 $this->add_to_log('grade submission', $this->format_grade_for_log($grade));
2744 }
2745
2746 return get_string('quickgradingchangessaved', 'assign');
2747 }
2748
bbd0e548
DW
2749 /**
2750 * save grading options
2751 *
2752 * @return void
2753 */
2754 private function process_save_grading_options() {
2755 global $USER, $CFG;
2756
2757 // Include grading options form
2758 require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
2759
2760 // Need submit permission to submit an assignment
2761 require_capability('mod/assign:grade', $this->context);
2762
145a300b
DW
2763 $mform = new mod_assign_grading_options_form(null, array('cm'=>$this->get_course_module()->id,
2764 'contextid'=>$this->context->id,
2765 'userid'=>$USER->id,
2766 'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
2767 'showquickgrading'=>false));
bbd0e548
DW
2768 if ($formdata = $mform->get_data()) {
2769 set_user_preference('assign_perpage', $formdata->perpage);
3bcff380
RL
2770 if (isset($formdata->filter)) {
2771 set_user_preference('assign_filter', $formdata->filter);
2772 }
bbd0e548
DW
2773 }
2774 }
2775
2776 /**
2777 * Take a grade object and print a short summary for the log file.
2778 * The size limit for the log file is 255 characters, so be careful not
2779 * to include too much information.
2780 *
2781 * @param stdClass $grade
2782 * @return string
2783 */
2784 private function format_grade_for_log(stdClass $grade) {
2785 global $DB;
2786
2787 $user = $DB->get_record('user', array('id' => $grade->userid), '*', MUST_EXIST);
2788
2789 $info = get_string('gradestudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user)));
2790 if ($grade->grade != '') {
bf78ebd6 2791 $info .= get_string('grade') . ': ' . $this->display_grade($grade->grade, false) . '. ';
bbd0e548
DW
2792 } else {
2793 $info .= get_string('nograde', 'assign');
2794 }
2795 if ($grade->locked) {
2796 $info .= get_string('submissionslocked', 'assign') . '. ';
2797 }
2798 return $info;
2799 }
2800
2801 /**
2802 * Take a submission object and print a short summary for the log file.
2803 * The size limit for the log file is 255 characters, so be careful not
2804 * to include too much information.
2805 *
2806 * @param stdClass $submission
2807 * @return string
2808 */
2809 private function format_submission_for_log(stdClass $submission) {
2810 $info = '';
2811 $info .= get_string('submissionstatus', 'assign') . ': ' . get_string('submissionstatus_' . $submission->status, 'assign') . '. <br>';
2812 // format_for_log here iterating every single log INFO from either submission or grade in every assignment plugin
2813
2814 foreach ($this->submissionplugins as $plugin) {
2815 if ($plugin->is_enabled() && $plugin->is_visible()) {
2816
2817
2818 $info .= "<br>" . $plugin->format_for_log($submission);
2819 }
2820 }
2821
2822
2823 return $info;
2824 }
2825
2826 /**
2827 * save assignment submission
2828 *
2829 * @param moodleform $mform
85b5e20c 2830 * @param array $notices Any error messages that should be shown to the user at the top of the edit submission form.
bbd0e548
DW
2831 * @return bool
2832 */
85b5e20c 2833 private function process_save_submission(&$mform, &$notices) {
bbd0e548
DW
2834 global $USER, $CFG;
2835
85b5e20c 2836 // Include submission form.
bbd0e548
DW
2837 require_once($CFG->dirroot . '/mod/assign/submission_form.php');
2838
85b5e20c 2839 // Need submit permission to submit an assignment.
bbd0e548
DW
2840 require_capability('mod/assign:submit', $this->context);
2841 require_sesskey();
2842
2843 $data = new stdClass();
2844 $mform = new mod_assign_submission_form(null, array($this, $data));
2845 if ($mform->is_cancelled()) {
2846 return true;
2847 }
2848 if ($data = $mform->get_data()) {
2849 $submission = $this->get_user_submission($USER->id, true); //create the submission if needed & its id
2850 $grade = $this->get_user_grade($USER->id, false); // get the grade to check if it is locked
2851 if ($grade && $grade->locked) {
2852 print_error('submissionslocked', 'assign');
2853 return true;
2854 }
2855
2856
85b5e20c
DW
2857 $allempty = true;
2858 $pluginerror = false;
bbd0e548
DW
2859 foreach ($this->submissionplugins as $plugin) {
2860 if ($plugin->is_enabled()) {
2861 if (!$plugin->save($submission, $data)) {
85b5e20c
DW
2862 $notices[] = $plugin->get_error();
2863 $pluginerror = true;
bbd0e548 2864 }
85b5e20c
DW
2865 if (!$allempty || !$plugin->is_empty($submission)) {
2866 $allempty = false;
2867 }
2868 }
2869 }
2870 if ($pluginerror || $allempty) {
2871 if ($allempty) {
2872 $notices[] = get_string('submissionempty', 'mod_assign');
bbd0e548 2873 }
85b5e20c 2874 return false;
bbd0e548
DW
2875 }
2876
2877 $this->update_submission($submission);
2878
2879 // Logging
2880 $this->add_to_log('submit', $this->format_submission_for_log($submission));
2881
2882 if (!$this->get_instance()->submissiondrafts) {
c1d09c6f
RK
2883 $this->notify_student_submission_receipt($submission);
2884 $this->notify_graders($submission);
bbd0e548
DW
2885 }
2886 return true;
2887 }
2888 return false;
2889 }
2890
bbd0e548
DW
2891
2892 /**
2893 * Determine if this users grade is locked or overridden
2894 *
2895 * @param int $userid - The student userid
2896 * @return bool $gradingdisabled
2897 */
09b46f0e 2898 public function grading_disabled($userid) {
bbd0e548
DW
2899 global $CFG;
2900
2901 $gradinginfo = grade_get_grades($this->get_course()->id, 'mod', 'assign', $this->get_instance()->id, array($userid));
2902 if (!$gradinginfo) {
2903 return false;
2904 }
2905
2906 if (!isset($gradinginfo->items[0]->grades[$userid])) {
2907 return false;
2908 }
2909 $gradingdisabled = $gradinginfo->items[0]->grades[$userid]->locked || $gradinginfo->items[0]->grades[$userid]->overridden;
2910 return $gradingdisabled;
2911 }
2912
2913
2914 /**
2915 * Get an instance of a grading form if advanced grading is enabled
2916 * This is specific to the assignment, marker and student
2917 *
2918 * @param int $userid - The student userid
2919 * @param bool $gradingdisabled
2920 * @return mixed gradingform_instance|null $gradinginstance
2921 */
2922 private function get_grading_instance($userid, $gradingdisabled) {
2923 global $CFG, $USER;
2924
2925 $grade = $this->get_user_grade($userid, false);
2926 $grademenu = make_grades_menu($this->get_instance()->grade);
2927
2928 $advancedgradingwarning = false;
2929 $gradingmanager = get_grading_manager($this->context, 'mod_assign', 'submissions');
2930 $gradinginstance = null;
2931 if ($gradingmethod = $gradingmanager->get_active_method()) {
2932 $controller = $gradingmanager->get_controller($gradingmethod);
2933 if ($controller->is_form_available()) {
2934 $itemid = null;
2935 if ($grade) {
2936 $itemid = $grade->id;
2937 }
2938 if ($gradingdisabled && $itemid) {
2939 $gradinginstance = ($controller->get_current_instance($USER->id, $itemid));
2940 } else if (!$gradingdisabled) {
2941 $instanceid = optional_param('advancedgradinginstanceid', 0, PARAM_INT);
2942 $gradinginstance = ($controller->get_or_create_instance($instanceid, $USER->id, $itemid));
2943 }
2944 } else {
2945 $advancedgradingwarning = $controller->form_unavailable_notification();
2946 }
2947 }
2948 if ($gradinginstance) {
2949 $gradinginstance->get_controller()->set_grade_range($grademenu);
2950 }
2951 return $gradinginstance;
2952 }
2953
2954 /**
2955 * add elements to grade form
2956 *
2957 * @param MoodleQuickForm $mform
2958 * @param stdClass $data
2959 * @param array $params
2960 * @return void
2961 */
2962 public function add_grade_form_elements(MoodleQuickForm $mform, stdClass $data, $params) {
2963 global $USER, $CFG;
2964 $settings = $this->get_instance();
2965
2966 $rownum = $params['rownum'];
2967 $last = $params['last'];
2968 $useridlist = $params['useridlist'];
2969 $userid = $useridlist[$rownum];
2970 $grade = $this->get_user_grade($userid, false);
2971
2972 // add advanced grading
2973 $gradingdisabled = $this->grading_disabled($userid);
2974 $gradinginstance = $this->get_grading_instance($userid, $gradingdisabled);
2975
2976 if ($gradinginstance) {
2977 $gradingelement = $mform->addElement('grading', 'advancedgrading', get_string('grade').':', array('gradinginstance' => $gradinginstance));
2978 if ($gradingdisabled) {
2979 $gradingelement->freeze();
2980 } else {
2981 $mform->addElement('hidden', 'advancedgradinginstanceid', $gradinginstance->get_id());
2982 }
2983 } else {
2984 // use simple direct grading
2985 if ($this->get_instance()->grade > 0) {
09b46f0e 2986 $gradingelement = $mform->addElement('text', 'grade', get_string('gradeoutof', 'assign',$this->get_instance()->grade));
bbd0e548
DW
2987 $mform->addHelpButton('grade', 'gradeoutofhelp', 'assign');
2988 $mform->setType('grade', PARAM_TEXT);
09b46f0e
AA
2989 if ($gradingdisabled) {
2990 $gradingelement->freeze();
2991 }
bbd0e548
DW
2992 } else {
2993 $grademenu = make_grades_menu($this->get_instance()->grade);
2994 if (count($grademenu) > 0) {
09b46f0e 2995 $gradingelement = $mform->addElement('select', 'grade', get_string('grade').':', $grademenu);
bbd0e548 2996 $mform->setType('grade', PARAM_INT);
09b46f0e
AA
2997 if ($gradingdisabled) {
2998 $gradingelement->freeze();
2999 }
bbd0e548
DW
3000 }
3001 }
3002 }
bbd0e548 3003
c45261df
DW
3004 $gradinginfo = grade_get_grades($this->get_course()->id,
3005 'mod',
3006 'assign',
3007 $this->get_instance()->id,
3008 $userid);
3009 if (!empty($CFG->enableoutcomes)) {
3010 foreach($gradinginfo->outcomes as $index=>$outcome) {
3011 $options = make_grades_menu(-$outcome->scaleid);
3012 if ($outcome->grades[$userid]->locked) {
3013 $options[0] = get_string('nooutcome', 'grades');
3014 $mform->addElement('static', 'outcome_'.$index.'['.$userid.']', $outcome->name.':',
3015 $options[$outcome->grades[$userid]->grade]);
3016 } else {
3017 $options[''] = get_string('nooutcome', 'grades');
3018 $attributes = array('id' => 'menuoutcome_'.$index );
3019 $mform->addElement('select', 'outcome_'.$index.'['.$userid.']', $outcome->name.':', $options, $attributes );
3020 $mform->setType('outcome_'.$index.'['.$userid.']', PARAM_INT);
3021 $mform->setDefault('outcome_'.$index.'['.$userid.']', $outcome->grades[$userid]->grade );
3022 }
3023 }
3024 }
3025
8ad459ed 3026 if (has_all_capabilities(array('gradereport/grader:view', 'moodle/grade:viewall'), $this->get_course_context())) {
4c600684 3027 $gradestring = $this->output->action_link(new moodle_url('/grade/report/grader/index.php',
8ad459ed
DW
3028 array('id'=>$this->get_course()->id)),
3029 $gradinginfo->items[0]->grades[$userid]->str_grade);
3030 } else {
4c600684 3031 $gradestring = $gradinginfo->items[0]->grades[$userid]->str_grade;
8ad459ed 3032 }
4c600684 3033 $mform->addElement('static', 'finalgrade', get_string('currentgrade', 'assign').':', $gradestring);
8ad459ed
DW
3034
3035
c45261df 3036 $mform->addElement('static', 'progress', '', get_string('gradingstudentprogress', 'assign', array('index'=>$rownum+1, 'count'=>count($useridlist))));
bbd0e548 3037
5f845b3e
DW
3038 // Let feedback plugins add elements to the grading form.
3039 $this->add_plugin_grade_elements($grade, $mform, $data, $userid);
bbd0e548
DW
3040
3041 // hidden params
3042 $mform->addElement('hidden', 'id', $this->get_course_module()->id);
3043 $mform->setType('id', PARAM_INT);
3044 $mform->addElement('hidden', 'rownum', $rownum);
3045 $mform->setType('rownum', PARAM_INT);
2b702484 3046 $mform->setConstant('rownum', $rownum);
bbd0e548
DW
3047 $mform->addElement('hidden', 'useridlist', implode(',', $useridlist));
3048 $mform->setType('useridlist', PARAM_TEXT);
3049 $mform->addElement('hidden', 'ajax', optional_param('ajax', 0, PARAM_INT));
3050 $mform->setType('ajax', PARAM_INT);
3051
3052 $mform->addElement('hidden', 'action', 'submitgrade');
3053 $mform->setType('action', PARAM_ALPHA);
3054
3055
3056 $buttonarray=array();
3057 $buttonarray[] = $mform->createElement('submit', 'savegrade', get_string('savechanges', 'assign'));
3058 if (!$last){
3059 $buttonarray[] = $mform->createElement('submit', 'saveandshownext', get_string('savenext','assign'));
3060 }
3061 $buttonarray[] = $mform->createElement('cancel', 'cancelbutton', get_string('cancel'));
3062 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
3063 $mform->closeHeaderBefore('buttonar');
3064 $buttonarray=array();
3065
3066 if ($rownum > 0) {
3067 $buttonarray[] = $mform->createElement('submit', 'nosaveandprevious', get_string('previous','assign'));
3068 }
3069
3070 if (!$last){
3071 $buttonarray[] = $mform->createElement('submit', 'nosaveandnext', get_string('nosavebutnext', 'assign'));
3072 }
62d70e07
DW
3073 if (!empty($buttonarray)) {
3074 $mform->addGroup($buttonarray, 'navar', '', array(' '), false);
3075 }
bbd0e548
DW
3076 }
3077
3078
3079 /**
3080 * add elements in submission plugin form
3081 *
3082 * @param mixed $submission stdClass|null
3083 * @param MoodleQuickForm $mform
3084 * @param stdClass $data
5f845b3e 3085 * @param int $userid The current userid (same as $USER->id)
bbd0e548
DW
3086 * @return void
3087 */
5f845b3e 3088 private function add_plugin_submission_elements($submission, MoodleQuickForm $mform, stdClass $data, $userid) {
bbd0e548
DW
3089 foreach ($this->submissionplugins as $plugin) {
3090 if ($plugin->is_enabled() && $plugin->is_visible() && $plugin->allow_submissions()) {
3091 $mform->addElement('header', 'header_' . $plugin->get_type(), $plugin->get_name());
5f845b3e 3092 if (!$plugin->get_form_elements_for_user($submission, $mform, $data, $userid)) {
bbd0e548
DW
3093 $mform->removeElement('header_' . $plugin->get_type());
3094 }
3095 }
3096 }
3097 }
3098
3099 /**
3100 * check if feedback plugins installed are enabled
3101 *
3102 * @return bool
3103 */
3104 public function is_any_feedback_plugin_enabled() {
3105 if (!isset($this->cache['any_feedback_plugin_enabled'])) {
3106 $this->cache['any_feedback_plugin_enabled'] = false;
3107 foreach ($this->feedbackplugins as $plugin) {
3108 if ($plugin->is_enabled() && $plugin->is_visible()) {
3109 $this->cache['any_feedback_plugin_enabled'] = true;
3110 break;
3111 }
3112 }
3113 }
3114
3115 return $this->cache['any_feedback_plugin_enabled'];
3116
3117 }
3118
3119 /**
3120 * check if submission plugins installed are enabled
3121 *
3122 * @return bool
3123 */
3124 public function is_any_submission_plugin_enabled() {
3125 if (!isset($this->cache['any_submission_plugin_enabled'])) {
3126 $this->cache['any_submission_plugin_enabled'] = false;
3127 foreach ($this->submissionplugins as $plugin) {
3128 if ($plugin->is_enabled() && $plugin->is_visible() && $plugin->allow_submissions()) {
3129 $this->cache['any_submission_plugin_enabled'] = true;
3130 break;
3131 }
3132 }
3133 }
3134
3135 return $this->cache['any_submission_plugin_enabled'];
3136
3137 }
3138
3139 /**
3140 * add elements to submission form
3141 * @param MoodleQuickForm $mform
3142 * @param stdClass $data
3143 * @return void
3144 */
3145 public function add_submission_form_elements(MoodleQuickForm $mform, stdClass $data) {
3146 global $USER;
3147
3148 // online text submissions
3149
3150 $submission = $this->get_user_submission($USER->id, false);
3151
5f845b3e 3152 $this->add_plugin_submission_elements($submission, $mform, $data, $USER->id);
bbd0e548
DW
3153
3154 // hidden params
3155 $mform->addElement('hidden', 'id', $this->get_course_module()->id);
3156 $mform->setType('id', PARAM_INT);
3157
3158 $mform->addElement('hidden', 'action', 'savesubmission');
3159 $mform->setType('action', PARAM_TEXT);
3160 // buttons
3161
3162 }
3163
3164 /**
3165 * revert to draft
3166 * Uses url parameter userid
9682626e 3167 *
bbd0e548
DW
3168 * @param int $userid
3169 * @return void
3170 */
3171 private function process_revert_to_draft($userid = 0) {
3172 global $USER, $DB;
3173
3174 // Need grade permission
3175 require_capability('mod/assign:grade', $this->context);
3176 require_sesskey();
3177
3178 if (!$userid) {
3179 $userid = required_param('userid', PARAM_INT);
3180 }
3181
3182 $submission = $this->get_user_submission($userid, false);
3183 if (!$submission) {
3184 return;
3185 }
3186 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
3187 $this->update_submission($submission, false);
3188
3189 // update the modified time on the grade (grader modified)
3190 $grade = $this->get_user_grade($userid, true);
3191 $this->update_grade($grade);
3192
3193 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
3194
3195 $this->add_to_log('revert submission to draft', get_string('reverttodraftforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user))));
3196
3197 }
3198
3199 /**
3200 * lock the process
3201 * Uses url parameter userid
3202 * @param int $userid
3203 * @return void
3204 */
3205 private function process_lock($userid = 0) {
3206 global $USER, $DB;
3207
3208 // Need grade permission
3209 require_capability('mod/assign:grade', $this->context);
3210 require_sesskey();
3211
3212 if (!$userid) {
3213 $userid = required_param('userid', PARAM_INT);
3214 }
3215
3216 $grade = $this->get_user_grade($userid, true);
3217 $grade->locked = 1;
3218 $grade->grader = $USER->id;
3219 $this->update_grade($grade);
3220
3221 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
3222
3223 $this->add_to_log('lock submission', get_string('locksubmissionforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user))));
3224 }
3225
3226 /**
3227 * unlock the process
3228 *
3229 * @param int $userid
3230 * @return void
3231 */
3232 private function process_unlock($userid = 0) {
3233 global $USER, $DB;
3234
3235 // Need grade permission
3236 require_capability('mod/assign:grade', $this->context);
3237 require_sesskey();
3238
3239 if (!$userid) {
3240 $userid = required_param('userid', PARAM_INT);
3241 }
3242
3243 $grade = $this->get_user_grade($userid, true);
3244 $grade->locked = 0;
3245 $grade->grader = $USER->id;
3246 $this->update_grade($grade);
3247
3248 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
3249
3250 $this->add_to_log('unlock submission', get_string('unlocksubmissionforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user))));
3251 }
3252
c45261df
DW
3253 /**
3254 * save outcomes submitted from grading form
3255 *
3256 * @param int $userid
3257 * @param stdClass $formdata
3258 */
3259 private function process_outcomes($userid, $formdata) {
3260 global $CFG, $USER;
3261
3262 if (empty($CFG->enableoutcomes)) {
3263 return;
3264 }
09b46f0e
AA
3265 if ($this->grading_disabled($userid)) {
3266 return;
3267 }
c45261df
DW
3268
3269 require_once($CFG->libdir.'/gradelib.php');
3270
3271 $data = array();
3272 $gradinginfo = grade_get_grades($this->get_course()->id,
3273 'mod',
3274 'assign',
3275 $this->get_instance()->id,
3276 $userid);
3277
3278 if (!empty($gradinginfo->outcomes)) {
3279 foreach($gradinginfo->outcomes as $index=>$oldoutcome) {
3280 $name = 'outcome_'.$index;
3281 if (isset($formdata->{$name}[$userid]) and $oldoutcome->grades[$userid]->grade != $formdata->{$name}[$userid]) {
3282 $data[$index] = $formdata->{$name}[$userid];
3283 }
3284 }
3285 }
3286 if (count($data) > 0) {
3287 grade_update_outcomes('mod/assign', $this->course->id, 'mod', 'assign', $this->get_instance()->id, $userid, $data);
3288 }
3289
3290 }
3291
3292
bbd0e548
DW
3293 /**
3294 * save grade
3295 *
3296 * @param moodleform $mform
3297 * @return bool - was the grade saved
3298 */
3299 private function process_save_grade(&$mform) {
3300 global $USER, $DB, $CFG;
3301 // Include grade form
3302 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
3303
3304 // Need submit permission to submit an assignment
3305 require_capability('mod/assign:grade', $this->context);
3306 require_sesskey();
3307
3308 $rownum = required_param('rownum', PARAM_INT);
3309 $useridlist = optional_param('useridlist', '', PARAM_TEXT);
3310 if ($useridlist) {
3311 $useridlist = explode(',', $useridlist);
3312 } else {
3313 $useridlist = $this->get_grading_userid_list();
3314 }
3315 $last = false;
3316 $userid = $useridlist[$rownum];
3317 if ($rownum == count($useridlist) - 1) {
3318 $last = true;
3319 }
3320
3321 $data = new stdClass();
3322 $mform = new mod_assign_grade_form(null, array($this, $data, array('rownum'=>$rownum, 'useridlist'=>$useridlist, 'last'=>false)), 'post', '', array('class'=>'gradeform'));
3323
3324 if ($formdata = $mform->get_data()) {
3325 $grade = $this->get_user_grade($userid, true);
3326 $gradingdisabled = $this->grading_disabled($userid);
3327 $gradinginstance = $this->get_grading_instance($userid, $gradingdisabled);
09b46f0e
AA
3328 if (!$gradingdisabled) {
3329 if ($gradinginstance) {
3330 $grade->grade = $gradinginstance->submit_and_get_grade($formdata->advancedgrading, $grade->id);
3331 } else {
3332 // handle the case when grade is set to No Grade
3333 if (isset($formdata->grade)) {
3334 $grade->grade = grade_floatval(unformat_float($formdata->grade));
3335 }
bbd0e548
DW
3336 }
3337 }
3338 $grade->grader= $USER->id;
3339
cfc81f03
DW
3340 $adminconfig = $this->get_admin_config();
3341 $gradebookplugin = $adminconfig->feedback_plugin_for_gradebook;
bbd0e548
DW
3342
3343 // call save in plugins
3344 foreach ($this->feedbackplugins as $plugin) {
3345 if ($plugin->is_enabled() && $plugin->is_visible()) {
3346 if (!$plugin->save($grade, $formdata)) {
3347 $result = false;
3348 print_error($plugin->get_error());
3349 }
3350 if (('assignfeedback_' . $plugin->get_type()) == $gradebookplugin) {
3351 // this is the feedback plugin chose to push comments to the gradebook
3352 $grade->feedbacktext = $plugin->text_for_gradebook($grade);
3353 $grade->feedbackformat = $plugin->format_for_gradebook($grade);
3354 }
3355 }
3356 }
c45261df 3357 $this->process_outcomes($userid, $formdata);
75f87a57
DW
3358
3359 $grade->mailed = 0;
3360
bbd0e548
DW
3361 $this->update_grade($grade);
3362
3363 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
3364
3365 $this->add_to_log('grade submission', $this->format_grade_for_log($grade));
3366
3367
3368 } else {
3369 return false;
3370 }
3371 return true;
3372 }
3373
3374 /**
3375 * This function is a static wrapper around can_upgrade
3376 *
3377 * @param string $type The plugin type
3378 * @param int $version The plugin version
3379 * @return bool
3380 */
3381 public static function can_upgrade_assignment($type, $version) {
3382 $assignment = new assign(null, null, null);
3383 return $assignment->can_upgrade($type, $version);
3384 }
3385
3386 /**
3387 * This function returns true if it can upgrade an assignment from the 2.2
3388 * module.
3389 * @param string $type The plugin type
3390 * @param int $version The plugin version
3391 * @return bool
3392 */
3393 public function can_upgrade($type, $version) {
3394 if ($type == 'offline' && $version >= 2011112900) {
3395 return true;
3396 }
3397 foreach ($this->submissionplugins as $plugin) {
3398 if ($plugin->can_upgrade($type, $version)) {
3399 return true;
3400 }
3401 }
3402 foreach ($this->feedbackplugins as $plugin) {
3403 if ($plugin->can_upgrade($type, $version)) {
3404 return true;
3405 }
3406 }
3407 return false;
3408 }
3409
3410 /**
3411 * Copy all the files from the old assignment files area to the new one.
3412 * This is used by the plugin upgrade code.
3413 *
3414 * @param int $oldcontextid The old assignment context id
3415 * @param int $oldcomponent The old assignment component ('assignment')
3416 * @param int $oldfilearea The old assignment filearea ('submissions')
3417 * @param int $olditemid The old submissionid (can be null e.g. intro)
3418 * @param int $newcontextid The new assignment context id
3419 * @param int $newcomponent The new assignment component ('assignment')
3420 * @param int $newfilearea The new assignment filearea ('submissions')
3421 * @param int $newitemid The new submissionid (can be null e.g. intro)
3422 * @return int The number of files copied
3423 */
3424 public function copy_area_files_for_upgrade($oldcontextid, $oldcomponent, $oldfilearea, $olditemid, $newcontextid, $newcomponent, $newfilearea, $newitemid) {
3425 // Note, this code is based on some code in filestorage - but that code
3426 // deleted the old files (which we don't want)
3427 $count = 0;
3428
3429 $fs = get_file_storage();
3430
3431 $oldfiles = $fs->get_area_files($oldcontextid, $oldcomponent, $oldfilearea, $olditemid, 'id', false);
3432 foreach ($oldfiles as $oldfile) {
3433 $filerecord = new stdClass();
3434 $filerecord->contextid = $newcontextid;
3435 $filerecord->component = $newcomponent;
3436 $filerecord->filearea = $newfilearea;
3437 $filerecord->itemid = $newitemid;
3438 $fs->create_file_from_storedfile($filerecord, $oldfile);
3439 $count += 1;
3440 }
3441
3442 return $count;
3443 }
3444
3445 /**
3446 * Get an upto date list of user grades and feedback for the gradebook
3447 *
3448 * @param int $userid int or 0 for all users
3449 * @return array of grade data formated for the gradebook api
3450 * The data required by the gradebook api is userid,
3451 * rawgrade,
3452 * feedback,
3453 * feedbackformat,
3454 * usermodified,
3455 * dategraded,
3456 * datesubmitted
3457 */
3458 public function get_user_grades_for_gradebook($userid) {
3459 global $DB, $CFG;
3460 $grades = array();
3461 $assignmentid = $this->get_instance()->id;
3462
b11808c7
DW
3463 $adminconfig = $this->get_admin_config();
3464 $gradebookpluginname = $adminconfig->feedback_plugin_for_gradebook;
bbd0e548
DW
3465 $gradebookplugin = null;
3466
3467 // find the gradebook plugin
3468 foreach ($this->feedbackplugins as $plugin) {
3469 if ($plugin->is_enabled() && $plugin->is_visible()) {
3470 if (('assignfeedback_' . $plugin->get_type()) == $gradebookpluginname) {
3471 $gradebookplugin = $plugin;
3472 }
3473 }
3474 }
3475 if ($userid) {
3476 $where = ' WHERE u.id = ? ';
3477 } else {
3478 $where = ' WHERE u.id != ? ';
3479 }
3480
3481 $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
3482 FROM {user} u
3483 LEFT JOIN {assign_submission} s ON u.id = s.userid and s.assignment = ?
ff61f14c 3484 JOIN {assign_grades} g ON u.id = g.userid and g.assignment = ?
bbd0e548
DW
3485 ' . $where, array($assignmentid, $assignmentid, $userid));
3486
3487
3488 foreach ($graderesults as $result) {
3489 $gradebookgrade = clone $result;
3490 // now get the feedback
3491 if ($gradebookplugin) {
3492 $grade = $this->get_user_grade($result->userid, false);
14c46e24
DW
3493 if ($grade) {
3494 $gradebookgrade->feedbacktext = $gradebookplugin->text_for_gradebook($grade);
3495 $gradebookgrade->feedbackformat = $gradebookplugin->format_for_gradebook($grade);
3496 }
bbd0e548
DW
3497 }
3498 $grades[$gradebookgrade->userid] = $gradebookgrade;
3499 }
3500
3501 $graderesults->close();
3502 return $grades;
3503 }
3504
3505}
3506