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