MDL-34258: Plagiarism API now returns strings so mod_assign needs these updates
[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);
bbd0e548
DW
364 } else if ($action == 'grade') {
365 $o .= $this->view_single_grade_page($mform);
366 } else if ($action == 'viewpluginassignfeedback') {
367 $o .= $this->view_plugin_content('assignfeedback');
368 } else if ($action == 'viewpluginassignsubmission') {
369 $o .= $this->view_plugin_content('assignsubmission');
370 } else if ($action == 'editsubmission') {
371 $o .= $this->view_edit_submission_page($mform);
372 } else if ($action == 'grading') {
373 $o .= $this->view_grading_page();
374 } else if ($action == 'downloadall') {
375 $o .= $this->download_submissions();
376 } else if ($action == 'submit') {
377 $o .= $this->check_submit_for_grading();
378 } else {
379 $o .= $this->view_submission_page();
380 }
381
382 return $o;
383 }
384
385
386 /**
387 * Add this instance to the database
388 *
389 * @param stdClass $formdata The data submitted from the form
390 * @param bool $callplugins This is used to skip the plugin code
391 * when upgrading an old assignment to a new one (the plugins get called manually)
392 * @return mixed false if an error occurs or the int id of the new instance
393 */
394 public function add_instance(stdClass $formdata, $callplugins) {
395 global $DB;
396
397 $err = '';
398
399 // add the database record
400 $update = new stdClass();
401 $update->name = $formdata->name;
402 $update->timemodified = time();
403 $update->timecreated = time();
404 $update->course = $formdata->course;
405 $update->courseid = $formdata->course;
406 $update->intro = $formdata->intro;
407 $update->introformat = $formdata->introformat;
408 $update->alwaysshowdescription = $formdata->alwaysshowdescription;
409 $update->preventlatesubmissions = $formdata->preventlatesubmissions;
410 $update->submissiondrafts = $formdata->submissiondrafts;
411 $update->sendnotifications = $formdata->sendnotifications;
75f87a57 412 $update->sendlatenotifications = $formdata->sendlatenotifications;
bbd0e548
DW
413 $update->duedate = $formdata->duedate;
414 $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
415 $update->grade = $formdata->grade;
416 $returnid = $DB->insert_record('assign', $update);
417 $this->instance = $DB->get_record('assign', array('id'=>$returnid), '*', MUST_EXIST);
418 // cache the course record
419 $this->course = $DB->get_record('course', array('id'=>$formdata->course), '*', MUST_EXIST);
420
421 if ($callplugins) {
422 // call save_settings hook for submission plugins
423 foreach ($this->submissionplugins as $plugin) {
424 if (!$this->update_plugin_instance($plugin, $formdata)) {
425 print_error($plugin->get_error());
426 return false;
427 }
428 }
429 foreach ($this->feedbackplugins as $plugin) {
430 if (!$this->update_plugin_instance($plugin, $formdata)) {
431 print_error($plugin->get_error());
432 return false;
433 }
434 }
435
436 // in the case of upgrades the coursemodule has not been set so we need to wait before calling these two
437 // TODO: add event to the calendar
438 $this->update_calendar($formdata->coursemodule);
439 // TODO: add the item in the gradebook
440 $this->update_gradebook(false, $formdata->coursemodule);
441
442 }
443
444 $update = new stdClass();
445 $update->id = $this->get_instance()->id;
446 $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
447 $DB->update_record('assign', $update);
448
449 return $returnid;
450 }
451
452 /**
453 * Delete all grades from the gradebook for this assignment
454 *
455 * @return bool
456 */
457 private function delete_grades() {
458 global $CFG;
459
460 return grade_update('mod/assign', $this->get_course()->id, 'mod', 'assign', $this->get_instance()->id, 0, NULL, array('deleted'=>1)) == GRADE_UPDATE_OK;
461 }
462
463 /**
464 * Delete this instance from the database
465 *
466 * @return bool false if an error occurs
467 */
468 public function delete_instance() {
469 global $DB;
470 $result = true;
471
472 foreach ($this->submissionplugins as $plugin) {
473 if (!$plugin->delete_instance()) {
474 print_error($plugin->get_error());
475 $result = false;
476 }
477 }
478 foreach ($this->feedbackplugins as $plugin) {
479 if (!$plugin->delete_instance()) {
480 print_error($plugin->get_error());
481 $result = false;
482 }
483 }
484
485 // delete files associated with this assignment
486 $fs = get_file_storage();
487 if (! $fs->delete_area_files($this->context->id) ) {
488 $result = false;
489 }
490
491 // delete_records will throw an exception if it fails - so no need for error checking here
492
493 $DB->delete_records('assign_submission', array('assignment'=>$this->get_instance()->id));
494 $DB->delete_records('assign_grades', array('assignment'=>$this->get_instance()->id));
495 $DB->delete_records('assign_plugin_config', array('assignment'=>$this->get_instance()->id));
496
497 // delete items from the gradebook
498 if (! $this->delete_grades()) {
499 $result = false;
500 }
501
502 // delete the instance
503 $DB->delete_records('assign', array('id'=>$this->get_instance()->id));
504
505 return $result;
506 }
507
508 /**
509 * Update the settings for a single plugin
510 *
511 * @param assign_plugin $plugin The plugin to update
512 * @param stdClass $formdata The form data
513 * @return bool false if an error occurs
514 */
515 private function update_plugin_instance(assign_plugin $plugin, stdClass $formdata) {
516 if ($plugin->is_visible()) {
517 $enabledname = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
518 if ($formdata->$enabledname) {
519 $plugin->enable();
520 if (!$plugin->save_settings($formdata)) {
521 print_error($plugin->get_error());
522 return false;
523 }
524 } else {
525 $plugin->disable();
526 }
527 }
528 return true;
529 }
530
531 /**
532 * Update the gradebook information for this assignment
533 *
534 * @param bool $reset If true, will reset all grades in the gradbook for this assignment
535 * @param int $coursemoduleid This is required because it might not exist in the database yet
536 * @return bool
537 */
538 public function update_gradebook($reset, $coursemoduleid) {
539 global $CFG;
540 /** Include lib.php */
541 require_once($CFG->dirroot.'/mod/assign/lib.php');
542 $assign = clone $this->get_instance();
543 $assign->cmidnumber = $coursemoduleid;
544 $param = null;
545 if ($reset) {
546 $param = 'reset';
547 }
548
549 return assign_grade_item_update($assign, $param);
550 }
551
cfc81f03 552 /** Load and cache the admin config for this module
bc5a657b 553 *
cfc81f03
DW
554 * @return stdClass the plugin config
555 */
556 public function get_admin_config() {
557 if ($this->adminconfig) {
558 return $this->adminconfig;
559 }
b11808c7 560 $this->adminconfig = get_config('assign');
cfc81f03
DW
561 return $this->adminconfig;
562 }
563
bbd0e548
DW
564
565 /**
566 * Update the calendar entries for this assignment
567 *
568 * @param int $coursemoduleid - Required to pass this in because it might not exist in the database yet
569 * @return bool
570 */
571 public function update_calendar($coursemoduleid) {
572 global $DB, $CFG;
573 require_once($CFG->dirroot.'/calendar/lib.php');
574
575 // special case for add_instance as the coursemodule has not been set yet.
576
577 if ($this->get_instance()->duedate) {
578 $event = new stdClass();
579
580 if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assign', 'instance'=>$this->get_instance()->id))) {
581
582 $event->name = $this->get_instance()->name;
583
584 $event->description = format_module_intro('assign', $this->get_instance(), $coursemoduleid);
585 $event->timestart = $this->get_instance()->duedate;
586
587 $calendarevent = calendar_event::load($event->id);
588 $calendarevent->update($event);
589 } else {
590 $event = new stdClass();
591 $event->name = $this->get_instance()->name;
592 $event->description = format_module_intro('assign', $this->get_instance(), $coursemoduleid);
593 $event->courseid = $this->get_instance()->course;
594 $event->groupid = 0;
595 $event->userid = 0;
596 $event->modulename = 'assign';
597 $event->instance = $this->get_instance()->id;
598 $event->eventtype = 'due';
599 $event->timestart = $this->get_instance()->duedate;
600 $event->timeduration = 0;
601
602 calendar_event::create($event);
603 }
604 } else {
605 $DB->delete_records('event', array('modulename'=>'assign', 'instance'=>$this->get_instance()->id));
606 }
607 }
608
609
610 /**
611 * Update this instance in the database
612 *
613 * @param stdClass $formdata - the data submitted from the form
614 * @return bool false if an error occurs
615 */
616 public function update_instance($formdata) {
617 global $DB;
618
619 $update = new stdClass();
620 $update->id = $formdata->instance;
621 $update->name = $formdata->name;
622 $update->timemodified = time();
623 $update->course = $formdata->course;
624 $update->intro = $formdata->intro;
625 $update->introformat = $formdata->introformat;
626 $update->alwaysshowdescription = $formdata->alwaysshowdescription;
627 $update->preventlatesubmissions = $formdata->preventlatesubmissions;
628 $update->submissiondrafts = $formdata->submissiondrafts;
629 $update->sendnotifications = $formdata->sendnotifications;
75f87a57 630 $update->sendlatenotifications = $formdata->sendlatenotifications;
bbd0e548
DW
631 $update->duedate = $formdata->duedate;
632 $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
633 $update->grade = $formdata->grade;
634
635 $result = $DB->update_record('assign', $update);
636 $this->instance = $DB->get_record('assign', array('id'=>$update->id), '*', MUST_EXIST);
637
638 // load the assignment so the plugins have access to it
639
640 // call save_settings hook for submission plugins
641 foreach ($this->submissionplugins as $plugin) {
642 if (!$this->update_plugin_instance($plugin, $formdata)) {
643 print_error($plugin->get_error());
644 return false;
645 }
646 }
647 foreach ($this->feedbackplugins as $plugin) {
648 if (!$this->update_plugin_instance($plugin, $formdata)) {
649 print_error($plugin->get_error());
650 return false;
651 }
652 }
653
654
655 // update the database record
656
657
658 // update all the calendar events
659 $this->update_calendar($this->get_course_module()->id);
660
661 $this->update_gradebook(false, $this->get_course_module()->id);
662
663 $update = new stdClass();
664 $update->id = $this->get_instance()->id;
665 $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
666 $DB->update_record('assign', $update);
667
668
669
670
671
672 return $result;
673 }
674
675 /**
676 * add elements in grading plugin form
677 *
678 * @param mixed $grade stdClass|null
679 * @param MoodleQuickForm $mform
680 * @param stdClass $data
681 * @return void
682 */
683 private function add_plugin_grade_elements($grade, MoodleQuickForm $mform, stdClass $data) {
684 foreach ($this->feedbackplugins as $plugin) {
685 if ($plugin->is_enabled() && $plugin->is_visible()) {
686 $mform->addElement('header', 'header_' . $plugin->get_type(), $plugin->get_name());
687 if (!$plugin->get_form_elements($grade, $mform, $data)) {
688 $mform->removeElement('header_' . $plugin->get_type());
689 }
690 }
691 }
692 }
693
694
695
696 /**
697 * Add one plugins settings to edit plugin form
698 *
699 * @param assign_plugin $plugin The plugin to add the settings from
700 * @param MoodleQuickForm $mform The form to add the configuration settings to. This form is modified directly (not returned)
701 * @return void
702 */
703 private function add_plugin_settings(assign_plugin $plugin, MoodleQuickForm $mform) {
704 global $CFG;
705 if ($plugin->is_visible()) {
706 // enabled
707 //tied disableIf rule to this select element
708 $mform->addElement('selectyesno', $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $plugin->get_name());
709 $mform->addHelpButton($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', 'enabled', $plugin->get_subtype() . '_' . $plugin->get_type());
710
bbd0e548 711
cfc81f03 712 $default = get_config($plugin->get_subtype() . '_' . $plugin->get_type(), 'default');
bbd0e548
DW
713 if ($plugin->get_config('enabled') !== false) {
714 $default = $plugin->is_enabled();
715 }
716 $mform->setDefault($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $default);
717
718 $plugin->get_settings($mform);
719
720 }
721
722 }
723
724
725 /**
726 * Add settings to edit plugin form
727 *
728 * @param MoodleQuickForm $mform The form to add the configuration settings to. This form is modified directly (not returned)
729 * @return void
730 */
731 public function add_all_plugin_settings(MoodleQuickForm $mform) {
732 $mform->addElement('header', 'general', get_string('submissionsettings', 'assign'));
733
734 foreach ($this->submissionplugins as $plugin) {
735 $this->add_plugin_settings($plugin, $mform);
736
737 }
738 $mform->addElement('header', 'general', get_string('feedbacksettings', 'assign'));
739 foreach ($this->feedbackplugins as $plugin) {
740 $this->add_plugin_settings($plugin, $mform);
741 }
742 }
743
744 /**
745 * Allow each plugin an opportunity to update the defaultvalues
746 * passed in to the settings form (needed to set up draft areas for
747 * editor and filemanager elements)
748 * @param array $defaultvalues
749 */
750 public function plugin_data_preprocessing(&$defaultvalues) {
751 foreach ($this->submissionplugins as $plugin) {
752 if ($plugin->is_visible()) {
753 $plugin->data_preprocessing($defaultvalues);
754 }
755 }
756 foreach ($this->feedbackplugins as $plugin) {
757 if ($plugin->is_visible()) {
758 $plugin->data_preprocessing($defaultvalues);
759 }
760 }
761 }
762
763 /**
764 * Get the name of the current module.
765 *
766 * @return string the module name (Assignment)
767 */
768 protected function get_module_name() {
769 if (isset(self::$modulename)) {
770 return self::$modulename;
771 }
772 self::$modulename = get_string('modulename', 'assign');
773 return self::$modulename;
774 }
775
776 /**
777 * Get the plural name of the current module.
778 *
779 * @return string the module name plural (Assignments)
780 */
781 protected function get_module_name_plural() {
782 if (isset(self::$modulenameplural)) {
783 return self::$modulenameplural;
784 }
785 self::$modulenameplural = get_string('modulenameplural', 'assign');
786 return self::$modulenameplural;
787 }
788
789 /**
790 * Has this assignment been constructed from an instance?
791 *
792 * @return bool
793 */
794 public function has_instance() {
795 return $this->instance || $this->get_course_module();
796 }
797
798 /**
799 * Get the settings for the current instance of this assignment
800 *
801 * @return stdClass The settings
802 */
803 public function get_instance() {
804 global $DB;
805 if ($this->instance) {
806 return $this->instance;
807 }
808 if ($this->get_course_module()) {
809 $this->instance = $DB->get_record('assign', array('id' => $this->get_course_module()->instance), '*', MUST_EXIST);
810 }
811 if (!$this->instance) {
812 throw new coding_exception('Improper use of the assignment class. Cannot load the assignment record.');
813 }
814 return $this->instance;
815 }
816
817 /**
818 * Get the context of the current course
819 * @return mixed context|null The course context
820 */
821 public function get_course_context() {
822 if (!$this->context && !$this->course) {
823 throw new coding_exception('Improper use of the assignment class. Cannot load the course context.');
824 }
825 if ($this->context) {
826 return $this->context->get_course_context();
827 } else {
828 return context_course::instance($this->course->id);
829 }
830 }
831
832
833 /**
834 * Get the current course module
835 *
836 * @return mixed stdClass|null The course module
837 */
838 public function get_course_module() {
839 if ($this->coursemodule) {
840 return $this->coursemodule;
841 }
842 if (!$this->context) {
843 return null;
844 }
845
846 if ($this->context->contextlevel == CONTEXT_MODULE) {
847 $this->coursemodule = get_coursemodule_from_id('assign', $this->context->instanceid, 0, false, MUST_EXIST);
848 return $this->coursemodule;
849 }
850 return null;
851 }
852
853 /**
854 * Get context module
855 *
856 * @return context
857 */
858 public function get_context() {
859 return $this->context;
860 }
861
862 /**
863 * Get the current course
864 * @return mixed stdClass|null The course
865 */
866 public function get_course() {
867 global $DB;
868 if ($this->course) {
869 return $this->course;
870 }
871
872 if (!$this->context) {
873 return null;
874 }
875 $this->course = $DB->get_record('course', array('id' => $this->get_course_context()->instanceid), '*', MUST_EXIST);
876 return $this->course;
877 }
878
879 /**
880 * Return a grade in user-friendly form, whether it's a scale or not
881 *
9682626e 882 * @param mixed $grade int|null
bf78ebd6 883 * @param boolean $editing Are we allowing changes to this grade?
2a4fbc32
SH
884 * @param int $userid The user id the grade belongs to
885 * @param int $modified Timestamp from when the grade was last modified
bbd0e548
DW
886 * @return string User-friendly representation of grade
887 */
bf78ebd6 888 public function display_grade($grade, $editing, $userid=0, $modified=0) {
bbd0e548
DW
889 global $DB;
890
891 static $scalegrades = array();
892
2a4fbc32
SH
893 if ($this->get_instance()->grade >= 0) {
894 // Normal number
e7ade405 895 if ($editing && $this->get_instance()->grade > 0) {
2d8a9ce9
DW
896 if ($grade < 0) {
897 $displaygrade = '';
898 } else {
899 $displaygrade = format_float($grade);
900 }
502be9a0 901 $o = '<input type="text" name="quickgrade_' . $userid . '" value="' . $displaygrade . '" size="6" maxlength="10" class="quickgrade"/>';
bf78ebd6 902 $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade,2);
2a4fbc32 903 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
bf78ebd6 904 return $o;
bbd0e548 905 } else {
a1e54f4d
DW
906 if ($grade == -1 || $grade === null) {
907 return '-';
908 } else {
909 return format_float(($grade),2) .'&nbsp;/&nbsp;'. format_float($this->get_instance()->grade,2);
910 }
bbd0e548
DW
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 1183 $messagetype = 'feedbackavailable';
f750cf71 1184 $eventtype = 'assign_notification';
3f7b501e
SH
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');
bf78ebd6 1693 require_once($CFG->dirroot . '/mod/assign/quickgradingform.php');
bbd0e548
DW
1694 require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
1695 $o = '';
1696
1697 $links = array();
bbd0e548
DW
1698 if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
1699 has_capability('moodle/grade:viewall', $this->get_course_context())) {
a1e54f4d 1700 $gradebookurl = '/grade/report/grader/index.php?id=' . $this->get_course()->id;
bbd0e548
DW
1701 $links[$gradebookurl] = get_string('viewgradebook', 'assign');
1702 }
1703 if ($this->is_any_submission_plugin_enabled()) {
a1e54f4d 1704 $downloadurl = '/mod/assign/view.php?id=' . $this->get_course_module()->id . '&action=downloadall';
bbd0e548
DW
1705 $links[$downloadurl] = get_string('downloadall', 'assign');
1706 }
a1e54f4d
DW
1707
1708 $gradingactions = new url_select($links);
bbd0e548 1709
bf78ebd6
DW
1710 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
1711
bbd0e548
DW
1712 $perpage = get_user_preferences('assign_perpage', 10);
1713 $filter = get_user_preferences('assign_filter', '');
bf78ebd6
DW
1714 $controller = $gradingmanager->get_active_controller();
1715 $showquickgrading = empty($controller);
1716 if (optional_param('action', '', PARAM_ALPHA) == 'saveoptions') {
1717 $quickgrading = optional_param('quickgrading', false, PARAM_BOOL);
1718 set_user_preference('assign_quickgrading', $quickgrading);
1719 }
1720 $quickgrading = get_user_preferences('assign_quickgrading', false);
1721
bbd0e548
DW
1722 // print options for changing the filter and changing the number of results per page
1723 $gradingoptionsform = new mod_assign_grading_options_form(null,
1724 array('cm'=>$this->get_course_module()->id,
1725 'contextid'=>$this->context->id,
bf78ebd6
DW
1726 'userid'=>$USER->id,
1727 'showquickgrading'=>$showquickgrading,
1728 'quickgrading'=>$quickgrading),
bbd0e548
DW
1729 'post', '',
1730 array('class'=>'gradingoptionsform'));
1731
1732 $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
1733 array('cm'=>$this->get_course_module()->id,
1734 'submissiondrafts'=>$this->get_instance()->submissiondrafts),
1735 'post', '',
1736 array('class'=>'gradingbatchoperationsform'));
1737
1738 $gradingoptionsdata = new stdClass();
1739 $gradingoptionsdata->perpage = $perpage;
1740 $gradingoptionsdata->filter = $filter;
1741 $gradingoptionsform->set_data($gradingoptionsdata);
1742
1743 // plagiarism update status apearring in the grading book
1744 if (!empty($CFG->enableplagiarism)) {
1745 /** Include plagiarismlib.php */
1746 require_once($CFG->libdir . '/plagiarismlib.php');
66681a51 1747 $o .= plagiarism_update_status($this->get_course(), $this->get_course_module());
bbd0e548
DW
1748 }
1749
a1e54f4d
DW
1750 $actionformtext = $this->output->render($gradingactions);
1751 $o .= $this->output->render(new assign_header($this->get_instance(),
1752 $this->get_context(), false, $this->get_course_module()->id, get_string('grading', 'assign'), $actionformtext));
1753 $o .= groups_print_activity_menu($this->get_course_module(), $CFG->wwwroot . '/mod/assign/view.php?id=' . $this->get_course_module()->id.'&action=grading', true);
1754
bbd0e548
DW
1755
1756 // load and print the table of submissions
bf78ebd6
DW
1757 if ($showquickgrading && $quickgrading) {
1758 $table = $this->output->render(new assign_grading_table($this, $perpage, $filter, 0, true));
1759 $quickgradingform = new mod_assign_quick_grading_form(null,
1760 array('cm'=>$this->get_course_module()->id,
1761 'gradingtable'=>$table));
1762 $o .= $this->output->render(new assign_form('quickgradingform', $quickgradingform));
1763 } else {
1764 $o .= $this->output->render(new assign_grading_table($this, $perpage, $filter, 0, false));
1765 }
bbd0e548
DW
1766
1767 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1768 $users = array_keys($this->list_participants($currentgroup, true));
1769 if (count($users) != 0) {
1770 // if no enrolled user in a course then don't display the batch operations feature
1771 $o .= $this->output->render(new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform));
1772 }
a1e54f4d 1773 $o .= $this->output->render(new assign_form('gradingoptionsform', $gradingoptionsform, 'M.mod_assign.init_grading_options'));
bbd0e548
DW
1774 return $o;
1775 }
1776
1777 /**
1778 * View entire grading page.
1779 *
1780 * @return string
1781 */
1782 private function view_grading_page() {
1783 global $CFG;
1784
1785 $o = '';
1786 // Need submit permission to submit an assignment
1787 require_capability('mod/assign:grade', $this->context);
1788 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
1789
1790 // only load this if it is
1791
bbd0e548
DW
1792 $o .= $this->view_grading_table();
1793
1794 $o .= $this->view_footer();
1795 $this->add_to_log('view submission grading table', get_string('viewsubmissiongradingtable', 'assign'));
1796 return $o;
1797 }
1798
1799 /**
1800 * Capture the output of the plagiarism plugins disclosures and return it as a string
1801 *
1802 * @return void
1803 */
1804 private function plagiarism_print_disclosure() {
1805 global $CFG;
1806 $o = '';
1807
1808 if (!empty($CFG->enableplagiarism)) {
1809 /** Include plagiarismlib.php */
1810 require_once($CFG->libdir . '/plagiarismlib.php');
bbd0e548 1811
66681a51 1812 $o .= plagiarism_print_disclosure($this->get_course_module()->id);
bbd0e548
DW
1813 }
1814
1815 return $o;
1816 }
1817
1818 /**
1819 * message for students when assignment submissions have been closed
1820 *
1821 * @return string
1822 */
1823 private function view_student_error_message() {
1824 global $CFG;
1825
1826 $o = '';
1827 // Need submit permission to submit an assignment
1828 require_capability('mod/assign:submit', $this->context);
1829
1830 $o .= $this->output->render(new assign_header($this->get_instance(),
1831 $this->get_context(),
1832 $this->show_intro(),
1833 $this->get_course_module()->id,
1834 get_string('editsubmission', 'assign')));
1835
bf78ebd6 1836 $o .= $this->output->notification(get_string('submissionsclosed', 'assign'));
bbd0e548
DW
1837
1838 $o .= $this->view_footer();
1839
1840 return $o;
1841
1842 }
1843
1844 /**
1845 * View edit submissions page.
1846 *
1847 * @param moodleform $mform
1848 * @return void
1849 */
1850 private function view_edit_submission_page($mform) {
1851 global $CFG;
1852
1853 $o = '';
1854 // Include submission form
1855 require_once($CFG->dirroot . '/mod/assign/submission_form.php');
1856 // Need submit permission to submit an assignment
1857 require_capability('mod/assign:submit', $this->context);
1858
1859 if (!$this->submissions_open()) {
bf78ebd6 1860 return $this->view_student_error_message();
bbd0e548
DW
1861 }
1862 $o .= $this->output->render(new assign_header($this->get_instance(),
1863 $this->get_context(),
1864 $this->show_intro(),
1865 $this->get_course_module()->id,
1866 get_string('editsubmission', 'assign')));
1867 $o .= $this->plagiarism_print_disclosure();
1868 $data = new stdClass();
1869
1870 if (!$mform) {
1871 $mform = new mod_assign_submission_form(null, array($this, $data));
1872 }
1873
1874 $o .= $this->output->render(new assign_form('editsubmissionform',$mform));
1875
1876 $o .= $this->view_footer();
1877 $this->add_to_log('view submit assignment form', get_string('viewownsubmissionform', 'assign'));
1878
1879 return $o;
1880 }
1881
1882 /**
1883 * See if this assignment has a grade yet
1884 *
1885 * @param int $userid
1886 * @return bool
1887 */
1888 private function is_graded($userid) {
1889 $grade = $this->get_user_grade($userid, false);
1890 if ($grade) {
2d8a9ce9 1891 return ($grade->grade !== NULL && $grade->grade >= 0);
bbd0e548
DW
1892 }
1893 return false;
1894 }
1895
1896
1897 /**
1898 * Perform an access check to see if the current $USER can view this users submission
1899 *
1900 * @param int $userid
1901 * @return bool
1902 */
1903 public function can_view_submission($userid) {
1904 global $USER;
1905
1906 if (!is_enrolled($this->get_course_context(), $userid)) {
1907 return false;
1908 }
1909 if ($userid == $USER->id && !has_capability('mod/assign:submit', $this->context)) {
1910 return false;
1911 }
1912 if ($userid != $USER->id && !has_capability('mod/assign:grade', $this->context)) {
1913 return false;
1914 }
1915 return true;
1916 }
1917
1918 /**
1919 * Ask the user to confirm they want to perform this batch operation
1920 * @return string
1921 */
1922 private function process_batch_grading_operation() {
1923 global $CFG;
1924 require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
1925 require_sesskey();
1926
1927 $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
1928 array('cm'=>$this->get_course_module()->id,
1929 'submissiondrafts'=>$this->get_instance()->submissiondrafts),
1930 'post', '',
1931 array('class'=>'gradingbatchoperationsform'));
1932
1933 if ($data = $gradingbatchoperationsform->get_data()) {
1934 // get the list of users
1935 $users = $data->selectedusers;
1936 $userlist = explode(',', $users);
1937
1938 foreach ($userlist as $userid) {
1939 if ($data->operation == 'lock') {
1940 $this->process_lock($userid);
1941 } else if ($data->operation == 'unlock') {
1942 $this->process_unlock($userid);
1943 } else if ($data->operation == 'reverttodraft') {
1944 $this->process_revert_to_draft($userid);
1945 }
1946 }
1947 }
1948
1949 return true;
1950 }
1951
1952 /**
1953 * Ask the user to confirm they want to submit their work for grading
1954 * @return string
1955 */
1956 private function check_submit_for_grading() {
1957 global $USER;
1958 // Check that all of the submission plugins are ready for this submission
1959 $notifications = array();
1960 $submission = $this->get_user_submission($USER->id, false);
1961 $plugins = $this->get_submission_plugins();
1962 foreach ($plugins as $plugin) {
1963 if ($plugin->is_enabled() && $plugin->is_visible()) {
1964 $check = $plugin->precheck_submission($submission);
1965 if ($check !== true) {
1966 $notifications[] = $check;
1967 }
1968 }
1969 }
1970
1971 $o = '';
1972 $o .= $this->output->header();
1973 $o .= $this->output->render(new assign_submit_for_grading_page($notifications, $this->get_course_module()->id));
1974 $o .= $this->view_footer();
1975 return $o;
1976 }
1977
1978 /**
1979 * Print 2 tables of information with no action links -
1980 * the submission summary and the grading summary
1981 *
1982 * @param stdClass $user the user to print the report for
1983 * @param bool $showlinks - Return plain text or links to the profile
1984 * @return string - the html summary
1985 */
1986 public function view_student_summary($user, $showlinks) {
1987 global $CFG, $DB, $PAGE;
1988
1989 $grade = $this->get_user_grade($user->id, false);
1990 $submission = $this->get_user_submission($user->id, false);
1991 $o = '';
1992
1993 if ($this->can_view_submission($user->id)) {
1994 $showedit = has_capability('mod/assign:submit', $this->context) &&
1995 $this->submissions_open() && ($this->is_any_submission_plugin_enabled()) && $showlinks;
1996 $showsubmit = $submission && ($submission->status == ASSIGN_SUBMISSION_STATUS_DRAFT) && $showlinks;
1997 $gradelocked = ($grade && $grade->locked) || $this->grading_disabled($user->id);
1998
1999 $o .= $this->output->render(new assign_submission_status($this->get_instance()->allowsubmissionsfromdate,
2000 $this->get_instance()->alwaysshowdescription,
2001 $submission,
2002 $this->is_any_submission_plugin_enabled(),
2003 $gradelocked,
2004 $this->is_graded($user->id),
2005 $this->get_instance()->duedate,
2006 $this->get_submission_plugins(),
2007 $this->get_return_action(),
2008 $this->get_return_params(),
2009 $this->get_course_module()->id,
2010 assign_submission_status::STUDENT_VIEW,
2011 $showedit,
2012 $showsubmit));
2013 require_once($CFG->libdir.'/gradelib.php');
2014 require_once($CFG->dirroot.'/grade/grading/lib.php');
2015
2016 $gradinginfo = grade_get_grades($this->get_course()->id,
2017 'mod',
2018 'assign',
2019 $this->get_instance()->id,
2020 $user->id);
2021
2022 $gradingitem = $gradinginfo->items[0];
2023 $gradebookgrade = $gradingitem->grades[$user->id];
2024
2025 // check to see if all feedback plugins are empty
2026 $emptyplugins = true;
2027 if ($grade) {
2028 foreach ($this->get_feedback_plugins() as $plugin) {
2029 if ($plugin->is_visible() && $plugin->is_enabled()) {
2030 if (!$plugin->is_empty($grade)) {
2031 $emptyplugins = false;
2032 }
2033 }
2034 }
2035 }
2036
2037
2038 if (!($gradebookgrade->hidden) && ($gradebookgrade->grade !== null || !$emptyplugins)) {
2039
2040 $gradefordisplay = '';
2041 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2042
2043 if ($controller = $gradingmanager->get_active_controller()) {
2044 $controller->set_grade_range(make_grades_menu($this->get_instance()->grade));
2045 $gradefordisplay = $controller->render_grade($PAGE,
2046 $grade->id,
2047 $gradingitem,
2048 $gradebookgrade->str_long_grade,
2049 has_capability('mod/assign:grade', $this->get_context()));
2050 } else {
bf78ebd6 2051 $gradefordisplay = $this->display_grade($gradebookgrade->grade, false);
bbd0e548
DW
2052 }
2053
2054 $gradeddate = $gradebookgrade->dategraded;
2055 $grader = $DB->get_record('user', array('id'=>$gradebookgrade->usermodified));
2056
2057 $feedbackstatus = new assign_feedback_status($gradefordisplay,
2058 $gradeddate,
2059 $grader,
2060 $this->get_feedback_plugins(),
2061 $grade,
2062 $this->get_course_module()->id,
2063 $this->get_return_action(),
2064 $this->get_return_params());
2065
2066 $o .= $this->output->render($feedbackstatus);
2067 }
2068
2069 }
2070 return $o;
2071 }
2072
2073 /**
2074 * View submissions page (contains details of current submission).
2075 *
2076 * @return string
2077 */
2078 private function view_submission_page() {
2079 global $CFG, $DB, $USER, $PAGE;
2080
2081 $o = '';
2082 $o .= $this->output->render(new assign_header($this->get_instance(),
2083 $this->get_context(),
2084 $this->show_intro(),
2085 $this->get_course_module()->id));
2086
2087 if ($this->can_grade()) {
2088 $o .= $this->output->render(new assign_grading_summary($this->count_participants(0),
2089 $this->get_instance()->submissiondrafts,
2090 $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_DRAFT),
2091 $this->is_any_submission_plugin_enabled(),
2092 $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED),
2093 $this->get_instance()->duedate,
2094 $this->get_course_module()->id
2095 ));
2096 }
2097 $grade = $this->get_user_grade($USER->id, false);
2098 $submission = $this->get_user_submission($USER->id, false);
2099
2100 if ($this->can_view_submission($USER->id)) {
2101 $o .= $this->view_student_summary($USER, true);
2102 }
2103
2104
2105 $o .= $this->view_footer();
2106 $this->add_to_log('view', get_string('viewownsubmissionstatus', 'assign'));
2107 return $o;
2108 }
2109
2110 /**
2111 * convert the final raw grade(s) in the grading table for the gradebook
2112 *
2113 * @param stdClass $grade
2114 * @return array
2115 */
2116 private function convert_grade_for_gradebook(stdClass $grade) {
2117 $gradebookgrade = array();
2118 // trying to match those array keys in grade update function in gradelib.php
2119 // with keys in th database table assign_grades
2120 // starting around line 262
99467a9f
DW
2121 if ($grade->grade >= 0) {
2122 $gradebookgrade['rawgrade'] = $grade->grade;
2123 }
bbd0e548
DW
2124 $gradebookgrade['userid'] = $grade->userid;
2125 $gradebookgrade['usermodified'] = $grade->grader;
2126 $gradebookgrade['datesubmitted'] = NULL;
2127 $gradebookgrade['dategraded'] = $grade->timemodified;
2128 if (isset($grade->feedbackformat)) {
2129 $gradebookgrade['feedbackformat'] = $grade->feedbackformat;
2130 }
2131 if (isset($grade->feedbacktext)) {
2132 $gradebookgrade['feedback'] = $grade->feedbacktext;
2133 }
2134
2135 return $gradebookgrade;
2136 }
2137
2138 /**
2139 * convert submission details for the gradebook
2140 *
2141 * @param stdClass $submission
2142 * @return array
2143 */
2144 private function convert_submission_for_gradebook(stdClass $submission) {
2145 $gradebookgrade = array();
2146
2147
2148 $gradebookgrade['userid'] = $submission->userid;
2149 $gradebookgrade['usermodified'] = $submission->userid;
2150 $gradebookgrade['datesubmitted'] = $submission->timemodified;
2151
2152 return $gradebookgrade;
2153 }
2154
2155 /**
2156 * update grades in the gradebook
2157 *
2158 * @param mixed $submission stdClass|null
2159 * @param mixed $grade stdClass|null
2160 * @return bool
2161 */
2162 private function gradebook_item_update($submission=NULL, $grade=NULL) {
2163
2164 if($submission != NULL){
bbd0e548 2165 $gradebookgrade = $this->convert_submission_for_gradebook($submission);
bbd0e548 2166 }else{
bbd0e548
DW
2167 $gradebookgrade = $this->convert_grade_for_gradebook($grade);
2168 }
09b46f0e
AA
2169 // Grading is disabled, return.
2170 if ($this->grading_disabled($gradebookgrade['userid'])) {
2171 return false;
2172 }
bbd0e548
DW
2173 $assign = clone $this->get_instance();
2174 $assign->cmidnumber = $this->get_course_module()->id;
2175
2176 return assign_grade_item_update($assign, $gradebookgrade);
2177 }
2178
2179 /**
2180 * update grades in the gradebook based on submission time
2181 *
2182 * @param stdClass $submission
2183 * @param bool $updatetime
2184 * @return bool
2185 */
2186 private function update_submission(stdClass $submission, $updatetime=true) {
2187 global $DB;
2188
2189 if ($updatetime) {
2190 $submission->timemodified = time();
2191 }
2192 $result= $DB->update_record('assign_submission', $submission);
2193 if ($result) {
2194 $this->gradebook_item_update($submission);
2195 }
2196 return $result;
2197 }
2198
2199 /**
2200 * Is this assignment open for submissions?
2201 *
2202 * Check the due date,
2203 * prevent late submissions,
2204 * has this person already submitted,
2205 * is the assignment locked?
2206 *
2207 * @return bool
2208 */
2209 private function submissions_open() {
2210 global $USER;
2211
2212 $time = time();
2213 $dateopen = true;
2214 if ($this->get_instance()->preventlatesubmissions && $this->get_instance()->duedate) {
2215 $dateopen = ($this->get_instance()->allowsubmissionsfromdate <= $time && $time <= $this->get_instance()->duedate);
2216 } else {
2217 $dateopen = ($this->get_instance()->allowsubmissionsfromdate <= $time);
2218 }
2219
2220 if (!$dateopen) {
2221 return false;
2222 }
2223
2224 // now check if this user has already submitted etc.
2225 if (!is_enrolled($this->get_course_context(), $USER)) {
2226 return false;
2227 }
2228 if ($submission = $this->get_user_submission($USER->id, false)) {
2229 if ($this->get_instance()->submissiondrafts && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
2230 // drafts are tracked and the student has submitted the assignment
2231 return false;
2232 }
2233 }
2234 if ($grade = $this->get_user_grade($USER->id, false)) {
2235 if ($grade->locked) {
2236 return false;
2237 }
2238 }
2239
2240 if ($this->grading_disabled($USER->id)) {
2241 return false;
2242 }
2243
2244 return true;
2245 }
2246
2247 /**
2248 * render the files in file area
2249 * @param string $component
2250 * @param string $area
2251 * @param int $submissionid
2252 * @return string
2253 */
2254 public function render_area_files($component, $area, $submissionid) {
2255 global $USER;
2256
2257 if (!$submissionid) {
2258 $submission = $this->get_user_submission($USER->id,false);
2259 $submissionid = $submission->id;
2260 }
2261
bbd0e548
DW
2262 $fs = get_file_storage();
2263 $browser = get_file_browser();
2264 $files = $fs->get_area_files($this->get_context()->id, $component, $area , $submissionid , "timemodified", false);
2265 return $this->output->assign_files($this->context, $submissionid, $area, $component);
2266
2267 }
2268
2269 /**
2270 * Returns a list of teachers that should be grading given submission
2271 *
75f87a57 2272 * @param int $userid
bbd0e548
DW
2273 * @return array
2274 */
75f87a57 2275 private function get_graders($userid) {
bbd0e548 2276 //potential graders
75f87a57 2277 $potentialgraders = get_enrolled_users($this->context, "mod/assign:grade");
bbd0e548
DW
2278
2279 $graders = array();
2280 if (groups_get_activity_groupmode($this->get_course_module()) == SEPARATEGROUPS) { // Separate groups are being used
75f87a57 2281 if ($groups = groups_get_all_groups($this->get_course()->id, $userid)) { // Try to find all groups
bbd0e548
DW
2282 foreach ($groups as $group) {
2283 foreach ($potentialgraders as $grader) {
75f87a57 2284 if ($grader->id == $userid) {
bbd0e548
DW
2285 continue; // do not send self
2286 }
2287 if (groups_is_member($group->id, $grader->id)) {
2288 $graders[$grader->id] = $grader;
2289 }
2290 }
2291 }
2292 } else {
2293 // user not in group, try to find graders without group
2294 foreach ($potentialgraders as $grader) {
75f87a57 2295 if ($grader->id == $userid) {
bbd0e548
DW
2296 continue; // do not send self
2297 }
2298 if (!groups_has_membership($this->get_course_module(), $grader->id)) {
2299 $graders[$grader->id] = $grader;
2300 }
2301 }
2302 }
2303 } else {
2304 foreach ($potentialgraders as $grader) {
75f87a57 2305 if ($grader->id == $userid) {
bbd0e548
DW
2306 continue; // do not send self
2307 }
2308 // must be enrolled
2309 if (is_enrolled($this->get_course_context(), $grader->id)) {
2310 $graders[$grader->id] = $grader;
2311 }
2312 }
2313 }
2314 return $graders;
2315 }
2316
2317 /**
3f7b501e 2318 * Format a notification for plain text
bbd0e548 2319 *
75f87a57
DW
2320 * @param string $messagetype
2321 * @param stdClass $info
2322 * @param stdClass $course
2323 * @param stdClass $context
2324 * @param string $modulename
2325 * @param string $assignmentname
bbd0e548 2326 */
75f87a57
DW
2327 private static function format_notification_message_text($messagetype, $info, $course, $context, $modulename, $assignmentname) {
2328 $posttext = format_string($course->shortname, true, array('context' => $context->get_course_context())).' -> '.
2329 $modulename.' -> '.
2330 format_string($assignmentname, true, array('context' => $context))."\n";
bbd0e548 2331 $posttext .= '---------------------------------------------------------------------'."\n";
75f87a57 2332 $posttext .= get_string($messagetype . 'text', "assign", $info)."\n";
bbd0e548
DW
2333 $posttext .= "\n---------------------------------------------------------------------\n";
2334 return $posttext;
2335 }
2336
75f87a57 2337 /**
3f7b501e 2338 * Format a notification for HTML
bbd0e548 2339 *
75f87a57
DW
2340 * @param string $messagetype
2341 * @param stdClass $info
3f7b501e
SH
2342 * @param stdClass $course
2343 * @param stdClass $context
2344 * @param string $modulename
2345 * @param stdClass $coursemodule
2346 * @param string $assignmentname
2347 * @param stdClass $info
bbd0e548 2348 */
75f87a57 2349 private static function format_notification_message_html($messagetype, $info, $course, $context, $modulename, $coursemodule, $assignmentname) {
bbd0e548
DW
2350 global $CFG;
2351 $posthtml = '<p><font face="sans-serif">'.
75f87a57 2352 '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.format_string($course->shortname, true, array('context' => $context->get_course_context())).'</a> ->'.
599f7a27
RK
2353 '<a href="'.$CFG->wwwroot.'/mod/assign/index.php?id='.$course->id.'">'.$modulename.'</a> ->'.
2354 '<a href="'.$CFG->wwwroot.'/mod/assign/view.php?id='.$coursemodule->id.'">'.format_string($assignmentname, true, array('context' => $context)).'</a></font></p>';
bbd0e548 2355 $posthtml .= '<hr /><font face="sans-serif">';
75f87a57 2356 $posthtml .= '<p>'.get_string($messagetype . 'html', 'assign', $info).'</p>';
bbd0e548
DW
2357 $posthtml .= '</font><hr />';
2358 return $posthtml;
2359 }
2360
75f87a57 2361 /**
c1d09c6f 2362 * Message someone about something (static so it can be called from cron)
75f87a57 2363 *
75f87a57
DW
2364 * @param stdClass $userfrom
2365 * @param stdClass $userto
2366 * @param string $messagetype
2367 * @param string $eventtype
2368 * @param int $updatetime
2369 * @param stdClass $coursemodule
2370 * @param stdClass $context
2371 * @param stdClass $course
2372 * @param string $modulename
75f87a57
DW
2373 * @param string $assignmentname
2374 * @return void
2375 */
2376 public static function send_assignment_notification($userfrom, $userto, $messagetype, $eventtype,
2377 $updatetime, $coursemodule, $context, $course,
2378 $modulename, $assignmentname) {
3f7b501e 2379 global $CFG;
75f87a57
DW
2380
2381 $info = new stdClass();
2382 $info->username = fullname($userfrom, true);
2383 $info->assignment = format_string($assignmentname,true, array('context'=>$context));
2384 $info->url = $CFG->wwwroot.'/mod/assign/view.php?id='.$coursemodule->id;
2385 $info->timeupdated = strftime('%c',$updatetime);
2386
2387 $postsubject = get_string($messagetype . 'small', 'assign', $info);
2388 $posttext = self::format_notification_message_text($messagetype, $info, $course, $context, $modulename, $assignmentname);
2389 $posthtml = ($userto->mailformat == 1) ? self::format_notification_message_html($messagetype, $info, $course, $context, $modulename, $coursemodule, $assignmentname) : '';
2390
2391 $eventdata = new stdClass();
2392 $eventdata->modulename = 'assign';
2393 $eventdata->userfrom = $userfrom;
2394 $eventdata->userto = $userto;
2395 $eventdata->subject = $postsubject;
2396 $eventdata->fullmessage = $posttext;
2397 $eventdata->fullmessageformat = FORMAT_PLAIN;
2398 $eventdata->fullmessagehtml = $posthtml;
2399 $eventdata->smallmessage = $postsubject;
2400
2401 $eventdata->name = $eventtype;
2402 $eventdata->component = 'mod_assign';
2403 $eventdata->notification = 1;
2404 $eventdata->contexturl = $info->url;
2405 $eventdata->contexturlname = $info->assignment;
2406
2407 message_send($eventdata);
75f87a57
DW
2408 }
2409
2410 /**
c1d09c6f 2411 * Message someone about something
75f87a57 2412 *
3f7b501e
SH
2413 * @param stdClass $userfrom
2414 * @param stdClass $userto
2415 * @param string $messagetype
2416 * @param string $eventtype
2417 * @param int $updatetime
75f87a57
DW
2418 * @return void
2419 */
2420 public function send_notification($userfrom, $userto, $messagetype, $eventtype, $updatetime) {
2421 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);
2422 }
2423
2424 /**
c1d09c6f 2425 * Notify student upon successful submission
75f87a57 2426 *
75f87a57
DW
2427 * @global moodle_database $DB
2428 * @param stdClass $submission
2429 * @return void
2430 */
c1d09c6f 2431 private function notify_student_submission_receipt(stdClass $submission) {
75f87a57
DW
2432 global $DB;
2433
2434 $adminconfig = $this->get_admin_config();
3f7b501e
SH
2435 if (!$adminconfig->submissionreceipts) {
2436 // No need to do anything
75f87a57
DW
2437 return;
2438 }
75f87a57 2439 $user = $DB->get_record('user', array('id'=>$submission->userid), '*', MUST_EXIST);
f750cf71 2440 $this->send_notification($user, $user, 'submissionreceipt', 'assign_notification', $submission->timemodified);
75f87a57
DW
2441 }
2442
bbd0e548 2443 /**
c1d09c6f 2444 * Send notifications to graders upon student submissions
bbd0e548 2445 *
75f87a57 2446 * @global moodle_database $DB
bbd0e548
DW
2447 * @param stdClass $submission
2448 * @return void
2449 */
c1d09c6f 2450 private function notify_graders(stdClass $submission) {
75f87a57
DW
2451 global $DB;
2452
2453 $late = $this->get_instance()->duedate && ($this->get_instance()->duedate < time());
bbd0e548 2454
75f87a57 2455 if (!$this->get_instance()->sendnotifications && !($late && $this->get_instance()->sendlatenotifications)) { // No need to do anything
bbd0e548
DW
2456 return;
2457 }
2458
2459 $user = $DB->get_record('user', array('id'=>$submission->userid), '*', MUST_EXIST);
75f87a57 2460 if ($teachers = $this->get_graders($user->id)) {
bbd0e548 2461 foreach ($teachers as $teacher) {
f750cf71 2462 $this->send_notification($user, $teacher, 'gradersubmissionupdated', 'assign_notification', $submission->timemodified);
bbd0e548
DW
2463 }
2464 }
2465 }
2466
2467 /**
2468 * assignment submission is processed before grading
2469 *
2470 * @return void
2471 */
2472 private function process_submit_for_grading() {
2473 global $USER;
2474
2475 // Need submit permission to submit an assignment
2476 require_capability('mod/assign:submit', $this->context);
2477 require_sesskey();
2478
2479 $submission = $this->get_user_submission($USER->id,true);
2480 if ($submission->status != ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
2481 // Give each submission plugin a chance to process the submission
2482 $plugins = $this->get_submission_plugins();
2483 foreach ($plugins as $plugin) {
2484 $plugin->submit_for_grading();
2485 }
2486
2487 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
2488 $this->update_submission($submission);
2489 $this->add_to_log('submit for grading', $this->format_submission_for_log($submission));
c1d09c6f
RK
2490 $this->notify_graders($submission);
2491 $this->notify_student_submission_receipt($submission);
bbd0e548
DW
2492 }
2493 }
2494
bf78ebd6
DW
2495 /**
2496 * save quick grades
2497 *
2a4fbc32
SH
2498 * @global moodle_database $DB
2499 * @return string The result of the save operation
bf78ebd6
DW
2500 */
2501 private function process_save_quick_grades() {
2502 global $USER, $DB, $CFG;
2503
2504 // Need grade permission
2505 require_capability('mod/assign:grade', $this->context);
2506
2507 // make sure advanced grading is disabled
2508 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2509 $controller = $gradingmanager->get_active_controller();
2510 if (!empty($controller)) {
2a4fbc32 2511 return get_string('errorquickgradingvsadvancedgrading', 'assign');
bf78ebd6
DW
2512 }
2513
2514 $users = array();
2515 // first check all the last modified values
2c6a3dbf
DW
2516 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
2517 $participants = $this->list_participants($currentgroup, true);
2518
2a4fbc32 2519 // gets a list of possible users and look for values based upon that.
2c6a3dbf
DW
2520 foreach ($participants as $userid => $unused) {
2521 $modified = optional_param('grademodified_' . $userid, -1, PARAM_INT);
2522 if ($modified >= 0) {
bf78ebd6
DW
2523 // gather the userid, updated grade and last modified value
2524 $record = new stdClass();
2c6a3dbf 2525 $record->userid = $userid;
4913af93 2526 $record->grade = unformat_float(required_param('quickgrade_' . $record->userid, PARAM_TEXT));
2c6a3dbf
DW
2527 $record->lastmodified = $modified;
2528 $record->gradinginfo = grade_get_grades($this->get_course()->id, 'mod', 'assign', $this->get_instance()->id, array($userid));
2529 $users[$userid] = $record;
bf78ebd6
DW
2530 }
2531 }
2a4fbc32
SH
2532 if (empty($users)) {
2533 // Quick check to see whether we have any users to update and we don't
2534 return get_string('quickgradingchangessaved', 'assign'); // Technical lie
2535 }
bf78ebd6 2536
2a4fbc32
SH
2537 list($userids, $params) = $DB->get_in_or_equal(array_keys($users), SQL_PARAMS_NAMED);
2538 $params['assignment'] = $this->get_instance()->id;
bf78ebd6 2539 // check them all for currency
2a4fbc32
SH
2540 $sql = 'SELECT u.id as userid, g.grade as grade, g.timemodified as lastmodified
2541 FROM {user} u
2542 LEFT JOIN {assign_grades} g ON u.id = g.userid AND g.assignment = :assignment
2543 WHERE u.id ' . $userids;
2544 $currentgrades = $DB->get_recordset_sql($sql, $params);
bf78ebd6
DW
2545
2546 $modifiedusers = array();
2547 foreach ($currentgrades as $current) {
2548 $modified = $users[(int)$current->userid];
2c6a3dbf 2549 $grade = $this->get_user_grade($userid, false);
bf78ebd6
DW
2550
2551 // check to see if the outcomes were modified
2552 if ($CFG->enableoutcomes) {
2553 foreach ($modified->gradinginfo->outcomes as $outcomeid => $outcome) {
2554 $oldoutcome = $outcome->grades[$modified->userid]->grade;
4913af93 2555 $newoutcome = optional_param('outcome_' . $outcomeid . '_' . $modified->userid, -1, PARAM_FLOAT);
bf78ebd6
DW
2556 if ($oldoutcome != $newoutcome) {
2557 // can't check modified time for outcomes because it is not reported
2558 $modifiedusers[$modified->userid] = $modified;
2559 continue;
2560 }
2561 }
2562 }
2563
2c6a3dbf
DW
2564 // let plugins participate
2565 foreach ($this->feedbackplugins as $plugin) {
2566 if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->supports_quickgrading()) {
2567 if ($plugin->is_quickgrading_modified($modified->userid, $grade)) {
2568 if ((int)$current->lastmodified > (int)$modified->lastmodified) {
2569 return get_string('errorrecordmodified', 'assign');
2570 } else {
2571 $modifiedusers[$modified->userid] = $modified;
2572 continue;
2573 }
2574 }
2575 }
2576 }
2577
bf78ebd6
DW
2578
2579 if (($current->grade < 0 || $current->grade === NULL) &&
2580 ($modified->grade < 0 || $modified->grade === NULL)) {
2581 // different ways to indicate no grade
2582 continue;
2583 }
a13edd49
DW
2584 // Treat 0 and null as different values
2585 if ($current->grade !== null) {
2586 $current->grade = floatval($current->grade);
2587 }
2588 if ($current->grade !== $modified->grade) {
bf78ebd6 2589 // grade changed
09b46f0e
AA
2590 if ($this->grading_disabled($modified->userid)) {
2591 continue;
2592 }
bf78ebd6
DW
2593 if ((int)$current->lastmodified > (int)$modified->lastmodified) {
2594 // error - record has been modified since viewing the page
2595 return get_string('errorrecordmodified', 'assign');
2596 } else {
2597 $modifiedusers[$modified->userid] = $modified;
2598 }
2599 }
2600
2601 }
2a4fbc32 2602 $currentgrades->close();
bf78ebd6
DW
2603
2604 // ok - ready to process the updates
2605 foreach ($modifiedusers as $userid => $modified) {
2606 $grade = $this->get_user_grade($userid, true);
4913af93 2607 $grade->grade= grade_floatval(unformat_float($modified->grade));
bf78ebd6
DW
2608 $grade->grader= $USER->id;
2609
2610 $this->update_grade($grade);
2611
2c6a3dbf
DW
2612 // save plugins data
2613 foreach ($this->feedbackplugins as $plugin) {
2614 if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->supports_quickgrading()) {
2615 $plugin->save_quickgrading_changes($userid, $grade);
2616 }
2617 }
2618
bf78ebd6
DW
2619 // save outcomes
2620 if ($CFG->enableoutcomes) {
2621 $data = array();
2622 foreach ($modified->gradinginfo->outcomes as $outcomeid => $outcome) {
2623 $oldoutcome = $outcome->grades[$modified->userid]->grade;
2624 $newoutcome = optional_param('outcome_' . $outcomeid . '_' . $modified->userid, -1, PARAM_INT);
2625 if ($oldoutcome != $newoutcome) {
2626 $data[$outcomeid] = $newoutcome;
2627 }
2628 }
2629 if (count($data) > 0) {
2630 grade_update_outcomes('mod/assign', $this->course->id, 'mod', 'assign', $this->get_instance()->id, $userid, $data);
2631 }
2632 }
2633
bf78ebd6
DW
2634 $this->add_to_log('grade submission', $this->format_grade_for_log($grade));
2635 }
2636
2637 return get_string('quickgradingchangessaved', 'assign');
2638 }
2639
bbd0e548
DW
2640 /**
2641 * save grading options
2642 *
2643 * @return void
2644 */
2645 private function process_save_grading_options() {
2646 global $USER, $CFG;
2647
2648 // Include grading options form
2649 require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
2650
2651 // Need submit permission to submit an assignment
2652 require_capability('mod/assign:grade', $this->context);
2653
bf78ebd6 2654 $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
2655 if ($formdata = $mform->get_data()) {
2656 set_user_preference('assign_perpage', $formdata->perpage);
2657 set_user_preference('assign_filter', $formdata->filter);
2658 }
2659 }
2660
2661 /**
2662 * Take a grade object and print a short summary for the log file.
2663 * The size limit for the log file is 255 characters, so be careful not
2664 * to include too much information.
2665 *
2666 * @param stdClass $grade
2667 * @return string
2668 */
2669 private function format_grade_for_log(stdClass $grade) {
2670 global $DB;
2671
2672 $user = $DB->get_record('user', array('id' => $grade->userid), '*', MUST_EXIST);
2673
2674 $info = get_string('gradestudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user)));
2675 if ($grade->grade != '') {
bf78ebd6 2676 $info .= get_string('grade') . ': ' . $this->display_grade($grade->grade, false) . '. ';
bbd0e548
DW
2677 } else {
2678 $info .= get_string('nograde', 'assign');
2679 }
2680 if ($grade->locked) {
2681 $info .= get_string('submissionslocked', 'assign') . '. ';
2682 }
2683 return $info;
2684 }
2685
2686 /**
2687 * Take a submission object and print a short summary for the log file.
2688 * The size limit for the log file is 255 characters, so be careful not
2689 * to include too much information.
2690 *
2691 * @param stdClass $submission
2692 * @return string
2693 */
2694 private function format_submission_for_log(stdClass $submission) {
2695 $info = '';
2696 $info .= get_string('submissionstatus', 'assign') . ': ' . get_string('submissionstatus_' . $submission->status, 'assign') . '. <br>';
2697 // format_for_log here iterating every single log INFO from either submission or grade in every assignment plugin
2698
2699 foreach ($this->submissionplugins as $plugin) {
2700 if ($plugin->is_enabled() && $plugin->is_visible()) {
2701
2702
2703 $info .= "<br>" . $plugin->format_for_log($submission);
2704 }
2705 }
2706
2707
2708 return $info;
2709 }
2710
2711 /**
2712 * save assignment submission
2713 *
2714 * @param moodleform $mform
2715 * @return bool
2716 */
2717 private function process_save_submission(&$mform) {
2718 global $USER, $CFG;
2719
2720 // Include submission form
2721 require_once($CFG->dirroot . '/mod/assign/submission_form.php');
2722
2723 // Need submit permission to submit an assignment
2724 require_capability('mod/assign:submit', $this->context);
2725 require_sesskey();
2726
2727 $data = new stdClass();
2728 $mform = new mod_assign_submission_form(null, array($this, $data));
2729 if ($mform->is_cancelled()) {
2730 return true;
2731 }
2732 if ($data = $mform->get_data()) {
2733 $submission = $this->get_user_submission($USER->id, true); //create the submission if needed & its id
2734 $grade = $this->get_user_grade($USER->id, false); // get the grade to check if it is locked
2735 if ($grade && $grade->locked) {
2736 print_error('submissionslocked', 'assign');
2737 return true;
2738 }
2739
2740
2741 foreach ($this->submissionplugins as $plugin) {
2742 if ($plugin->is_enabled()) {
2743 if (!$plugin->save($submission, $data)) {
2744 print_error($plugin->get_error());
2745 }
2746 }
2747 }
2748
2749 $this->update_submission($submission);
2750
2751 // Logging
2752 $this->add_to_log('submit', $this->format_submission_for_log($submission));
2753
2754 if (!$this->get_instance()->submissiondrafts) {
c1d09c6f
RK
2755 $this->notify_student_submission_receipt($submission);
2756 $this->notify_graders($submission);
bbd0e548
DW
2757 }
2758 return true;
2759 }
2760 return false;
2761 }
2762
bbd0e548
DW
2763
2764 /**
2765 * Determine if this users grade is locked or overridden
2766 *
2767 * @param int $userid - The student userid
2768 * @return bool $gradingdisabled
2769 */
09b46f0e 2770 public function grading_disabled($userid) {
bbd0e548
DW
2771 global $CFG;
2772
2773 $gradinginfo = grade_get_grades($this->get_course()->id, 'mod', 'assign', $this->get_instance()->id, array($userid));
2774 if (!$gradinginfo) {
2775 return false;
2776 }
2777
2778 if (!isset($gradinginfo->items[0]->grades[$userid])) {
2779 return false;
2780 }
2781 $gradingdisabled = $gradinginfo->items[0]->grades[$userid]->locked || $gradinginfo->items[0]->grades[$userid]->overridden;
2782 return $gradingdisabled;
2783 }
2784
2785
2786 /**
2787 * Get an instance of a grading form if advanced grading is enabled
2788 * This is specific to the assignment, marker and student
2789 *
2790 * @param int $userid - The student userid
2791 * @param bool $gradingdisabled
2792 * @return mixed gradingform_instance|null $gradinginstance
2793 */
2794 private function get_grading_instance($userid, $gradingdisabled) {
2795 global $CFG, $USER;
2796
2797 $grade = $this->get_user_grade($userid, false);
2798 $grademenu = make_grades_menu($this->get_instance()->grade);
2799
2800 $advancedgradingwarning = false;
2801 $gradingmanager = get_grading_manager($this->context, 'mod_assign', 'submissions');
2802 $gradinginstance = null;
2803 if ($gradingmethod = $gradingmanager->get_active_method()) {
2804 $controller = $gradingmanager->get_controller($gradingmethod);
2805 if ($controller->is_form_available()) {
2806 $itemid = null;
2807 if ($grade) {
2808 $itemid = $grade->id;
2809 }
2810 if ($gradingdisabled && $itemid) {
2811 $gradinginstance = ($controller->get_current_instance($USER->id, $itemid));
2812 } else if (!$gradingdisabled) {
2813 $instanceid = optional_param('advancedgradinginstanceid', 0, PARAM_INT);
2814 $gradinginstance = ($controller->get_or_create_instance($instanceid, $USER->id, $itemid));
2815 }
2816 } else {
2817 $advancedgradingwarning = $controller->form_unavailable_notification();
2818 }
2819 }
2820 if ($gradinginstance) {
2821 $gradinginstance->get_controller()->set_grade_range($grademenu);
2822 }
2823 return $gradinginstance;
2824 }
2825
2826 /**
2827 * add elements to grade form
2828 *
2829 * @param MoodleQuickForm $mform
2830 * @param stdClass $data
2831 * @param array $params
2832 * @return void
2833 */
2834 public function add_grade_form_elements(MoodleQuickForm $mform, stdClass $data, $params) {
2835 global $USER, $CFG;
2836 $settings = $this->get_instance();
2837
2838 $rownum = $params['rownum'];
2839 $last = $params['last'];
2840 $useridlist = $params['useridlist'];
2841 $userid = $useridlist[$rownum];
2842 $grade = $this->get_user_grade($userid, false);
2843
2844 // add advanced grading
2845 $gradingdisabled = $this->grading_disabled($userid);
2846 $gradinginstance = $this->get_grading_instance($userid, $gradingdisabled);
2847
2848 if ($gradinginstance) {
2849 $gradingelement = $mform->addElement('grading', 'advancedgrading', get_string('grade').':', array('gradinginstance' => $gradinginstance));
2850 if ($gradingdisabled) {
2851 $gradingelement->freeze();
2852 } else {
2853 $mform->addElement('hidden', 'advancedgradinginstanceid', $gradinginstance->get_id());
2854 }
2855 } else {
2856 // use simple direct grading
2857 if ($this->get_instance()->grade > 0) {
09b46f0e 2858 $gradingelement = $mform->addElement('text', 'grade', get_string('gradeoutof', 'assign',$this->get_instance()->grade));
bbd0e548
DW
2859 $mform->addHelpButton('grade', 'gradeoutofhelp', 'assign');
2860 $mform->setType('grade', PARAM_TEXT);
09b46f0e
AA
2861 if ($gradingdisabled) {
2862 $gradingelement->freeze();
2863 }
bbd0e548
DW
2864 } else {
2865 $grademenu = make_grades_menu($this->get_instance()->grade);
2866 if (count($grademenu) > 0) {
09b46f0e 2867 $gradingelement = $mform->addElement('select', 'grade', get_string('grade').':', $grademenu);
bbd0e548 2868 $mform->setType('grade', PARAM_INT);
09b46f0e
AA
2869 if ($gradingdisabled) {
2870 $gradingelement->freeze();
2871 }
bbd0e548
DW
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
8ad459ed
DW
2898 if (has_all_capabilities(array('gradereport/grader:view', 'moodle/grade:viewall'), $this->get_course_context())) {
2899 $grade = $this->output->action_link(new moodle_url('/grade/report/grader/index.php',
2900 array('id'=>$this->get_course()->id)),
2901 $gradinginfo->items[0]->grades[$userid]->str_grade);
2902 } else {
2903 $grade = $gradinginfo->items[0]->grades[$userid]->str_grade;
2904 }
2905 $mform->addElement('static', 'finalgrade', get_string('currentgrade', 'assign').':' ,$grade);
2906
2907
c45261df 2908 $mform->addElement('static', 'progress', '', get_string('gradingstudentprogress', 'assign', array('index'=>$rownum+1, 'count'=>count($useridlist))));
bbd0e548
DW
2909
2910 // plugins
2911 $this->add_plugin_grade_elements($grade, $mform, $data);
2912
2913 // hidden params
2914 $mform->addElement('hidden', 'id', $this->get_course_module()->id);
2915 $mform->setType('id', PARAM_INT);
2916 $mform->addElement('hidden', 'rownum', $rownum);
2917 $mform->setType('rownum', PARAM_INT);
2918 $mform->addElement('hidden', 'useridlist', implode(',', $useridlist));
2919 $mform->setType('useridlist', PARAM_TEXT);
2920 $mform->addElement('hidden', 'ajax', optional_param('ajax', 0, PARAM_INT));
2921 $mform->setType('ajax', PARAM_INT);
2922
2923 $mform->addElement('hidden', 'action', 'submitgrade');
2924 $mform->setType('action', PARAM_ALPHA);
2925
2926
2927 $buttonarray=array();
2928 $buttonarray[] = $mform->createElement('submit', 'savegrade', get_string('savechanges', 'assign'));
2929 if (!$last){
2930 $buttonarray[] = $mform->createElement('submit', 'saveandshownext', get_string('savenext','assign'));
2931 }
2932 $buttonarray[] = $mform->createElement('cancel', 'cancelbutton', get_string('cancel'));
2933 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
2934 $mform->closeHeaderBefore('buttonar');
2935 $buttonarray=array();
2936
2937 if ($rownum > 0) {
2938 $buttonarray[] = $mform->createElement('submit', 'nosaveandprevious', get_string('previous','assign'));
2939 }
2940
2941 if (!$last){
2942 $buttonarray[] = $mform->createElement('submit', 'nosaveandnext', get_string('nosavebutnext', 'assign'));
2943 }
2944 $mform->addGroup($buttonarray, 'navar', '', array(' '), false);
2945 }
2946
2947
2948 /**
2949 * add elements in submission plugin form
2950 *
2951 * @param mixed $submission stdClass|null
2952 * @param MoodleQuickForm $mform
2953 * @param stdClass $data
2954 * @return void
2955 */
2956 private function add_plugin_submission_elements($submission, MoodleQuickForm $mform, stdClass $data) {
2957 foreach ($this->submissionplugins as $plugin) {
2958 if ($plugin->is_enabled() && $plugin->is_visible() && $plugin->allow_submissions()) {
2959 $mform->addElement('header', 'header_' . $plugin->get_type(), $plugin->get_name());
2960 if (!$plugin->get_form_elements($submission, $mform, $data)) {
2961 $mform->removeElement('header_' . $plugin->get_type());
2962 }
2963 }
2964 }
2965 }
2966
2967 /**
2968 * check if feedback plugins installed are enabled
2969 *
2970 * @return bool
2971 */
2972 public function is_any_feedback_plugin_enabled() {
2973 if (!isset($this->cache['any_feedback_plugin_enabled'])) {
2974 $this->cache['any_feedback_plugin_enabled'] = false;
2975 foreach ($this->feedbackplugins as $plugin) {
2976 if ($plugin->is_enabled() && $plugin->is_visible()) {
2977 $this->cache['any_feedback_plugin_enabled'] = true;
2978 break;
2979 }
2980 }
2981 }
2982
2983 return $this->cache['any_feedback_plugin_enabled'];
2984
2985 }
2986
2987 /**
2988 * check if submission plugins installed are enabled
2989 *
2990 * @return bool
2991 */
2992 public function is_any_submission_plugin_enabled() {
2993 if (!isset($this->cache['any_submission_plugin_enabled'])) {
2994 $this->cache['any_submission_plugin_enabled'] = false;
2995 foreach ($this->submissionplugins as $plugin) {
2996 if ($plugin->is_enabled() && $plugin->is_visible() && $plugin->allow_submissions()) {
2997 $this->cache['any_submission_plugin_enabled'] = true;
2998 break;
2999 }
3000 }
3001 }
3002
3003 return $this->cache['any_submission_plugin_enabled'];
3004
3005 }
3006
3007 /**
3008 * add elements to submission form
3009 * @param MoodleQuickForm $mform
3010 * @param stdClass $data
3011 * @return void
3012 */
3013 public function add_submission_form_elements(MoodleQuickForm $mform, stdClass $data) {
3014 global $USER;
3015
3016 // online text submissions
3017
3018 $submission = $this->get_user_submission($USER->id, false);
3019
3020 $this->add_plugin_submission_elements($submission, $mform, $data);
3021
3022 // hidden params
3023 $mform->addElement('hidden', 'id', $this->get_course_module()->id);
3024 $mform->setType('id', PARAM_INT);
3025
3026 $mform->addElement('hidden', 'action', 'savesubmission');
3027 $mform->setType('action', PARAM_TEXT);
3028 // buttons
3029
3030 }
3031
3032 /**
3033 * revert to draft
3034 * Uses url parameter userid
9682626e 3035 *
bbd0e548
DW
3036 * @param int $userid
3037 * @return void
3038 */
3039 private function process_revert_to_draft($userid = 0) {
3040 global $USER, $DB;
3041
3042 // Need grade permission
3043 require_capability('mod/assign:grade', $this->context);
3044 require_sesskey();
3045
3046 if (!$userid) {
3047 $userid = required_param('userid', PARAM_INT);
3048 }
3049
3050 $submission = $this->get_user_submission($userid, false);
3051 if (!$submission) {
3052 return;
3053 }
3054 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
3055 $this->update_submission($submission, false);
3056
3057 // update the modified time on the grade (grader modified)
3058 $grade = $this->get_user_grade($userid, true);
3059 $this->update_grade($grade);
3060
3061 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
3062
3063 $this->add_to_log('revert submission to draft', get_string('reverttodraftforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user))));
3064
3065 }
3066
3067 /**
3068 * lock the process
3069 * Uses url parameter userid
3070 * @param int $userid
3071 * @return void
3072 */
3073 private function process_lock($userid = 0) {
3074 global $USER, $DB;
3075
3076 // Need grade permission
3077 require_capability('mod/assign:grade', $this->context);
3078 require_sesskey();
3079
3080 if (!$userid) {
3081 $userid = required_param('userid', PARAM_INT);
3082 }
3083
3084 $grade = $this->get_user_grade($userid, true);
3085 $grade->locked = 1;
3086 $grade->grader = $USER->id;
3087 $this->update_grade($grade);
3088
3089 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
3090
3091 $this->add_to_log('lock submission', get_string('locksubmissionforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user))));
3092 }
3093
3094 /**
3095 * unlock the process
3096 *
3097 * @param int $userid
3098 * @return void
3099 */
3100 private function process_unlock($userid = 0) {
3101 global $USER, $DB;
3102
3103 // Need grade permission
3104 require_capability('mod/assign:grade', $this->context);
3105 require_sesskey();
3106
3107 if (!$userid) {
3108 $userid = required_param('userid', PARAM_INT);
3109 }
3110
3111 $grade = $this->get_user_grade($userid, true);
3112 $grade->locked = 0;
3113 $grade->grader = $USER->id;
3114 $this->update_grade($grade);
3115
3116 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
3117
3118 $this->add_to_log('unlock submission', get_string('unlocksubmissionforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user))));
3119 }
3120
c45261df
DW
3121 /**
3122 * save outcomes submitted from grading form
3123 *
3124 * @param int $userid
3125 * @param stdClass $formdata
3126 */
3127 private function process_outcomes($userid, $formdata) {
3128 global $CFG, $USER;
3129
3130 if (empty($CFG->enableoutcomes)) {
3131 return;
3132 }
09b46f0e
AA
3133 if ($this->grading_disabled($userid)) {
3134 return;
3135 }
c45261df
DW
3136
3137 require_once($CFG->libdir.'/gradelib.php');
3138
3139 $data = array();
3140 $gradinginfo = grade_get_grades($this->get_course()->id,
3141 'mod',
3142 'assign',
3143 $this->get_instance()->id,
3144 $userid);
3145
3146 if (!empty($gradinginfo->outcomes)) {
3147 foreach($gradinginfo->outcomes as $index=>$oldoutcome) {
3148 $name = 'outcome_'.$index;
3149 if (isset($formdata->{$name}[$userid]) and $oldoutcome->grades[$userid]->grade != $formdata->{$name}[$userid]) {
3150 $data[$index] = $formdata->{$name}[$userid];
3151 }
3152 }
3153 }
3154 if (count($data) > 0) {
3155 grade_update_outcomes('mod/assign', $this->course->id, 'mod', 'assign', $this->get_instance()->id, $userid, $data);
3156 }
3157
3158 }
3159
3160
bbd0e548
DW
3161 /**
3162 * save grade
3163 *
3164 * @param moodleform $mform
3165 * @return bool - was the grade saved
3166 */
3167 private function process_save_grade(&$mform) {
3168 global $USER, $DB, $CFG;
3169 // Include grade form
3170 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
3171
3172 // Need submit permission to submit an assignment
3173 require_capability('mod/assign:grade', $this->context);
3174 require_sesskey();
3175
3176 $rownum = required_param('rownum', PARAM_INT);
3177 $useridlist = optional_param('useridlist', '', PARAM_TEXT);
3178 if ($useridlist) {
3179 $useridlist = explode(',', $useridlist);
3180 } else {
3181 $useridlist = $this->get_grading_userid_list();
3182 }
3183 $last = false;
3184 $userid = $useridlist[$rownum];
3185 if ($rownum == count($useridlist) - 1) {
3186 $last = true;
3187 }
3188
3189 $data = new stdClass();
3190 $mform = new mod_assign_grade_form(null, array($this, $data, array('rownum'=>$rownum, 'useridlist'=>$useridlist, 'last'=>false)), 'post', '', array('class'=>'gradeform'));
3191
3192 if ($formdata = $mform->get_data()) {
3193 $grade = $this->get_user_grade($userid, true);
3194 $gradingdisabled = $this->grading_disabled($userid);
3195 $gradinginstance = $this->get_grading_instance($userid, $gradingdisabled);
09b46f0e
AA
3196 if (!$gradingdisabled) {
3197 if ($gradinginstance) {
3198 $grade->grade = $gradinginstance->submit_and_get_grade($formdata->advancedgrading, $grade->id);
3199 } else {
3200 // handle the case when grade is set to No Grade
3201 if (isset($formdata->grade)) {
3202 $grade->grade = grade_floatval(unformat_float($formdata->grade));
3203 }
bbd0e548
DW
3204 }
3205 }
3206 $grade->grader= $USER->id;
3207
cfc81f03
DW
3208 $adminconfig = $this->get_admin_config();
3209 $gradebookplugin = $adminconfig->feedback_plugin_for_gradebook;
bbd0e548
DW
3210
3211 // call save in plugins
3212 foreach ($this->feedbackplugins as $plugin) {
3213 if ($plugin->is_enabled() && $plugin->is_visible()) {
3214 if (!$plugin->save($grade, $formdata)) {
3215 $result = false;
3216 print_error($plugin->get_error());
3217 }
3218 if (('assignfeedback_' . $plugin->get_type()) == $gradebookplugin) {
3219 // this is the feedback plugin chose to push comments to the gradebook
3220 $grade->feedbacktext = $plugin->text_for_gradebook($grade);
3221 $grade->feedbackformat = $plugin->format_for_gradebook($grade);
3222 }
3223 }
3224 }
c45261df 3225 $this->process_outcomes($userid, $formdata);
75f87a57
DW
3226
3227 $grade->mailed = 0;
3228
bbd0e548
DW
3229 $this->update_grade($grade);
3230
3231 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
3232
3233 $this->add_to_log('grade submission', $this->format_grade_for_log($grade));
3234
3235
3236 } else {
3237 return false;
3238 }
3239 return true;
3240 }
3241
3242 /**
3243 * This function is a static wrapper around can_upgrade
3244 *
3245 * @param string $type The plugin type
3246 * @param int $version The plugin version
3247 * @return bool
3248 */
3249 public static function can_upgrade_assignment($type, $version) {
3250 $assignment = new assign(null, null, null);
3251 return $assignment->can_upgrade($type, $version);
3252 }
3253
3254 /**
3255 * This function returns true if it can upgrade an assignment from the 2.2
3256 * module.
3257 * @param string $type The plugin type
3258 * @param int $version The plugin version
3259 * @return bool
3260 */
3261 public function can_upgrade($type, $version) {
3262 if ($type == 'offline' && $version >= 2011112900) {
3263 return true;
3264 }
3265 foreach ($this->submissionplugins as $plugin) {
3266 if ($plugin->can_upgrade($type, $version)) {
3267 return true;
3268 }
3269 }
3270 foreach ($this->feedbackplugins as $plugin) {
3271 if ($plugin->can_upgrade($type, $version)) {
3272 return true;
3273 }
3274 }
3275 return false;
3276 }
3277
3278 /**
3279 * Copy all the files from the old assignment files area to the new one.
3280 * This is used by the plugin upgrade code.
3281 *
3282 * @param int $oldcontextid The old assignment context id
3283 * @param int $oldcomponent The old assignment component ('assignment')
3284 * @param int $oldfilearea The old assignment filearea ('submissions')
3285 * @param int $olditemid The old submissionid (can be null e.g. intro)
3286 * @param int $newcontextid The new assignment context id
3287 * @param int $newcomponent The new assignment component ('assignment')
3288 * @param int $newfilearea The new assignment filearea ('submissions')
3289 * @param int $newitemid The new submissionid (can be null e.g. intro)
3290 * @return int The number of files copied
3291 */
3292 public function copy_area_files_for_upgrade($oldcontextid, $oldcomponent, $oldfilearea, $olditemid, $newcontextid, $newcomponent, $newfilearea, $newitemid) {
3293 // Note, this code is based on some code in filestorage - but that code
3294 // deleted the old files (which we don't want)
3295 $count = 0;
3296
3297 $fs = get_file_storage();
3298
3299 $oldfiles = $fs->get_area_files($oldcontextid, $oldcomponent, $oldfilearea, $olditemid, 'id', false);
3300 foreach ($oldfiles as $oldfile) {
3301 $filerecord = new stdClass();
3302 $filerecord->contextid = $newcontextid;
3303 $filerecord->component = $newcomponent;
3304 $filerecord->filearea = $newfilearea;
3305 $filerecord->itemid = $newitemid;
3306 $fs->create_file_from_storedfile($filerecord, $oldfile);
3307 $count += 1;
3308 }
3309
3310 return $count;
3311 }
3312
3313 /**
3314 * Get an upto date list of user grades and feedback for the gradebook
3315 *
3316 * @param int $userid int or 0 for all users
3317 * @return array of grade data formated for the gradebook api
3318 * The data required by the gradebook api is userid,
3319 * rawgrade,
3320 * feedback,
3321 * feedbackformat,
3322 * usermodified,
3323 * dategraded,
3324 * datesubmitted
3325 */
3326 public function get_user_grades_for_gradebook($userid) {
3327 global $DB, $CFG;
3328 $grades = array();
3329 $assignmentid = $this->get_instance()->id;
3330
b11808c7
DW
3331 $adminconfig = $this->get_admin_config();
3332 $gradebookpluginname = $adminconfig->feedback_plugin_for_gradebook;
bbd0e548
DW
3333 $gradebookplugin = null;
3334
3335 // find the gradebook plugin
3336 foreach ($this->feedbackplugins as $plugin) {
3337 if ($plugin->is_enabled() && $plugin->is_visible()) {
3338 if (('assignfeedback_' . $plugin->get_type()) == $gradebookpluginname) {
3339 $gradebookplugin = $plugin;
3340 }
3341 }
3342 }
3343 if ($userid) {
3344 $where = ' WHERE u.id = ? ';
3345 } else {
3346 $where = ' WHERE u.id != ? ';
3347 }
3348
3349 $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
3350 FROM {user} u
3351 LEFT JOIN {assign_submission} s ON u.id = s.userid and s.assignment = ?
3352 LEFT JOIN {assign_grades} g ON u.id = g.userid and g.assignment = ?
3353 ' . $where, array($assignmentid, $assignmentid, $userid));
3354
3355
3356 foreach ($graderesults as $result) {
3357 $gradebookgrade = clone $result;
3358 // now get the feedback
3359 if ($gradebookplugin) {
3360 $grade = $this->get_user_grade($result->userid, false);
14c46e24
DW
3361 if ($grade) {
3362 $gradebookgrade->feedbacktext = $gradebookplugin->text_for_gradebook($grade);
3363 $gradebookgrade->feedbackformat = $gradebookplugin->format_for_gradebook($grade);
3364 }
bbd0e548
DW
3365 }
3366 $grades[$gradebookgrade->userid] = $gradebookgrade;
3367 }
3368
3369 $graderesults->close();
3370 return $grades;
3371 }
3372
3373}
3374