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