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