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