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