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