MDL-35476 Assignment: Make submissions_open public so it can be used by plugins
[moodle.git] / mod / assign / locallib.php
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/>.
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  */
27 defined('MOODLE_INTERNAL') || die();
29 /**
30  * Assignment submission statuses
31  */
32 define('ASSIGN_SUBMISSION_STATUS_DRAFT', 'draft'); // student thinks it is a draft
33 define('ASSIGN_SUBMISSION_STATUS_SUBMITTED', 'submitted'); // student thinks it is finished
35 /**
36  * Search filters for grading page
37  */
38 define('ASSIGN_FILTER_SUBMITTED', 'submitted');
39 define('ASSIGN_FILTER_SINGLE_USER', 'singleuser');
40 define('ASSIGN_FILTER_REQUIRE_GRADING', 'require_grading');
42 /** Include accesslib.php */
43 require_once($CFG->libdir.'/accesslib.php');
44 /** Include formslib.php */
45 require_once($CFG->libdir.'/formslib.php');
46 /** Include repository/lib.php */
47 require_once($CFG->dirroot . '/repository/lib.php');
48 /** Include local mod_form.php */
49 require_once($CFG->dirroot.'/mod/assign/mod_form.php');
50 /** gradelib.php */
51 require_once($CFG->libdir.'/gradelib.php');
52 /** grading lib.php */
53 require_once($CFG->dirroot.'/grade/grading/lib.php');
54 /** Include feedbackplugin.php */
55 require_once($CFG->dirroot.'/mod/assign/feedbackplugin.php');
56 /** Include submissionplugin.php */
57 require_once($CFG->dirroot.'/mod/assign/submissionplugin.php');
58 /** Include renderable.php */
59 require_once($CFG->dirroot.'/mod/assign/renderable.php');
60 /** Include gradingtable.php */
61 require_once($CFG->dirroot.'/mod/assign/gradingtable.php');
62 /** Include eventslib.php */
63 require_once($CFG->libdir.'/eventslib.php');
64 /** Include portfolio caller.php */
65 require_once($CFG->libdir . '/portfolio/caller.php');
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  */
74 class assign {
77     /** @var stdClass the assignment record that contains the global settings for this assign instance */
78     private $instance;
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;
84     /** @var stdClass the course this assign instance belongs to */
85     private $course;
87     /** @var stdClass the admin config for all assign instances  */
88     private $adminconfig;
91     /** @var assign_renderer the custom renderer for this module */
92     private $output;
94     /** @var stdClass the course module for this assign instance */
95     private $coursemodule;
97     /** @var array cache for things like the coursemodule name or the scale menu - only lives for a single
98         request */
99     private $cache;
101     /** @var array list of the installed submission plugins */
102     private $submissionplugins;
104     /** @var array list of the installed feedback plugins */
105     private $feedbackplugins;
107     /** @var string action to be used to return to this page (without repeating any form submissions etc.) */
108     private $returnaction = 'view';
110     /** @var array params to be used to return to this page */
111     private $returnparams = array();
113     /** @var string modulename prevents excessive calls to get_string */
114     private static $modulename = null;
116     /** @var string modulenameplural prevents excessive calls to get_string */
117     private static $modulenameplural = null;
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;
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
134         $this->submissionplugins = $this->load_plugins('assignsubmission');
135         $this->feedbackplugins = $this->load_plugins('assignfeedback');
136     }
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     }
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     }
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     }
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     }
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     }
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     }
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     }
202     /**
203      * get list of feedback plugins installed
204      * @return array
205      */
206     public function get_feedback_plugins() {
207         return $this->feedbackplugins;
208     }
210     /**
211      * get list of submission plugins installed
212      * @return array
213      */
214     public function get_submission_plugins() {
215         return $this->submissionplugins;
216     }
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     }
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     }
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      */
247     public function get_plugin_by_type($subtype, $type) {
248         $shortsubtype = substr($subtype, strlen('assign'));
249         $name = $shortsubtype . 'plugins';
250         if ($name != 'feedbackplugins' && $name != 'submissionplugins') {
251             return null;
252         }
253         $pluginlist = $this->$name;
254         foreach ($pluginlist as $plugin) {
255             if ($plugin->get_type() == $type) {
256                 return $plugin;
257             }
258         }
259         return null;
260     }
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     }
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     }
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();
289         $names = get_plugin_list($subtype);
291         foreach ($names as $name => $path) {
292             if (file_exists($path . '/locallib.php')) {
293                 require_once($path . '/locallib.php');
295                 $shortsubtype = substr($subtype, strlen('assign'));
296                 $pluginclass = 'assign_' . $shortsubtype . '_' . $name;
298                 $plugin = new $pluginclass($this, $name);
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     }
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='') {
321         $o = '';
322         $mform = null;
323         $notices = array();
325         // Handle form submissions first.
326         if ($action == 'savesubmission') {
327             $action = 'editsubmission';
328             if ($this->process_save_submission($mform, $notices)) {
329                 $action = 'view';
330             }
331         } else if ($action == 'lock') {
332             $this->process_lock();
333             $action = 'grading';
334         } else if ($action == 'reverttodraft') {
335             $this->process_revert_to_draft();
336             $action = 'grading';
337         } else if ($action == 'unlock') {
338             $this->process_unlock();
339             $action = 'grading';
340         } else if ($action == 'confirmsubmit') {
341             $action = 'submit';
342             if ($this->process_submit_for_grading($mform)) {
343                 $action = 'view';
344             }
345         } else if ($action == 'gradingbatchoperation') {
346             $action = $this->process_grading_batch_operation($mform);
347         } else if ($action == 'submitgrade') {
348             if (optional_param('saveandshownext', null, PARAM_RAW)) {
349                 //save and show next
350                 $action = 'grade';
351                 if ($this->process_save_grade($mform)) {
352                     $action = 'nextgrade';
353                 }
354             } else if (optional_param('nosaveandprevious', null, PARAM_RAW)) {
355                 $action = 'previousgrade';
356             } else if (optional_param('nosaveandnext', null, PARAM_RAW)) {
357                 //show next button
358                 $action = 'nextgrade';
359             } else if (optional_param('savegrade', null, PARAM_RAW)) {
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             }
369         } else if ($action == 'quickgrade') {
370             $message = $this->process_save_quick_grades();
371             $action = 'quickgradingresult';
372         } else if ($action == 'saveoptions') {
373             $this->process_save_grading_options();
374             $action = 'grading';
375         } else if ($action == 'saveextension') {
376             $action = 'grantextension';
377             if ($this->process_save_extension($mform)) {
378                 $action = 'grading';
379             }
380         } else if ($action == 'revealidentitiesconfirm') {
381             $this->process_reveal_identities();
382             $action = 'grading';
383         }
385         $returnparams = array('rownum'=>optional_param('rownum', 0, PARAM_INT));
386         $this->register_return_link($action, $returnparams);
388         // Now show the right view page.
389         if ($action == 'previousgrade') {
390             $mform = null;
391             $o .= $this->view_single_grade_page($mform, -1);
392         } else if ($action == 'quickgradingresult') {
393             $mform = null;
394             $o .= $this->view_quickgrading_result($message);
395         } else if ($action == 'nextgrade') {
396             $mform = null;
397             $o .= $this->view_single_grade_page($mform, 1);
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') {
405             $o .= $this->view_edit_submission_page($mform, $notices);
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') {
411             $o .= $this->check_submit_for_grading($mform);
412         } else if ($action == 'grantextension') {
413             $o .= $this->view_grant_extension($mform);
414         } else if ($action == 'revealidentities') {
415             $o .= $this->view_reveal_identities_confirm($mform);
416         } else if ($action == 'plugingradingbatchoperation') {
417             $o .= $this->view_plugin_grading_batch_operation($mform);
418         } else if ($action == 'viewpluginpage') {
419              $o .= $this->view_plugin_page();
420         } else {
421             $o .= $this->view_submission_page();
422         }
424         return $o;
425     }
428     /**
429      * Add this instance to the database
430      *
431      * @param stdClass $formdata The data submitted from the form
432      * @param bool $callplugins This is used to skip the plugin code
433      *             when upgrading an old assignment to a new one (the plugins get called manually)
434      * @return mixed false if an error occurs or the int id of the new instance
435      */
436     public function add_instance(stdClass $formdata, $callplugins) {
437         global $DB;
439         $err = '';
441         // add the database record
442         $update = new stdClass();
443         $update->name = $formdata->name;
444         $update->timemodified = time();
445         $update->timecreated = time();
446         $update->course = $formdata->course;
447         $update->courseid = $formdata->course;
448         $update->intro = $formdata->intro;
449         $update->introformat = $formdata->introformat;
450         $update->alwaysshowdescription = $formdata->alwaysshowdescription;
451         $update->submissiondrafts = $formdata->submissiondrafts;
452         $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
453         $update->sendnotifications = $formdata->sendnotifications;
454         $update->sendlatenotifications = $formdata->sendlatenotifications;
455         $update->duedate = $formdata->duedate;
456         $update->cutoffdate = $formdata->cutoffdate;
457         $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
458         $update->grade = $formdata->grade;
459         $update->completionsubmit = !empty($formdata->completionsubmit);
460         $update->teamsubmission = $formdata->teamsubmission;
461         $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
462         $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
463         $update->blindmarking = $formdata->blindmarking;
465         $returnid = $DB->insert_record('assign', $update);
466         $this->instance = $DB->get_record('assign', array('id'=>$returnid), '*', MUST_EXIST);
467         // cache the course record
468         $this->course = $DB->get_record('course', array('id'=>$formdata->course), '*', MUST_EXIST);
470         if ($callplugins) {
471             // call save_settings hook for submission plugins
472             foreach ($this->submissionplugins as $plugin) {
473                 if (!$this->update_plugin_instance($plugin, $formdata)) {
474                     print_error($plugin->get_error());
475                     return false;
476                 }
477             }
478             foreach ($this->feedbackplugins as $plugin) {
479                 if (!$this->update_plugin_instance($plugin, $formdata)) {
480                     print_error($plugin->get_error());
481                     return false;
482                 }
483             }
485             // in the case of upgrades the coursemodule has not been set so we need to wait before calling these two
486             // TODO: add event to the calendar
487             $this->update_calendar($formdata->coursemodule);
488             // TODO: add the item in the gradebook
489             $this->update_gradebook(false, $formdata->coursemodule);
491         }
493         $update = new stdClass();
494         $update->id = $this->get_instance()->id;
495         $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
496         $DB->update_record('assign', $update);
498         return $returnid;
499     }
501     /**
502      * Delete all grades from the gradebook for this assignment
503      *
504      * @return bool
505      */
506     private function delete_grades() {
507         global $CFG;
509         return grade_update('mod/assign', $this->get_course()->id, 'mod', 'assign', $this->get_instance()->id, 0, NULL, array('deleted'=>1)) == GRADE_UPDATE_OK;
510     }
512     /**
513      * Delete this instance from the database
514      *
515      * @return bool false if an error occurs
516      */
517     public function delete_instance() {
518         global $DB;
519         $result = true;
521         foreach ($this->submissionplugins as $plugin) {
522             if (!$plugin->delete_instance()) {
523                 print_error($plugin->get_error());
524                 $result = false;
525             }
526         }
527         foreach ($this->feedbackplugins as $plugin) {
528             if (!$plugin->delete_instance()) {
529                 print_error($plugin->get_error());
530                 $result = false;
531             }
532         }
534         // delete files associated with this assignment
535         $fs = get_file_storage();
536         if (! $fs->delete_area_files($this->context->id) ) {
537             $result = false;
538         }
540         // delete_records will throw an exception if it fails - so no need for error checking here
542         $DB->delete_records('assign_submission', array('assignment'=>$this->get_instance()->id));
543         $DB->delete_records('assign_grades', array('assignment'=>$this->get_instance()->id));
544         $DB->delete_records('assign_plugin_config', array('assignment'=>$this->get_instance()->id));
546         // delete items from the gradebook
547         if (! $this->delete_grades()) {
548             $result = false;
549         }
551         // delete the instance
552         $DB->delete_records('assign', array('id'=>$this->get_instance()->id));
554         return $result;
555     }
557     /**
558     * Actual implementation of the reset course functionality, delete all the
559     * assignment submissions for course $data->courseid.
560     *
561     * @param $data the data submitted from the reset course.
562     * @return array status array
563     */
564     public function reset_userdata($data) {
565         global $CFG,$DB;
567         $componentstr = get_string('modulenameplural', 'assign');
568         $status = array();
570         $fs = get_file_storage();
571         if (!empty($data->reset_assign_submissions)) {
572             // Delete files associated with this assignment.
573             foreach ($this->submissionplugins as $plugin) {
574                 $fileareas = array();
575                 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
576                 $fileareas = $plugin->get_file_areas();
577                 foreach ($fileareas as $filearea) {
578                     $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
579                 }
581                 if (!$plugin->delete_instance()) {
582                     $status[] = array('component'=>$componentstr,
583                                       'item'=>get_string('deleteallsubmissions','assign'),
584                                       'error'=>$plugin->get_error());
585                 }
586             }
588             foreach ($this->feedbackplugins as $plugin) {
589                 $fileareas = array();
590                 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
591                 $fileareas = $plugin->get_file_areas();
592                 foreach ($fileareas as $filearea) {
593                     $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
594                 }
596                 if (!$plugin->delete_instance()) {
597                     $status[] = array('component'=>$componentstr,
598                                       'item'=>get_string('deleteallsubmissions','assign'),
599                                       'error'=>$plugin->get_error());
600                 }
601             }
603             $assignssql = "SELECT a.id
604                              FROM {assign} a
605                            WHERE a.course=:course";
606             $params = array ("course" => $data->courseid);
608             $DB->delete_records_select('assign_submission', "assignment IN ($assignssql)", $params);
609             $status[] = array('component'=>$componentstr,
610                               'item'=>get_string('deleteallsubmissions','assign'),
611                               'error'=>false);
613             if (empty($data->reset_gradebook_grades)) {
614                 // Remove all grades from gradebook.
615                 require_once($CFG->dirroot.'/mod/assign/lib.php');
616                 assign_reset_gradebook($data->courseid);
617             }
618         }
619         // Updating dates - shift may be negative too.
620         if ($data->timeshift) {
621             shift_course_mod_dates('assign',
622                                     array('duedate', 'allowsubmissionsfromdate','cutoffdate'),
623                                     $data->timeshift,
624                                     $data->courseid);
625             $status[] = array('component'=>$componentstr,
626                               'item'=>get_string('datechanged'),
627                               'error'=>false);
628         }
630         return $status;
631     }
633     /**
634      * Update the settings for a single plugin
635      *
636      * @param assign_plugin $plugin The plugin to update
637      * @param stdClass $formdata The form data
638      * @return bool false if an error occurs
639      */
640     private function update_plugin_instance(assign_plugin $plugin, stdClass $formdata) {
641         if ($plugin->is_visible()) {
642             $enabledname = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
643             if ($formdata->$enabledname) {
644                 $plugin->enable();
645                 if (!$plugin->save_settings($formdata)) {
646                     print_error($plugin->get_error());
647                     return false;
648                 }
649             } else {
650                 $plugin->disable();
651             }
652         }
653         return true;
654     }
656     /**
657      * Update the gradebook information for this assignment
658      *
659      * @param bool $reset If true, will reset all grades in the gradbook for this assignment
660      * @param int $coursemoduleid This is required because it might not exist in the database yet
661      * @return bool
662      */
663     public function update_gradebook($reset, $coursemoduleid) {
664          global $CFG;
665         /** Include lib.php */
666         require_once($CFG->dirroot.'/mod/assign/lib.php');
667         $assign = clone $this->get_instance();
668         $assign->cmidnumber = $coursemoduleid;
669         $param = null;
670         if ($reset) {
671             $param = 'reset';
672         }
674         return assign_grade_item_update($assign, $param);
675     }
677     /** Load and cache the admin config for this module
678      *
679      * @return stdClass the plugin config
680      */
681     public function get_admin_config() {
682         if ($this->adminconfig) {
683             return $this->adminconfig;
684         }
685         $this->adminconfig = get_config('assign');
686         return $this->adminconfig;
687     }
690     /**
691      * Update the calendar entries for this assignment
692      *
693      * @param int $coursemoduleid - Required to pass this in because it might not exist in the database yet
694      * @return bool
695      */
696     public function update_calendar($coursemoduleid) {
697         global $DB, $CFG;
698         require_once($CFG->dirroot.'/calendar/lib.php');
700         // special case for add_instance as the coursemodule has not been set yet.
702         if ($this->get_instance()->duedate) {
703             $event = new stdClass();
705             if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assign', 'instance'=>$this->get_instance()->id))) {
707                 $event->name        = $this->get_instance()->name;
709                 $event->description = format_module_intro('assign', $this->get_instance(), $coursemoduleid);
710                 $event->timestart   = $this->get_instance()->duedate;
712                 $calendarevent = calendar_event::load($event->id);
713                 $calendarevent->update($event);
714             } else {
715                 $event = new stdClass();
716                 $event->name        = $this->get_instance()->name;
717                 $event->description = format_module_intro('assign', $this->get_instance(), $coursemoduleid);
718                 $event->courseid    = $this->get_instance()->course;
719                 $event->groupid     = 0;
720                 $event->userid      = 0;
721                 $event->modulename  = 'assign';
722                 $event->instance    = $this->get_instance()->id;
723                 $event->eventtype   = 'due';
724                 $event->timestart   = $this->get_instance()->duedate;
725                 $event->timeduration = 0;
727                 calendar_event::create($event);
728             }
729         } else {
730             $DB->delete_records('event', array('modulename'=>'assign', 'instance'=>$this->get_instance()->id));
731         }
732     }
735     /**
736      * Update this instance in the database
737      *
738      * @param stdClass $formdata - the data submitted from the form
739      * @return bool false if an error occurs
740      */
741     public function update_instance($formdata) {
742         global $DB;
744         $update = new stdClass();
745         $update->id = $formdata->instance;
746         $update->name = $formdata->name;
747         $update->timemodified = time();
748         $update->course = $formdata->course;
749         $update->intro = $formdata->intro;
750         $update->introformat = $formdata->introformat;
751         $update->alwaysshowdescription = $formdata->alwaysshowdescription;
752         $update->submissiondrafts = $formdata->submissiondrafts;
753         $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
754         $update->sendnotifications = $formdata->sendnotifications;
755         $update->sendlatenotifications = $formdata->sendlatenotifications;
756         $update->duedate = $formdata->duedate;
757         $update->cutoffdate = $formdata->cutoffdate;
758         $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
759         $update->grade = $formdata->grade;
760         $update->completionsubmit = !empty($formdata->completionsubmit);
761         $update->teamsubmission = $formdata->teamsubmission;
762         $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
763         $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
764         $update->blindmarking = $formdata->blindmarking;
766         $result = $DB->update_record('assign', $update);
767         $this->instance = $DB->get_record('assign', array('id'=>$update->id), '*', MUST_EXIST);
769         // load the assignment so the plugins have access to it
771         // call save_settings hook for submission plugins
772         foreach ($this->submissionplugins as $plugin) {
773             if (!$this->update_plugin_instance($plugin, $formdata)) {
774                 print_error($plugin->get_error());
775                 return false;
776             }
777         }
778         foreach ($this->feedbackplugins as $plugin) {
779             if (!$this->update_plugin_instance($plugin, $formdata)) {
780                 print_error($plugin->get_error());
781                 return false;
782             }
783         }
786         // update the database record
789         // update all the calendar events
790         $this->update_calendar($this->get_course_module()->id);
792         $this->update_gradebook(false, $this->get_course_module()->id);
794         $update = new stdClass();
795         $update->id = $this->get_instance()->id;
796         $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
797         $DB->update_record('assign', $update);
803         return $result;
804     }
806     /**
807      * add elements in grading plugin form
808      *
809      * @param mixed $grade stdClass|null
810      * @param MoodleQuickForm $mform
811      * @param stdClass $data
812      * @param int $userid - The userid we are grading
813      * @return void
814      */
815     private function add_plugin_grade_elements($grade, MoodleQuickForm $mform, stdClass $data, $userid) {
816         foreach ($this->feedbackplugins as $plugin) {
817             if ($plugin->is_enabled() && $plugin->is_visible()) {
818                 $mform->addElement('header', 'header_' . $plugin->get_type(), $plugin->get_name());
819                 if (!$plugin->get_form_elements_for_user($grade, $mform, $data, $userid)) {
820                     $mform->removeElement('header_' . $plugin->get_type());
821                 }
822             }
823         }
824     }
828     /**
829      * Add one plugins settings to edit plugin form
830      *
831      * @param assign_plugin $plugin The plugin to add the settings from
832      * @param MoodleQuickForm $mform The form to add the configuration settings to. This form is modified directly (not returned)
833      * @return void
834      */
835     private function add_plugin_settings(assign_plugin $plugin, MoodleQuickForm $mform) {
836         global $CFG;
837         if ($plugin->is_visible()) {
838             // enabled
839             //tied disableIf rule to this select element
840             $mform->addElement('selectyesno', $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $plugin->get_name());
841             $mform->addHelpButton($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', 'enabled', $plugin->get_subtype() . '_' . $plugin->get_type());
844             $default = get_config($plugin->get_subtype() . '_' . $plugin->get_type(), 'default');
845             if ($plugin->get_config('enabled') !== false) {
846                 $default = $plugin->is_enabled();
847             }
848             $mform->setDefault($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $default);
850             $plugin->get_settings($mform);
852         }
854     }
857     /**
858      * Add settings to edit plugin form
859      *
860      * @param MoodleQuickForm $mform The form to add the configuration settings to. This form is modified directly (not returned)
861      * @return void
862      */
863     public function add_all_plugin_settings(MoodleQuickForm $mform) {
864         $mform->addElement('header', 'general', get_string('submissionsettings', 'assign'));
866         foreach ($this->submissionplugins as $plugin) {
867             $this->add_plugin_settings($plugin, $mform);
869         }
870         $mform->addElement('header', 'general', get_string('feedbacksettings', 'assign'));
871         foreach ($this->feedbackplugins as $plugin) {
872             $this->add_plugin_settings($plugin, $mform);
873         }
874     }
876     /**
877      * Allow each plugin an opportunity to update the defaultvalues
878      * passed in to the settings form (needed to set up draft areas for
879      * editor and filemanager elements)
880      * @param array $defaultvalues
881      */
882     public function plugin_data_preprocessing(&$defaultvalues) {
883         foreach ($this->submissionplugins as $plugin) {
884             if ($plugin->is_visible()) {
885                 $plugin->data_preprocessing($defaultvalues);
886             }
887         }
888         foreach ($this->feedbackplugins as $plugin) {
889             if ($plugin->is_visible()) {
890                 $plugin->data_preprocessing($defaultvalues);
891             }
892         }
893     }
895     /**
896      * Get the name of the current module.
897      *
898      * @return string the module name (Assignment)
899      */
900     protected function get_module_name() {
901         if (isset(self::$modulename)) {
902             return self::$modulename;
903         }
904         self::$modulename = get_string('modulename', 'assign');
905         return self::$modulename;
906     }
908     /**
909      * Get the plural name of the current module.
910      *
911      * @return string the module name plural (Assignments)
912      */
913     protected function get_module_name_plural() {
914         if (isset(self::$modulenameplural)) {
915             return self::$modulenameplural;
916         }
917         self::$modulenameplural = get_string('modulenameplural', 'assign');
918         return self::$modulenameplural;
919     }
921     /**
922      * Has this assignment been constructed from an instance?
923      *
924      * @return bool
925      */
926     public function has_instance() {
927         return $this->instance || $this->get_course_module();
928     }
930     /**
931      * Get the settings for the current instance of this assignment
932      *
933      * @return stdClass The settings
934      */
935     public function get_instance() {
936         global $DB;
937         if ($this->instance) {
938             return $this->instance;
939         }
940         if ($this->get_course_module()) {
941             $this->instance = $DB->get_record('assign', array('id' => $this->get_course_module()->instance), '*', MUST_EXIST);
942         }
943         if (!$this->instance) {
944             throw new coding_exception('Improper use of the assignment class. Cannot load the assignment record.');
945         }
946         return $this->instance;
947     }
949     /**
950      * Get the context of the current course
951      * @return mixed context|null The course context
952      */
953     public function get_course_context() {
954         if (!$this->context && !$this->course) {
955             throw new coding_exception('Improper use of the assignment class. Cannot load the course context.');
956         }
957         if ($this->context) {
958             return $this->context->get_course_context();
959         } else {
960             return context_course::instance($this->course->id);
961         }
962     }
965     /**
966      * Get the current course module
967      *
968      * @return mixed stdClass|null The course module
969      */
970     public function get_course_module() {
971         if ($this->coursemodule) {
972             return $this->coursemodule;
973         }
974         if (!$this->context) {
975             return null;
976         }
978         if ($this->context->contextlevel == CONTEXT_MODULE) {
979             $this->coursemodule = get_coursemodule_from_id('assign', $this->context->instanceid, 0, false, MUST_EXIST);
980             return $this->coursemodule;
981         }
982         return null;
983     }
985     /**
986      * Get context module
987      *
988      * @return context
989      */
990     public function get_context() {
991         return $this->context;
992     }
994     /**
995      * Get the current course
996      * @return mixed stdClass|null The course
997      */
998     public function get_course() {
999         global $DB;
1000         if ($this->course) {
1001             return $this->course;
1002         }
1004         if (!$this->context) {
1005             return null;
1006         }
1007         $this->course = $DB->get_record('course', array('id' => $this->get_course_context()->instanceid), '*', MUST_EXIST);
1008         return $this->course;
1009     }
1011     /**
1012      * Return a grade in user-friendly form, whether it's a scale or not
1013      *
1014      * @param mixed $grade int|null
1015      * @param boolean $editing Are we allowing changes to this grade?
1016      * @param int $userid The user id the grade belongs to
1017      * @param int $modified Timestamp from when the grade was last modified
1018      * @return string User-friendly representation of grade
1019      */
1020     public function display_grade($grade, $editing, $userid=0, $modified=0) {
1021         global $DB;
1023         static $scalegrades = array();
1025         if ($this->get_instance()->grade >= 0) {
1026             // Normal number
1027             if ($editing && $this->get_instance()->grade > 0) {
1028                 if ($grade < 0) {
1029                     $displaygrade = '';
1030                 } else {
1031                     $displaygrade = format_float($grade);
1032                 }
1033                 $o = '<label class="accesshide" for="quickgrade_' . $userid . '">' . get_string('usergrade', 'assign') . '</label>';
1034                 $o .= '<input type="text" id="quickgrade_' . $userid . '" name="quickgrade_' . $userid . '" value="' . $displaygrade
1035                         . '" size="6" maxlength="10" class="quickgrade"/>';
1036                 $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade,2);
1037                 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
1038                 return $o;
1039             } else {
1040                 if ($grade == -1 || $grade === null) {
1041                     return '-';
1042                 } else {
1043                     return format_float(($grade),2) .'&nbsp;/&nbsp;'. format_float($this->get_instance()->grade,2);
1044                 }
1045             }
1047         } else {
1048             // Scale
1049             if (empty($this->cache['scale'])) {
1050                 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
1051                     $this->cache['scale'] = make_menu_from_list($scale->scale);
1052                 } else {
1053                     return '-';
1054                 }
1055             }
1056             if ($editing) {
1057                 $o = '<label class="accesshide" for="quickgrade_' . $userid . '">' . get_string('usergrade', 'assign') . '</label>';
1058                 $o .= '<select name="quickgrade_' . $userid . '" class="quickgrade">';
1059                 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
1060                 foreach ($this->cache['scale'] as $optionid => $option) {
1061                     $selected = '';
1062                     if ($grade == $optionid) {
1063                         $selected = 'selected="selected"';
1064                     }
1065                     $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
1066                 }
1067                 $o .= '</select>';
1068                 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
1069                 return $o;
1070             } else {
1071                 $scaleid = (int)$grade;
1072                 if (isset($this->cache['scale'][$scaleid])) {
1073                     return $this->cache['scale'][$scaleid];
1074                 }
1075                 return '-';
1076             }
1077         }
1078     }
1080     /**
1081      * Load a list of users enrolled in the current course with the specified permission and group (0 for no group)
1082      *
1083      * @param int $currentgroup
1084      * @param bool $idsonly
1085      * @return array List of user records
1086      */
1087     public function list_participants($currentgroup, $idsonly) {
1088         if ($idsonly) {
1089             return get_enrolled_users($this->context, "mod/assign:submit", $currentgroup, 'u.id');
1090         } else {
1091             return get_enrolled_users($this->context, "mod/assign:submit", $currentgroup);
1092         }
1093     }
1095     /**
1096      * Load a count of valid teams for this assignment
1097      *
1098      * @return int number of valid teams
1099      */
1100     public function count_teams() {
1102         $groups = groups_get_all_groups($this->get_course()->id, 0, $this->get_instance()->teamsubmissiongroupingid, 'g.id');
1103         $count = count($groups);
1105         // See if there are any users in the default group.
1106         $defaultusers = $this->get_submission_group_members(0, true);
1107         if (count($defaultusers) > 0) {
1108             $count += 1;
1109         }
1110         return $count;
1111     }
1113     /**
1114      * Load a count of users enrolled in the current course with the specified permission and group (0 for no group)
1115      *
1116      * @param int $currentgroup
1117      * @return int number of matching users
1118      */
1119     public function count_participants($currentgroup) {
1120         return count_enrolled_users($this->context, "mod/assign:submit", $currentgroup);
1121     }
1123     /**
1124      * Load a count of users submissions in the current module that require grading
1125      * This means the submission modification time is more recent than the
1126      * grading modification time.
1127      *
1128      * @return int number of matching submissions
1129      */
1130     public function count_submissions_need_grading() {
1131         global $DB;
1133         $params = array($this->get_course_module()->instance);
1135         return $DB->count_records_sql("SELECT COUNT('x')
1136                                        FROM {assign_submission} s
1137                                        LEFT JOIN {assign_grades} g ON s.assignment = g.assignment AND s.userid = g.userid
1138                                        WHERE s.assignment = ?
1139                                            AND s.timemodified IS NOT NULL
1140                                            AND (s.timemodified > g.timemodified OR g.timemodified IS NULL)",
1141                                        $params);
1142     }
1144     /**
1145      * Load a count of grades
1146      *
1147      * @return int number of grades
1148      */
1149     public function count_grades() {
1150         global $DB;
1152         if (!$this->has_instance()) {
1153             return 0;
1154         }
1156         $sql = 'SELECT COUNT(id) FROM {assign_grades} WHERE assignment = ?';
1157         $params = array($this->get_course_module()->instance);
1159         return $DB->count_records_sql($sql, $params);
1160     }
1162     /**
1163      * Load a count of submissions
1164      *
1165      * @return int number of submissions
1166      */
1167     public function count_submissions() {
1168         global $DB;
1170         if (!$this->has_instance()) {
1171             return 0;
1172         }
1174         $sql = 'SELECT COUNT(id) FROM {assign_submission} WHERE assignment = ?';
1175         $params = array($this->get_course_module()->instance);
1177         if ($this->get_instance()->teamsubmission) {
1178             // only look at team submissions
1179             $sql .= ' AND userid = ?';
1180             $params[] = 0;
1181         }
1182         return $DB->count_records_sql($sql, $params);
1183     }
1185     /**
1186      * Load a count of submissions with a specified status
1187      *
1188      * @param string $status The submission status - should match one of the constants
1189      * @return int number of matching submissions
1190      */
1191     public function count_submissions_with_status($status) {
1192         global $DB;
1193         $sql = 'SELECT COUNT(id) FROM {assign_submission} WHERE assignment = ? AND status = ?';
1194         $params = array($this->get_course_module()->instance, $status);
1196         if ($this->get_instance()->teamsubmission) {
1197             // only look at team submissions
1198             $sql .= ' AND userid = ?';
1199             $params[] = 0;
1200         }
1201         return $DB->count_records_sql($sql, $params);
1202     }
1204     /**
1205      * Utility function to get the userid for every row in the grading table
1206      * so the order can be frozen while we iterate it
1207      *
1208      * @return array An array of userids
1209      */
1210     private function get_grading_userid_list() {
1211         $filter = get_user_preferences('assign_filter', '');
1212         $table = new assign_grading_table($this, 0, $filter, 0, false);
1214         $useridlist = $table->get_column_data('userid');
1216         return $useridlist;
1217     }
1220     /**
1221      * Utility function get the userid based on the row number of the grading table.
1222      * This takes into account any active filters on the table.
1223      *
1224      * @param int $num The row number of the user
1225      * @param bool $last This is set to true if this is the last user in the table
1226      * @return mixed The user id of the matching user or false if there was an error
1227      */
1228     private function get_userid_for_row($num, $last) {
1229         if (!array_key_exists('userid_for_row', $this->cache)) {
1230             $this->cache['userid_for_row'] = array();
1231         }
1232         if (array_key_exists($num, $this->cache['userid_for_row'])) {
1233             list($userid, $last) = $this->cache['userid_for_row'][$num];
1234             return $userid;
1235         }
1237         $filter = get_user_preferences('assign_filter', '');
1238         $table = new assign_grading_table($this, 0, $filter, 0, false);
1240         $userid = $table->get_cell_data($num, 'userid', $last);
1242         $this->cache['userid_for_row'][$num] = array($userid, $last);
1243         return $userid;
1244     }
1246     /**
1247      * Generate zip file from array of given files
1248      *
1249      * @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
1250      * @return path of temp file - note this returned file does not have a .zip extension - it is a temp file.
1251      */
1252      private function pack_files($filesforzipping) {
1253          global $CFG;
1254          //create path for new zip file.
1255          $tempzip = tempnam($CFG->tempdir.'/', 'assignment_');
1256          //zip files
1257          $zipper = new zip_packer();
1258          if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
1259              return $tempzip;
1260          }
1261          return false;
1262     }
1264     /**
1265      * Finds all assignment notifications that have yet to be mailed out, and mails them.
1266      *
1267      * Cron function to be run periodically according to the moodle cron
1268      *
1269      * @return bool
1270      */
1271     static function cron() {
1272         global $DB;
1274         // only ever send a max of one days worth of updates
1275         $yesterday = time() - (24 * 3600);
1276         $timenow   = time();
1278         // Collect all submissions from the past 24 hours that require mailing.
1279         $sql = "SELECT s.*, a.course, a.name, a.blindmarking, a.revealidentities,
1280                        g.*, g.id as gradeid, g.timemodified as lastmodified
1281                  FROM {assign} a
1282                  JOIN {assign_grades} g ON g.assignment = a.id
1283             LEFT JOIN {assign_submission} s ON s.assignment = a.id AND s.userid = g.userid
1284                 WHERE g.timemodified >= :yesterday AND
1285                       g.timemodified <= :today AND
1286                       g.mailed = 0";
1287         $params = array('yesterday' => $yesterday, 'today' => $timenow);
1288         $submissions = $DB->get_records_sql($sql, $params);
1290         if (empty($submissions)) {
1291             mtrace('done.');
1292             return true;
1293         }
1295         mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
1297         // Preload courses we are going to need those.
1298         $courseids = array();
1299         foreach ($submissions as $submission) {
1300             $courseids[] = $submission->course;
1301         }
1302         // Filter out duplicates
1303         $courseids = array_unique($courseids);
1304         $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1305         list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
1306         $sql = "SELECT c.*, {$ctxselect}
1307                   FROM {course} c
1308              LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
1309                  WHERE c.id {$courseidsql}";
1310         $params['contextlevel'] = CONTEXT_COURSE;
1311         $courses = $DB->get_records_sql($sql, $params);
1312         // Clean up... this could go on for a while.
1313         unset($courseids);
1314         unset($ctxselect);
1315         unset($courseidsql);
1316         unset($params);
1318         // Simple array we'll use for caching modules.
1319         $modcache = array();
1321         // Message students about new feedback
1322         foreach ($submissions as $submission) {
1324             mtrace("Processing assignment submission $submission->id ...");
1326             // do not cache user lookups - could be too many
1327             if (!$user = $DB->get_record("user", array("id"=>$submission->userid))) {
1328                 mtrace("Could not find user $submission->userid");
1329                 continue;
1330             }
1332             // use a cache to prevent the same DB queries happening over and over
1333             if (!array_key_exists($submission->course, $courses)) {
1334                 mtrace("Could not find course $submission->course");
1335                 continue;
1336             }
1337             $course = $courses[$submission->course];
1338             if (isset($course->ctxid)) {
1339                 // Context has not yet been preloaded. Do so now.
1340                 context_helper::preload_from_record($course);
1341             }
1343             // Override the language and timezone of the "current" user, so that
1344             // mail is customised for the receiver.
1345             cron_setup_user($user, $course);
1347             // context lookups are already cached
1348             $coursecontext = context_course::instance($course->id);
1349             if (!is_enrolled($coursecontext, $user->id)) {
1350                 $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
1351                 mtrace(fullname($user)." not an active participant in " . $courseshortname);
1352                 continue;
1353             }
1355             if (!$grader = $DB->get_record("user", array("id"=>$submission->grader))) {
1356                 mtrace("Could not find grader $submission->grader");
1357                 continue;
1358             }
1360             if (!array_key_exists($submission->assignment, $modcache)) {
1361                 if (! $mod = get_coursemodule_from_instance("assign", $submission->assignment, $course->id)) {
1362                     mtrace("Could not find course module for assignment id $submission->assignment");
1363                     continue;
1364                 }
1365                 $modcache[$submission->assignment] = $mod;
1366             } else {
1367                 $mod = $modcache[$submission->assignment];
1368             }
1369             // context lookups are already cached
1370             $contextmodule = context_module::instance($mod->id);
1372             if (!$mod->visible) {
1373                 // Hold mail notification for hidden assignments until later
1374                 continue;
1375             }
1377             // need to send this to the student
1378             $messagetype = 'feedbackavailable';
1379             $eventtype = 'assign_notification';
1380             $updatetime = $submission->lastmodified;
1381             $modulename = get_string('modulename', 'assign');
1383             $uniqueid = 0;
1384             if ($submission->blindmarking && !$submission->revealidentities) {
1385                 $uniqueid = self::get_uniqueid_for_user_static($submission->assignment, $user->id);
1386             }
1387             self::send_assignment_notification($grader, $user, $messagetype, $eventtype, $updatetime,
1388                                                $mod, $contextmodule, $course, $modulename, $submission->name,
1389                                                $submission->blindmarking && !$submission->revealidentities,
1390                                                $uniqueid);
1392             $grade = new stdClass();
1393             $grade->id = $submission->gradeid;
1394             $grade->mailed = 1;
1395             $DB->update_record('assign_grades', $grade);
1397             mtrace('Done');
1398         }
1399         mtrace('Done processing ' . count($submissions) . ' assignment submissions');
1401         cron_setup_user();
1403         // Free up memory just to be sure
1404         unset($courses);
1405         unset($modcache);
1407         return true;
1408     }
1410     /**
1411      * Update a grade in the grade table for the assignment and in the gradebook
1412      *
1413      * @param stdClass $grade a grade record keyed on id
1414      * @return bool true for success
1415      */
1416     public function update_grade($grade) {
1417         global $DB;
1419         $grade->timemodified = time();
1421         if ($grade->grade && $grade->grade != -1) {
1422             if ($this->get_instance()->grade > 0) {
1423                 if (!is_numeric($grade->grade)) {
1424                     return false;
1425                 } else if ($grade->grade > $this->get_instance()->grade) {
1426                     return false;
1427                 } else if ($grade->grade < 0) {
1428                     return false;
1429                 }
1430             } else {
1431                 // this is a scale
1432                 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
1433                     $scaleoptions = make_menu_from_list($scale->scale);
1434                     if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
1435                         return false;
1436                     }
1437                 }
1438             }
1439         }
1441         $result = $DB->update_record('assign_grades', $grade);
1442         if ($result) {
1443             $this->gradebook_item_update(null, $grade);
1444         }
1445         return $result;
1446     }
1448     /**
1449      * View the grant extension date page
1450      *
1451      * Uses url parameters 'userid'
1452      * or from parameter 'selectedusers'
1453      * @param moodleform $mform - Used for validation of the submitted data
1454      * @return string
1455      */
1456     private function view_grant_extension($mform) {
1457         global $DB, $CFG;
1458         require_once($CFG->dirroot . '/mod/assign/extensionform.php');
1460         $o = '';
1461         $batchusers = optional_param('selectedusers', '', PARAM_TEXT);
1462         $data = new stdClass();
1463         $data->extensionduedate = null;
1464         $userid = 0;
1465         if (!$batchusers) {
1466             $userid = required_param('userid', PARAM_INT);
1468             $grade = $this->get_user_grade($userid, false);
1470             $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
1472             if ($grade) {
1473                 $data->extensionduedate = $grade->extensionduedate;
1474             }
1475             $data->userid = $userid;
1476         } else {
1477             $data->batchusers = $batchusers;
1478         }
1479         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
1480                                                       $this->get_context(),
1481                                                       $this->show_intro(),
1482                                                       $this->get_course_module()->id,
1483                                                       get_string('grantextension', 'assign')));
1485         if (!$mform) {
1486             $mform = new mod_assign_extension_form(null, array($this->get_course_module()->id,
1487                                                                $userid,
1488                                                                $batchusers,
1489                                                                $this->get_instance(),
1490                                                                $data));
1491         }
1492         $o .= $this->get_renderer()->render(new assign_form('extensionform', $mform));
1493         $o .= $this->view_footer();
1494         return $o;
1495     }
1497     /**
1498      * Get a list of the users in the same group as this user
1499      *
1500      * @param int $groupid The id of the group whose members we want or 0 for the default group
1501      * @param bool $onlyids Whether to retrieve only the user id's
1502      * @return array The users (possibly id's only)
1503      */
1504     public function get_submission_group_members($groupid, $onlyids) {
1505         $members = array();
1506         if ($groupid != 0) {
1507             if ($onlyids) {
1508                 $allusers = groups_get_members($groupid, 'u.id');
1509             } else {
1510                 $allusers = groups_get_members($groupid);
1511             }
1512             foreach ($allusers as $user) {
1513                 if ($this->get_submission_group($user->id)) {
1514                     $members[] = $user;
1515                 }
1516             }
1517         } else {
1518             $allusers = $this->list_participants(null, $onlyids);
1519             foreach ($allusers as $user) {
1520                 if ($this->get_submission_group($user->id) == null) {
1521                     $members[] = $user;
1522                 }
1523             }
1524         }
1525         return $members;
1526     }
1528     /**
1529      * Get a list of the users in the same group as this user that have not submitted the assignment
1530      *
1531      * @param int $groupid The id of the group whose members we want or 0 for the default group
1532      * @param bool $onlyids Whether to retrieve only the user id's
1533      * @return array The users (possibly id's only)
1534      */
1535     public function get_submission_group_members_who_have_not_submitted($groupid, $onlyids) {
1536         if (!$this->get_instance()->teamsubmission || !$this->get_instance()->requireallteammemberssubmit) {
1537             return array();
1538         }
1539         $members = $this->get_submission_group_members($groupid, $onlyids);
1541         foreach ($members as $id => $member) {
1542             $submission = $this->get_user_submission($member->id, false);
1543             if ($submission && $submission->status != ASSIGN_SUBMISSION_STATUS_DRAFT) {
1544                 unset($members[$id]);
1545             } else {
1546                 if ($this->is_blind_marking()) {
1547                     $members[$id]->alias = get_string('hiddenuser', 'assign') . $this->get_uniqueid_for_user($id);
1548                 }
1549             }
1550         }
1551         return $members;
1552     }
1554     /**
1555      * Load the group submission object for a particular user, optionally creating it if required
1556      *
1557      * This will create the user submission and the group submission if required
1558      *
1559      * @param int $userid The id of the user whose submission we want
1560      * @param int $groupid The id of the group for this user - may be 0 in which case it is determined from the userid
1561      * @param bool $create If set to true a new submission object will be created in the database
1562      * @return stdClass The submission
1563      */
1564     public function get_group_submission($userid, $groupid, $create) {
1565         global $DB;
1567         if ($groupid == 0) {
1568             $group = $this->get_submission_group($userid);
1569             if ($group) {
1570                 $groupid = $group->id;
1571             }
1572         }
1574         if ($create) {
1575             // Make sure there is a submission for this user.
1576             $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>0, 'userid'=>$userid);
1577             $submission = $DB->get_record('assign_submission', $params);
1579             if (!$submission) {
1580                 $submission = new stdClass();
1581                 $submission->assignment   = $this->get_instance()->id;
1582                 $submission->userid       = $userid;
1583                 $submission->groupid      = 0;
1584                 $submission->timecreated  = time();
1585                 $submission->timemodified = $submission->timecreated;
1587                 if ($this->get_instance()->submissiondrafts) {
1588                     $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
1589                 } else {
1590                     $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1591                 }
1592                 $DB->insert_record('assign_submission', $submission);
1593             }
1594         }
1595         // Now get the group submission.
1596         $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
1597         $submission = $DB->get_record('assign_submission', $params);
1599         if ($submission) {
1600             return $submission;
1601         }
1602         if ($create) {
1603             $submission = new stdClass();
1604             $submission->assignment   = $this->get_instance()->id;
1605             $submission->userid       = 0;
1606             $submission->groupid       = $groupid;
1607             $submission->timecreated = time();
1608             $submission->timemodified = $submission->timecreated;
1610             if ($this->get_instance()->submissiondrafts) {
1611                 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
1612             } else {
1613                 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1614             }
1615             $sid = $DB->insert_record('assign_submission', $submission);
1616             $submission->id = $sid;
1617             return $submission;
1618         }
1619         return false;
1620     }
1622     /**
1623      * View a page rendered by a plugin
1624      *
1625      * Uses url parameters 'pluginaction', 'pluginsubtype', 'plugin', and 'id'
1626      *
1627      * @return string
1628      */
1629     private function view_plugin_page() {
1630         global $USER;
1632         $o = '';
1634         $pluginsubtype = required_param('pluginsubtype', PARAM_ALPHA);
1635         $plugintype = required_param('plugin', PARAM_TEXT);
1636         $pluginaction = required_param('pluginaction', PARAM_ALPHA);
1638         $plugin = $this->get_plugin_by_type($pluginsubtype, $plugintype);
1639         if (!$plugin) {
1640             print_error('invalidformdata', '');
1641             return;
1642         }
1644         $o .= $plugin->view_page($pluginaction);
1646         return $o;
1647     }
1650     /**
1651      * This is used for team assignments to get the group for the specified user.
1652      * If the user is a member of multiple or no groups this will return false
1653      *
1654      * @param int $userid The id of the user whose submission we want
1655      * @return mixed The group or false
1656      */
1657     public function get_submission_group($userid) {
1658         $groups = groups_get_all_groups($this->get_course()->id, $userid, $this->get_instance()->teamsubmissiongroupingid);
1659         if (count($groups) != 1) {
1660             return false;
1661         }
1662         return array_pop($groups);
1663     }
1666     /**
1667      * display the submission that is used by a plugin
1668      * Uses url parameters 'sid', 'gid' and 'plugin'
1669      * @param string $pluginsubtype
1670      * @return string
1671      */
1672     private function view_plugin_content($pluginsubtype) {
1673         global $USER;
1675         $o = '';
1677         $submissionid = optional_param('sid', 0, PARAM_INT);
1678         $gradeid = optional_param('gid', 0, PARAM_INT);
1679         $plugintype = required_param('plugin', PARAM_TEXT);
1680         $item = null;
1681         if ($pluginsubtype == 'assignsubmission') {
1682             $plugin = $this->get_submission_plugin_by_type($plugintype);
1683             if ($submissionid <= 0) {
1684                 throw new coding_exception('Submission id should not be 0');
1685             }
1686             $item = $this->get_submission($submissionid);
1688             // permissions
1689             if ($item->userid != $USER->id) {
1690                 require_capability('mod/assign:grade', $this->context);
1691             }
1692             $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
1693                                                               $this->get_context(),
1694                                                               $this->show_intro(),
1695                                                               $this->get_course_module()->id,
1696                                                               $plugin->get_name()));
1697             $o .= $this->get_renderer()->render(new assign_submission_plugin_submission($plugin,
1698                                                               $item,
1699                                                               assign_submission_plugin_submission::FULL,
1700                                                               $this->get_course_module()->id,
1701                                                               $this->get_return_action(),
1702                                                               $this->get_return_params()));
1704             $this->add_to_log('view submission', get_string('viewsubmissionforuser', 'assign', $item->userid));
1705         } else {
1706             $plugin = $this->get_feedback_plugin_by_type($plugintype);
1707             if ($gradeid <= 0) {
1708                 throw new coding_exception('Grade id should not be 0');
1709             }
1710             $item = $this->get_grade($gradeid);
1711             // permissions
1712             if ($item->userid != $USER->id) {
1713                 require_capability('mod/assign:grade', $this->context);
1714             }
1715             $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
1716                                                               $this->get_context(),
1717                                                               $this->show_intro(),
1718                                                               $this->get_course_module()->id,
1719                                                               $plugin->get_name()));
1720             $o .= $this->get_renderer()->render(new assign_feedback_plugin_feedback($plugin,
1721                                                               $item,
1722                                                               assign_feedback_plugin_feedback::FULL,
1723                                                               $this->get_course_module()->id,
1724                                                               $this->get_return_action(),
1725                                                               $this->get_return_params()));
1726             $this->add_to_log('view feedback', get_string('viewfeedbackforuser', 'assign', $item->userid));
1727         }
1730         $o .= $this->view_return_links();
1732         $o .= $this->view_footer();
1733         return $o;
1734     }
1736     /**
1737      * render the content in editor that is often used by plugin
1738      *
1739      * @param string $filearea
1740      * @param int  $submissionid
1741      * @param string $plugintype
1742      * @param string $editor
1743      * @param string $component
1744      * @return string
1745      */
1746     public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
1747         global $CFG;
1749         $result = '';
1751         $plugin = $this->get_submission_plugin_by_type($plugintype);
1753         $text = $plugin->get_editor_text($editor, $submissionid);
1754         $format = $plugin->get_editor_format($editor, $submissionid);
1756         $finaltext = file_rewrite_pluginfile_urls($text, 'pluginfile.php', $this->get_context()->id, $component, $filearea, $submissionid);
1757         $result .= format_text($finaltext, $format, array('overflowdiv' => true, 'context' => $this->get_context()));
1761         if ($CFG->enableportfolios) {
1762             require_once($CFG->libdir . '/portfoliolib.php');
1764             $button = new portfolio_add_button();
1765             $button->set_callback_options('assign_portfolio_caller', array('cmid' => $this->get_course_module()->id,
1766                                           'sid' => $submissionid, 'plugin' => $plugintype, 'editor' => $editor, 'area'=>$filearea),
1767                                           'mod_assign');
1768             $fs = get_file_storage();
1770             if ($files = $fs->get_area_files($this->context->id, $component,$filearea, $submissionid, "timemodified", false)) {
1771                 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
1772             } else {
1773                 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
1774             }
1775             $result .= $button->to_html();
1776         }
1777         return $result;
1778     }
1780     /**
1781      * Display a grading error
1782      *
1783      * @param string $message - The description of the result
1784      * @return string
1785      */
1786     private function view_quickgrading_result($message) {
1787         $o = '';
1788         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
1789                                                       $this->get_context(),
1790                                                       $this->show_intro(),
1791                                                       $this->get_course_module()->id,
1792                                                       get_string('quickgradingresult', 'assign')));
1793         $o .= $this->get_renderer()->render(new assign_quickgrading_result($message, $this->get_course_module()->id));
1794         $o .= $this->view_footer();
1795         return $o;
1796     }
1798     /**
1799      * Display the page footer
1800      *
1801      * @return string
1802      */
1803     private function view_footer() {
1804         return $this->get_renderer()->render_footer();
1805     }
1807     /**
1808      * Does this user have grade permission for this assignment
1809      *
1810      * @return bool
1811      */
1812     private function can_grade() {
1813         // Permissions check
1814         if (!has_capability('mod/assign:grade', $this->context)) {
1815             return false;
1816         }
1818         return true;
1819     }
1821     /**
1822      * Download a zip file of all assignment submissions
1823      *
1824      * @return void
1825      */
1826     private function download_submissions() {
1827         global $CFG,$DB;
1829         // More efficient to load this here.
1830         require_once($CFG->libdir.'/filelib.php');
1832         // Load all users with submit.
1833         $students = get_enrolled_users($this->context, "mod/assign:submit");
1835         // Build a list of files to zip.
1836         $filesforzipping = array();
1837         $fs = get_file_storage();
1839         $groupmode = groups_get_activity_groupmode($this->get_course_module());
1840         // All users.
1841         $groupid = 0;
1842         $groupname = '';
1843         if ($groupmode) {
1844             $groupid = groups_get_activity_group($this->get_course_module(), true);
1845             $groupname = groups_get_group_name($groupid).'-';
1846         }
1848         // Construct the zip file name.
1849         $filename = clean_filename($this->get_course()->shortname.'-'.
1850                                    $this->get_instance()->name.'-'.
1851                                    $groupname.$this->get_course_module()->id.".zip");
1853         // Get all the files for each student.
1854         foreach ($students as $student) {
1855             $userid = $student->id;
1857             if ((groups_is_member($groupid, $userid) or !$groupmode or !$groupid)) {
1858                 // Get the plugins to add their own files to the zip.
1860                 $submissiongroup = false;
1861                 $groupname = '';
1862                 if ($this->get_instance()->teamsubmission) {
1863                     $submission = $this->get_group_submission($userid, 0, false);
1864                     $submissiongroup = $this->get_submission_group($userid);
1865                     if ($submissiongroup) {
1866                         $groupname = $submissiongroup->name . '-';
1867                     } else {
1868                         $groupname = get_string('defaultteam', 'assign') . '-';
1869                     }
1870                 } else {
1871                     $submission = $this->get_user_submission($userid, false);
1872                 }
1874                 if ($this->is_blind_marking()) {
1875                     $prefix = clean_filename(str_replace('_', ' ', $groupname . get_string('participant', 'assign')) .
1876                                              "_" . $this->get_uniqueid_for_user($userid) . "_");
1877                 } else {
1878                     $prefix = clean_filename(str_replace('_', ' ', $groupname . fullname($student)) .
1879                                              "_" . $this->get_uniqueid_for_user($userid) . "_");
1880                 }
1882                 if ($submission) {
1883                     foreach ($this->submissionplugins as $plugin) {
1884                         if ($plugin->is_enabled() && $plugin->is_visible()) {
1885                             $pluginfiles = $plugin->get_files($submission);
1886                             foreach ($pluginfiles as $zipfilename => $file) {
1887                                 $subtype = $plugin->get_subtype();
1888                                 $type = $plugin->get_type();
1889                                 $prefixedfilename = $prefix . $subtype . '_' . $type . '_' . $zipfilename;
1890                                 $filesforzipping[$prefixedfilename] = $file;
1891                             }
1892                         }
1893                     }
1894                 }
1895             }
1896         }
1897         if ($zipfile = $this->pack_files($filesforzipping)) {
1898             $this->add_to_log('download all submissions', get_string('downloadall', 'assign'));
1899             // Send file and delete after sending.
1900             send_temp_file($zipfile, $filename);
1901         }
1902     }
1904     /**
1905      * Util function to add a message to the log
1906      *
1907      * @param string $action The current action
1908      * @param string $info A detailed description of the change. But no more than 255 characters.
1909      * @param string $url The url to the assign module instance.
1910      * @return void
1911      */
1912     public function add_to_log($action = '', $info = '', $url='') {
1913         global $USER;
1915         $fullurl = 'view.php?id=' . $this->get_course_module()->id;
1916         if ($url != '') {
1917             $fullurl .= '&' . $url;
1918         }
1920         add_to_log($this->get_course()->id, 'assign', $action, $fullurl, $info, $this->get_course_module()->id, $USER->id);
1921     }
1923     /**
1924      * Lazy load the page renderer and expose the renderer to plugins
1925      *
1926      * @return assign_renderer
1927      */
1928     public function get_renderer() {
1929         global $PAGE;
1930         if ($this->output) {
1931             return $this->output;
1932         }
1933         $this->output = $PAGE->get_renderer('mod_assign');
1934         return $this->output;
1935     }
1937     /**
1938      * Load the submission object for a particular user, optionally creating it if required
1939      *
1940      * For team assignments there are 2 submissions - the student submission and the team submission
1941      * All files are associated with the team submission but the status of the students contribution is
1942      * recorded separately.
1943      *
1944      * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
1945      * @param bool $create optional Defaults to false. If set to true a new submission object will be created in the database
1946      * @return stdClass The submission
1947      */
1948     public function get_user_submission($userid, $create) {
1949         global $DB, $USER;
1951         if (!$userid) {
1952             $userid = $USER->id;
1953         }
1954         // If the userid is not null then use userid.
1955         $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid, 'groupid'=>0);
1956         $submission = $DB->get_record('assign_submission', $params);
1958         if ($submission) {
1959             return $submission;
1960         }
1961         if ($create) {
1962             $submission = new stdClass();
1963             $submission->assignment   = $this->get_instance()->id;
1964             $submission->userid       = $userid;
1965             $submission->timecreated = time();
1966             $submission->timemodified = $submission->timecreated;
1968             if ($this->get_instance()->submissiondrafts) {
1969                 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
1970             } else {
1971                 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1972             }
1973             $sid = $DB->insert_record('assign_submission', $submission);
1974             $submission->id = $sid;
1975             return $submission;
1976         }
1977         return false;
1978     }
1980     /**
1981      * Load the submission object from it's id
1982      *
1983      * @param int $submissionid The id of the submission we want
1984      * @return stdClass The submission
1985      */
1986     private function get_submission($submissionid) {
1987         global $DB;
1989         return $DB->get_record('assign_submission', array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid), '*', MUST_EXIST);
1990     }
1992     /**
1993      * This will retrieve a grade object from the db, optionally creating it if required
1994      *
1995      * @param int $userid The user we are grading
1996      * @param bool $create If true the grade will be created if it does not exist
1997      * @return stdClass The grade record
1998      */
1999     public function get_user_grade($userid, $create) {
2000         global $DB, $USER;
2002         if (!$userid) {
2003             $userid = $USER->id;
2004         }
2006         // if the userid is not null then use userid
2007         $grade = $DB->get_record('assign_grades', array('assignment'=>$this->get_instance()->id, 'userid'=>$userid));
2009         if ($grade) {
2010             return $grade;
2011         }
2012         if ($create) {
2013             $grade = new stdClass();
2014             $grade->assignment   = $this->get_instance()->id;
2015             $grade->userid       = $userid;
2016             $grade->timecreated = time();
2017             $grade->timemodified = $grade->timecreated;
2018             $grade->locked = 0;
2019             $grade->grade = -1;
2020             $grade->grader = $USER->id;
2021             $grade->extensionduedate = 0;
2022             $gid = $DB->insert_record('assign_grades', $grade);
2023             $grade->id = $gid;
2024             return $grade;
2025         }
2026         return false;
2027     }
2029     /**
2030      * This will retrieve a grade object from the db
2031      *
2032      * @param int $gradeid The id of the grade
2033      * @return stdClass The grade record
2034      */
2035     private function get_grade($gradeid) {
2036         global $DB;
2038         return $DB->get_record('assign_grades', array('assignment'=>$this->get_instance()->id, 'id'=>$gradeid), '*', MUST_EXIST);
2039     }
2041     /**
2042      * Print the grading page for a single user submission
2043      *
2044      * @param moodleform $mform
2045      * @param int $offset
2046      * @return string
2047      */
2048     private function view_single_grade_page($mform, $offset=0) {
2049         global $DB, $CFG;
2051         $o = '';
2053         // Include grade form
2054         require_once($CFG->dirroot . '/mod/assign/gradeform.php');
2056         // Need submit permission to submit an assignment
2057         require_capability('mod/assign:grade', $this->context);
2059         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2060                                                       $this->get_context(), false, $this->get_course_module()->id,get_string('grading', 'assign')));
2062         $rownum = required_param('rownum', PARAM_INT) + $offset;
2063         $useridlist = optional_param('useridlist', '', PARAM_TEXT);
2064         if ($useridlist) {
2065             $useridlist = explode(',', $useridlist);
2066         } else {
2067             $useridlist = $this->get_grading_userid_list();
2068         }
2069         $last = false;
2070         $userid = $useridlist[$rownum];
2071         if ($rownum == count($useridlist) - 1) {
2072             $last = true;
2073         }
2074         if (!$userid) {
2075             throw new coding_exception('Row is out of bounds for the current grading table: ' . $rownum);
2076         }
2077         $user = $DB->get_record('user', array('id' => $userid));
2078         if ($user) {
2079             $o .= $this->get_renderer()->render(new assign_user_summary($user,
2080                                                                 $this->get_course()->id,
2081                                                                 has_capability('moodle/site:viewfullnames',
2082                                                                 $this->get_course_context()),
2083                                                                 $this->is_blind_marking(),
2084                                                                 $this->get_uniqueid_for_user($user->id)));
2085         }
2086         $submission = $this->get_user_submission($userid, false);
2087         $submissiongroup = null;
2088         $submissiongroupmemberswhohavenotsubmitted = array();
2089         $teamsubmission = null;
2090         $notsubmitted = array();
2091         if ($this->get_instance()->teamsubmission) {
2092             $teamsubmission = $this->get_group_submission($userid, 0, false);
2093             $submissiongroup = $this->get_submission_group($userid);
2094             $groupid = 0;
2095             if ($submissiongroup) {
2096                 $groupid = $submissiongroup->id;
2097             }
2098             $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
2100         }
2102         // get the current grade
2103         $grade = $this->get_user_grade($userid, false);
2104         if ($this->can_view_submission($userid)) {
2105             $gradelocked = ($grade && $grade->locked) || $this->grading_disabled($userid);
2106             $extensionduedate = null;
2107             if ($grade) {
2108                 $extensionduedate = $grade->extensionduedate;
2109             }
2110             $showedit = $this->submissions_open($userid) && ($this->is_any_submission_plugin_enabled());
2112             if ($teamsubmission) {
2113                 $showsubmit = $showedit && $teamsubmission && ($teamsubmission->status == ASSIGN_SUBMISSION_STATUS_DRAFT);
2114             } else {
2115                 $showsubmit = $showedit && $submission && ($submission->status == ASSIGN_SUBMISSION_STATUS_DRAFT);
2116             }
2117             $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2119             $o .= $this->get_renderer()->render(new assign_submission_status($this->get_instance()->allowsubmissionsfromdate,
2120                                                               $this->get_instance()->alwaysshowdescription,
2121                                                               $submission,
2122                                                               $this->get_instance()->teamsubmission,
2123                                                               $teamsubmission,
2124                                                               $submissiongroup,
2125                                                               $notsubmitted,
2126                                                               $this->is_any_submission_plugin_enabled(),
2127                                                               $gradelocked,
2128                                                               $this->is_graded($userid),
2129                                                               $this->get_instance()->duedate,
2130                                                               $this->get_instance()->cutoffdate,
2131                                                               $this->get_submission_plugins(),
2132                                                               $this->get_return_action(),
2133                                                               $this->get_return_params(),
2134                                                               $this->get_course_module()->id,
2135                                                               $this->get_course()->id,
2136                                                               assign_submission_status::GRADER_VIEW,
2137                                                               $showedit,
2138                                                               $showsubmit,
2139                                                               $viewfullnames,
2140                                                               $extensionduedate,
2141                                                               $this->get_context(),
2142                                                               $this->is_blind_marking(),
2143                                                               ''));
2144         }
2145         if ($grade) {
2146             $data = new stdClass();
2147             if ($grade->grade !== NULL && $grade->grade >= 0) {
2148                 $data->grade = format_float($grade->grade,2);
2149             }
2150         } else {
2151             $data = new stdClass();
2152             $data->grade = '';
2153         }
2155         // now show the grading form
2156         if (!$mform) {
2157             $pagination = array( 'rownum'=>$rownum, 'useridlist'=>$useridlist, 'last'=>$last);
2158             $formparams = array($this, $data, $pagination);
2159             $mform = new mod_assign_grade_form(null,
2160                                                $formparams,
2161                                                'post',
2162                                                '',
2163                                                array('class'=>'gradeform'));
2164         }
2165         $o .= $this->get_renderer()->render(new assign_form('gradingform',$mform));
2167         $msg = get_string('viewgradingformforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user)));
2168         $this->add_to_log('view grading form', $msg);
2170         $o .= $this->view_footer();
2171         return $o;
2172     }
2174     /**
2175      * Show a confirmation page to make sure they want to release student identities
2176      *
2177      * @return string
2178      */
2179     private function view_reveal_identities_confirm() {
2180         global $CFG, $USER;
2182         require_capability('mod/assign:revealidentities', $this->get_context());
2184         $o = '';
2185         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2186                                                       $this->get_context(), false, $this->get_course_module()->id));
2188         $confirmurl = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id,
2189                                                                     'action'=>'revealidentitiesconfirm',
2190                                                                     'sesskey'=>sesskey()));
2192         $cancelurl = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id,
2193                                                                     'action'=>'grading'));
2195         $o .= $this->get_renderer()->confirm(get_string('revealidentitiesconfirm', 'assign'), $confirmurl, $cancelurl);
2196         $o .= $this->view_footer();
2197         $this->add_to_log('view', get_string('viewrevealidentitiesconfirm', 'assign'));
2198         return $o;
2199     }
2204     /**
2205      * View a link to go back to the previous page. Uses url parameters returnaction and returnparams.
2206      *
2207      * @return string
2208      */
2209     private function view_return_links() {
2211         $returnaction = optional_param('returnaction','', PARAM_ALPHA);
2212         $returnparams = optional_param('returnparams','', PARAM_TEXT);
2214         $params = array();
2215         parse_str($returnparams, $params);
2216         $params = array_merge( array('id' => $this->get_course_module()->id, 'action' => $returnaction), $params);
2218         return $this->get_renderer()->single_button(new moodle_url('/mod/assign/view.php', $params), get_string('back'), 'get');
2220     }
2222     /**
2223      * View the grading table of all submissions for this assignment
2224      *
2225      * @return string
2226      */
2227     private function view_grading_table() {
2228         global $USER, $CFG;
2229         // Include grading options form
2230         require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
2231         require_once($CFG->dirroot . '/mod/assign/quickgradingform.php');
2232         require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
2233         $o = '';
2235         $links = array();
2236         if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
2237                 has_capability('moodle/grade:viewall', $this->get_course_context())) {
2238             $gradebookurl = '/grade/report/grader/index.php?id=' . $this->get_course()->id;
2239             $links[$gradebookurl] = get_string('viewgradebook', 'assign');
2240         }
2241         if ($this->is_any_submission_plugin_enabled()) {
2242             $downloadurl = '/mod/assign/view.php?id=' . $this->get_course_module()->id . '&action=downloadall';
2243             $links[$downloadurl] = get_string('downloadall', 'assign');
2244         }
2245         if ($this->is_blind_marking() && has_capability('mod/assign:revealidentities', $this->get_context())) {
2246             $revealidentitiesurl = '/mod/assign/view.php?id=' . $this->get_course_module()->id . '&action=revealidentities';
2247             $links[$revealidentitiesurl] = get_string('revealidentities', 'assign');
2248         }
2249         foreach ($this->get_feedback_plugins() as $plugin) {
2250             if ($plugin->is_enabled() && $plugin->is_visible()) {
2251                 foreach ($plugin->get_grading_actions() as $action => $description) {
2252                     $url = '/mod/assign/view.php' .
2253                            '?id=' .  $this->get_course_module()->id .
2254                            '&plugin=' . $plugin->get_type() .
2255                            '&pluginsubtype=assignfeedback' .
2256                            '&action=viewpluginpage&pluginaction=' . $action;
2257                     $links[$url] = $description;
2258                 }
2259             }
2260         }
2262         $gradingactions = new url_select($links);
2264         $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2266         $perpage = get_user_preferences('assign_perpage', 10);
2267         $filter = get_user_preferences('assign_filter', '');
2268         $controller = $gradingmanager->get_active_controller();
2269         $showquickgrading = empty($controller);
2270         if (optional_param('action', '', PARAM_ALPHA) == 'saveoptions') {
2271             $quickgrading = optional_param('quickgrading', false, PARAM_BOOL);
2272             set_user_preference('assign_quickgrading', $quickgrading);
2273         }
2274         $quickgrading = get_user_preferences('assign_quickgrading', false);
2276         // print options  for changing the filter and changing the number of results per page
2277         $gradingoptionsform = new mod_assign_grading_options_form(null,
2278                                                                   array('cm'=>$this->get_course_module()->id,
2279                                                                         'contextid'=>$this->context->id,
2280                                                                         'userid'=>$USER->id,
2281                                                                         'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
2282                                                                         'showquickgrading'=>$showquickgrading,
2283                                                                         'quickgrading'=>$quickgrading),
2284                                                                   'post', '',
2285                                                                   array('class'=>'gradingoptionsform'));
2287         $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
2288                                                                   array('cm'=>$this->get_course_module()->id,
2289                                                                         'submissiondrafts'=>$this->get_instance()->submissiondrafts,
2290                                                                         'duedate'=>$this->get_instance()->duedate,
2291                                                                         'feedbackplugins'=>$this->get_feedback_plugins()),
2292                                                                   'post', '',
2293                                                                   array('class'=>'gradingbatchoperationsform'));
2295         $gradingoptionsdata = new stdClass();
2296         $gradingoptionsdata->perpage = $perpage;
2297         $gradingoptionsdata->filter = $filter;
2298         $gradingoptionsform->set_data($gradingoptionsdata);
2300         $actionformtext = $this->get_renderer()->render($gradingactions);
2301         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2302                                                       $this->get_context(), false, $this->get_course_module()->id, get_string('grading', 'assign'), $actionformtext));
2303         $o .= groups_print_activity_menu($this->get_course_module(), $CFG->wwwroot . '/mod/assign/view.php?id=' . $this->get_course_module()->id.'&action=grading', true);
2305         // plagiarism update status apearring in the grading book
2306         if (!empty($CFG->enableplagiarism)) {
2307             /** Include plagiarismlib.php */
2308             require_once($CFG->libdir . '/plagiarismlib.php');
2309             $o .= plagiarism_update_status($this->get_course(), $this->get_course_module());
2310         }
2312         // load and print the table of submissions
2313         if ($showquickgrading && $quickgrading) {
2314             $table = $this->get_renderer()->render(new assign_grading_table($this, $perpage, $filter, 0, true));
2315             $quickgradingform = new mod_assign_quick_grading_form(null,
2316                                                                   array('cm'=>$this->get_course_module()->id,
2317                                                                         'gradingtable'=>$table));
2318             $o .= $this->get_renderer()->render(new assign_form('quickgradingform', $quickgradingform));
2319         } else {
2320             $o .= $this->get_renderer()->render(new assign_grading_table($this, $perpage, $filter, 0, false));
2321         }
2323         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
2324         $users = array_keys($this->list_participants($currentgroup, true));
2325         if (count($users) != 0) {
2326             // if no enrolled user in a course then don't display the batch operations feature
2327             $o .= $this->get_renderer()->render(new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform));
2328         }
2329         $o .= $this->get_renderer()->render(new assign_form('gradingoptionsform', $gradingoptionsform, 'M.mod_assign.init_grading_options'));
2330         return $o;
2331     }
2333     /**
2334      * View entire grading page.
2335      *
2336      * @return string
2337      */
2338     private function view_grading_page() {
2339         global $CFG;
2341         $o = '';
2342         // Need submit permission to submit an assignment
2343         require_capability('mod/assign:grade', $this->context);
2344         require_once($CFG->dirroot . '/mod/assign/gradeform.php');
2346         // only load this if it is
2348         $o .= $this->view_grading_table();
2350         $o .= $this->view_footer();
2351         $this->add_to_log('view submission grading table', get_string('viewsubmissiongradingtable', 'assign'));
2352         return $o;
2353     }
2355     /**
2356      * Capture the output of the plagiarism plugins disclosures and return it as a string
2357      *
2358      * @return void
2359      */
2360     private function plagiarism_print_disclosure() {
2361         global $CFG;
2362         $o = '';
2364         if (!empty($CFG->enableplagiarism)) {
2365             /** Include plagiarismlib.php */
2366             require_once($CFG->libdir . '/plagiarismlib.php');
2368             $o .= plagiarism_print_disclosure($this->get_course_module()->id);
2369         }
2371         return $o;
2372     }
2374     /**
2375      * message for students when assignment submissions have been closed
2376      *
2377      * @return string
2378      */
2379     private function view_student_error_message() {
2380         global $CFG;
2382         $o = '';
2383         // Need submit permission to submit an assignment
2384         require_capability('mod/assign:submit', $this->context);
2386         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2387                                                       $this->get_context(),
2388                                                       $this->show_intro(),
2389                                                       $this->get_course_module()->id,
2390                                                       get_string('editsubmission', 'assign')));
2392         $o .= $this->get_renderer()->notification(get_string('submissionsclosed', 'assign'));
2394         $o .= $this->view_footer();
2396         return $o;
2398     }
2400     /**
2401      * View edit submissions page.
2402      *
2403      * @param moodleform $mform
2404      * @param array $notices A list of notices to display at the top of the edit submission form (e.g. from plugins).
2405      * @return void
2406      */
2407     private function view_edit_submission_page($mform, $notices) {
2408         global $CFG;
2410         $o = '';
2411         // Include submission form
2412         require_once($CFG->dirroot . '/mod/assign/submission_form.php');
2413         // Need submit permission to submit an assignment
2414         require_capability('mod/assign:submit', $this->context);
2416         if (!$this->submissions_open()) {
2417             return $this->view_student_error_message();
2418         }
2419         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2420                                                       $this->get_context(),
2421                                                       $this->show_intro(),
2422                                                       $this->get_course_module()->id,
2423                                                       get_string('editsubmission', 'assign')));
2424         $o .= $this->plagiarism_print_disclosure();
2425         $data = new stdClass();
2427         if (!$mform) {
2428             $mform = new mod_assign_submission_form(null, array($this, $data));
2429         }
2431         foreach ($notices as $notice) {
2432             $o .= $this->get_renderer()->notification($notice);
2433         }
2435         $o .= $this->get_renderer()->render(new assign_form('editsubmissionform',$mform));
2437         $o .= $this->view_footer();
2438         $this->add_to_log('view submit assignment form', get_string('viewownsubmissionform', 'assign'));
2440         return $o;
2441     }
2443     /**
2444      * See if this assignment has a grade yet
2445      *
2446      * @param int $userid
2447      * @return bool
2448      */
2449     private function is_graded($userid) {
2450         $grade = $this->get_user_grade($userid, false);
2451         if ($grade) {
2452             return ($grade->grade !== NULL && $grade->grade >= 0);
2453         }
2454         return false;
2455     }
2458     /**
2459      * Perform an access check to see if the current $USER can view this users submission
2460      *
2461      * @param int $userid
2462      * @return bool
2463      */
2464     public function can_view_submission($userid) {
2465         global $USER;
2467         if (!is_enrolled($this->get_course_context(), $userid)) {
2468             return false;
2469         }
2470         if ($userid == $USER->id && !has_capability('mod/assign:submit', $this->context)) {
2471             return false;
2472         }
2473         if ($userid != $USER->id && !has_capability('mod/assign:grade', $this->context)) {
2474             return false;
2475         }
2476         return true;
2477     }
2479     /**
2480      * Allows the plugin to show a batch grading operation page.
2481      *
2482      * @return none
2483      */
2484     private function view_plugin_grading_batch_operation($mform) {
2485         require_capability('mod/assign:grade', $this->context);
2486         $prefix = 'plugingradingbatchoperation_';
2488         if ($data = $mform->get_data()) {
2489             $tail = substr($data->operation, strlen($prefix));
2490             list($plugintype, $action) = explode('_', $tail, 2);
2492             $plugin = $this->get_feedback_plugin_by_type($plugintype);
2493             if ($plugin) {
2494                 $users = $data->selectedusers;
2495                 $userlist = explode(',', $users);
2496                 echo $plugin->grading_batch_operation($action, $userlist);
2497                 return;
2498             }
2499         }
2500         print_error('invalidformdata', '');
2501     }
2503     /**
2504      * Ask the user to confirm they want to perform this batch operation
2505      * @param moodleform $mform Set to a grading batch operations form
2506      * @return string - the page to view after processing these actions
2507      */
2508     private function process_grading_batch_operation(& $mform) {
2509         global $CFG;
2510         require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
2511         require_sesskey();
2513         $mform = new mod_assign_grading_batch_operations_form(null,
2514                                                               array('cm'=>$this->get_course_module()->id,
2515                                                                     'submissiondrafts'=>$this->get_instance()->submissiondrafts,
2516                                                                     'duedate'=>$this->get_instance()->duedate,
2517                                                                     'feedbackplugins'=>$this->get_feedback_plugins()),
2518                                                               'post',
2519                                                               '',
2520                                                               array('class'=>'gradingbatchoperationsform'));
2522         if ($data = $mform->get_data()) {
2523             // get the list of users
2524             $users = $data->selectedusers;
2525             $userlist = explode(',', $users);
2527             $prefix = 'plugingradingbatchoperation_';
2529             if ($data->operation == 'grantextension') {
2530                 // Reset the form so the grant extension page will create the extension form.
2531                 $mform = null;
2532                 return 'grantextension';
2533             } else if (strpos($data->operation, $prefix) === 0) {
2534                 $tail = substr($data->operation, strlen($prefix));
2535                 list($plugintype, $action) = explode('_', $tail, 2);
2537                 $plugin = $this->get_feedback_plugin_by_type($plugintype);
2538                 if ($plugin) {
2539                     return 'plugingradingbatchoperation';
2540                 }
2541             }
2543             foreach ($userlist as $userid) {
2544                 if ($data->operation == 'lock') {
2545                     $this->process_lock($userid);
2546                 } else if ($data->operation == 'unlock') {
2547                     $this->process_unlock($userid);
2548                 } else if ($data->operation == 'reverttodraft') {
2549                     $this->process_revert_to_draft($userid);
2550                 }
2551             }
2552         }
2554         return 'grading';
2555     }
2557     /**
2558      * Ask the user to confirm they want to submit their work for grading
2559      * @param $mform moodleform - null unless form validation has failed
2560      * @return string
2561      */
2562     private function check_submit_for_grading($mform) {
2563         global $USER, $CFG;
2565         require_once($CFG->dirroot . '/mod/assign/submissionconfirmform.php');
2567         // Check that all of the submission plugins are ready for this submission
2568         $notifications = array();
2569         $submission = $this->get_user_submission($USER->id, false);
2570         $plugins = $this->get_submission_plugins();
2571         foreach ($plugins as $plugin) {
2572             if ($plugin->is_enabled() && $plugin->is_visible()) {
2573                 $check = $plugin->precheck_submission($submission);
2574                 if ($check !== true) {
2575                     $notifications[] = $check;
2576                 }
2577             }
2578         }
2580         $data = new stdClass();
2581         $adminconfig = $this->get_admin_config();
2582         $requiresubmissionstatement = (!empty($adminconfig->requiresubmissionstatement) ||
2583                                        $this->get_instance()->requiresubmissionstatement) &&
2584                                        !empty($adminconfig->submissionstatement);
2586         $submissionstatement = '';
2587         if (!empty($adminconfig->submissionstatement)) {
2588             $submissionstatement = $adminconfig->submissionstatement;
2589         }
2591         if ($mform == null) {
2592             $mform = new mod_assign_confirm_submission_form(null, array($requiresubmissionstatement,
2593                                                                         $submissionstatement,
2594                                                                         $this->get_course_module()->id,
2595                                                                         $data));
2596         }
2597         $o = '';
2598         $o .= $this->get_renderer()->header();
2599         $o .= $this->get_renderer()->render(new assign_submit_for_grading_page($notifications, $this->get_course_module()->id, $mform));
2600         $o .= $this->view_footer();
2602         $this->add_to_log('view confirm submit assignment form', get_string('viewownsubmissionform', 'assign'));
2604         return $o;
2605     }
2607     /**
2608      * Print 2 tables of information with no action links -
2609      * the submission summary and the grading summary
2610      *
2611      * @param stdClass $user the user to print the report for
2612      * @param bool $showlinks - Return plain text or links to the profile
2613      * @return string - the html summary
2614      */
2615     public function view_student_summary($user, $showlinks) {
2616         global $CFG, $DB, $PAGE;
2618         $grade = $this->get_user_grade($user->id, false);
2619         $submission = $this->get_user_submission($user->id, false);
2620         $o = '';
2622         $teamsubmission = null;
2623         $submissiongroup = null;
2624         $notsubmitted = array();
2625         if ($this->get_instance()->teamsubmission) {
2626             $teamsubmission = $this->get_group_submission($user->id, 0, false);
2627             $submissiongroup = $this->get_submission_group($user->id);
2628             $groupid = 0;
2629             if ($submissiongroup) {
2630                 $groupid = $submissiongroup->id;
2631             }
2632             $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
2633         }
2635         if ($this->can_view_submission($user->id)) {
2636             $showedit = has_capability('mod/assign:submit', $this->context) &&
2637                          $this->submissions_open($user->id) && ($this->is_any_submission_plugin_enabled()) && $showlinks;
2638             $gradelocked = ($grade && $grade->locked) || $this->grading_disabled($user->id);
2639             // Grading criteria preview.
2640             $gradingmanager = get_grading_manager($this->context, 'mod_assign', 'submissions');
2641             $gradingcontrollerpreview = '';
2642             if ($gradingmethod = $gradingmanager->get_active_method()) {
2643                 $controller = $gradingmanager->get_controller($gradingmethod);
2644                 if ($controller->is_form_defined()) {
2645                     $gradingcontrollerpreview = $controller->render_preview($PAGE);
2646                 }
2647             }
2649             $showsubmit = ($submission || $teamsubmission) && $showlinks;
2650             if ($teamsubmission && ($teamsubmission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED)) {
2651                 $showsubmit = false;
2652             }
2653             if ($submission && ($submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED)) {
2654                 $showsubmit = false;
2655             }
2656             $extensionduedate = null;
2657             if ($grade) {
2658                 $extensionduedate = $grade->extensionduedate;
2659             }
2660             $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2661             $o .= $this->get_renderer()->render(new assign_submission_status($this->get_instance()->allowsubmissionsfromdate,
2662                                                               $this->get_instance()->alwaysshowdescription,
2663                                                               $submission,
2664                                                               $this->get_instance()->teamsubmission,
2665                                                               $teamsubmission,
2666                                                               $submissiongroup,
2667                                                               $notsubmitted,
2668                                                               $this->is_any_submission_plugin_enabled(),
2669                                                               $gradelocked,
2670                                                               $this->is_graded($user->id),
2671                                                               $this->get_instance()->duedate,
2672                                                               $this->get_instance()->cutoffdate,
2673                                                               $this->get_submission_plugins(),
2674                                                               $this->get_return_action(),
2675                                                               $this->get_return_params(),
2676                                                               $this->get_course_module()->id,
2677                                                               $this->get_course()->id,
2678                                                               assign_submission_status::STUDENT_VIEW,
2679                                                               $showedit,
2680                                                               $showsubmit,
2681                                                               $viewfullnames,
2682                                                               $extensionduedate,
2683                                                               $this->get_context(),
2684                                                               $this->is_blind_marking(),
2685                                                               $gradingcontrollerpreview));
2687             require_once($CFG->libdir.'/gradelib.php');
2688             require_once($CFG->dirroot.'/grade/grading/lib.php');
2690             $gradinginfo = grade_get_grades($this->get_course()->id,
2691                                         'mod',
2692                                         'assign',
2693                                         $this->get_instance()->id,
2694                                         $user->id);
2696             $gradingitem = $gradinginfo->items[0];
2697             $gradebookgrade = $gradingitem->grades[$user->id];
2699             // check to see if all feedback plugins are empty
2700             $emptyplugins = true;
2701             if ($grade) {
2702                 foreach ($this->get_feedback_plugins() as $plugin) {
2703                     if ($plugin->is_visible() && $plugin->is_enabled()) {
2704                         if (!$plugin->is_empty($grade)) {
2705                             $emptyplugins = false;
2706                         }
2707                     }
2708                 }
2709             }
2712             if (!($gradebookgrade->hidden) && ($gradebookgrade->grade !== null || !$emptyplugins)) {
2714                 $gradefordisplay = '';
2715                 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2717                 if ($controller = $gradingmanager->get_active_controller()) {
2718                     $controller->set_grade_range(make_grades_menu($this->get_instance()->grade));
2719                     $gradefordisplay = $controller->render_grade($PAGE,
2720                                                                  $grade->id,
2721                                                                  $gradingitem,
2722                                                                  $gradebookgrade->str_long_grade,
2723                                                                  has_capability('mod/assign:grade', $this->get_context()));
2724                 } else {
2725                     $gradefordisplay = $this->display_grade($gradebookgrade->grade, false);
2726                 }
2728                 $gradeddate = $gradebookgrade->dategraded;
2729                 $grader = $DB->get_record('user', array('id'=>$gradebookgrade->usermodified));
2731                 $feedbackstatus = new assign_feedback_status($gradefordisplay,
2732                                                       $gradeddate,
2733                                                       $grader,
2734                                                       $this->get_feedback_plugins(),
2735                                                       $grade,
2736                                                       $this->get_course_module()->id,
2737                                                       $this->get_return_action(),
2738                                                       $this->get_return_params());
2740                 $o .= $this->get_renderer()->render($feedbackstatus);
2741             }
2743         }
2744         return $o;
2745     }
2747     /**
2748      * View submissions page (contains details of current submission).
2749      *
2750      * @return string
2751      */
2752     private function view_submission_page() {
2753         global $CFG, $DB, $USER, $PAGE;
2755         $o = '';
2756         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2757                                                       $this->get_context(),
2758                                                       $this->show_intro(),
2759                                                       $this->get_course_module()->id));
2761         if ($this->can_grade()) {
2762             if ($this->get_instance()->teamsubmission) {
2763                 $summary = new assign_grading_summary($this->count_teams(),
2764                                                       $this->get_instance()->submissiondrafts,
2765                                                       $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_DRAFT),
2766                                                       $this->is_any_submission_plugin_enabled(),
2767                                                       $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED),
2768                                                       $this->get_instance()->cutoffdate,
2769                                                       $this->get_instance()->duedate,
2770                                                       $this->get_course_module()->id,
2771                                                       $this->count_submissions_need_grading(),
2772                                                       $this->get_instance()->teamsubmission);
2773                 $o .= $this->get_renderer()->render($summary);
2774             } else {
2775                 $summary = new assign_grading_summary($this->count_participants(0),
2776                                                       $this->get_instance()->submissiondrafts,
2777                                                       $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_DRAFT),
2778                                                       $this->is_any_submission_plugin_enabled(),
2779                                                       $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED),
2780                                                       $this->get_instance()->cutoffdate,
2781                                                       $this->get_instance()->duedate,
2782                                                       $this->get_course_module()->id,
2783                                                       $this->count_submissions_need_grading(),
2784                                                       $this->get_instance()->teamsubmission);
2785                 $o .= $this->get_renderer()->render($summary);
2786             }
2787         }
2788         $grade = $this->get_user_grade($USER->id, false);
2789         $submission = $this->get_user_submission($USER->id, false);
2791         if ($this->can_view_submission($USER->id)) {
2792             $o .= $this->view_student_summary($USER, true);
2793         }
2796         $o .= $this->view_footer();
2797         $this->add_to_log('view', get_string('viewownsubmissionstatus', 'assign'));
2798         return $o;
2799     }
2801     /**
2802      * convert the final raw grade(s) in the  grading table for the gradebook
2803      *
2804      * @param stdClass $grade
2805      * @return array
2806      */
2807     private function convert_grade_for_gradebook(stdClass $grade) {
2808         $gradebookgrade = array();
2809         // trying to match those array keys in grade update function in gradelib.php
2810         // with keys in th database table assign_grades
2811         // starting around line 262
2812         if ($grade->grade >= 0) {
2813             $gradebookgrade['rawgrade'] = $grade->grade;
2814         }
2815         $gradebookgrade['userid'] = $grade->userid;
2816         $gradebookgrade['usermodified'] = $grade->grader;
2817         $gradebookgrade['datesubmitted'] = NULL;
2818         $gradebookgrade['dategraded'] = $grade->timemodified;
2819         if (isset($grade->feedbackformat)) {
2820             $gradebookgrade['feedbackformat'] = $grade->feedbackformat;
2821         }
2822         if (isset($grade->feedbacktext)) {
2823             $gradebookgrade['feedback'] = $grade->feedbacktext;
2824         }
2826         return $gradebookgrade;
2827     }
2829     /**
2830      * convert submission details for the gradebook
2831      *
2832      * @param stdClass $submission
2833      * @return array
2834      */
2835     private function convert_submission_for_gradebook(stdClass $submission) {
2836         $gradebookgrade = array();
2839         $gradebookgrade['userid'] = $submission->userid;
2840         $gradebookgrade['usermodified'] = $submission->userid;
2841         $gradebookgrade['datesubmitted'] = $submission->timemodified;
2843         return $gradebookgrade;
2844     }
2846     /**
2847      * update grades in the gradebook
2848      *
2849      * @param mixed $submission stdClass|null
2850      * @param mixed $grade stdClass|null
2851      * @return bool
2852      */
2853     private function gradebook_item_update($submission=NULL, $grade=NULL) {
2855         // Do not push grade to gradebook if blind marking is active as the gradebook would reveal the students.
2856         if ($this->is_blind_marking()) {
2857             return false;
2858         }
2859         if ($submission != NULL) {
2860             if ($submission->userid == 0) {
2861                 // This is a group submission update.
2862                 $team = groups_get_members($submission->groupid, 'u.id');
2864                 foreach ($team as $member) {
2865                     $submission->groupid = 0;
2866                     $submission->userid = $member->id;
2867                     $this->gradebook_item_update($submission, null);
2868                 }
2869                 return;
2870             }
2872             $gradebookgrade = $this->convert_submission_for_gradebook($submission);
2874         } else {
2875             $gradebookgrade = $this->convert_grade_for_gradebook($grade);
2876         }
2877         // Grading is disabled, return.
2878         if ($this->grading_disabled($gradebookgrade['userid'])) {
2879             return false;
2880         }
2881         $assign = clone $this->get_instance();
2882         $assign->cmidnumber = $this->get_course_module()->id;
2884         return assign_grade_item_update($assign, $gradebookgrade);
2885     }
2887     /**
2888      * update team submission
2889      *
2890      * @param stdClass $submission
2891      * @param int $userid
2892      * @param bool $updatetime
2893      * @return bool
2894      */
2895     private function update_team_submission(stdClass $submission, $userid, $updatetime) {
2896         global $DB;
2898         if ($updatetime) {
2899             $submission->timemodified = time();
2900         }
2902         // First update the submission for the current user.
2903         $mysubmission = $this->get_user_submission($userid, true);
2904         $mysubmission->status = $submission->status;
2906         $this->update_submission($mysubmission, 0, $updatetime, false);
2908         // Now check the team settings to see if this assignment qualifies as submitted or draft.
2909         $team = $this->get_submission_group_members($submission->groupid, true);
2911         $allsubmitted = true;
2912         $anysubmitted = false;
2913         foreach ($team as $member) {
2914             $membersubmission = $this->get_user_submission($member->id, false);
2916             if (!$membersubmission || $membersubmission->status != ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
2917                 $allsubmitted = false;
2918                 if ($anysubmitted) {
2919                     break;
2920                 }
2921             } else {
2922                 $anysubmitted = true;
2923             }
2924         }
2925         if ($this->get_instance()->requireallteammemberssubmit) {
2926             if ($allsubmitted) {
2927                 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
2928             } else {
2929                 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
2930             }
2931             $result= $DB->update_record('assign_submission', $submission);
2932         } else {
2933             if ($anysubmitted) {
2934                 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
2935             } else {
2936                 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
2937             }
2938             $result= $DB->update_record('assign_submission', $submission);
2939         }
2941         $this->gradebook_item_update($submission);
2942         return $result;
2943     }
2946     /**
2947      * update grades in the gradebook based on submission time
2948      *
2949      * @param stdClass $submission
2950      * @param int $userid
2951      * @param bool $updatetime
2952      * @param bool $teamsubmission
2953      * @return bool
2954      */
2955     private function update_submission(stdClass $submission, $userid, $updatetime, $teamsubmission) {
2956         global $DB;
2958         if ($teamsubmission) {
2959             return $this->update_team_submission($submission, $userid, $updatetime);
2960         }
2962         if ($updatetime) {
2963             $submission->timemodified = time();
2964         }
2965         $result= $DB->update_record('assign_submission', $submission);
2966         if ($result) {
2967             $this->gradebook_item_update($submission);
2968         }
2969         return $result;
2970     }
2972     /**
2973      * Is this assignment open for submissions?
2974      *
2975      * Check the due date,
2976      * prevent late submissions,
2977      * has this person already submitted,
2978      * is the assignment locked?
2979      *
2980      * @param int $userid - Optional userid so we can see if a different user can submit
2981      * @return bool
2982      */
2983     public function submissions_open($userid = 0) {
2984         global $USER;
2986         if (!$userid) {
2987             $userid = $USER->id;
2988         }
2990         $time = time();
2991         $dateopen = true;
2992         $finaldate = false;
2993         if ($this->get_instance()->cutoffdate) {
2994             $finaldate = $this->get_instance()->cutoffdate;
2995         }
2996         // User extensions.
2997         if ($finaldate) {
2998             $grade = $this->get_user_grade($userid, false);
2999             if ($grade && $grade->extensionduedate) {
3000                 // Extension can be before cut off date.
3001                 if ($grade->extensionduedate > $finaldate) {
3002                     $finaldate = $grade->extensionduedate;
3003                 }
3004             }
3005         }
3007         if ($finaldate) {
3008             $dateopen = ($this->get_instance()->allowsubmissionsfromdate <= $time && $time <= $finaldate);
3009         } else {
3010             $dateopen = ($this->get_instance()->allowsubmissionsfromdate <= $time);
3011         }
3013         if (!$dateopen) {
3014             return false;
3015         }
3017         // Now check if this user has already submitted etc.
3018         if (!is_enrolled($this->get_course_context(), $userid)) {
3019             return false;
3020         }
3021         $submission = false;
3022         if ($this->get_instance()->teamsubmission) {
3023             $submission = $this->get_group_submission($userid, 0, false);
3024         } else {
3025             $submission = $this->get_user_submission($userid, false);
3026         }
3027         if ($submission) {
3029             if ($this->get_instance()->submissiondrafts && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
3030                 // drafts are tracked and the student has submitted the assignment
3031                 return false;
3032             }
3033         }
3034         if ($grade = $this->get_user_grade($userid, false)) {
3035             if ($grade->locked) {
3036                 return false;
3037             }
3038         }
3040         if ($this->grading_disabled($userid)) {
3041             return false;
3042         }
3044         return true;
3045     }
3047     /**
3048      * render the files in file area
3049      * @param string $component
3050      * @param string $area
3051      * @param int $submissionid
3052      * @return string
3053      */
3054     public function render_area_files($component, $area, $submissionid) {
3055         global $USER;
3057         $fs = get_file_storage();
3058         $browser = get_file_browser();
3059         $files = $fs->get_area_files($this->get_context()->id, $component, $area , $submissionid , "timemodified", false);
3060         return $this->get_renderer()->assign_files($this->context, $submissionid, $area, $component);
3062     }
3064     /**
3065      * Returns a list of teachers that should be grading given submission
3066      *
3067      * @param int $userid
3068      * @return array
3069      */
3070     private function get_graders($userid) {
3071         //potential graders
3072         $potentialgraders = get_enrolled_users($this->context, "mod/assign:grade");
3074         $graders = array();
3075         if (groups_get_activity_groupmode($this->get_course_module()) == SEPARATEGROUPS) {   // Separate groups are being used
3076             if ($groups = groups_get_all_groups($this->get_course()->id, $userid)) {  // Try to find all groups
3077                 foreach ($groups as $group) {
3078                     foreach ($potentialgraders as $grader) {
3079                         if ($grader->id == $userid) {
3080                             continue; // do not send self
3081                         }
3082                         if (groups_is_member($group->id, $grader->id)) {
3083                             $graders[$grader->id] = $grader;
3084                         }
3085                     }
3086                 }
3087             } else {
3088                 // user not in group, try to find graders without group
3089                 foreach ($potentialgraders as $grader) {
3090                     if ($grader->id == $userid) {
3091                         continue; // do not send self
3092                     }
3093                     if (!groups_has_membership($this->get_course_module(), $grader->id)) {
3094                         $graders[$grader->id] = $grader;
3095                     }
3096                 }
3097             }
3098         } else {
3099             foreach ($potentialgraders as $grader) {
3100                 if ($grader->id == $userid) {
3101                     continue; // do not send self
3102                 }
3103                 // must be enrolled
3104                 if (is_enrolled($this->get_course_context(), $grader->id)) {
3105                     $graders[$grader->id] = $grader;
3106                 }
3107             }
3108         }
3109         return $graders;
3110     }
3112     /**
3113      * Format a notification for plain text
3114      *
3115      * @param string $messagetype
3116      * @param stdClass $info
3117      * @param stdClass $course
3118      * @param stdClass $context
3119      * @param string $modulename
3120      * @param string $assignmentname
3121      */
3122     private static function format_notification_message_text($messagetype, $info, $course, $context, $modulename, $assignmentname) {
3123         $posttext  = format_string($course->shortname, true, array('context' => $context->get_course_context())).' -> '.
3124                      $modulename.' -> '.
3125                      format_string($assignmentname, true, array('context' => $context))."\n";
3126         $posttext .= '---------------------------------------------------------------------'."\n";
3127         $posttext .= get_string($messagetype . 'text', "assign", $info)."\n";
3128         $posttext .= "\n---------------------------------------------------------------------\n";
3129         return $posttext;
3130     }
3132     /**
3133      * Format a notification for HTML
3134      *
3135      * @param string $messagetype
3136      * @param stdClass $info
3137      * @param stdClass $course
3138      * @param stdClass $context
3139      * @param string $modulename
3140      * @param stdClass $coursemodule
3141      * @param string $assignmentname
3142      * @param stdClass $info
3143      */
3144     private static function format_notification_message_html($messagetype, $info, $course, $context, $modulename, $coursemodule, $assignmentname) {
3145         global $CFG;
3146         $posthtml  = '<p><font face="sans-serif">'.
3147                      '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.format_string($course->shortname, true, array('context' => $context->get_course_context())).'</a> ->'.
3148                      '<a href="'.$CFG->wwwroot.'/mod/assign/index.php?id='.$course->id.'">'.$modulename.'</a> ->'.
3149                      '<a href="'.$CFG->wwwroot.'/mod/assign/view.php?id='.$coursemodule->id.'">'.format_string($assignmentname, true, array('context' => $context)).'</a></font></p>';
3150         $posthtml .= '<hr /><font face="sans-serif">';
3151         $posthtml .= '<p>'.get_string($messagetype . 'html', 'assign', $info).'</p>';
3152         $posthtml .= '</font><hr />';
3153         return $posthtml;
3154     }
3156     /**
3157      * Message someone about something (static so it can be called from cron)
3158      *
3159      * @param stdClass $userfrom
3160      * @param stdClass $userto
3161      * @param string $messagetype
3162      * @param string $eventtype
3163      * @param int $updatetime
3164      * @param stdClass $coursemodule
3165      * @param stdClass $context
3166      * @param stdClass $course
3167      * @param string $modulename
3168      * @param string $assignmentname
3169      * @return void
3170      */
3171     public static function send_assignment_notification($userfrom, $userto, $messagetype, $eventtype,
3172                                                         $updatetime, $coursemodule, $context, $course,
3173                                                         $modulename, $assignmentname, $blindmarking,
3174                                                         $uniqueidforuser) {
3175         global $CFG;
3177         $info = new stdClass();
3178         if ($blindmarking) {
3179             $info->username = get_string('participant', 'assign') . ' ' . $uniqueidforuser;
3180         } else {
3181             $info->username = fullname($userfrom, true);
3182         }
3183         $info->assignment = format_string($assignmentname,true, array('context'=>$context));
3184         $info->url = $CFG->wwwroot.'/mod/assign/view.php?id='.$coursemodule->id;
3185         $info->timeupdated = strftime('%c',$updatetime);
3187         $postsubject = get_string($messagetype . 'small', 'assign', $info);
3188         $posttext = self::format_notification_message_text($messagetype, $info, $course, $context, $modulename, $assignmentname);
3189         $posthtml = ($userto->mailformat == 1) ? self::format_notification_message_html($messagetype, $info, $course, $context, $modulename, $coursemodule, $assignmentname) : '';
3191         $eventdata = new stdClass();
3192         $eventdata->modulename       = 'assign';
3193         $eventdata->userfrom         = $userfrom;
3194         $eventdata->userto           = $userto;
3195         $eventdata->subject          = $postsubject;
3196         $eventdata->fullmessage      = $posttext;
3197         $eventdata->fullmessageformat = FORMAT_PLAIN;
3198         $eventdata->fullmessagehtml  = $posthtml;
3199         $eventdata->smallmessage     = $postsubject;
3201         $eventdata->name            = $eventtype;
3202         $eventdata->component       = 'mod_assign';
3203         $eventdata->notification    = 1;
3204         $eventdata->contexturl      = $info->url;
3205         $eventdata->contexturlname  = $info->assignment;
3207         message_send($eventdata);
3208     }
3210     /**
3211      * Message someone about something
3212      *
3213      * @param stdClass $userfrom
3214      * @param stdClass $userto
3215      * @param string $messagetype
3216      * @param string $eventtype
3217      * @param int $updatetime
3218      * @return void
3219      */
3220     public function send_notification($userfrom, $userto, $messagetype, $eventtype, $updatetime) {
3221         self::send_assignment_notification($userfrom, $userto, $messagetype, $eventtype,
3222                                            $updatetime, $this->get_course_module(), $this->get_context(),
3223                                            $this->get_course(), $this->get_module_name(),
3224                                            $this->get_instance()->name, $this->is_blind_marking(),
3225                                            $this->get_uniqueid_for_user($userfrom->id));
3226     }
3228     /**
3229      * Notify student upon successful submission
3230      *
3231      * @param stdClass $submission
3232      * @return void
3233      */
3234     private function notify_student_submission_receipt(stdClass $submission) {
3235         global $DB, $USER;
3237         $adminconfig = $this->get_admin_config();
3238         if (empty($adminconfig->submissionreceipts)) {
3239             // No need to do anything
3240             return;
3241         }
3242         if ($submission->userid) {
3243             $user = $DB->get_record('user', array('id'=>$submission->userid), '*', MUST_EXIST);
3244         } else {
3245             $user = $USER;
3246         }
3247         $this->send_notification($user, $user, 'submissionreceipt', 'assign_notification', $submission->timemodified);
3248     }
3250     /**
3251      * Send notifications to graders upon student submissions
3252      *
3253      * @param stdClass $submission
3254      * @return void
3255      */
3256     private function notify_graders(stdClass $submission) {
3257         global $DB, $USER;
3259         $late = $this->get_instance()->duedate && ($this->get_instance()->duedate < time());
3261         if (!$this->get_instance()->sendnotifications && !($late && $this->get_instance()->sendlatenotifications)) {          // No need to do anything
3262             return;
3263         }
3265         if ($submission->userid) {
3266             $user = $DB->get_record('user', array('id'=>$submission->userid), '*', MUST_EXIST);
3267         } else {
3268             $user = $USER;
3269         }
3270         if ($teachers = $this->get_graders($user->id)) {