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