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