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