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