MDL-35740 Assignment: Hide the number of assignment submissions for all students...
[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
be79d93f
DW
1025 $o = '';
1026
2a4fbc32
SH
1027 if ($this->get_instance()->grade >= 0) {
1028 // Normal number
e7ade405 1029 if ($editing && $this->get_instance()->grade > 0) {
2d8a9ce9
DW
1030 if ($grade < 0) {
1031 $displaygrade = '';
1032 } else {
1033 $displaygrade = format_float($grade);
1034 }
be79d93f 1035 $o .= '<label class="accesshide" for="quickgrade_' . $userid . '">' . get_string('usergrade', 'assign') . '</label>';
6aa4fccc 1036 $o .= '<input type="text" id="quickgrade_' . $userid . '" name="quickgrade_' . $userid . '" value="' .
be79d93f 1037 $displaygrade . '" size="6" maxlength="10" class="quickgrade"/>';
bf78ebd6 1038 $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade,2);
2a4fbc32 1039 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
bf78ebd6 1040 return $o;
bbd0e548 1041 } else {
be79d93f 1042 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
a1e54f4d 1043 if ($grade == -1 || $grade === null) {
be79d93f
DW
1044 $o .= '-';
1045 return $o;
a1e54f4d 1046 } else {
be79d93f
DW
1047 $o .= format_float(($grade),2) .'&nbsp;/&nbsp;'. format_float($this->get_instance()->grade,2);
1048 return $o;
a1e54f4d 1049 }
bbd0e548
DW
1050 }
1051
2a4fbc32
SH
1052 } else {
1053 // Scale
bbd0e548
DW
1054 if (empty($this->cache['scale'])) {
1055 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
1056 $this->cache['scale'] = make_menu_from_list($scale->scale);
1057 } else {
be79d93f
DW
1058 $o .= '-';
1059 return $o;
bbd0e548
DW
1060 }
1061 }
bf78ebd6 1062 if ($editing) {
be79d93f 1063 $o .= '<label class="accesshide" for="quickgrade_' . $userid . '">' . get_string('usergrade', 'assign') . '</label>';
7400be1b 1064 $o .= '<select name="quickgrade_' . $userid . '" class="quickgrade">';
bf78ebd6
DW
1065 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
1066 foreach ($this->cache['scale'] as $optionid => $option) {
1067 $selected = '';
1068 if ($grade == $optionid) {
1069 $selected = 'selected="selected"';
1070 }
1071 $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
1072 }
1073 $o .= '</select>';
1074 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
1075 return $o;
1076 } else {
1077 $scaleid = (int)$grade;
1078 if (isset($this->cache['scale'][$scaleid])) {
be79d93f
DW
1079 $o .= $this->cache['scale'][$scaleid];
1080 return $o;
bf78ebd6 1081 }
be79d93f
DW
1082 $o .= '-';
1083 return $o;
bbd0e548 1084 }
bbd0e548
DW
1085 }
1086 }
1087
1088 /**
1089 * Load a list of users enrolled in the current course with the specified permission and group (0 for no group)
1090 *
1091 * @param int $currentgroup
1092 * @param bool $idsonly
1093 * @return array List of user records
1094 */
1095 public function list_participants($currentgroup, $idsonly) {
1096 if ($idsonly) {
1097 return get_enrolled_users($this->context, "mod/assign:submit", $currentgroup, 'u.id');
1098 } else {
1099 return get_enrolled_users($this->context, "mod/assign:submit", $currentgroup);
1100 }
1101 }
1102
12a1a0da
DW
1103 /**
1104 * Load a count of valid teams for this assignment
1105 *
1106 * @return int number of valid teams
1107 */
1108 public function count_teams() {
1109
1110 $groups = groups_get_all_groups($this->get_course()->id, 0, $this->get_instance()->teamsubmissiongroupingid, 'g.id');
1111 $count = count($groups);
1112
1113 // See if there are any users in the default group.
1114 $defaultusers = $this->get_submission_group_members(0, true);
1115 if (count($defaultusers) > 0) {
1116 $count += 1;
1117 }
1118 return $count;
1119 }
1120
bbd0e548
DW
1121 /**
1122 * Load a count of users enrolled in the current course with the specified permission and group (0 for no group)
1123 *
1124 * @param int $currentgroup
1125 * @return int number of matching users
1126 */
1127 public function count_participants($currentgroup) {
1128 return count_enrolled_users($this->context, "mod/assign:submit", $currentgroup);
1129 }
1130
f70079b9
DW
1131 /**
1132 * Load a count of users submissions in the current module that require grading
1133 * This means the submission modification time is more recent than the
7a9fd6da 1134 * grading modification time and the status is SUBMITTED.
f70079b9
DW
1135 *
1136 * @return int number of matching submissions
1137 */
1138 public function count_submissions_need_grading() {
1139 global $DB;
1140
8f7e1c05
DW
1141 if ($this->get_instance()->teamsubmission) {
1142 // This does not make sense for group assignment because the submission is shared.
1143 return 0;
1144 }
1145
1146 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1147 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1148
1149 $params['assignid'] = $this->get_instance()->id;
1150 $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1151
1152 $sql = 'SELECT COUNT(s.userid)
1153 FROM {assign_submission} s
1154 LEFT JOIN {assign_grades} g ON
1155 s.assignment = g.assignment AND
1156 s.userid = g.userid
0c7b6910 1157 JOIN(' . $esql . ') e ON e.id = s.userid
8f7e1c05
DW
1158 WHERE
1159 s.assignment = :assignid AND
1160 s.timemodified IS NOT NULL AND
1161 s.status = :submitted AND
1162 (s.timemodified > g.timemodified OR g.timemodified IS NULL)';
f70079b9 1163
8f7e1c05 1164 return $DB->count_records_sql($sql, $params);
f70079b9
DW
1165 }
1166
bbd0e548 1167 /**
b473171a
DW
1168 * Load a count of grades
1169 *
1170 * @return int number of grades
1171 */
1172 public function count_grades() {
1173 global $DB;
1174
1175 if (!$this->has_instance()) {
1176 return 0;
1177 }
1178
8f7e1c05
DW
1179 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1180 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1181
1182 $params['assignid'] = $this->get_instance()->id;
1183
1184 $sql = 'SELECT COUNT(g.userid)
1185 FROM {assign_grades} g
0c7b6910 1186 JOIN(' . $esql . ') e ON e.id = g.userid
8f7e1c05 1187 WHERE g.assignment = :assignid';
b473171a
DW
1188
1189 return $DB->count_records_sql($sql, $params);
1190 }
1191
1192 /**
1193 * Load a count of submissions
1194 *
1195 * @return int number of submissions
1196 */
1197 public function count_submissions() {
1198 global $DB;
1199
1200 if (!$this->has_instance()) {
1201 return 0;
1202 }
1203
8f7e1c05 1204 $params = array();
b473171a
DW
1205
1206 if ($this->get_instance()->teamsubmission) {
8f7e1c05
DW
1207 // We cannot join on the enrolment tables for group submissions (no userid).
1208 $sql = 'SELECT COUNT(s.groupid)
1209 FROM {assign_submission} s
1210 WHERE
1211 s.assignment = :assignid AND
1212 s.timemodified IS NOT NULL AND
1213 s.userid = :groupuserid';
1214
1215 $params['assignid'] = $this->get_instance()->id;
1216 $params['groupuserid'] = 0;
1217 } else {
1218 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1219 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1220
1221 $params['assignid'] = $this->get_instance()->id;
1222
1223 $sql = 'SELECT COUNT(s.userid)
1224 FROM {assign_submission} s
0c7b6910 1225 JOIN(' . $esql . ') e ON e.id = s.userid
8f7e1c05
DW
1226 WHERE
1227 s.assignment = :assignid AND
1228 s.timemodified IS NOT NULL';
b473171a 1229 }
8f7e1c05 1230
b473171a
DW
1231 return $DB->count_records_sql($sql, $params);
1232 }
1233
1234 /**
1235 * Load a count of submissions with a specified status
bbd0e548
DW
1236 *
1237 * @param string $status The submission status - should match one of the constants
1238 * @return int number of matching submissions
1239 */
1240 public function count_submissions_with_status($status) {
1241 global $DB;
8f7e1c05
DW
1242
1243 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1244 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1245
1246 $params['assignid'] = $this->get_instance()->id;
1247 $params['submissionstatus'] = $status;
12a1a0da
DW
1248
1249 if ($this->get_instance()->teamsubmission) {
8f7e1c05
DW
1250 $sql = 'SELECT COUNT(s.groupid)
1251 FROM {assign_submission} s
1252 WHERE
1253 s.assignment = :assignid AND
1254 s.timemodified IS NOT NULL AND
1255 s.userid = :groupuserid AND
1256 s.status = :submissionstatus';
1257 $params['groupuserid'] = 0;
1258 } else {
1259 $sql = 'SELECT COUNT(s.userid)
1260 FROM {assign_submission} s
0c7b6910 1261 JOIN(' . $esql . ') e ON e.id = s.userid
8f7e1c05
DW
1262 WHERE
1263 s.assignment = :assignid AND
1264 s.timemodified IS NOT NULL AND
1265 s.status = :submissionstatus';
12a1a0da 1266 }
8f7e1c05 1267
12a1a0da 1268 return $DB->count_records_sql($sql, $params);
bbd0e548
DW
1269 }
1270
1271 /**
1272 * Utility function to get the userid for every row in the grading table
1273 * so the order can be frozen while we iterate it
1274 *
1275 * @return array An array of userids
1276 */
12a1a0da 1277 private function get_grading_userid_list() {
bbd0e548 1278 $filter = get_user_preferences('assign_filter', '');
bf78ebd6 1279 $table = new assign_grading_table($this, 0, $filter, 0, false);
bbd0e548
DW
1280
1281 $useridlist = $table->get_column_data('userid');
1282
1283 return $useridlist;
1284 }
1285
1286
1287 /**
1288 * Utility function get the userid based on the row number of the grading table.
1289 * This takes into account any active filters on the table.
1290 *
1291 * @param int $num The row number of the user
1292 * @param bool $last This is set to true if this is the last user in the table
1293 * @return mixed The user id of the matching user or false if there was an error
1294 */
12a1a0da 1295 private function get_userid_for_row($num, $last) {
bbd0e548
DW
1296 if (!array_key_exists('userid_for_row', $this->cache)) {
1297 $this->cache['userid_for_row'] = array();
1298 }
1299 if (array_key_exists($num, $this->cache['userid_for_row'])) {
1300 list($userid, $last) = $this->cache['userid_for_row'][$num];
1301 return $userid;
1302 }
1303
1304 $filter = get_user_preferences('assign_filter', '');
bf78ebd6 1305 $table = new assign_grading_table($this, 0, $filter, 0, false);
bbd0e548
DW
1306
1307 $userid = $table->get_cell_data($num, 'userid', $last);
1308
1309 $this->cache['userid_for_row'][$num] = array($userid, $last);
1310 return $userid;
1311 }
1312
bbd0e548
DW
1313 /**
1314 * Generate zip file from array of given files
1315 *
1316 * @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
1317 * @return path of temp file - note this returned file does not have a .zip extension - it is a temp file.
1318 */
1319 private function pack_files($filesforzipping) {
1320 global $CFG;
1321 //create path for new zip file.
1322 $tempzip = tempnam($CFG->tempdir.'/', 'assignment_');
1323 //zip files
1324 $zipper = new zip_packer();
1325 if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
1326 return $tempzip;
1327 }
1328 return false;
1329 }
1330
bbd0e548 1331 /**
3f7b501e
SH
1332 * Finds all assignment notifications that have yet to be mailed out, and mails them.
1333 *
1334 * Cron function to be run periodically according to the moodle cron
bbd0e548
DW
1335 *
1336 * @return bool
1337 */
1338 static function cron() {
3f7b501e 1339 global $DB;
75f87a57
DW
1340
1341 // only ever send a max of one days worth of updates
1342 $yesterday = time() - (24 * 3600);
1343 $timenow = time();
1344
3f7b501e 1345 // Collect all submissions from the past 24 hours that require mailing.
b473171a
DW
1346 $sql = "SELECT s.*, a.course, a.name, a.blindmarking, a.revealidentities,
1347 g.*, g.id as gradeid, g.timemodified as lastmodified
3f7b501e
SH
1348 FROM {assign} a
1349 JOIN {assign_grades} g ON g.assignment = a.id
1350 LEFT JOIN {assign_submission} s ON s.assignment = a.id AND s.userid = g.userid
1351 WHERE g.timemodified >= :yesterday AND
1352 g.timemodified <= :today AND
1353 g.mailed = 0";
1354 $params = array('yesterday' => $yesterday, 'today' => $timenow);
1355 $submissions = $DB->get_records_sql($sql, $params);
75f87a57 1356
c8314005
SH
1357 if (empty($submissions)) {
1358 mtrace('done.');
1359 return true;
1360 }
1361
75f87a57
DW
1362 mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
1363
3f7b501e
SH
1364 // Preload courses we are going to need those.
1365 $courseids = array();
1366 foreach ($submissions as $submission) {
1367 $courseids[] = $submission->course;
1368 }
1369 // Filter out duplicates
1370 $courseids = array_unique($courseids);
1371 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1372 list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
1373 $sql = "SELECT c.*, {$ctxselect}
1374 FROM {course} c
1375 LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
1376 WHERE c.id {$courseidsql}";
1377 $params['contextlevel'] = CONTEXT_COURSE;
1378 $courses = $DB->get_records_sql($sql, $params);
1379 // Clean up... this could go on for a while.
1380 unset($courseids);
1381 unset($ctxselect);
1382 unset($courseidsql);
1383 unset($params);
1384
1385 // Simple array we'll use for caching modules.
1386 $modcache = array();
1387
c1d09c6f 1388 // Message students about new feedback
75f87a57
DW
1389 foreach ($submissions as $submission) {
1390
1391 mtrace("Processing assignment submission $submission->id ...");
1392
1393 // do not cache user lookups - could be too many
3f7b501e 1394 if (!$user = $DB->get_record("user", array("id"=>$submission->userid))) {
75f87a57
DW
1395 mtrace("Could not find user $submission->userid");
1396 continue;
1397 }
1398
1399 // use a cache to prevent the same DB queries happening over and over
3f7b501e
SH
1400 if (!array_key_exists($submission->course, $courses)) {
1401 mtrace("Could not find course $submission->course");
1402 continue;
1403 }
1404 $course = $courses[$submission->course];
1405 if (isset($course->ctxid)) {
1406 // Context has not yet been preloaded. Do so now.
1407 context_helper::preload_from_record($course);
75f87a57
DW
1408 }
1409
3f7b501e
SH
1410 // Override the language and timezone of the "current" user, so that
1411 // mail is customised for the receiver.
75f87a57
DW
1412 cron_setup_user($user, $course);
1413
1414 // context lookups are already cached
3f7b501e 1415 $coursecontext = context_course::instance($course->id);
75f87a57 1416 if (!is_enrolled($coursecontext, $user->id)) {
3f7b501e 1417 $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
75f87a57
DW
1418 mtrace(fullname($user)." not an active participant in " . $courseshortname);
1419 continue;
1420 }
1421
3f7b501e 1422 if (!$grader = $DB->get_record("user", array("id"=>$submission->grader))) {
75f87a57
DW
1423 mtrace("Could not find grader $submission->grader");
1424 continue;
1425 }
1426
3f7b501e 1427 if (!array_key_exists($submission->assignment, $modcache)) {
75f87a57
DW
1428 if (! $mod = get_coursemodule_from_instance("assign", $submission->assignment, $course->id)) {
1429 mtrace("Could not find course module for assignment id $submission->assignment");
1430 continue;
1431 }
3f7b501e
SH
1432 $modcache[$submission->assignment] = $mod;
1433 } else {
1434 $mod = $modcache[$submission->assignment];
75f87a57 1435 }
75f87a57
DW
1436 // context lookups are already cached
1437 $contextmodule = context_module::instance($mod->id);
bbd0e548 1438
3f7b501e
SH
1439 if (!$mod->visible) {
1440 // Hold mail notification for hidden assignments until later
75f87a57
DW
1441 continue;
1442 }
1443
1444 // need to send this to the student
3f7b501e 1445 $messagetype = 'feedbackavailable';
f750cf71 1446 $eventtype = 'assign_notification';
3f7b501e
SH
1447 $updatetime = $submission->lastmodified;
1448 $modulename = get_string('modulename', 'assign');
b473171a
DW
1449
1450 $uniqueid = 0;
1451 if ($submission->blindmarking && !$submission->revealidentities) {
1452 $uniqueid = self::get_uniqueid_for_user_static($submission->assignment, $user->id);
1453 }
1454 self::send_assignment_notification($grader, $user, $messagetype, $eventtype, $updatetime,
1455 $mod, $contextmodule, $course, $modulename, $submission->name,
1456 $submission->blindmarking && !$submission->revealidentities,
1457 $uniqueid);
75f87a57
DW
1458
1459 $grade = new stdClass();
1460 $grade->id = $submission->gradeid;
1461 $grade->mailed = 1;
1462 $DB->update_record('assign_grades', $grade);
1463
1464 mtrace('Done');
1465 }
1466 mtrace('Done processing ' . count($submissions) . ' assignment submissions');
1467
1468 cron_setup_user();
3f7b501e
SH
1469
1470 // Free up memory just to be sure
1471 unset($courses);
1472 unset($modcache);
bbd0e548
DW
1473
1474 return true;
1475 }
1476
1477 /**
1478 * Update a grade in the grade table for the assignment and in the gradebook
1479 *
1480 * @param stdClass $grade a grade record keyed on id
1481 * @return bool true for success
1482 */
df47b77f 1483 public function update_grade($grade) {
bbd0e548
DW
1484 global $DB;
1485
1486 $grade->timemodified = time();
1487
1488 if ($grade->grade && $grade->grade != -1) {
1489 if ($this->get_instance()->grade > 0) {
1490 if (!is_numeric($grade->grade)) {
1491 return false;
1492 } else if ($grade->grade > $this->get_instance()->grade) {
1493 return false;
1494 } else if ($grade->grade < 0) {
1495 return false;
1496 }
1497 } else {
1498 // this is a scale
1499 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
1500 $scaleoptions = make_menu_from_list($scale->scale);
1501 if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
1502 return false;
1503 }
1504 }
1505 }
1506 }
1507
1508 $result = $DB->update_record('assign_grades', $grade);
1509 if ($result) {
1510 $this->gradebook_item_update(null, $grade);
1511 }
1512 return $result;
1513 }
1514
9e795179
DW
1515 /**
1516 * View the grant extension date page
1517 *
1518 * Uses url parameters 'userid'
1519 * or from parameter 'selectedusers'
1520 * @param moodleform $mform - Used for validation of the submitted data
1521 * @return string
1522 */
1523 private function view_grant_extension($mform) {
1524 global $DB, $CFG;
1525 require_once($CFG->dirroot . '/mod/assign/extensionform.php');
1526
1527 $o = '';
1528 $batchusers = optional_param('selectedusers', '', PARAM_TEXT);
1529 $data = new stdClass();
1530 $data->extensionduedate = null;
1531 $userid = 0;
1532 if (!$batchusers) {
1533 $userid = required_param('userid', PARAM_INT);
1534
1535 $grade = $this->get_user_grade($userid, false);
1536
1537 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
1538
1539 if ($grade) {
1540 $data->extensionduedate = $grade->extensionduedate;
1541 }
1542 $data->userid = $userid;
1543 } else {
1544 $data->batchusers = $batchusers;
1545 }
49d83b9d 1546 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
9e795179
DW
1547 $this->get_context(),
1548 $this->show_intro(),
1549 $this->get_course_module()->id,
1550 get_string('grantextension', 'assign')));
1551
1552 if (!$mform) {
1553 $mform = new mod_assign_extension_form(null, array($this->get_course_module()->id,
1554 $userid,
1555 $batchusers,
1556 $this->get_instance(),
1557 $data));
1558 }
49d83b9d 1559 $o .= $this->get_renderer()->render(new assign_form('extensionform', $mform));
9e795179
DW
1560 $o .= $this->view_footer();
1561 return $o;
1562 }
1563
12a1a0da
DW
1564 /**
1565 * Get a list of the users in the same group as this user
1566 *
1567 * @param int $groupid The id of the group whose members we want or 0 for the default group
1568 * @param bool $onlyids Whether to retrieve only the user id's
1569 * @return array The users (possibly id's only)
1570 */
1571 public function get_submission_group_members($groupid, $onlyids) {
1572 $members = array();
1573 if ($groupid != 0) {
1574 if ($onlyids) {
1575 $allusers = groups_get_members($groupid, 'u.id');
1576 } else {
1577 $allusers = groups_get_members($groupid);
1578 }
1579 foreach ($allusers as $user) {
1580 if ($this->get_submission_group($user->id)) {
1581 $members[] = $user;
1582 }
1583 }
1584 } else {
1585 $allusers = $this->list_participants(null, $onlyids);
1586 foreach ($allusers as $user) {
1587 if ($this->get_submission_group($user->id) == null) {
1588 $members[] = $user;
1589 }
1590 }
1591 }
1592 return $members;
1593 }
1594
1595 /**
1596 * Get a list of the users in the same group as this user that have not submitted the assignment
1597 *
1598 * @param int $groupid The id of the group whose members we want or 0 for the default group
1599 * @param bool $onlyids Whether to retrieve only the user id's
1600 * @return array The users (possibly id's only)
1601 */
1602 public function get_submission_group_members_who_have_not_submitted($groupid, $onlyids) {
1603 if (!$this->get_instance()->teamsubmission || !$this->get_instance()->requireallteammemberssubmit) {
1604 return array();
1605 }
1606 $members = $this->get_submission_group_members($groupid, $onlyids);
1607
1608 foreach ($members as $id => $member) {
1609 $submission = $this->get_user_submission($member->id, false);
1610 if ($submission && $submission->status != ASSIGN_SUBMISSION_STATUS_DRAFT) {
1611 unset($members[$id]);
88cfe469
DW
1612 } else {
1613 if ($this->is_blind_marking()) {
1614 $members[$id]->alias = get_string('hiddenuser', 'assign') . $this->get_uniqueid_for_user($id);
1615 }
12a1a0da
DW
1616 }
1617 }
1618 return $members;
1619 }
1620
1621 /**
1622 * Load the group submission object for a particular user, optionally creating it if required
1623 *
1624 * This will create the user submission and the group submission if required
1625 *
1626 * @param int $userid The id of the user whose submission we want
1627 * @param int $groupid The id of the group for this user - may be 0 in which case it is determined from the userid
1628 * @param bool $create If set to true a new submission object will be created in the database
1629 * @return stdClass The submission
1630 */
1631 public function get_group_submission($userid, $groupid, $create) {
1632 global $DB;
1633
1634 if ($groupid == 0) {
1635 $group = $this->get_submission_group($userid);
1636 if ($group) {
1637 $groupid = $group->id;
1638 }
1639 }
1640
1641 if ($create) {
1642 // Make sure there is a submission for this user.
1643 $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>0, 'userid'=>$userid);
1644 $submission = $DB->get_record('assign_submission', $params);
1645
1646 if (!$submission) {
1647 $submission = new stdClass();
1648 $submission->assignment = $this->get_instance()->id;
1649 $submission->userid = $userid;
1650 $submission->groupid = 0;
1651 $submission->timecreated = time();
1652 $submission->timemodified = $submission->timecreated;
1653
1654 if ($this->get_instance()->submissiondrafts) {
1655 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
1656 } else {
1657 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1658 }
1659 $DB->insert_record('assign_submission', $submission);
1660 }
1661 }
1662 // Now get the group submission.
1663 $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
1664 $submission = $DB->get_record('assign_submission', $params);
1665
1666 if ($submission) {
1667 return $submission;
1668 }
1669 if ($create) {
1670 $submission = new stdClass();
1671 $submission->assignment = $this->get_instance()->id;
1672 $submission->userid = 0;
1673 $submission->groupid = $groupid;
1674 $submission->timecreated = time();
1675 $submission->timemodified = $submission->timecreated;
1676
1677 if ($this->get_instance()->submissiondrafts) {
1678 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
1679 } else {
1680 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1681 }
1682 $sid = $DB->insert_record('assign_submission', $submission);
1683 $submission->id = $sid;
1684 return $submission;
1685 }
1686 return false;
1687 }
1688
df47b77f
DW
1689 /**
1690 * View a page rendered by a plugin
1691 *
1692 * Uses url parameters 'pluginaction', 'pluginsubtype', 'plugin', and 'id'
1693 *
1694 * @return string
1695 */
1696 private function view_plugin_page() {
1697 global $USER;
1698
1699 $o = '';
1700
1701 $pluginsubtype = required_param('pluginsubtype', PARAM_ALPHA);
1702 $plugintype = required_param('plugin', PARAM_TEXT);
1703 $pluginaction = required_param('pluginaction', PARAM_ALPHA);
1704
1705 $plugin = $this->get_plugin_by_type($pluginsubtype, $plugintype);
1706 if (!$plugin) {
1707 print_error('invalidformdata', '');
1708 return;
1709 }
1710
1711 $o .= $plugin->view_page($pluginaction);
1712
1713 return $o;
1714 }
1715
1716
12a1a0da
DW
1717 /**
1718 * This is used for team assignments to get the group for the specified user.
1719 * If the user is a member of multiple or no groups this will return false
1720 *
1721 * @param int $userid The id of the user whose submission we want
1722 * @return mixed The group or false
1723 */
1724 public function get_submission_group($userid) {
1725 $groups = groups_get_all_groups($this->get_course()->id, $userid, $this->get_instance()->teamsubmissiongroupingid);
1726 if (count($groups) != 1) {
1727 return false;
1728 }
1729 return array_pop($groups);
1730 }
1731
9e795179 1732
bbd0e548
DW
1733 /**
1734 * display the submission that is used by a plugin
1735 * Uses url parameters 'sid', 'gid' and 'plugin'
1736 * @param string $pluginsubtype
1737 * @return string
1738 */
1739 private function view_plugin_content($pluginsubtype) {
1740 global $USER;
1741
1742 $o = '';
1743
1744 $submissionid = optional_param('sid', 0, PARAM_INT);
1745 $gradeid = optional_param('gid', 0, PARAM_INT);
1746 $plugintype = required_param('plugin', PARAM_TEXT);
1747 $item = null;
1748 if ($pluginsubtype == 'assignsubmission') {
1749 $plugin = $this->get_submission_plugin_by_type($plugintype);
1750 if ($submissionid <= 0) {
1751 throw new coding_exception('Submission id should not be 0');
1752 }
1753 $item = $this->get_submission($submissionid);
1754
1755 // permissions
1756 if ($item->userid != $USER->id) {
1757 require_capability('mod/assign:grade', $this->context);
1758 }
49d83b9d 1759 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
bbd0e548
DW
1760 $this->get_context(),
1761 $this->show_intro(),
1762 $this->get_course_module()->id,
1763 $plugin->get_name()));
49d83b9d 1764 $o .= $this->get_renderer()->render(new assign_submission_plugin_submission($plugin,
bbd0e548
DW
1765 $item,
1766 assign_submission_plugin_submission::FULL,
1767 $this->get_course_module()->id,
1768 $this->get_return_action(),
1769 $this->get_return_params()));
1770
1771 $this->add_to_log('view submission', get_string('viewsubmissionforuser', 'assign', $item->userid));
1772 } else {
1773 $plugin = $this->get_feedback_plugin_by_type($plugintype);
1774 if ($gradeid <= 0) {
1775 throw new coding_exception('Grade id should not be 0');
1776 }
1777 $item = $this->get_grade($gradeid);
1778 // permissions
1779 if ($item->userid != $USER->id) {
1780 require_capability('mod/assign:grade', $this->context);
1781 }
49d83b9d 1782 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
bbd0e548
DW
1783 $this->get_context(),
1784 $this->show_intro(),
1785 $this->get_course_module()->id,
1786 $plugin->get_name()));
49d83b9d 1787 $o .= $this->get_renderer()->render(new assign_feedback_plugin_feedback($plugin,
bbd0e548
DW
1788 $item,
1789 assign_feedback_plugin_feedback::FULL,
1790 $this->get_course_module()->id,
1791 $this->get_return_action(),
1792 $this->get_return_params()));
1793 $this->add_to_log('view feedback', get_string('viewfeedbackforuser', 'assign', $item->userid));
1794 }
1795
1796
1797 $o .= $this->view_return_links();
1798
1799 $o .= $this->view_footer();
1800 return $o;
1801 }
1802
1803 /**
1804 * render the content in editor that is often used by plugin
1805 *
1806 * @param string $filearea
1807 * @param int $submissionid
1808 * @param string $plugintype
1809 * @param string $editor
1810 * @param string $component
1811 * @return string
1812 */
1813 public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
1814 global $CFG;
1815
1816 $result = '';
1817
1818 $plugin = $this->get_submission_plugin_by_type($plugintype);
1819
1820 $text = $plugin->get_editor_text($editor, $submissionid);
1821 $format = $plugin->get_editor_format($editor, $submissionid);
1822
1823 $finaltext = file_rewrite_pluginfile_urls($text, 'pluginfile.php', $this->get_context()->id, $component, $filearea, $submissionid);
1824 $result .= format_text($finaltext, $format, array('overflowdiv' => true, 'context' => $this->get_context()));
1825
1826
1827
1828 if ($CFG->enableportfolios) {
1829 require_once($CFG->libdir . '/portfoliolib.php');
1830
1831 $button = new portfolio_add_button();
37743241
MN
1832 $button->set_callback_options('assign_portfolio_caller', array('cmid' => $this->get_course_module()->id,
1833 'sid' => $submissionid, 'plugin' => $plugintype, 'editor' => $editor, 'area'=>$filearea),
1834 'mod_assign');
bbd0e548
DW
1835 $fs = get_file_storage();
1836
1837 if ($files = $fs->get_area_files($this->context->id, $component,$filearea, $submissionid, "timemodified", false)) {
1838 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
1839 } else {
1840 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
1841 }
1842 $result .= $button->to_html();
1843 }
1844 return $result;
1845 }
1846
bf78ebd6
DW
1847 /**
1848 * Display a grading error
1849 *
1850 * @param string $message - The description of the result
1851 * @return string
1852 */
1853 private function view_quickgrading_result($message) {
1854 $o = '';
49d83b9d 1855 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
bf78ebd6
DW
1856 $this->get_context(),
1857 $this->show_intro(),
1858 $this->get_course_module()->id,
1859 get_string('quickgradingresult', 'assign')));
49d83b9d 1860 $o .= $this->get_renderer()->render(new assign_quickgrading_result($message, $this->get_course_module()->id));
bf78ebd6
DW
1861 $o .= $this->view_footer();
1862 return $o;
1863 }
bbd0e548
DW
1864
1865 /**
1866 * Display the page footer
1867 *
bf78ebd6 1868 * @return string
bbd0e548
DW
1869 */
1870 private function view_footer() {
49d83b9d 1871 return $this->get_renderer()->render_footer();
bbd0e548
DW
1872 }
1873
1874 /**
1875 * Does this user have grade permission for this assignment
1876 *
1877 * @return bool
1878 */
1879 private function can_grade() {
1880 // Permissions check
1881 if (!has_capability('mod/assign:grade', $this->context)) {
1882 return false;
1883 }
1884
1885 return true;
1886 }
1887
1888 /**
1889 * Download a zip file of all assignment submissions
1890 *
1891 * @return void
1892 */
1893 private function download_submissions() {
1894 global $CFG,$DB;
1895
d0d4796b 1896 // More efficient to load this here.
bbd0e548
DW
1897 require_once($CFG->libdir.'/filelib.php');
1898
d0d4796b
DW
1899 // Load all users with submit.
1900 $students = get_enrolled_users($this->context, "mod/assign:submit");
bbd0e548 1901
d0d4796b 1902 // Build a list of files to zip.
bbd0e548
DW
1903 $filesforzipping = array();
1904 $fs = get_file_storage();
1905
1906 $groupmode = groups_get_activity_groupmode($this->get_course_module());
d0d4796b
DW
1907 // All users.
1908 $groupid = 0;
bbd0e548
DW
1909 $groupname = '';
1910 if ($groupmode) {
1911 $groupid = groups_get_activity_group($this->get_course_module(), true);
1912 $groupname = groups_get_group_name($groupid).'-';
1913 }
1914
d0d4796b
DW
1915 // Construct the zip file name.
1916 $filename = clean_filename($this->get_course()->shortname.'-'.
1917 $this->get_instance()->name.'-'.
1918 $groupname.$this->get_course_module()->id.".zip");
bbd0e548 1919
d0d4796b
DW
1920 // Get all the files for each student.
1921 foreach ($students as $student) {
1922 $userid = $student->id;
bbd0e548 1923
7a2b911c 1924 if ((groups_is_member($groupid, $userid) or !$groupmode or !$groupid)) {
d0d4796b 1925 // Get the plugins to add their own files to the zip.
bbd0e548 1926
d0d4796b
DW
1927 $submissiongroup = false;
1928 $groupname = '';
1929 if ($this->get_instance()->teamsubmission) {
1930 $submission = $this->get_group_submission($userid, 0, false);
1931 $submissiongroup = $this->get_submission_group($userid);
21f77397
DW
1932 if ($submissiongroup) {
1933 $groupname = $submissiongroup->name . '-';
1934 } else {
1935 $groupname = get_string('defaultteam', 'assign') . '-';
1936 }
b473171a 1937 } else {
d0d4796b 1938 $submission = $this->get_user_submission($userid, false);
b473171a 1939 }
bbd0e548 1940
b473171a 1941 if ($this->is_blind_marking()) {
21f77397 1942 $prefix = clean_filename(str_replace('_', ' ', $groupname . get_string('participant', 'assign')) .
d0d4796b 1943 "_" . $this->get_uniqueid_for_user($userid) . "_");
b473171a 1944 } else {
21f77397 1945 $prefix = clean_filename(str_replace('_', ' ', $groupname . fullname($student)) .
d0d4796b 1946 "_" . $this->get_uniqueid_for_user($userid) . "_");
b473171a 1947 }
bbd0e548 1948
d0d4796b
DW
1949 if ($submission) {
1950 foreach ($this->submissionplugins as $plugin) {
1951 if ($plugin->is_enabled() && $plugin->is_visible()) {
1952 $pluginfiles = $plugin->get_files($submission);
1953 foreach ($pluginfiles as $zipfilename => $file) {
7a2b911c
DW
1954 $subtype = $plugin->get_subtype();
1955 $type = $plugin->get_type();
1956 $prefixedfilename = $prefix . $subtype . '_' . $type . '_' . $zipfilename;
d0d4796b
DW
1957 $filesforzipping[$prefixedfilename] = $file;
1958 }
bbd0e548
DW
1959 }
1960 }
1961 }
bbd0e548 1962 }
d0d4796b 1963 }
bbd0e548
DW
1964 if ($zipfile = $this->pack_files($filesforzipping)) {
1965 $this->add_to_log('download all submissions', get_string('downloadall', 'assign'));
d0d4796b
DW
1966 // Send file and delete after sending.
1967 send_temp_file($zipfile, $filename);
bbd0e548
DW
1968 }
1969 }
1970
1971 /**
1972 * Util function to add a message to the log
1973 *
1974 * @param string $action The current action
1975 * @param string $info A detailed description of the change. But no more than 255 characters.
1976 * @param string $url The url to the assign module instance.
1977 * @return void
1978 */
1979 public function add_to_log($action = '', $info = '', $url='') {
1980 global $USER;
1981
1982 $fullurl = 'view.php?id=' . $this->get_course_module()->id;
1983 if ($url != '') {
1984 $fullurl .= '&' . $url;
1985 }
1986
1987 add_to_log($this->get_course()->id, 'assign', $action, $fullurl, $info, $this->get_course_module()->id, $USER->id);
1988 }
1989
2cffef9f 1990 /**
49d83b9d
DW
1991 * Lazy load the page renderer and expose the renderer to plugins
1992 *
2cffef9f
PC
1993 * @return assign_renderer
1994 */
23fffa2b 1995 public function get_renderer() {
2cffef9f
PC
1996 global $PAGE;
1997 if ($this->output) {
1998 return $this->output;
1999 }
2000 $this->output = $PAGE->get_renderer('mod_assign');
2001 return $this->output;
2002 }
bbd0e548
DW
2003
2004 /**
2005 * Load the submission object for a particular user, optionally creating it if required
2006 *
12a1a0da
DW
2007 * For team assignments there are 2 submissions - the student submission and the team submission
2008 * All files are associated with the team submission but the status of the students contribution is
2009 * recorded separately.
2010 *
bbd0e548
DW
2011 * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
2012 * @param bool $create optional Defaults to false. If set to true a new submission object will be created in the database
2013 * @return stdClass The submission
2014 */
df47b77f 2015 public function get_user_submission($userid, $create) {
bbd0e548
DW
2016 global $DB, $USER;
2017
2018 if (!$userid) {
2019 $userid = $USER->id;
2020 }
12a1a0da
DW
2021 // If the userid is not null then use userid.
2022 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid, 'groupid'=>0);
2023 $submission = $DB->get_record('assign_submission', $params);
bbd0e548
DW
2024
2025 if ($submission) {
2026 return $submission;
2027 }
2028 if ($create) {
2029 $submission = new stdClass();
2030 $submission->assignment = $this->get_instance()->id;
2031 $submission->userid = $userid;
2032 $submission->timecreated = time();
2033 $submission->timemodified = $submission->timecreated;
7a9fd6da 2034 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
bbd0e548
DW
2035 $sid = $DB->insert_record('assign_submission', $submission);
2036 $submission->id = $sid;
2037 return $submission;
2038 }
2039 return false;
2040 }
2041
2042 /**
2043 * Load the submission object from it's id
2044 *
2045 * @param int $submissionid The id of the submission we want
2046 * @return stdClass The submission
2047 */
2048 private function get_submission($submissionid) {
2049 global $DB;
2050
2051 return $DB->get_record('assign_submission', array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid), '*', MUST_EXIST);
2052 }
2053
2054 /**
2055 * This will retrieve a grade object from the db, optionally creating it if required
2056 *
2057 * @param int $userid The user we are grading
2058 * @param bool $create If true the grade will be created if it does not exist
2059 * @return stdClass The grade record
2060 */
df47b77f 2061 public function get_user_grade($userid, $create) {
bbd0e548
DW
2062 global $DB, $USER;
2063
2064 if (!$userid) {
2065 $userid = $USER->id;
2066 }
2067
2068 // if the userid is not null then use userid
2069 $grade = $DB->get_record('assign_grades', array('assignment'=>$this->get_instance()->id, 'userid'=>$userid));
2070
2071 if ($grade) {
2072 return $grade;
2073 }
2074 if ($create) {
2075 $grade = new stdClass();
2076 $grade->assignment = $this->get_instance()->id;
2077 $grade->userid = $userid;
2078 $grade->timecreated = time();
2079 $grade->timemodified = $grade->timecreated;
2080 $grade->locked = 0;
2081 $grade->grade = -1;
2082 $grade->grader = $USER->id;
b3de95af 2083 $grade->extensionduedate = 0;
bbd0e548
DW
2084 $gid = $DB->insert_record('assign_grades', $grade);
2085 $grade->id = $gid;
2086 return $grade;
2087 }
2088 return false;
2089 }
2090
2091 /**
2092 * This will retrieve a grade object from the db
2093 *
2094 * @param int $gradeid The id of the grade
2095 * @return stdClass The grade record
2096 */
2097 private function get_grade($gradeid) {
2098 global $DB;
2099
2100 return $DB->get_record('assign_grades', array('assignment'=>$this->get_instance()->id, 'id'=>$gradeid), '*', MUST_EXIST);
2101 }
2102
2103 /**
2104 * Print the grading page for a single user submission
2105 *
2106 * @param moodleform $mform
2107 * @param int $offset
2108 * @return string
2109 */
2110 private function view_single_grade_page($mform, $offset=0) {
2111 global $DB, $CFG;
2112
2113 $o = '';
2114
2115 // Include grade form
2116 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
2117
2118 // Need submit permission to submit an assignment
2119 require_capability('mod/assign:grade', $this->context);
2120
49d83b9d 2121 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
bbd0e548
DW
2122 $this->get_context(), false, $this->get_course_module()->id,get_string('grading', 'assign')));
2123
2124 $rownum = required_param('rownum', PARAM_INT) + $offset;
2125 $useridlist = optional_param('useridlist', '', PARAM_TEXT);
2126 if ($useridlist) {
2127 $useridlist = explode(',', $useridlist);
2128 } else {
2129 $useridlist = $this->get_grading_userid_list();
2130 }
2131 $last = false;
2132 $userid = $useridlist[$rownum];
2133 if ($rownum == count($useridlist) - 1) {
2134 $last = true;
2135 }
12a1a0da 2136 if (!$userid) {
bbd0e548
DW
2137 throw new coding_exception('Row is out of bounds for the current grading table: ' . $rownum);
2138 }
2139 $user = $DB->get_record('user', array('id' => $userid));
2140 if ($user) {
49d83b9d 2141 $o .= $this->get_renderer()->render(new assign_user_summary($user,
b473171a
DW
2142 $this->get_course()->id,
2143 has_capability('moodle/site:viewfullnames',
2144 $this->get_course_context()),
2145 $this->is_blind_marking(),
2146 $this->get_uniqueid_for_user($user->id)));
bbd0e548
DW
2147 }
2148 $submission = $this->get_user_submission($userid, false);
12a1a0da
DW
2149 $submissiongroup = null;
2150 $submissiongroupmemberswhohavenotsubmitted = array();
2151 $teamsubmission = null;
2152 $notsubmitted = array();
2153 if ($this->get_instance()->teamsubmission) {
2154 $teamsubmission = $this->get_group_submission($userid, 0, false);
2155 $submissiongroup = $this->get_submission_group($userid);
2156 $groupid = 0;
2157 if ($submissiongroup) {
2158 $groupid = $submissiongroup->id;
2159 }
2160 $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
2161
2162 }
2163
bbd0e548
DW
2164 // get the current grade
2165 $grade = $this->get_user_grade($userid, false);
2166 if ($this->can_view_submission($userid)) {
2167 $gradelocked = ($grade && $grade->locked) || $this->grading_disabled($userid);
9e795179
DW
2168 $extensionduedate = null;
2169 if ($grade) {
2170 $extensionduedate = $grade->extensionduedate;
2171 }
88cfe469 2172 $showedit = $this->submissions_open($userid) && ($this->is_any_submission_plugin_enabled());
9e795179 2173
12a1a0da
DW
2174 if ($teamsubmission) {
2175 $showsubmit = $showedit && $teamsubmission && ($teamsubmission->status == ASSIGN_SUBMISSION_STATUS_DRAFT);
2176 } else {
2177 $showsubmit = $showedit && $submission && ($submission->status == ASSIGN_SUBMISSION_STATUS_DRAFT);
2178 }
7a9fd6da
DW
2179 if (!$this->get_instance()->submissiondrafts) {
2180 $showsubmit = false;
2181 }
12a1a0da 2182 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
9e795179 2183
49d83b9d 2184 $o .= $this->get_renderer()->render(new assign_submission_status($this->get_instance()->allowsubmissionsfromdate,
bbd0e548
DW
2185 $this->get_instance()->alwaysshowdescription,
2186 $submission,
12a1a0da
DW
2187 $this->get_instance()->teamsubmission,
2188 $teamsubmission,
2189 $submissiongroup,
2190 $notsubmitted,
bbd0e548
DW
2191 $this->is_any_submission_plugin_enabled(),
2192 $gradelocked,
2193 $this->is_graded($userid),
2194 $this->get_instance()->duedate,
9e795179 2195 $this->get_instance()->cutoffdate,
bbd0e548
DW
2196 $this->get_submission_plugins(),
2197 $this->get_return_action(),
2198 $this->get_return_params(),
2199 $this->get_course_module()->id,
12a1a0da 2200 $this->get_course()->id,
bbd0e548 2201 assign_submission_status::GRADER_VIEW,
9e795179
DW
2202 $showedit,
2203 $showsubmit,
12a1a0da
DW
2204 $viewfullnames,
2205 $extensionduedate,
88cfe469 2206 $this->get_context(),
ec32d068
RW
2207 $this->is_blind_marking(),
2208 ''));
bbd0e548
DW
2209 }
2210 if ($grade) {
2211 $data = new stdClass();
2d8a9ce9 2212 if ($grade->grade !== NULL && $grade->grade >= 0) {
bbd0e548
DW
2213 $data->grade = format_float($grade->grade,2);
2214 }
2215 } else {
2216 $data = new stdClass();
2217 $data->grade = '';
2218 }
2219
2220 // now show the grading form
2221 if (!$mform) {
12a1a0da
DW
2222 $pagination = array( 'rownum'=>$rownum, 'useridlist'=>$useridlist, 'last'=>$last);
2223 $formparams = array($this, $data, $pagination);
2224 $mform = new mod_assign_grade_form(null,
2225 $formparams,
2226 'post',
2227 '',
2228 array('class'=>'gradeform'));
bbd0e548 2229 }
49d83b9d 2230 $o .= $this->get_renderer()->render(new assign_form('gradingform',$mform));
bbd0e548 2231
12a1a0da
DW
2232 $msg = get_string('viewgradingformforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user)));
2233 $this->add_to_log('view grading form', $msg);
bbd0e548
DW
2234
2235 $o .= $this->view_footer();
2236 return $o;
2237 }
2238
b473171a
DW
2239 /**
2240 * Show a confirmation page to make sure they want to release student identities
2241 *
2242 * @return string
2243 */
2244 private function view_reveal_identities_confirm() {
2245 global $CFG, $USER;
2246
2247 require_capability('mod/assign:revealidentities', $this->get_context());
2248
2249 $o = '';
49d83b9d 2250 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
b473171a
DW
2251 $this->get_context(), false, $this->get_course_module()->id));
2252
2253 $confirmurl = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id,
2254 'action'=>'revealidentitiesconfirm',
2255 'sesskey'=>sesskey()));
2256
2257 $cancelurl = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id,
2258 'action'=>'grading'));
2259
49d83b9d 2260 $o .= $this->get_renderer()->confirm(get_string('revealidentitiesconfirm', 'assign'), $confirmurl, $cancelurl);
b473171a
DW
2261 $o .= $this->view_footer();
2262 $this->add_to_log('view', get_string('viewrevealidentitiesconfirm', 'assign'));
2263 return $o;
2264 }
2265
2266
bbd0e548
DW
2267
2268
2269 /**
2270 * View a link to go back to the previous page. Uses url parameters returnaction and returnparams.
2271 *
2272 * @return string
2273 */
2274 private function view_return_links() {
2275
2276 $returnaction = optional_param('returnaction','', PARAM_ALPHA);
2277 $returnparams = optional_param('returnparams','', PARAM_TEXT);
2278
2279 $params = array();
2280 parse_str($returnparams, $params);
2281 $params = array_merge( array('id' => $this->get_course_module()->id, 'action' => $returnaction), $params);
2282
49d83b9d 2283 return $this->get_renderer()->single_button(new moodle_url('/mod/assign/view.php', $params), get_string('back'), 'get');
bbd0e548
DW
2284
2285 }
2286
2287 /**
2288 * View the grading table of all submissions for this assignment
2289 *
2290 * @return string
2291 */
2292 private function view_grading_table() {
2293 global $USER, $CFG;
2294 // Include grading options form
2295 require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
bf78ebd6 2296 require_once($CFG->dirroot . '/mod/assign/quickgradingform.php');
bbd0e548
DW
2297 require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
2298 $o = '';
2299
2300 $links = array();
bbd0e548
DW
2301 if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
2302 has_capability('moodle/grade:viewall', $this->get_course_context())) {
a1e54f4d 2303 $gradebookurl = '/grade/report/grader/index.php?id=' . $this->get_course()->id;
bbd0e548
DW
2304 $links[$gradebookurl] = get_string('viewgradebook', 'assign');
2305 }
2306 if ($this->is_any_submission_plugin_enabled()) {
a1e54f4d 2307 $downloadurl = '/mod/assign/view.php?id=' . $this->get_course_module()->id . '&action=downloadall';
bbd0e548
DW
2308 $links[$downloadurl] = get_string('downloadall', 'assign');
2309 }
b473171a
DW
2310 if ($this->is_blind_marking() && has_capability('mod/assign:revealidentities', $this->get_context())) {
2311 $revealidentitiesurl = '/mod/assign/view.php?id=' . $this->get_course_module()->id . '&action=revealidentities';
2312 $links[$revealidentitiesurl] = get_string('revealidentities', 'assign');
2313 }
df47b77f
DW
2314 foreach ($this->get_feedback_plugins() as $plugin) {
2315 if ($plugin->is_enabled() && $plugin->is_visible()) {
2316 foreach ($plugin->get_grading_actions() as $action => $description) {
2317 $url = '/mod/assign/view.php' .
2318 '?id=' . $this->get_course_module()->id .
2319 '&plugin=' . $plugin->get_type() .
2320 '&pluginsubtype=assignfeedback' .
2321 '&action=viewpluginpage&pluginaction=' . $action;
2322 $links[$url] = $description;
2323 }
2324 }
2325 }
a1e54f4d
DW
2326
2327 $gradingactions = new url_select($links);
49f0c151 2328 $gradingactions->set_label(get_string('choosegradingaction', 'assign'));
bbd0e548 2329
bf78ebd6
DW
2330 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2331
bbd0e548
DW
2332 $perpage = get_user_preferences('assign_perpage', 10);
2333 $filter = get_user_preferences('assign_filter', '');
bf78ebd6
DW
2334 $controller = $gradingmanager->get_active_controller();
2335 $showquickgrading = empty($controller);
2336 if (optional_param('action', '', PARAM_ALPHA) == 'saveoptions') {
2337 $quickgrading = optional_param('quickgrading', false, PARAM_BOOL);
2338 set_user_preference('assign_quickgrading', $quickgrading);
2339 }
2340 $quickgrading = get_user_preferences('assign_quickgrading', false);
2341
bbd0e548
DW
2342 // print options for changing the filter and changing the number of results per page
2343 $gradingoptionsform = new mod_assign_grading_options_form(null,
2344 array('cm'=>$this->get_course_module()->id,
2345 'contextid'=>$this->context->id,
bf78ebd6 2346 'userid'=>$USER->id,
44e2f0fe 2347 'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
bf78ebd6
DW
2348 'showquickgrading'=>$showquickgrading,
2349 'quickgrading'=>$quickgrading),
bbd0e548
DW
2350 'post', '',
2351 array('class'=>'gradingoptionsform'));
2352
2353 $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
2354 array('cm'=>$this->get_course_module()->id,
9e795179 2355 'submissiondrafts'=>$this->get_instance()->submissiondrafts,
df47b77f
DW
2356 'duedate'=>$this->get_instance()->duedate,
2357 'feedbackplugins'=>$this->get_feedback_plugins()),
bbd0e548
DW
2358 'post', '',
2359 array('class'=>'gradingbatchoperationsform'));
2360
2361 $gradingoptionsdata = new stdClass();
2362 $gradingoptionsdata->perpage = $perpage;
2363 $gradingoptionsdata->filter = $filter;
2364 $gradingoptionsform->set_data($gradingoptionsdata);
2365
49d83b9d
DW
2366 $actionformtext = $this->get_renderer()->render($gradingactions);
2367 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
c792565b
DM
2368 $this->get_context(), false, $this->get_course_module()->id, get_string('grading', 'assign'), $actionformtext));
2369 $o .= groups_print_activity_menu($this->get_course_module(), $CFG->wwwroot . '/mod/assign/view.php?id=' . $this->get_course_module()->id.'&action=grading', true);
2370
bbd0e548
DW
2371 // plagiarism update status apearring in the grading book
2372 if (!empty($CFG->enableplagiarism)) {
2373 /** Include plagiarismlib.php */
2374 require_once($CFG->libdir . '/plagiarismlib.php');
9650334f 2375 $o .= plagiarism_update_status($this->get_course(), $this->get_course_module());
bbd0e548
DW
2376 }
2377
bbd0e548 2378 // load and print the table of submissions
bf78ebd6 2379 if ($showquickgrading && $quickgrading) {
49d83b9d 2380 $table = $this->get_renderer()->render(new assign_grading_table($this, $perpage, $filter, 0, true));
bf78ebd6
DW
2381 $quickgradingform = new mod_assign_quick_grading_form(null,
2382 array('cm'=>$this->get_course_module()->id,
2383 'gradingtable'=>$table));
49d83b9d 2384 $o .= $this->get_renderer()->render(new assign_form('quickgradingform', $quickgradingform));
bf78ebd6 2385 } else {
49d83b9d 2386 $o .= $this->get_renderer()->render(new assign_grading_table($this, $perpage, $filter, 0, false));
bf78ebd6 2387 }
bbd0e548
DW
2388
2389 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
2390 $users = array_keys($this->list_participants($currentgroup, true));
2391 if (count($users) != 0) {
2392 // if no enrolled user in a course then don't display the batch operations feature
49d83b9d 2393 $o .= $this->get_renderer()->render(new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform));
bbd0e548 2394 }
49d83b9d 2395 $o .= $this->get_renderer()->render(new assign_form('gradingoptionsform', $gradingoptionsform, 'M.mod_assign.init_grading_options'));
bbd0e548
DW
2396 return $o;
2397 }
2398
2399 /**
2400 * View entire grading page.
2401 *
2402 * @return string
2403 */
2404 private function view_grading_page() {
2405 global $CFG;
2406
2407 $o = '';
2408 // Need submit permission to submit an assignment
2409 require_capability('mod/assign:grade', $this->context);
2410 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
2411
2412 // only load this if it is
2413
bbd0e548
DW
2414 $o .= $this->view_grading_table();
2415
2416 $o .= $this->view_footer();
2417 $this->add_to_log('view submission grading table', get_string('viewsubmissiongradingtable', 'assign'));
2418 return $o;
2419 }
2420
2421 /**
2422 * Capture the output of the plagiarism plugins disclosures and return it as a string
2423 *
2424 * @return void
2425 */
2426 private function plagiarism_print_disclosure() {
2427 global $CFG;
2428 $o = '';
2429
2430 if (!empty($CFG->enableplagiarism)) {
2431 /** Include plagiarismlib.php */
2432 require_once($CFG->libdir . '/plagiarismlib.php');
bbd0e548 2433
9650334f 2434 $o .= plagiarism_print_disclosure($this->get_course_module()->id);
bbd0e548
DW
2435 }
2436
2437 return $o;
2438 }
2439
2440 /**
2441 * message for students when assignment submissions have been closed
2442 *
2443 * @return string
2444 */
2445 private function view_student_error_message() {
2446 global $CFG;
2447
2448 $o = '';
2449 // Need submit permission to submit an assignment
2450 require_capability('mod/assign:submit', $this->context);
2451
49d83b9d 2452 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
bbd0e548
DW
2453 $this->get_context(),
2454 $this->show_intro(),
2455 $this->get_course_module()->id,
2456 get_string('editsubmission', 'assign')));
2457
49d83b9d 2458 $o .= $this->get_renderer()->notification(get_string('submissionsclosed', 'assign'));
bbd0e548
DW
2459
2460 $o .= $this->view_footer();
2461
2462 return $o;
2463
2464 }
2465
2466 /**
2467 * View edit submissions page.
2468 *
2469 * @param moodleform $mform
34b8f3a8 2470 * @param array $notices A list of notices to display at the top of the edit submission form (e.g. from plugins).
bbd0e548
DW
2471 * @return void
2472 */
34b8f3a8 2473 private function view_edit_submission_page($mform, $notices) {
bbd0e548
DW
2474 global $CFG;
2475
2476 $o = '';
2477 // Include submission form
2478 require_once($CFG->dirroot . '/mod/assign/submission_form.php');
2479 // Need submit permission to submit an assignment
2480 require_capability('mod/assign:submit', $this->context);
2481
2482 if (!$this->submissions_open()) {
bf78ebd6 2483 return $this->view_student_error_message();
bbd0e548 2484 }
49d83b9d 2485 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
bbd0e548
DW
2486 $this->get_context(),
2487 $this->show_intro(),
2488 $this->get_course_module()->id,
2489 get_string('editsubmission', 'assign')));
2490 $o .= $this->plagiarism_print_disclosure();
2491 $data = new stdClass();
2492
2493 if (!$mform) {
2494 $mform = new mod_assign_submission_form(null, array($this, $data));
2495 }
2496
34b8f3a8
DW
2497 foreach ($notices as $notice) {
2498 $o .= $this->get_renderer()->notification($notice);
2499 }
2500
49d83b9d 2501 $o .= $this->get_renderer()->render(new assign_form('editsubmissionform',$mform));
bbd0e548
DW
2502
2503 $o .= $this->view_footer();
2504 $this->add_to_log('view submit assignment form', get_string('viewownsubmissionform', 'assign'));
2505
2506 return $o;
2507 }
2508
2509 /**
2510 * See if this assignment has a grade yet
2511 *
2512 * @param int $userid
2513 * @return bool
2514 */
2515 private function is_graded($userid) {
2516 $grade = $this->get_user_grade($userid, false);
2517 if ($grade) {
2d8a9ce9 2518 return ($grade->grade !== NULL && $grade->grade >= 0);
bbd0e548
DW
2519 }
2520 return false;
2521 }
2522
2523
2524 /**
2525 * Perform an access check to see if the current $USER can view this users submission
2526 *
2527 * @param int $userid
2528 * @return bool
2529 */
2530 public function can_view_submission($userid) {
2531 global $USER;
2532
2533 if (!is_enrolled($this->get_course_context(), $userid)) {
2534 return false;
2535 }
2536 if ($userid == $USER->id && !has_capability('mod/assign:submit', $this->context)) {
2537 return false;
2538 }
2539 if ($userid != $USER->id && !has_capability('mod/assign:grade', $this->context)) {
2540 return false;
2541 }
2542 return true;
2543 }
2544
df47b77f
DW
2545 /**
2546 * Allows the plugin to show a batch grading operation page.
2547 *
2548 * @return none
2549 */
2550 private function view_plugin_grading_batch_operation($mform) {
2551 require_capability('mod/assign:grade', $this->context);
2552 $prefix = 'plugingradingbatchoperation_';
2553
2554 if ($data = $mform->get_data()) {
2555 $tail = substr($data->operation, strlen($prefix));
2556 list($plugintype, $action) = explode('_', $tail, 2);
2557
2558 $plugin = $this->get_feedback_plugin_by_type($plugintype);
2559 if ($plugin) {
2560 $users = $data->selectedusers;
2561 $userlist = explode(',', $users);
2562 echo $plugin->grading_batch_operation($action, $userlist);
2563 return;
2564 }
2565 }
2566 print_error('invalidformdata', '');
2567 }
2568
bbd0e548
DW
2569 /**
2570 * Ask the user to confirm they want to perform this batch operation
7a2b911c 2571 * @param moodleform $mform Set to a grading batch operations form
9e795179 2572 * @return string - the page to view after processing these actions
bbd0e548 2573 */
df47b77f 2574 private function process_grading_batch_operation(& $mform) {
bbd0e548
DW
2575 global $CFG;
2576 require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
2577 require_sesskey();
2578
df47b77f
DW
2579 $mform = new mod_assign_grading_batch_operations_form(null,
2580 array('cm'=>$this->get_course_module()->id,
2581 'submissiondrafts'=>$this->get_instance()->submissiondrafts,
2582 'duedate'=>$this->get_instance()->duedate,
2583 'feedbackplugins'=>$this->get_feedback_plugins()),
2584 'post',
2585 '',
2586 array('class'=>'gradingbatchoperationsform'));
bbd0e548 2587
df47b77f 2588 if ($data = $mform->get_data()) {
bbd0e548
DW
2589 // get the list of users
2590 $users = $data->selectedusers;
2591 $userlist = explode(',', $users);
2592
df47b77f
DW
2593 $prefix = 'plugingradingbatchoperation_';
2594
2595 if ($data->operation == 'grantextension') {
7a2565cd
DW
2596 // Reset the form so the grant extension page will create the extension form.
2597 $mform = null;
df47b77f 2598 return 'grantextension';
d0d4796b 2599 } else if (strpos($data->operation, $prefix) === 0) {
df47b77f
DW
2600 $tail = substr($data->operation, strlen($prefix));
2601 list($plugintype, $action) = explode('_', $tail, 2);
2602
2603 $plugin = $this->get_feedback_plugin_by_type($plugintype);
2604 if ($plugin) {
2605 return 'plugingradingbatchoperation';
2606 }
2607 }
2608
bbd0e548
DW
2609 foreach ($userlist as $userid) {
2610 if ($data->operation == 'lock') {
2611 $this->process_lock($userid);
2612 } else if ($data->operation == 'unlock') {
2613 $this->process_unlock($userid);
2614 } else if ($data->operation == 'reverttodraft') {
2615 $this->process_revert_to_draft($userid);
2616 }
2617 }
2618 }
2619
9e795179 2620 return 'grading';
bbd0e548
DW
2621 }
2622
2623 /**
2624 * Ask the user to confirm they want to submit their work for grading
94f26900 2625 * @param $mform moodleform - null unless form validation has failed
bbd0e548
DW
2626 * @return string
2627 */
94f26900
DW
2628 private function check_submit_for_grading($mform) {
2629 global $USER, $CFG;
2630
2631 require_once($CFG->dirroot . '/mod/assign/submissionconfirmform.php');
2632
bbd0e548
DW
2633 // Check that all of the submission plugins are ready for this submission
2634 $notifications = array();
2635 $submission = $this->get_user_submission($USER->id, false);
2636 $plugins = $this->get_submission_plugins();
2637 foreach ($plugins as $plugin) {
2638 if ($plugin->is_enabled() && $plugin->is_visible()) {
2639 $check = $plugin->precheck_submission($submission);
2640 if ($check !== true) {
2641 $notifications[] = $check;
2642 }
2643 }
2644 }
2645
94f26900
DW
2646 $data = new stdClass();
2647 $adminconfig = $this->get_admin_config();
a9b94aff
RW
2648 $requiresubmissionstatement = (!empty($adminconfig->requiresubmissionstatement) ||
2649 $this->get_instance()->requiresubmissionstatement) &&
2650 !empty($adminconfig->submissionstatement);
94f26900
DW
2651
2652 $submissionstatement = '';
2653 if (!empty($adminconfig->submissionstatement)) {
2654 $submissionstatement = $adminconfig->submissionstatement;
2655 }
2656
2657 if ($mform == null) {
2658 $mform = new mod_assign_confirm_submission_form(null, array($requiresubmissionstatement,
2659 $submissionstatement,
2660 $this->get_course_module()->id,
2661 $data));
2662 }
bbd0e548 2663 $o = '';
49d83b9d
DW
2664 $o .= $this->get_renderer()->header();
2665 $o .= $this->get_renderer()->render(new assign_submit_for_grading_page($notifications, $this->get_course_module()->id, $mform));
bbd0e548 2666 $o .= $this->view_footer();
94f26900
DW
2667
2668 $this->add_to_log('view confirm submit assignment form', get_string('viewownsubmissionform', 'assign'));
2669
bbd0e548
DW
2670 return $o;
2671 }
2672
2673 /**
2674 * Print 2 tables of information with no action links -
2675 * the submission summary and the grading summary
2676 *
2677 * @param stdClass $user the user to print the report for
2678 * @param bool $showlinks - Return plain text or links to the profile
2679 * @return string - the html summary
2680 */
2681 public function view_student_summary($user, $showlinks) {
2682 global $CFG, $DB, $PAGE;
2683
2684 $grade = $this->get_user_grade($user->id, false);
2685 $submission = $this->get_user_submission($user->id, false);
2686 $o = '';
2687
12a1a0da
DW
2688 $teamsubmission = null;
2689 $submissiongroup = null;
2690 $notsubmitted = array();
2691 if ($this->get_instance()->teamsubmission) {
2692 $teamsubmission = $this->get_group_submission($user->id, 0, false);
2693 $submissiongroup = $this->get_submission_group($user->id);
2694 $groupid = 0;
2695 if ($submissiongroup) {
2696 $groupid = $submissiongroup->id;
2697 }
2698 $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
2699 }
2700
bbd0e548
DW
2701 if ($this->can_view_submission($user->id)) {
2702 $showedit = has_capability('mod/assign:submit', $this->context) &&
9e795179 2703 $this->submissions_open($user->id) && ($this->is_any_submission_plugin_enabled()) && $showlinks;
bbd0e548 2704 $gradelocked = ($grade && $grade->locked) || $this->grading_disabled($user->id);
ec32d068
RW
2705 // Grading criteria preview.
2706 $gradingmanager = get_grading_manager($this->context, 'mod_assign', 'submissions');
2707 $gradingcontrollerpreview = '';
2708 if ($gradingmethod = $gradingmanager->get_active_method()) {
2709 $controller = $gradingmanager->get_controller($gradingmethod);
2710 if ($controller->is_form_defined()) {
2711 $gradingcontrollerpreview = $controller->render_preview($PAGE);
2712 }
2713 }
12a1a0da
DW
2714
2715 $showsubmit = ($submission || $teamsubmission) && $showlinks;
2716 if ($teamsubmission && ($teamsubmission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED)) {
2717 $showsubmit = false;
2718 }
2719 if ($submission && ($submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED)) {
2720 $showsubmit = false;
2721 }
7a9fd6da
DW
2722 if (!$this->get_instance()->submissiondrafts) {
2723 $showsubmit = false;
2724 }
9e795179
DW
2725 $extensionduedate = null;
2726 if ($grade) {
2727 $extensionduedate = $grade->extensionduedate;
2728 }
12a1a0da 2729 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
49d83b9d 2730 $o .= $this->get_renderer()->render(new assign_submission_status($this->get_instance()->allowsubmissionsfromdate,
bbd0e548
DW
2731 $this->get_instance()->alwaysshowdescription,
2732 $submission,
12a1a0da
DW
2733 $this->get_instance()->teamsubmission,
2734 $teamsubmission,
2735 $submissiongroup,
2736 $notsubmitted,
bbd0e548
DW
2737 $this->is_any_submission_plugin_enabled(),
2738 $gradelocked,
2739 $this->is_graded($user->id),
2740 $this->get_instance()->duedate,
9e795179 2741 $this->get_instance()->cutoffdate,
bbd0e548
DW
2742 $this->get_submission_plugins(),
2743 $this->get_return_action(),
2744 $this->get_return_params(),
2745 $this->get_course_module()->id,
12a1a0da 2746 $this->get_course()->id,
bbd0e548
DW
2747 assign_submission_status::STUDENT_VIEW,
2748 $showedit,
9e795179 2749 $showsubmit,
12a1a0da
DW
2750 $viewfullnames,
2751 $extensionduedate,
b98824c2 2752 $this->get_context(),
ec32d068
RW
2753 $this->is_blind_marking(),
2754 $gradingcontrollerpreview));
2755
bbd0e548
DW
2756 require_once($CFG->libdir.'/gradelib.php');
2757 require_once($CFG->dirroot.'/grade/grading/lib.php');
2758
2759 $gradinginfo = grade_get_grades($this->get_course()->id,
2760 'mod',
2761 'assign',
2762 $this->get_instance()->id,
2763 $user->id);
2764
2765 $gradingitem = $gradinginfo->items[0];
2766 $gradebookgrade = $gradingitem->grades[$user->id];
2767
2768 // check to see if all feedback plugins are empty
2769 $emptyplugins = true;
2770 if ($grade) {
2771 foreach ($this->get_feedback_plugins() as $plugin) {
2772 if ($plugin->is_visible() && $plugin->is_enabled()) {
2773 if (!$plugin->is_empty($grade)) {
2774 $emptyplugins = false;
2775 }
2776 }
2777 }
2778 }
2779
2780
2781 if (!($gradebookgrade->hidden) && ($gradebookgrade->grade !== null || !$emptyplugins)) {
2782
2783 $gradefordisplay = '';
2784 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2785
2786 if ($controller = $gradingmanager->get_active_controller()) {
2787 $controller->set_grade_range(make_grades_menu($this->get_instance()->grade));
2788 $gradefordisplay = $controller->render_grade($PAGE,
2789 $grade->id,
2790 $gradingitem,
2791 $gradebookgrade->str_long_grade,
2792 has_capability('mod/assign:grade', $this->get_context()));
2793 } else {
bf78ebd6 2794 $gradefordisplay = $this->display_grade($gradebookgrade->grade, false);
bbd0e548
DW
2795 }
2796
2797 $gradeddate = $gradebookgrade->dategraded;
2798 $grader = $DB->get_record('user', array('id'=>$gradebookgrade->usermodified));
2799
2800 $feedbackstatus = new assign_feedback_status($gradefordisplay,
2801 $gradeddate,
2802 $grader,
2803 $this->get_feedback_plugins(),
2804 $grade,
2805 $this->get_course_module()->id,
2806 $this->get_return_action(),
2807 $this->get_return_params());
2808
49d83b9d 2809 $o .= $this->get_renderer()->render($feedbackstatus);
bbd0e548
DW
2810 }
2811
2812 }
2813 return $o;
2814 }
2815
2816 /**
2817 * View submissions page (contains details of current submission).
2818 *
2819 * @return string
2820 */
2821 private function view_submission_page() {
2822 global $CFG, $DB, $USER, $PAGE;
2823
2824 $o = '';
49d83b9d 2825 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
bbd0e548
DW
2826 $this->get_context(),
2827 $this->show_intro(),
2828 $this->get_course_module()->id));
2829
2830 if ($this->can_grade()) {
12a1a0da
DW
2831 if ($this->get_instance()->teamsubmission) {
2832 $summary = new assign_grading_summary($this->count_teams(),
2833 $this->get_instance()->submissiondrafts,
2834 $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_DRAFT),
2835 $this->is_any_submission_plugin_enabled(),
2836 $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED),
2837 $this->get_instance()->cutoffdate,
2838 $this->get_instance()->duedate,
2839 $this->get_course_module()->id,
2840 $this->count_submissions_need_grading(),
2841 $this->get_instance()->teamsubmission);
49d83b9d 2842 $o .= $this->get_renderer()->render($summary);
12a1a0da
DW
2843 } else {
2844 $summary = new assign_grading_summary($this->count_participants(0),
2845 $this->get_instance()->submissiondrafts,
2846 $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_DRAFT),
2847 $this->is_any_submission_plugin_enabled(),
2848 $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED),
2849 $this->get_instance()->cutoffdate,
2850 $this->get_instance()->duedate,
2851 $this->get_course_module()->id,
2852 $this->count_submissions_need_grading(),
2853 $this->get_instance()->teamsubmission);
49d83b9d 2854 $o .= $this->get_renderer()->render($summary);
12a1a0da 2855 }
bbd0e548
DW
2856 }
2857 $grade = $this->get_user_grade($USER->id, false);
2858 $submission = $this->get_user_submission($USER->id, false);
2859
2860 if ($this->can_view_submission($USER->id)) {
2861 $o .= $this->view_student_summary($USER, true);
2862 }
2863
2864
2865 $o .= $this->view_footer();
2866 $this->add_to_log('view', get_string('viewownsubmissionstatus', 'assign'));
2867 return $o;
2868 }
2869
2870 /**
2871 * convert the final raw grade(s) in the grading table for the gradebook
2872 *
2873 * @param stdClass $grade
2874 * @return array
2875 */
2876 private function convert_grade_for_gradebook(stdClass $grade) {
2877 $gradebookgrade = array();
2878 // trying to match those array keys in grade update function in gradelib.php
2879 // with keys in th database table assign_grades
2880 // starting around line 262
99467a9f
DW
2881 if ($grade->grade >= 0) {
2882 $gradebookgrade['rawgrade'] = $grade->grade;
2883 }
bbd0e548
DW
2884 $gradebookgrade['userid'] = $grade->userid;
2885 $gradebookgrade['usermodified'] = $grade->grader;
2886 $gradebookgrade['datesubmitted'] = NULL;
2887 $gradebookgrade['dategraded'] = $grade->timemodified;
2888 if (isset($grade->feedbackformat)) {
2889 $gradebookgrade['feedbackformat'] = $grade->feedbackformat;
2890 }
2891 if (isset($grade->feedbacktext)) {
2892 $gradebookgrade['feedback'] = $grade->feedbacktext;
2893 }
2894
2895 return $gradebookgrade;
2896 }
2897
2898 /**
2899 * convert submission details for the gradebook
2900 *
2901 * @param stdClass $submission
2902 * @return array
2903 */
2904 private function convert_submission_for_gradebook(stdClass $submission) {
2905 $gradebookgrade = array();
2906
2907
2908 $gradebookgrade['userid'] = $submission->userid;
2909 $gradebookgrade['usermodified'] = $submission->userid;
2910 $gradebookgrade['datesubmitted'] = $submission->timemodified;
2911
2912 return $gradebookgrade;
2913 }
2914
2915 /**
2916 * update grades in the gradebook
2917 *
2918 * @param mixed $submission stdClass|null
2919 * @param mixed $grade stdClass|null
2920 * @return bool
2921 */
2922 private function gradebook_item_update($submission=NULL, $grade=NULL) {
2923
b473171a
DW
2924 // Do not push grade to gradebook if blind marking is active as the gradebook would reveal the students.
2925 if ($this->is_blind_marking()) {
2926 return false;
2927 }
12a1a0da
DW
2928 if ($submission != NULL) {
2929 if ($submission->userid == 0) {
2930 // This is a group submission update.
2931 $team = groups_get_members($submission->groupid, 'u.id');
2932
2933 foreach ($team as $member) {
2934 $submission->groupid = 0;
2935 $submission->userid = $member->id;
2936 $this->gradebook_item_update($submission, null);
2937 }
2938 return;
2939 }
2940
bbd0e548 2941 $gradebookgrade = $this->convert_submission_for_gradebook($submission);
12a1a0da
DW
2942
2943 } else {
bbd0e548
DW
2944 $gradebookgrade = $this->convert_grade_for_gradebook($grade);
2945 }
09b46f0e
AA
2946 // Grading is disabled, return.
2947 if ($this->grading_disabled($gradebookgrade['userid'])) {
2948 return false;
2949 }
bbd0e548
DW
2950 $assign = clone $this->get_instance();
2951 $assign->cmidnumber = $this->get_course_module()->id;
2952
2953 return assign_grade_item_update($assign, $gradebookgrade);
2954 }
2955
12a1a0da
DW
2956 /**
2957 * update team submission
2958 *
2959 * @param stdClass $submission
2960 * @param int $userid
2961 * @param bool $updatetime
2962 * @return bool
2963 */
2964 private function update_team_submission(stdClass $submission, $userid, $updatetime) {
2965 global $DB;
2966
2967 if ($updatetime) {
2968 $submission->timemodified = time();
2969 }
2970
2971 // First update the submission for the current user.
2972 $mysubmission = $this->get_user_submission($userid, true);
2973 $mysubmission->status = $submission->status;
2974
2975 $this->update_submission($mysubmission, 0, $updatetime, false);
2976
2977 // Now check the team settings to see if this assignment qualifies as submitted or draft.
2978 $team = $this->get_submission_group_members($submission->groupid, true);
2979
2980 $allsubmitted = true;
2981 $anysubmitted = false;
2982 foreach ($team as $member) {
2983 $membersubmission = $this->get_user_submission($member->id, false);
2984
2985 if (!$membersubmission || $membersubmission->status != ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
2986 $allsubmitted = false;
2987 if ($anysubmitted) {
2988 break;
2989 }
2990 } else {
2991 $anysubmitted = true;
2992 }
2993 }
2994 if ($this->get_instance()->requireallteammemberssubmit) {
2995 if ($allsubmitted) {
2996 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
2997 } else {
2998 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
2999 }
3000 $result= $DB->update_record('assign_submission', $submission);
3001 } else {
3002 if ($anysubmitted) {
3003 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
3004 } else {
3005 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
3006 }
3007 $result= $DB->update_record('assign_submission', $submission);
3008 }
3009
3010 $this->gradebook_item_update($submission);
3011 return $result;
3012 }
3013
3014
bbd0e548
DW
3015 /**
3016 * update grades in the gradebook based on submission time
3017 *
3018 * @param stdClass $submission
12a1a0da 3019 * @param int $userid
bbd0e548 3020 * @param bool $updatetime
12a1a0da 3021 * @param bool $teamsubmission
bbd0e548
DW
3022 * @return bool
3023 */
12a1a0da 3024 private function update_submission(stdClass $submission, $userid, $updatetime, $teamsubmission) {
bbd0e548
DW
3025 global $DB;
3026
12a1a0da
DW
3027 if ($teamsubmission) {
3028 return $this->update_team_submission($submission, $userid, $updatetime);
3029 }
3030
bbd0e548
DW
3031 if ($updatetime) {
3032 $submission->timemodified = time();
3033 }
3034 $result= $DB->update_record('assign_submission', $submission);
3035 if ($result) {
3036 $this->gradebook_item_update($submission);
3037 }
3038 return $result;
3039 }
3040
3041 /**
3042 * Is this assignment open for submissions?
3043 *
3044 * Check the due date,
3045 * prevent late submissions,
3046 * has this person already submitted,
3047 * is the assignment locked?
3048 *
9e795179 3049 * @param int $userid - Optional userid so we can see if a different user can submit
bbd0e548
DW
3050 * @return bool
3051 */
871941a3 3052 public function submissions_open($userid = 0) {
bbd0e548
DW
3053 global $USER;
3054
9e795179
DW
3055 if (!$userid) {
3056 $userid = $USER->id;
3057 }
3058
bbd0e548
DW
3059 $time = time();
3060 $dateopen = true;
9e795179
DW
3061 $finaldate = false;
3062 if ($this->get_instance()->cutoffdate) {
3063 $finaldate = $this->get_instance()->cutoffdate;
3064 }
3065 // User extensions.
3066 if ($finaldate) {
3067 $grade = $this->get_user_grade($userid, false);
3068 if ($grade && $grade->extensionduedate) {
3069 // Extension can be before cut off date.
3070 if ($grade->extensionduedate > $finaldate) {
3071 $finaldate = $grade->extensionduedate;
3072 }
3073 }
3074 }
3075
3076 if ($finaldate) {
3077 $dateopen = ($this->get_instance()->allowsubmissionsfromdate <= $time && $time <= $finaldate);
bbd0e548
DW
3078 } else {
3079 $dateopen = ($this->get_instance()->allowsubmissionsfromdate <= $time);
3080 }
3081
3082 if (!$dateopen) {
3083 return false;
3084 }
3085
9e795179
DW
3086 // Now check if this user has already submitted etc.
3087 if (!is_enrolled($this->get_course_context(), $userid)) {
bbd0e548
DW
3088 return false;
3089 }
cd01491c
DW
3090 $submission = false;
3091 if ($this->get_instance()->teamsubmission) {
87683428 3092 $submission = $this->get_group_submission($userid, 0, false);
cd01491c 3093 } else {
87683428 3094 $submission = $this->get_user_submission($userid, false);
cd01491c
DW
3095 }
3096 if ($submission) {
3097
bbd0e548
DW
3098 if ($this->get_instance()->submissiondrafts && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
3099 // drafts are tracked and the student has submitted the assignment
3100 return false;
3101 }
3102 }
9e795179 3103 if ($grade = $this->get_user_grade($userid, false)) {
bbd0e548
DW
3104 if ($grade->locked) {
3105 return false;
3106 }
3107 }
3108
9e795179 3109 if ($this->grading_disabled($userid)) {
bbd0e548
DW
3110 return false;
3111 }
3112
3113 return true;
3114 }
3115
3116 /**
3117 * render the files in file area
3118 * @param string $component
3119 * @param string $area
3120 * @param int $submissionid
3121 * @return string
3122 */
3123 public function render_area_files($component, $area, $submissionid) {
3124 global $USER;
3125
bbd0e548
DW
3126 $fs = get_file_storage();
3127 $browser = get_file_browser();
3128 $files = $fs->get_area_files($this->get_context()->id, $component, $area , $submissionid , "timemodified", false);
49d83b9d 3129 return $this->get_renderer()->assign_files($this->context, $submissionid, $area, $component);
bbd0e548
DW
3130
3131 }
3132
3133 /**
3134 * Returns a list of teachers that should be grading given submission
3135 *
75f87a57 3136 * @param int $userid
bbd0e548
DW
3137 * @return array
3138 */
75f87a57 3139 private function get_graders($userid) {
bbd0e548 3140 //potential graders
75f87a57 3141 $potentialgraders = get_enrolled_users($this->context, "mod/assign:grade");
bbd0e548
DW
3142
3143 $graders = array();
3144 if (groups_get_activity_groupmode($this->get_course_module()) == SEPARATEGROUPS) { // Separate groups are being used
75f87a57 3145 if ($groups = groups_get_all_groups($this->get_course()->id, $userid)) { // Try to find all groups
bbd0e548
DW
3146 foreach ($groups as $group) {
3147 foreach ($potentialgraders as $grader) {
75f87a57 3148 if ($grader->id == $userid) {
bbd0e548
DW
3149 continue; // do not send self
3150 }
3151 if (groups_is_member($group->id, $grader->id)) {
3152 $graders[$grader->id] = $grader;
3153 }
3154 }
3155 }
3156 } else {
3157 // user not in group, try to find graders without group
3158 foreach ($potentialgraders as $grader) {
75f87a57 3159 if ($grader->id == $userid) {
bbd0e548
DW
3160 continue; // do not send self
3161 }
3162 if (!groups_has_membership($this->get_course_module(), $grader->id)) {
3163 $graders[$grader->id] = $grader;
3164 }
3165 }
3166 }
3167 } else {
3168 foreach ($potentialgraders as $grader) {
75f87a57 3169 if ($grader->id == $userid) {
bbd0e548
DW
3170 continue; // do not send self
3171 }
3172 // must be enrolled
3173 if (is_enrolled($this->get_course_context(), $grader->id)) {
3174 $graders[$grader->id] = $grader;
3175 }
3176 }
3177 }
3178 return $graders;
3179 }
3180
3181 /**
3f7b501e 3182 * Format a notification for plain text
bbd0e548 3183 *
75f87a57
DW
3184 * @param string $messagetype
3185 * @param stdClass $info
3186 * @param stdClass $course
3187 * @param stdClass $context
3188 * @param string $modulename
3189 * @param string $assignmentname
bbd0e548 3190 */
75f87a57
DW
3191 private static function format_notification_message_text($messagetype, $info, $course, $context, $modulename, $assignmentname) {
3192 $posttext = format_string($course->shortname, true, array('context' => $context->get_course_context())).' -> '.
3193 $modulename.' -> '.
3194 format_string($assignmentname, true, array('context' => $context))."\n";
bbd0e548 3195 $posttext .= '---------------------------------------------------------------------'."\n";
75f87a57 3196 $posttext .= get_string($messagetype . 'text', "assign", $info)."\n";
bbd0e548
DW
3197 $posttext .= "\n---------------------------------------------------------------------\n";
3198 return $posttext;
3199 }
3200
75f87a57 3201 /**
3f7b501e 3202 * Format a notification for HTML
bbd0e548 3203 *
75f87a57
DW
3204 * @param string $messagetype
3205 * @param stdClass $info
3f7b501e
SH
3206 * @param stdClass $course
3207 * @param stdClass $context
3208 * @param string $modulename
3209 * @param stdClass $coursemodule
3210 * @param string $assignmentname
3211 * @param stdClass $info
bbd0e548 3212 */
75f87a57 3213 private static function format_notification_message_html($messagetype, $info, $course, $context, $modulename, $coursemodule, $assignmentname) {
bbd0e548
DW
3214 global $CFG;
3215 $posthtml = '<p><font face="sans-serif">'.
75f87a57 3216 '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.format_string($course->shortname, true, array('context' => $context->get_course_context())).'</a> ->'.
599f7a27
RK
3217 '<a href="'.$CFG->wwwroot.'/mod/assign/index.php?id='.$course->id.'">'.$modulename.'</a> ->'.
3218 '<a href="'.$CFG->wwwroot.'/mod/assign/view.php?id='.$coursemodule->id.'">'.format_string($assignmentname, true, array('context' => $context)).'</a></font></p>';
bbd0e548 3219 $posthtml .= '<hr /><font face="sans-serif">';
75f87a57 3220 $posthtml .= '<p>'.get_string($messagetype . 'html', 'assign', $info).'</p>';
bbd0e548
DW
3221 $posthtml .= '</font><hr />';
3222 return $posthtml;
3223 }
3224
75f87a57 3225 /**
c1d09c6f 3226 * Message someone about something (static so it can be called from cron)
75f87a57 3227 *
75f87a57
DW
3228 * @param stdClass $userfrom
3229 * @param stdClass $userto
3230 * @param string $messagetype
3231 * @param string $eventtype
3232 * @param int $updatetime
3233 * @param stdClass $coursemodule
3234 * @param stdClass $context
3235 * @param stdClass $course
3236 * @param string $modulename
75f87a57
DW
3237 * @param string $assignmentname
3238 * @return void
3239 */
3240 public static function send_assignment_notification($userfrom, $userto, $messagetype, $eventtype,
3241 $updatetime, $coursemodule, $context, $course,
b473171a
DW
3242 $modulename, $assignmentname, $blindmarking,
3243 $uniqueidforuser) {
3f7b501e 3244 global $CFG;
75f87a57
DW
3245
3246 $info = new stdClass();
b473171a
DW
3247 if ($blindmarking) {
3248 $info->username = get_string('participant', 'assign') . ' ' . $uniqueidforuser;
3249 } else {
3250 $info->username = fullname($userfrom, true);
3251 }
75f87a57
DW
3252 $info->assignment = format_string($assignmentname,true, array('context'=>$context));
3253 $info->url = $CFG->wwwroot.'/mod/assign/view.php?id='.$coursemodule->id;
a732e1f7 3254 $info->timeupdated = userdate($updatetime, get_string('strftimerecentfull'));
75f87a57
DW
3255
3256 $postsubject = get_string($messagetype . 'small', 'assign', $info);
3257 $posttext = self::format_notification_message_text($messagetype, $info, $course, $context, $modulename, $assignmentname);
3258 $posthtml = ($userto->mailformat == 1) ? self::format_notification_message_html($messagetype, $info, $course, $context, $modulename, $coursemodule, $assignmentname) : '';
3259
3260 $eventdata = new stdClass();
3261 $eventdata->modulename = 'assign';
3262 $eventdata->userfrom = $userfrom;
3263 $eventdata->userto = $userto;
3264 $eventdata->subject = $postsubject;
3265 $eventdata->fullmessage = $posttext;
3266 $eventdata->fullmessageformat = FORMAT_PLAIN;
3267 $eventdata->fullmessagehtml = $posthtml;
3268 $eventdata->smallmessage = $postsubject;
3269
3270 $eventdata->name = $eventtype;
3271 $eventdata->component = 'mod_assign';
3272 $eventdata->notification = 1;
3273 $eventdata->contexturl = $info->url;
3274 $eventdata->contexturlname = $info->assignment;
3275
3276 message_send($eventdata);
75f87a57
DW
3277 }
3278
3279 /**
c1d09c6f 3280 * Message someone about something
75f87a57 3281 *
3f7b501e
SH
3282 * @param stdClass $userfrom
3283 * @param stdClass $userto
3284 * @param string $messagetype
3285 * @param string $eventtype
3286 * @param int $updatetime
75f87a57
DW
3287 * @return void
3288 */
3289 public function send_notification($userfrom, $userto, $messagetype, $eventtype, $updatetime) {
b473171a
DW
3290 self::send_assignment_notification($userfrom, $userto, $messagetype, $eventtype,
3291 $updatetime, $this->get_course_module(), $this->get_context(),
3292 $this->get_course(), $this->get_module_name(),
3293 $this->get_instance()->name, $this->is_blind_marking(),
3294 $this->get_uniqueid_for_user($userfrom->id));
75f87a57
DW
3295 }
3296
3297 /**
c1d09c6f 3298 * Notify student upon successful submission
75f87a57 3299 *
75f87a57
DW
3300 * @param stdClass $submission
3301 * @return void
3302 */
c1d09c6f 3303 private function notify_student_submission_receipt(stdClass $submission) {
12a1a0da 3304 global $DB, $USER;
75f87a57
DW
3305
3306 $adminconfig = $this->get_admin_config();
94f26900 3307 if (empty($adminconfig->submissionreceipts)) {
3f7b501e 3308 // No need to do anything
75f87a57
DW
3309 return;
3310 }
12a1a0da
DW
3311 if ($submission->userid) {
3312 $user = $DB->get_record('user', array('id'=>$submission->userid), '*', MUST_EXIST);
3313 } else {
3314 $user = $USER;
3315 }
f750cf71 3316 $this->send_notification($user, $user, 'submissionreceipt', 'assign_notification', $submission->timemodified);
75f87a57
DW
3317 }
3318
bbd0e548 3319 /**
c1d09c6f 3320 * Send notifications to graders upon student submissions
bbd0e548
DW
3321 *
3322 * @param stdClass $submission
3323 * @return void
3324 */
c1d09c6f 3325 private function notify_graders(stdClass $submission) {
12a1a0da 3326 global $DB, $USER;
75f87a57
DW
3327
3328 $late = $this->get_instance()->duedate && ($this->get_instance()->duedate < time());
bbd0e548 3329
75f87a57 3330 if (!$this->get_instance()->sendnotifications && !($late && $this->get_instance()->sendlatenotifications)) { // No need to do anything
bbd0e548
DW
3331 return;
3332 }
3333
12a1a0da
DW
3334 if ($submission->userid) {
3335 $user = $DB->get_record('user', array('id'=>$submission->userid), '*', MUST_EXIST);
3336 } else {
3337 $user = $USER;
3338 }
75f87a57 3339 if ($teachers = $this->get_graders($user->id)) {
bbd0e548 3340 foreach ($teachers as $teacher) {
f750cf71 3341 $this->send_notification($user, $teacher, 'gradersubmissionupdated', 'assign_notification', $submission->timemodified);
bbd0e548
DW
3342 }
3343 }
3344 }
3345
3346 /**
3347 * assignment submission is processed before grading
3348 *
94f26900
DW
3349 * @param $mform If validation failed when submitting this form - this is the moodleform - it can be null
3350 * @return bool Return false if the validation fails. This affects which page is displayed next.
bbd0e548 3351 */
94f26900
DW
3352 private function process_submit_for_grading($mform) {
3353 global $USER, $CFG;
bbd0e548
DW
3354
3355 // Need submit permission to submit an assignment
3356 require_capability('mod/assign:submit', $this->context);
94f26900 3357 require_once($CFG->dirroot . '/mod/assign/submissionconfirmform.php');
bbd0e548
DW
3358 require_sesskey();
3359
94f26900
DW
3360 $data = new stdClass();
3361 $adminconfig = $this->get_admin_config();
a9b94aff
RW
3362 $requiresubmissionstatement = (!empty($adminconfig->requiresubmissionstatement) ||
3363 $this->get_instance()->requiresubmissionstatement) &&
3364 !empty($adminconfig->submissionstatement);
94f26900
DW
3365
3366 $submissionstatement = '';
3367 if (!empty($adminconfig->submissionstatement)) {
3368 $submissionstatement = $adminconfig->submissionstatement;
3369 }
3370
3371 if ($mform == null) {
3372 $mform = new mod_assign_confirm_submission_form(null, array($requiresubmissionstatement,
3373 $submissionstatement,
3374 $this->get_course_module()->id,
3375 $data));
3376 }
3377
3378 $data = $mform->get_data();
3379 if (!$mform->is_cancelled()) {
3380 if ($mform->get_data() == false) {
3381 return false;
bbd0e548 3382 }
12a1a0da
DW
3383 if ($this->get_instance()->teamsubmission) {
3384 $submission = $this->get_group_submission($USER->id, 0, true);
3385 } else {
3386 $submission = $this->get_user_submission($USER->id, true);
3387 }
3388
94f26900
DW
3389 if ($submission->status != ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
3390 // Give each submission plugin a chance to process the submission
3391 $plugins = $this->get_submission_plugins();
3392 foreach ($plugins as $plugin) {
3393 $plugin->submit_for_grading();
3394 }
bbd0e548 3395
94f26900 3396 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
12a1a0da 3397 $this->update_submission($submission, $USER->id, true, $this->get_instance()->teamsubmission);
79ed4d84
DW
3398 $completion = new completion_info($this->get_course());
3399 if ($completion->is_enabled($this->get_course_module()) && $this->get_instance()->completionsubmit) {
3400 $completion->update_state($this->get_course_module(), COMPLETION_COMPLETE, $USER->id);
3401 }
3402
94f26900
DW
3403 if (isset($data->submissionstatement)) {
3404 $this->add_to_log('submission statement accepted', get_string('submissionstatementacceptedlog', 'mod_assign', fullname($USER)));
3405 }
3406 $this->add_to_log('submit for grading', $this->format_submission_for_log($submission));
3407 $this->notify_graders($submission);
3408 $this->notify_student_submission_receipt($submission);
1defeabf 3409 // Trigger assessable_submitted event on submission.
d37781a5
KG
3410 $eventdata = new stdClass();
3411 $eventdata->modulename = 'assign';
3412 $eventdata->cmid = $this->get_course_module()->id;
3413 $eventdata->itemid = $submission->id;
3414 $eventdata->courseid = $this->get_course()->id;
3415 $eventdata->userid = $USER->id;
c14685e8
RK
3416 $eventdata->params = array(
3417 'submission_editable' => false,
3418 );
f04523f0 3419 events_trigger('assessable_submitted', $eventdata);
94f26900 3420 }
bbd0e548 3421 }
94f26900 3422 return true;
bbd0e548
DW
3423 }
3424
9e795179
DW
3425 /**
3426 * save the extension date for a single user
3427 *
3428 * @param int $userid The user id
3429 * @param mixed $extensionduedate Either an integer date or null
3430 * @return boolean
3431 */
3432 private function save_user_extension($userid, $extensionduedate) {
3433 global $DB;
3434
3435 $grade = $this->get_user_grade($userid, true);
3436 $grade->extensionduedate = $extensionduedate;
3437 $grade->timemodified = time();
3438
3439 $result = $DB->update_record('assign_grades', $grade);
3440
3441 if ($result) {
3442 $this->add_to_log('grant extension', $this->format_grade_for_log($grade));
3443 }
3444 return $result;
3445 }
3446
3447 /**
3448 * save extension date
3449 *
3450 * @param moodleform $mform The submitted form
3451 * @return boolean
3452 */
3453 private function process_save_extension(& $mform) {
3454 global $DB, $CFG;
3455
3456 // Include extension form.
3457 require_once($CFG->dirroot . '/mod/assign/extensionform.php');
3458
3459 // Need submit permission to submit an assignment.
3460 require_capability('mod/assign:grantextension', $this->context);
3461
3462 $batchusers = optional_param('selectedusers', '', PARAM_TEXT);
3463 $userid = 0;
3464 if (!$batchusers) {
3465 $userid = required_param('userid', PARAM_INT);
3466 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
3467 }
3468 $mform = new mod_assign_extension_form(null, array($this->get_course_module()->id,
3469 $userid,