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