MDL-38154 do not hardcode sha1 hash of empty string
[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 // Assignment submission statuses.
30 define('ASSIGN_SUBMISSION_STATUS_DRAFT', 'draft');
31 define('ASSIGN_SUBMISSION_STATUS_SUBMITTED', 'submitted');
33 // Search filters for grading page.
34 define('ASSIGN_FILTER_SUBMITTED', 'submitted');
35 define('ASSIGN_FILTER_SINGLE_USER', 'singleuser');
36 define('ASSIGN_FILTER_REQUIRE_GRADING', 'require_grading');
38 require_once($CFG->libdir . '/accesslib.php');
39 require_once($CFG->libdir . '/formslib.php');
40 require_once($CFG->dirroot . '/repository/lib.php');
41 require_once($CFG->dirroot . '/mod/assign/mod_form.php');
42 require_once($CFG->libdir . '/gradelib.php');
43 require_once($CFG->dirroot . '/grade/grading/lib.php');
44 require_once($CFG->dirroot . '/mod/assign/feedbackplugin.php');
45 require_once($CFG->dirroot . '/mod/assign/submissionplugin.php');
46 require_once($CFG->dirroot . '/mod/assign/renderable.php');
47 require_once($CFG->dirroot . '/mod/assign/gradingtable.php');
48 require_once($CFG->libdir . '/eventslib.php');
49 require_once($CFG->libdir . '/portfolio/caller.php');
51 /**
52  * Standard base class for mod_assign (assignment types).
53  *
54  * @package   mod_assign
55  * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
56  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
57  */
58 class assign {
60     /** @var stdClass the assignment record that contains the global settings for this assign instance */
61     private $instance;
63     /** @var context the context of the course module for this assign instance
64      *               (or just the course if we are creating a new one)
65      */
66     private $context;
68     /** @var stdClass the course this assign instance belongs to */
69     private $course;
71     /** @var stdClass the admin config for all assign instances  */
72     private $adminconfig;
74     /** @var assign_renderer the custom renderer for this module */
75     private $output;
77     /** @var stdClass the course module for this assign instance */
78     private $coursemodule;
80     /** @var array cache for things like the coursemodule name or the scale menu -
81      *             only lives for a single request.
82      */
83     private $cache;
85     /** @var array list of the installed submission plugins */
86     private $submissionplugins;
88     /** @var array list of the installed feedback plugins */
89     private $feedbackplugins;
91     /** @var string action to be used to return to this page
92      *              (without repeating any form submissions etc).
93      */
94     private $returnaction = 'view';
96     /** @var array params to be used to return to this page */
97     private $returnparams = array();
99     /** @var string modulename prevents excessive calls to get_string */
100     private static $modulename = null;
102     /** @var string modulenameplural prevents excessive calls to get_string */
103     private static $modulenameplural = null;
105     /**
106      * Constructor for the base assign class.
107      *
108      * @param mixed $coursemodulecontext context|null the course module context
109      *                                   (or the course context if the coursemodule has not been
110      *                                   created yet).
111      * @param mixed $coursemodule the current course module if it was already loaded,
112      *                            otherwise this class will load one from the context as required.
113      * @param mixed $course the current course  if it was already loaded,
114      *                      otherwise this class will load one from the context as required.
115      */
116     public function __construct($coursemodulecontext, $coursemodule, $course) {
117         global $PAGE;
119         $this->context = $coursemodulecontext;
120         $this->coursemodule = $coursemodule;
121         $this->course = $course;
123         // Temporary cache only lives for a single request - used to reduce db lookups.
124         $this->cache = array();
126         $this->submissionplugins = $this->load_plugins('assignsubmission');
127         $this->feedbackplugins = $this->load_plugins('assignfeedback');
128     }
130     /**
131      * Set the action and parameters that can be used to return to the current page.
132      *
133      * @param string $action The action for the current page
134      * @param array $params An array of name value pairs which form the parameters
135      *                      to return to the current page.
136      * @return void
137      */
138     public function register_return_link($action, $params) {
139         $this->returnaction = $action;
140         $this->returnparams = $params;
141     }
143     /**
144      * Return an action that can be used to get back to the current page.
145      *
146      * @return string action
147      */
148     public function get_return_action() {
149         return $this->returnaction;
150     }
152     /**
153      * Based on the current assignment settings should we display the intro.
154      *
155      * @return bool showintro
156      */
157     protected function show_intro() {
158         if ($this->get_instance()->alwaysshowdescription ||
159                 time() > $this->get_instance()->allowsubmissionsfromdate) {
160             return true;
161         }
162         return false;
163     }
165     /**
166      * Return a list of parameters that can be used to get back to the current page.
167      *
168      * @return array params
169      */
170     public function get_return_params() {
171         return $this->returnparams;
172     }
174     /**
175      * Set the submitted form data.
176      *
177      * @param stdClass $data The form data (instance)
178      */
179     public function set_instance(stdClass $data) {
180         $this->instance = $data;
181     }
183     /**
184      * Set the context.
185      *
186      * @param context $context The new context
187      */
188     public function set_context(context $context) {
189         $this->context = $context;
190     }
192     /**
193      * Set the course data.
194      *
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      *
204      * @return array
205      */
206     public function get_feedback_plugins() {
207         return $this->feedbackplugins;
208     }
210     /**
211      * Get list of submission plugins installed.
212      *
213      * @return array
214      */
215     public function get_submission_plugins() {
216         return $this->submissionplugins;
217     }
219     /**
220      * Is blind marking enabled and reveal identities not set yet?
221      *
222      * @return bool
223      */
224     public function is_blind_marking() {
225         return $this->get_instance()->blindmarking && !$this->get_instance()->revealidentities;
226     }
228     /**
229      * Does an assignment have submission(s) or grade(s) already?
230      *
231      * @return bool
232      */
233     public function has_submissions_or_grades() {
234         $allgrades = $this->count_grades();
235         $allsubmissions = $this->count_submissions();
236         if (($allgrades == 0) && ($allsubmissions == 0)) {
237             return false;
238         }
239         return true;
240     }
242     /**
243      * Get a specific submission plugin by its type.
244      *
245      * @param string $subtype assignsubmission | assignfeedback
246      * @param string $type
247      * @return mixed assign_plugin|null
248      */
249     public function get_plugin_by_type($subtype, $type) {
250         $shortsubtype = substr($subtype, strlen('assign'));
251         $name = $shortsubtype . 'plugins';
252         if ($name != 'feedbackplugins' && $name != 'submissionplugins') {
253             return null;
254         }
255         $pluginlist = $this->$name;
256         foreach ($pluginlist as $plugin) {
257             if ($plugin->get_type() == $type) {
258                 return $plugin;
259             }
260         }
261         return null;
262     }
264     /**
265      * Get a feedback plugin by type.
266      *
267      * @param string $type - The type of plugin e.g comments
268      * @return mixed assign_feedback_plugin|null
269      */
270     public function get_feedback_plugin_by_type($type) {
271         return $this->get_plugin_by_type('assignfeedback', $type);
272     }
274     /**
275      * Get a submission plugin by type.
276      *
277      * @param string $type - The type of plugin e.g comments
278      * @return mixed assign_submission_plugin|null
279      */
280     public function get_submission_plugin_by_type($type) {
281         return $this->get_plugin_by_type('assignsubmission', $type);
282     }
284     /**
285      * Load the plugins from the sub folders under subtype.
286      *
287      * @param string $subtype - either submission or feedback
288      * @return array - The sorted list of plugins
289      */
290     protected function load_plugins($subtype) {
291         global $CFG;
292         $result = array();
294         $names = get_plugin_list($subtype);
296         foreach ($names as $name => $path) {
297             if (file_exists($path . '/locallib.php')) {
298                 require_once($path . '/locallib.php');
300                 $shortsubtype = substr($subtype, strlen('assign'));
301                 $pluginclass = 'assign_' . $shortsubtype . '_' . $name;
303                 $plugin = new $pluginclass($this, $name);
305                 if ($plugin instanceof assign_plugin) {
306                     $idx = $plugin->get_sort_order();
307                     while (array_key_exists($idx, $result)) {
308                         $idx +=1;
309                     }
310                     $result[$idx] = $plugin;
311                 }
312             }
313         }
314         ksort($result);
315         return $result;
316     }
318     /**
319      * Display the assignment, used by view.php
320      *
321      * The assignment is displayed differently depending on your role,
322      * the settings for the assignment and the status of the assignment.
323      *
324      * @param string $action The current action if any.
325      * @return void
326      */
327     public function view($action='') {
329         $o = '';
330         $mform = null;
331         $notices = array();
333         // Handle form submissions first.
334         if ($action == 'savesubmission') {
335             $action = 'editsubmission';
336             if ($this->process_save_submission($mform, $notices)) {
337                 $action = 'view';
338             }
339         } else if ($action == 'lock') {
340             $this->process_lock();
341             $action = 'grading';
342         } else if ($action == 'reverttodraft') {
343             $this->process_revert_to_draft();
344             $action = 'grading';
345         } else if ($action == 'unlock') {
346             $this->process_unlock();
347             $action = 'grading';
348         } else if ($action == 'confirmsubmit') {
349             $action = 'submit';
350             if ($this->process_submit_for_grading($mform)) {
351                 $action = 'view';
352             }
353         } else if ($action == 'gradingbatchoperation') {
354             $action = $this->process_grading_batch_operation($mform);
355         } else if ($action == 'submitgrade') {
356             if (optional_param('saveandshownext', null, PARAM_RAW)) {
357                 // Save and show next.
358                 $action = 'grade';
359                 if ($this->process_save_grade($mform)) {
360                     $action = 'nextgrade';
361                 }
362             } else if (optional_param('nosaveandprevious', null, PARAM_RAW)) {
363                 $action = 'previousgrade';
364             } else if (optional_param('nosaveandnext', null, PARAM_RAW)) {
365                 // Show next button.
366                 $action = 'nextgrade';
367             } else if (optional_param('savegrade', null, PARAM_RAW)) {
368                 // Save changes button.
369                 $action = 'grade';
370                 if ($this->process_save_grade($mform)) {
371                     $action = 'grading';
372                 }
373             } else {
374                 // Cancel button.
375                 $action = 'grading';
376             }
377         } else if ($action == 'quickgrade') {
378             $message = $this->process_save_quick_grades();
379             $action = 'quickgradingresult';
380         } else if ($action == 'saveoptions') {
381             $this->process_save_grading_options();
382             $action = 'grading';
383         } else if ($action == 'saveextension') {
384             $action = 'grantextension';
385             if ($this->process_save_extension($mform)) {
386                 $action = 'grading';
387             }
388         } else if ($action == 'revealidentitiesconfirm') {
389             $this->process_reveal_identities();
390             $action = 'grading';
391         }
393         $returnparams = array('rownum'=>optional_param('rownum', 0, PARAM_INT));
394         $this->register_return_link($action, $returnparams);
396         // Now show the right view page.
397         if ($action == 'previousgrade') {
398             $mform = null;
399             $o .= $this->view_single_grade_page($mform, -1);
400         } else if ($action == 'quickgradingresult') {
401             $mform = null;
402             $o .= $this->view_quickgrading_result($message);
403         } else if ($action == 'nextgrade') {
404             $mform = null;
405             $o .= $this->view_single_grade_page($mform, 1);
406         } else if ($action == 'grade') {
407             $o .= $this->view_single_grade_page($mform);
408         } else if ($action == 'viewpluginassignfeedback') {
409             $o .= $this->view_plugin_content('assignfeedback');
410         } else if ($action == 'viewpluginassignsubmission') {
411             $o .= $this->view_plugin_content('assignsubmission');
412         } else if ($action == 'editsubmission') {
413             $o .= $this->view_edit_submission_page($mform, $notices);
414         } else if ($action == 'grading') {
415             $o .= $this->view_grading_page();
416         } else if ($action == 'downloadall') {
417             $o .= $this->download_submissions();
418         } else if ($action == 'submit') {
419             $o .= $this->check_submit_for_grading($mform);
420         } else if ($action == 'grantextension') {
421             $o .= $this->view_grant_extension($mform);
422         } else if ($action == 'revealidentities') {
423             $o .= $this->view_reveal_identities_confirm($mform);
424         } else if ($action == 'plugingradingbatchoperation') {
425             $o .= $this->view_plugin_grading_batch_operation($mform);
426         } else if ($action == 'viewpluginpage') {
427              $o .= $this->view_plugin_page();
428         } else if ($action == 'viewcourseindex') {
429              $o .= $this->view_course_index();
430         } else {
431             $o .= $this->view_submission_page();
432         }
434         return $o;
435     }
437     /**
438      * Add this instance to the database.
439      *
440      * @param stdClass $formdata The data submitted from the form
441      * @param bool $callplugins This is used to skip the plugin code
442      *             when upgrading an old assignment to a new one (the plugins get called manually)
443      * @return mixed false if an error occurs or the int id of the new instance
444      */
445     public function add_instance(stdClass $formdata, $callplugins) {
446         global $DB;
448         $err = '';
450         // Add the database record.
451         $update = new stdClass();
452         $update->name = $formdata->name;
453         $update->timemodified = time();
454         $update->timecreated = time();
455         $update->course = $formdata->course;
456         $update->courseid = $formdata->course;
457         $update->intro = $formdata->intro;
458         $update->introformat = $formdata->introformat;
459         $update->alwaysshowdescription = $formdata->alwaysshowdescription;
460         $update->submissiondrafts = $formdata->submissiondrafts;
461         $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
462         $update->sendnotifications = $formdata->sendnotifications;
463         $update->sendlatenotifications = $formdata->sendlatenotifications;
464         $update->duedate = $formdata->duedate;
465         $update->cutoffdate = $formdata->cutoffdate;
466         $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
467         $update->grade = $formdata->grade;
468         $update->completionsubmit = !empty($formdata->completionsubmit);
469         $update->teamsubmission = $formdata->teamsubmission;
470         $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
471         $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
472         $update->blindmarking = $formdata->blindmarking;
474         $returnid = $DB->insert_record('assign', $update);
475         $this->instance = $DB->get_record('assign', array('id'=>$returnid), '*', MUST_EXIST);
476         // Cache the course record.
477         $this->course = $DB->get_record('course', array('id'=>$formdata->course), '*', MUST_EXIST);
479         if ($callplugins) {
480             // Call save_settings hook for submission plugins.
481             foreach ($this->submissionplugins as $plugin) {
482                 if (!$this->update_plugin_instance($plugin, $formdata)) {
483                     print_error($plugin->get_error());
484                     return false;
485                 }
486             }
487             foreach ($this->feedbackplugins as $plugin) {
488                 if (!$this->update_plugin_instance($plugin, $formdata)) {
489                     print_error($plugin->get_error());
490                     return false;
491                 }
492             }
494             // In the case of upgrades the coursemodule has not been set,
495             // so we need to wait before calling these two.
496             $this->update_calendar($formdata->coursemodule);
497             $this->update_gradebook(false, $formdata->coursemodule);
499         }
501         $update = new stdClass();
502         $update->id = $this->get_instance()->id;
503         $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
504         $DB->update_record('assign', $update);
506         return $returnid;
507     }
509     /**
510      * Delete all grades from the gradebook for this assignment.
511      *
512      * @return bool
513      */
514     protected function delete_grades() {
515         global $CFG;
517         $result = grade_update('mod/assign',
518                                $this->get_course()->id,
519                                'mod',
520                                'assign',
521                                $this->get_instance()->id,
522                                0,
523                                null,
524                                array('deleted'=>1));
525         return $result == GRADE_UPDATE_OK;
526     }
528     /**
529      * Delete this instance from the database.
530      *
531      * @return bool false if an error occurs
532      */
533     public function delete_instance() {
534         global $DB;
535         $result = true;
537         foreach ($this->submissionplugins as $plugin) {
538             if (!$plugin->delete_instance()) {
539                 print_error($plugin->get_error());
540                 $result = false;
541             }
542         }
543         foreach ($this->feedbackplugins as $plugin) {
544             if (!$plugin->delete_instance()) {
545                 print_error($plugin->get_error());
546                 $result = false;
547             }
548         }
550         // Delete files associated with this assignment.
551         $fs = get_file_storage();
552         if (! $fs->delete_area_files($this->context->id) ) {
553             $result = false;
554         }
556         // Delete_records will throw an exception if it fails - so no need for error checking here.
557         $DB->delete_records('assign_submission', array('assignment'=>$this->get_instance()->id));
558         $DB->delete_records('assign_grades', array('assignment'=>$this->get_instance()->id));
559         $DB->delete_records('assign_plugin_config', array('assignment'=>$this->get_instance()->id));
561         // Delete items from the gradebook.
562         if (! $this->delete_grades()) {
563             $result = false;
564         }
566         // Delete the instance.
567         $DB->delete_records('assign', array('id'=>$this->get_instance()->id));
569         return $result;
570     }
572     /**
573      * Actual implementation of the reset course functionality, delete all the
574      * assignment submissions for course $data->courseid.
575      *
576      * @param $data the data submitted from the reset course.
577      * @return array status array
578      */
579     public function reset_userdata($data) {
580         global $CFG, $DB;
582         $componentstr = get_string('modulenameplural', 'assign');
583         $status = array();
585         $fs = get_file_storage();
586         if (!empty($data->reset_assign_submissions)) {
587             // Delete files associated with this assignment.
588             foreach ($this->submissionplugins as $plugin) {
589                 $fileareas = array();
590                 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
591                 $fileareas = $plugin->get_file_areas();
592                 foreach ($fileareas as $filearea) {
593                     $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
594                 }
596                 if (!$plugin->delete_instance()) {
597                     $status[] = array('component'=>$componentstr,
598                                       'item'=>get_string('deleteallsubmissions', 'assign'),
599                                       'error'=>$plugin->get_error());
600                 }
601             }
603             foreach ($this->feedbackplugins as $plugin) {
604                 $fileareas = array();
605                 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
606                 $fileareas = $plugin->get_file_areas();
607                 foreach ($fileareas as $filearea) {
608                     $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
609                 }
611                 if (!$plugin->delete_instance()) {
612                     $status[] = array('component'=>$componentstr,
613                                       'item'=>get_string('deleteallsubmissions', 'assign'),
614                                       'error'=>$plugin->get_error());
615                 }
616             }
618             $assignssql = 'SELECT a.id
619                              FROM {assign} a
620                            WHERE a.course=:course';
621             $params = array('course'=>$data->courseid);
623             $DB->delete_records_select('assign_submission', "assignment IN ($assignssql)", $params);
625             $status[] = array('component'=>$componentstr,
626                               'item'=>get_string('deleteallsubmissions', 'assign'),
627                               'error'=>false);
629             if (!empty($data->reset_gradebook_grades)) {
630                 $DB->delete_records_select('assign_grades', "assignment IN ($assignssql)", $params);
631                 // Remove all grades from gradebook.
632                 require_once($CFG->dirroot.'/mod/assign/lib.php');
633                 assign_reset_gradebook($data->courseid);
634             }
635         }
636         // Updating dates - shift may be negative too.
637         if ($data->timeshift) {
638             shift_course_mod_dates('assign',
639                                     array('duedate', 'allowsubmissionsfromdate', 'cutoffdate'),
640                                     $data->timeshift,
641                                     $data->courseid);
642             $status[] = array('component'=>$componentstr,
643                               'item'=>get_string('datechanged'),
644                               'error'=>false);
645         }
647         return $status;
648     }
650     /**
651      * Update the settings for a single plugin.
652      *
653      * @param assign_plugin $plugin The plugin to update
654      * @param stdClass $formdata The form data
655      * @return bool false if an error occurs
656      */
657     protected function update_plugin_instance(assign_plugin $plugin, stdClass $formdata) {
658         if ($plugin->is_visible()) {
659             $enabledname = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
660             if (!empty($formdata->$enabledname)) {
661                 $plugin->enable();
662                 if (!$plugin->save_settings($formdata)) {
663                     print_error($plugin->get_error());
664                     return false;
665                 }
666             } else {
667                 $plugin->disable();
668             }
669         }
670         return true;
671     }
673     /**
674      * Update the gradebook information for this assignment.
675      *
676      * @param bool $reset If true, will reset all grades in the gradbook for this assignment
677      * @param int $coursemoduleid This is required because it might not exist in the database yet
678      * @return bool
679      */
680     public function update_gradebook($reset, $coursemoduleid) {
681         global $CFG;
683         require_once($CFG->dirroot.'/mod/assign/lib.php');
684         $assign = clone $this->get_instance();
685         $assign->cmidnumber = $coursemoduleid;
686         $param = null;
687         if ($reset) {
688             $param = 'reset';
689         }
691         return assign_grade_item_update($assign, $param);
692     }
694     /**
695      * Load and cache the admin config for this module.
696      *
697      * @return stdClass the plugin config
698      */
699     public function get_admin_config() {
700         if ($this->adminconfig) {
701             return $this->adminconfig;
702         }
703         $this->adminconfig = get_config('assign');
704         return $this->adminconfig;
705     }
707     /**
708      * Update the calendar entries for this assignment.
709      *
710      * @param int $coursemoduleid - Required to pass this in because it might
711      *                              not exist in the database yet.
712      * @return bool
713      */
714     public function update_calendar($coursemoduleid) {
715         global $DB, $CFG;
716         require_once($CFG->dirroot.'/calendar/lib.php');
718         // Special case for add_instance as the coursemodule has not been set yet.
719         $instance = $this->get_instance();
721         if ($instance->duedate) {
722             $event = new stdClass();
724             $params = array('modulename'=>'assign', 'instance'=>$instance->id);
725             $event->id = $DB->get_field('event',
726                                         'id',
727                                         $params);
729             if ($event->id) {
730                 $event->name        = $instance->name;
731                 $event->description = format_module_intro('assign', $instance, $coursemoduleid);
732                 $event->timestart   = $instance->duedate;
734                 $calendarevent = calendar_event::load($event->id);
735                 $calendarevent->update($event);
736             } else {
737                 $event = new stdClass();
738                 $event->name        = $instance->name;
739                 $event->description = format_module_intro('assign', $instance, $coursemoduleid);
740                 $event->courseid    = $instance->course;
741                 $event->groupid     = 0;
742                 $event->userid      = 0;
743                 $event->modulename  = 'assign';
744                 $event->instance    = $instance->id;
745                 $event->eventtype   = 'due';
746                 $event->timestart   = $instance->duedate;
747                 $event->timeduration = 0;
749                 calendar_event::create($event);
750             }
751         } else {
752             $DB->delete_records('event', array('modulename'=>'assign', 'instance'=>$instance->id));
753         }
754     }
757     /**
758      * Update this instance in the database.
759      *
760      * @param stdClass $formdata - the data submitted from the form
761      * @return bool false if an error occurs
762      */
763     public function update_instance($formdata) {
764         global $DB;
766         $update = new stdClass();
767         $update->id = $formdata->instance;
768         $update->name = $formdata->name;
769         $update->timemodified = time();
770         $update->course = $formdata->course;
771         $update->intro = $formdata->intro;
772         $update->introformat = $formdata->introformat;
773         $update->alwaysshowdescription = $formdata->alwaysshowdescription;
774         $update->submissiondrafts = $formdata->submissiondrafts;
775         $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
776         $update->sendnotifications = $formdata->sendnotifications;
777         $update->sendlatenotifications = $formdata->sendlatenotifications;
778         $update->duedate = $formdata->duedate;
779         $update->cutoffdate = $formdata->cutoffdate;
780         $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
781         $update->grade = $formdata->grade;
782         $update->completionsubmit = !empty($formdata->completionsubmit);
783         $update->teamsubmission = $formdata->teamsubmission;
784         $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
785         $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
786         $update->blindmarking = $formdata->blindmarking;
788         $result = $DB->update_record('assign', $update);
789         $this->instance = $DB->get_record('assign', array('id'=>$update->id), '*', MUST_EXIST);
791         // Load the assignment so the plugins have access to it.
793         // Call save_settings hook for submission plugins.
794         foreach ($this->submissionplugins as $plugin) {
795             if (!$this->update_plugin_instance($plugin, $formdata)) {
796                 print_error($plugin->get_error());
797                 return false;
798             }
799         }
800         foreach ($this->feedbackplugins as $plugin) {
801             if (!$this->update_plugin_instance($plugin, $formdata)) {
802                 print_error($plugin->get_error());
803                 return false;
804             }
805         }
807         $this->update_calendar($this->get_course_module()->id);
808         $this->update_gradebook(false, $this->get_course_module()->id);
810         $update = new stdClass();
811         $update->id = $this->get_instance()->id;
812         $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
813         $DB->update_record('assign', $update);
815         return $result;
816     }
818     /**
819      * Add elements in grading plugin form.
820      *
821      * @param mixed $grade stdClass|null
822      * @param MoodleQuickForm $mform
823      * @param stdClass $data
824      * @param int $userid - The userid we are grading
825      * @return void
826      */
827     protected function add_plugin_grade_elements($grade, MoodleQuickForm $mform, stdClass $data, $userid) {
828         foreach ($this->feedbackplugins as $plugin) {
829             if ($plugin->is_enabled() && $plugin->is_visible()) {
830                 $mform->addElement('header', 'header_' . $plugin->get_type(), $plugin->get_name());
831                 if (!$plugin->get_form_elements_for_user($grade, $mform, $data, $userid)) {
832                     $mform->removeElement('header_' . $plugin->get_type());
833                 }
834             }
835         }
836     }
840     /**
841      * Add one plugins settings to edit plugin form.
842      *
843      * @param assign_plugin $plugin The plugin to add the settings from
844      * @param MoodleQuickForm $mform The form to add the configuration settings to.
845      *                               This form is modified directly (not returned).
846      * @param array $pluginsenabled A list of form elements to be added to a group.
847      *                              The new element is added to this array by this function.
848      * @return void
849      */
850     protected function add_plugin_settings(assign_plugin $plugin, MoodleQuickForm $mform, & $pluginsenabled) {
851         global $CFG;
852         if ($plugin->is_visible()) {
854             $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
855             $label = $plugin->get_name();
856             $label .= ' ' . $this->get_renderer()->help_icon('enabled', $plugin->get_subtype() . '_' . $plugin->get_type());
857             $pluginsenabled[] = $mform->createElement('checkbox', $name, '', $label);
859             $default = get_config($plugin->get_subtype() . '_' . $plugin->get_type(), 'default');
860             if ($plugin->get_config('enabled') !== false) {
861                 $default = $plugin->is_enabled();
862             }
863             $mform->setDefault($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $default);
865             $plugin->get_settings($mform);
867         }
868     }
870     /**
871      * Add settings to edit plugin form.
872      *
873      * @param MoodleQuickForm $mform The form to add the configuration settings to.
874      *                               This form is modified directly (not returned).
875      * @return void
876      */
877     public function add_all_plugin_settings(MoodleQuickForm $mform) {
878         $mform->addElement('header', 'submissiontypes', get_string('submissionsettings', 'assign'));
880         $submissionpluginsenabled = array();
881         $group = $mform->addGroup(array(), 'submissionplugins', get_string('submissiontypes', 'assign'), array(' '), false);
882         foreach ($this->submissionplugins as $plugin) {
883             $this->add_plugin_settings($plugin, $mform, $submissionpluginsenabled);
884         }
885         $group->setElements($submissionpluginsenabled);
887         $mform->addElement('header', 'feedbacktypes', get_string('feedbacksettings', 'assign'));
888         $feedbackpluginsenabled = array();
889         $group = $mform->addGroup(array(), 'feedbackplugins', get_string('feedbacktypes', 'assign'), array(' '), false);
890         foreach ($this->feedbackplugins as $plugin) {
891             $this->add_plugin_settings($plugin, $mform, $feedbackpluginsenabled);
892         }
893         $group->setElements($feedbackpluginsenabled);
894         $mform->setExpanded('submissiontypes');
895     }
897     /**
898      * Allow each plugin an opportunity to update the defaultvalues
899      * passed in to the settings form (needed to set up draft areas for
900      * editor and filemanager elements)
901      *
902      * @param array $defaultvalues
903      */
904     public function plugin_data_preprocessing(&$defaultvalues) {
905         foreach ($this->submissionplugins as $plugin) {
906             if ($plugin->is_visible()) {
907                 $plugin->data_preprocessing($defaultvalues);
908             }
909         }
910         foreach ($this->feedbackplugins as $plugin) {
911             if ($plugin->is_visible()) {
912                 $plugin->data_preprocessing($defaultvalues);
913             }
914         }
915     }
917     /**
918      * Get the name of the current module.
919      *
920      * @return string the module name (Assignment)
921      */
922     protected function get_module_name() {
923         if (isset(self::$modulename)) {
924             return self::$modulename;
925         }
926         self::$modulename = get_string('modulename', 'assign');
927         return self::$modulename;
928     }
930     /**
931      * Get the plural name of the current module.
932      *
933      * @return string the module name plural (Assignments)
934      */
935     protected function get_module_name_plural() {
936         if (isset(self::$modulenameplural)) {
937             return self::$modulenameplural;
938         }
939         self::$modulenameplural = get_string('modulenameplural', 'assign');
940         return self::$modulenameplural;
941     }
943     /**
944      * Has this assignment been constructed from an instance?
945      *
946      * @return bool
947      */
948     public function has_instance() {
949         return $this->instance || $this->get_course_module();
950     }
952     /**
953      * Get the settings for the current instance of this assignment
954      *
955      * @return stdClass The settings
956      */
957     public function get_instance() {
958         global $DB;
959         if ($this->instance) {
960             return $this->instance;
961         }
962         if ($this->get_course_module()) {
963             $params = array('id' => $this->get_course_module()->instance);
964             $this->instance = $DB->get_record('assign', $params, '*', MUST_EXIST);
965         }
966         if (!$this->instance) {
967             throw new coding_exception('Improper use of the assignment class. ' .
968                                        'Cannot load the assignment record.');
969         }
970         return $this->instance;
971     }
973     /**
974      * Get the context of the current course.
975      *
976      * @return mixed context|null The course context
977      */
978     public function get_course_context() {
979         if (!$this->context && !$this->course) {
980             throw new coding_exception('Improper use of the assignment class. ' .
981                                        'Cannot load the course context.');
982         }
983         if ($this->context) {
984             return $this->context->get_course_context();
985         } else {
986             return context_course::instance($this->course->id);
987         }
988     }
991     /**
992      * Get the current course module.
993      *
994      * @return mixed stdClass|null The course module
995      */
996     public function get_course_module() {
997         if ($this->coursemodule) {
998             return $this->coursemodule;
999         }
1000         if (!$this->context) {
1001             return null;
1002         }
1004         if ($this->context->contextlevel == CONTEXT_MODULE) {
1005             $this->coursemodule = get_coursemodule_from_id('assign',
1006                                                            $this->context->instanceid,
1007                                                            0,
1008                                                            false,
1009                                                            MUST_EXIST);
1010             return $this->coursemodule;
1011         }
1012         return null;
1013     }
1015     /**
1016      * Get context module.
1017      *
1018      * @return context
1019      */
1020     public function get_context() {
1021         return $this->context;
1022     }
1024     /**
1025      * Get the current course.
1026      *
1027      * @return mixed stdClass|null The course
1028      */
1029     public function get_course() {
1030         global $DB;
1032         if ($this->course) {
1033             return $this->course;
1034         }
1036         if (!$this->context) {
1037             return null;
1038         }
1039         $params = array('id' => $this->get_course_context()->instanceid);
1040         $this->course = $DB->get_record('course', $params, '*', MUST_EXIST);
1042         return $this->course;
1043     }
1045     /**
1046      * Return a grade in user-friendly form, whether it's a scale or not.
1047      *
1048      * @param mixed $grade int|null
1049      * @param boolean $editing Are we allowing changes to this grade?
1050      * @param int $userid The user id the grade belongs to
1051      * @param int $modified Timestamp from when the grade was last modified
1052      * @return string User-friendly representation of grade
1053      */
1054     public function display_grade($grade, $editing, $userid=0, $modified=0) {
1055         global $DB;
1057         static $scalegrades = array();
1059         $o = '';
1061         if ($this->get_instance()->grade >= 0) {
1062             // Normal number.
1063             if ($editing && $this->get_instance()->grade > 0) {
1064                 if ($grade < 0) {
1065                     $displaygrade = '';
1066                 } else {
1067                     $displaygrade = format_float($grade);
1068                 }
1069                 $o .= '<label class="accesshide" for="quickgrade_' . $userid . '">' .
1070                        get_string('usergrade', 'assign') .
1071                        '</label>';
1072                 $o .= '<input type="text"
1073                               id="quickgrade_' . $userid . '"
1074                               name="quickgrade_' . $userid . '"
1075                               value="' .  $displaygrade . '"
1076                               size="6"
1077                               maxlength="10"
1078                               class="quickgrade"/>';
1079                 $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade, 2);
1080                 $o .= '<input type="hidden"
1081                               name="grademodified_' . $userid . '"
1082                               value="' . $modified . '"/>';
1083                 return $o;
1084             } else {
1085                 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
1086                 if ($grade == -1 || $grade === null) {
1087                     $o .= '-';
1088                     return $o;
1089                 } else {
1090                     $o .= format_float($grade, 2) .
1091                           '&nbsp;/&nbsp;' .
1092                           format_float($this->get_instance()->grade, 2);
1093                     return $o;
1094                 }
1095             }
1097         } else {
1098             // Scale.
1099             if (empty($this->cache['scale'])) {
1100                 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
1101                     $this->cache['scale'] = make_menu_from_list($scale->scale);
1102                 } else {
1103                     $o .= '-';
1104                     return $o;
1105                 }
1106             }
1107             if ($editing) {
1108                 $o .= '<label class="accesshide"
1109                               for="quickgrade_' . $userid . '">' .
1110                       get_string('usergrade', 'assign') .
1111                       '</label>';
1112                 $o .= '<select name="quickgrade_' . $userid . '" class="quickgrade">';
1113                 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
1114                 foreach ($this->cache['scale'] as $optionid => $option) {
1115                     $selected = '';
1116                     if ($grade == $optionid) {
1117                         $selected = 'selected="selected"';
1118                     }
1119                     $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
1120                 }
1121                 $o .= '</select>';
1122                 $o .= '<input type="hidden" ' .
1123                              'name="grademodified_' . $userid . '" ' .
1124                              'value="' . $modified . '"/>';
1125                 return $o;
1126             } else {
1127                 $scaleid = (int)$grade;
1128                 if (isset($this->cache['scale'][$scaleid])) {
1129                     $o .= $this->cache['scale'][$scaleid];
1130                     return $o;
1131                 }
1132                 $o .= '-';
1133                 return $o;
1134             }
1135         }
1136     }
1138     /**
1139      * Load a list of users enrolled in the current course with the specified permission and group.
1140      * 0 for no group.
1141      *
1142      * @param int $currentgroup
1143      * @param bool $idsonly
1144      * @return array List of user records
1145      */
1146     public function list_participants($currentgroup, $idsonly) {
1147         if ($idsonly) {
1148             return get_enrolled_users($this->context, 'mod/assign:submit', $currentgroup, 'u.id');
1149         } else {
1150             return get_enrolled_users($this->context, 'mod/assign:submit', $currentgroup);
1151         }
1152     }
1154     /**
1155      * Load a count of valid teams for this assignment.
1156      *
1157      * @return int number of valid teams
1158      */
1159     public function count_teams() {
1161         $groups = groups_get_all_groups($this->get_course()->id,
1162                                         0,
1163                                         $this->get_instance()->teamsubmissiongroupingid,
1164                                         'g.id');
1165         $count = count($groups);
1167         // See if there are any users in the default group.
1168         $defaultusers = $this->get_submission_group_members(0, true);
1169         if (count($defaultusers) > 0) {
1170             $count += 1;
1171         }
1172         return $count;
1173     }
1175     /**
1176      * Load a count of users enrolled in the current course with the specified permission and group.
1177      * 0 for no group.
1178      *
1179      * @param int $currentgroup
1180      * @return int number of matching users
1181      */
1182     public function count_participants($currentgroup) {
1183         return count_enrolled_users($this->context, 'mod/assign:submit', $currentgroup);
1184     }
1186     /**
1187      * Load a count of users submissions in the current module that require grading
1188      * This means the submission modification time is more recent than the
1189      * grading modification time and the status is SUBMITTED.
1190      *
1191      * @return int number of matching submissions
1192      */
1193     public function count_submissions_need_grading() {
1194         global $DB;
1196         if ($this->get_instance()->teamsubmission) {
1197             // This does not make sense for group assignment because the submission is shared.
1198             return 0;
1199         }
1201         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1202         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1204         $params['assignid'] = $this->get_instance()->id;
1205         $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1207         $sql = 'SELECT COUNT(s.userid)
1208                    FROM {assign_submission} s
1209                    LEFT JOIN {assign_grades} g ON
1210                         s.assignment = g.assignment AND
1211                         s.userid = g.userid
1212                    JOIN(' . $esql . ') e ON e.id = s.userid
1213                    WHERE
1214                         s.assignment = :assignid AND
1215                         s.timemodified IS NOT NULL AND
1216                         s.status = :submitted AND
1217                         (s.timemodified > g.timemodified OR g.timemodified IS NULL)';
1219         return $DB->count_records_sql($sql, $params);
1220     }
1222     /**
1223      * Load a count of grades.
1224      *
1225      * @return int number of grades
1226      */
1227     public function count_grades() {
1228         global $DB;
1230         if (!$this->has_instance()) {
1231             return 0;
1232         }
1234         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1235         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1237         $params['assignid'] = $this->get_instance()->id;
1239         $sql = 'SELECT COUNT(g.userid)
1240                    FROM {assign_grades} g
1241                    JOIN(' . $esql . ') e ON e.id = g.userid
1242                    WHERE g.assignment = :assignid';
1244         return $DB->count_records_sql($sql, $params);
1245     }
1247     /**
1248      * Load a count of submissions.
1249      *
1250      * @return int number of submissions
1251      */
1252     public function count_submissions() {
1253         global $DB;
1255         if (!$this->has_instance()) {
1256             return 0;
1257         }
1259         $params = array();
1261         if ($this->get_instance()->teamsubmission) {
1262             // We cannot join on the enrolment tables for group submissions (no userid).
1263             $sql = 'SELECT COUNT(s.groupid)
1264                         FROM {assign_submission} s
1265                         WHERE
1266                             s.assignment = :assignid AND
1267                             s.timemodified IS NOT NULL AND
1268                             s.userid = :groupuserid';
1270             $params['assignid'] = $this->get_instance()->id;
1271             $params['groupuserid'] = 0;
1272         } else {
1273             $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1274             list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1276             $params['assignid'] = $this->get_instance()->id;
1278             $sql = 'SELECT COUNT(s.userid)
1279                        FROM {assign_submission} s
1280                        JOIN(' . $esql . ') e ON e.id = s.userid
1281                        WHERE
1282                             s.assignment = :assignid AND
1283                             s.timemodified IS NOT NULL';
1284         }
1286         return $DB->count_records_sql($sql, $params);
1287     }
1289     /**
1290      * Load a count of submissions with a specified status.
1291      *
1292      * @param string $status The submission status - should match one of the constants
1293      * @return int number of matching submissions
1294      */
1295     public function count_submissions_with_status($status) {
1296         global $DB;
1298         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1299         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1301         $params['assignid'] = $this->get_instance()->id;
1302         $params['submissionstatus'] = $status;
1304         if ($this->get_instance()->teamsubmission) {
1305             $sql = 'SELECT COUNT(s.groupid)
1306                         FROM {assign_submission} s
1307                         WHERE
1308                             s.assignment = :assignid AND
1309                             s.timemodified IS NOT NULL AND
1310                             s.userid = :groupuserid AND
1311                             s.status = :submissionstatus';
1312             $params['groupuserid'] = 0;
1313         } else {
1314             $sql = 'SELECT COUNT(s.userid)
1315                         FROM {assign_submission} s
1316                         JOIN(' . $esql . ') e ON e.id = s.userid
1317                         WHERE
1318                             s.assignment = :assignid AND
1319                             s.timemodified IS NOT NULL AND
1320                             s.status = :submissionstatus';
1321         }
1323         return $DB->count_records_sql($sql, $params);
1324     }
1326     /**
1327      * Utility function to get the userid for every row in the grading table
1328      * so the order can be frozen while we iterate it.
1329      *
1330      * @return array An array of userids
1331      */
1332     protected function get_grading_userid_list() {
1333         $filter = get_user_preferences('assign_filter', '');
1334         $table = new assign_grading_table($this, 0, $filter, 0, false);
1336         $useridlist = $table->get_column_data('userid');
1338         return $useridlist;
1339     }
1341     /**
1342      * Generate zip file from array of given files.
1343      *
1344      * @param array $filesforzipping - array of files to pass into archive_to_pathname.
1345      *                                 This array is indexed by the final file name and each
1346      *                                 element in the array is an instance of a stored_file object.
1347      * @return path of temp file - note this returned file does
1348      *         not have a .zip extension - it is a temp file.
1349      */
1350     protected function pack_files($filesforzipping) {
1351         global $CFG;
1352         // Create path for new zip file.
1353         $tempzip = tempnam($CFG->tempdir . '/', 'assignment_');
1354         // Zip files.
1355         $zipper = new zip_packer();
1356         if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
1357             return $tempzip;
1358         }
1359         return false;
1360     }
1362     /**
1363      * Finds all assignment notifications that have yet to be mailed out, and mails them.
1364      *
1365      * Cron function to be run periodically according to the moodle cron.
1366      *
1367      * @return bool
1368      */
1369     public static function cron() {
1370         global $DB;
1372         // Only ever send a max of one days worth of updates.
1373         $yesterday = time() - (24 * 3600);
1374         $timenow   = time();
1376         // Collect all submissions from the past 24 hours that require mailing.
1377         $sql = 'SELECT s.*, a.course, a.name, a.blindmarking, a.revealidentities,
1378                        g.*, g.id as gradeid, g.timemodified as lastmodified
1379                  FROM {assign} a
1380                  JOIN {assign_grades} g ON g.assignment = a.id
1381             LEFT JOIN {assign_submission} s ON s.assignment = a.id AND s.userid = g.userid
1382                 WHERE g.timemodified >= :yesterday AND
1383                       g.timemodified <= :today AND
1384                       g.mailed = 0';
1386         $params = array('yesterday' => $yesterday, 'today' => $timenow);
1387         $submissions = $DB->get_records_sql($sql, $params);
1389         if (empty($submissions)) {
1390             return true;
1391         }
1393         mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
1395         // Preload courses we are going to need those.
1396         $courseids = array();
1397         foreach ($submissions as $submission) {
1398             $courseids[] = $submission->course;
1399         }
1401         // Filter out duplicates.
1402         $courseids = array_unique($courseids);
1403         $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1404         list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
1405         $sql = 'SELECT c.*, ' . $ctxselect .
1406                   ' FROM {course} c
1407              LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
1408                  WHERE c.id ' . $courseidsql;
1410         $params['contextlevel'] = CONTEXT_COURSE;
1411         $courses = $DB->get_records_sql($sql, $params);
1413         // Clean up... this could go on for a while.
1414         unset($courseids);
1415         unset($ctxselect);
1416         unset($courseidsql);
1417         unset($params);
1419         // Simple array we'll use for caching modules.
1420         $modcache = array();
1422         // Message students about new feedback.
1423         foreach ($submissions as $submission) {
1425             mtrace("Processing assignment submission $submission->id ...");
1427             // Do not cache user lookups - could be too many.
1428             if (!$user = $DB->get_record('user', array('id'=>$submission->userid))) {
1429                 mtrace('Could not find user ' . $submission->userid);
1430                 continue;
1431             }
1433             // Use a cache to prevent the same DB queries happening over and over.
1434             if (!array_key_exists($submission->course, $courses)) {
1435                 mtrace('Could not find course ' . $submission->course);
1436                 continue;
1437             }
1438             $course = $courses[$submission->course];
1439             if (isset($course->ctxid)) {
1440                 // Context has not yet been preloaded. Do so now.
1441                 context_helper::preload_from_record($course);
1442             }
1444             // Override the language and timezone of the "current" user, so that
1445             // mail is customised for the receiver.
1446             cron_setup_user($user, $course);
1448             // Context lookups are already cached.
1449             $coursecontext = context_course::instance($course->id);
1450             if (!is_enrolled($coursecontext, $user->id)) {
1451                 $courseshortname = format_string($course->shortname,
1452                                                  true,
1453                                                  array('context' => $coursecontext));
1454                 mtrace(fullname($user) . ' not an active participant in ' . $courseshortname);
1455                 continue;
1456             }
1458             if (!$grader = $DB->get_record('user', array('id'=>$submission->grader))) {
1459                 mtrace('Could not find grader ' . $submission->grader);
1460                 continue;
1461             }
1463             if (!array_key_exists($submission->assignment, $modcache)) {
1464                 $mod = get_coursemodule_from_instance('assign', $submission->assignment, $course->id);
1465                 if (empty($mod)) {
1466                     mtrace('Could not find course module for assignment id ' . $submission->assignment);
1467                     continue;
1468                 }
1469                 $modcache[$submission->assignment] = $mod;
1470             } else {
1471                 $mod = $modcache[$submission->assignment];
1472             }
1473             // Context lookups are already cached.
1474             $contextmodule = context_module::instance($mod->id);
1476             if (!$mod->visible) {
1477                 // Hold mail notification for hidden assignments until later.
1478                 continue;
1479             }
1481             // Need to send this to the student.
1482             $messagetype = 'feedbackavailable';
1483             $eventtype = 'assign_notification';
1484             $updatetime = $submission->lastmodified;
1485             $modulename = get_string('modulename', 'assign');
1487             $uniqueid = 0;
1488             if ($submission->blindmarking && !$submission->revealidentities) {
1489                 $uniqueid = self::get_uniqueid_for_user_static($submission->assignment, $user->id);
1490             }
1491             $showusers = $submission->blindmarking && !$submission->revealidentities;
1492             self::send_assignment_notification($grader,
1493                                                $user,
1494                                                $messagetype,
1495                                                $eventtype,
1496                                                $updatetime,
1497                                                $mod,
1498                                                $contextmodule,
1499                                                $course,
1500                                                $modulename,
1501                                                $submission->name,
1502                                                $showusers,
1503                                                $uniqueid);
1505             $grade = new stdClass();
1506             $grade->id = $submission->gradeid;
1507             $grade->mailed = 1;
1508             $DB->update_record('assign_grades', $grade);
1510             mtrace('Done');
1511         }
1512         mtrace('Done processing ' . count($submissions) . ' assignment submissions');
1514         cron_setup_user();
1516         // Free up memory just to be sure.
1517         unset($courses);
1518         unset($modcache);
1520         return true;
1521     }
1523     /**
1524      * Mark in the database that this grade record should have an update notification sent by cron.
1525      *
1526      * @param stdClass $grade a grade record keyed on id
1527      * @return bool true for success
1528      */
1529     public function notify_grade_modified($grade) {
1530         global $DB;
1532         $grade->timemodified = time();
1533         if ($grade->mailed != 1) {
1534             $grade->mailed = 0;
1535         }
1537         return $DB->update_record('assign_grades', $grade);
1538     }
1540     /**
1541      * Update a grade in the grade table for the assignment and in the gradebook.
1542      *
1543      * @param stdClass $grade a grade record keyed on id
1544      * @return bool true for success
1545      */
1546     public function update_grade($grade) {
1547         global $DB;
1549         $grade->timemodified = time();
1551         if ($grade->grade && $grade->grade != -1) {
1552             if ($this->get_instance()->grade > 0) {
1553                 if (!is_numeric($grade->grade)) {
1554                     return false;
1555                 } else if ($grade->grade > $this->get_instance()->grade) {
1556                     return false;
1557                 } else if ($grade->grade < 0) {
1558                     return false;
1559                 }
1560             } else {
1561                 // This is a scale.
1562                 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
1563                     $scaleoptions = make_menu_from_list($scale->scale);
1564                     if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
1565                         return false;
1566                     }
1567                 }
1568             }
1569         }
1571         $result = $DB->update_record('assign_grades', $grade);
1572         if ($result) {
1573             $this->gradebook_item_update(null, $grade);
1574         }
1575         return $result;
1576     }
1578     /**
1579      * View the grant extension date page.
1580      *
1581      * Uses url parameters 'userid'
1582      * or from parameter 'selectedusers'
1583      *
1584      * @param moodleform $mform - Used for validation of the submitted data
1585      * @return string
1586      */
1587     protected function view_grant_extension($mform) {
1588         global $DB, $CFG;
1589         require_once($CFG->dirroot . '/mod/assign/extensionform.php');
1591         $o = '';
1592         $batchusers = optional_param('selectedusers', '', PARAM_TEXT);
1593         $data = new stdClass();
1594         $data->extensionduedate = null;
1595         $userid = 0;
1596         if (!$batchusers) {
1597             $userid = required_param('userid', PARAM_INT);
1599             $grade = $this->get_user_grade($userid, false);
1601             $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
1603             if ($grade) {
1604                 $data->extensionduedate = $grade->extensionduedate;
1605             }
1606             $data->userid = $userid;
1607         } else {
1608             $data->batchusers = $batchusers;
1609         }
1610         $header = new assign_header($this->get_instance(),
1611                                     $this->get_context(),
1612                                     $this->show_intro(),
1613                                     $this->get_course_module()->id,
1614                                     get_string('grantextension', 'assign'));
1615         $o .= $this->get_renderer()->render($header);
1617         if (!$mform) {
1618             $formparams = array($this->get_course_module()->id,
1619                                 $userid,
1620                                 $batchusers,
1621                                 $this->get_instance(),
1622                                 $data);
1623             $mform = new mod_assign_extension_form(null, $formparams);
1624         }
1625         $o .= $this->get_renderer()->render(new assign_form('extensionform', $mform));
1626         $o .= $this->view_footer();
1627         return $o;
1628     }
1630     /**
1631      * Get a list of the users in the same group as this user.
1632      *
1633      * @param int $groupid The id of the group whose members we want or 0 for the default group
1634      * @param bool $onlyids Whether to retrieve only the user id's
1635      * @return array The users (possibly id's only)
1636      */
1637     public function get_submission_group_members($groupid, $onlyids) {
1638         $members = array();
1639         if ($groupid != 0) {
1640             if ($onlyids) {
1641                 $allusers = groups_get_members($groupid, 'u.id');
1642             } else {
1643                 $allusers = groups_get_members($groupid);
1644             }
1645             foreach ($allusers as $user) {
1646                 if ($this->get_submission_group($user->id)) {
1647                     $members[] = $user;
1648                 }
1649             }
1650         } else {
1651             $allusers = $this->list_participants(null, $onlyids);
1652             foreach ($allusers as $user) {
1653                 if ($this->get_submission_group($user->id) == null) {
1654                     $members[] = $user;
1655                 }
1656             }
1657         }
1658         return $members;
1659     }
1661     /**
1662      * Get a list of the users in the same group as this user that have not submitted the assignment.
1663      *
1664      * @param int $groupid The id of the group whose members we want or 0 for the default group
1665      * @param bool $onlyids Whether to retrieve only the user id's
1666      * @return array The users (possibly id's only)
1667      */
1668     public function get_submission_group_members_who_have_not_submitted($groupid, $onlyids) {
1669         $instance = $this->get_instance();
1670         if (!$instance->teamsubmission || !$instance->requireallteammemberssubmit) {
1671             return array();
1672         }
1673         $members = $this->get_submission_group_members($groupid, $onlyids);
1675         foreach ($members as $id => $member) {
1676             $submission = $this->get_user_submission($member->id, false);
1677             if ($submission && $submission->status != ASSIGN_SUBMISSION_STATUS_DRAFT) {
1678                 unset($members[$id]);
1679             } else {
1680                 if ($this->is_blind_marking()) {
1681                     $members[$id]->alias = get_string('hiddenuser', 'assign') .
1682                                            $this->get_uniqueid_for_user($id);
1683                 }
1684             }
1685         }
1686         return $members;
1687     }
1689     /**
1690      * Load the group submission object for a particular user, optionally creating it if required.
1691      *
1692      * @param int $userid The id of the user whose submission we want
1693      * @param int $groupid The id of the group for this user - may be 0 in which
1694      *                     case it is determined from the userid.
1695      * @param bool $create If set to true a new submission object will be created in the database
1696      * @return stdClass The submission
1697      */
1698     public function get_group_submission($userid, $groupid, $create) {
1699         global $DB;
1701         if ($groupid == 0) {
1702             $group = $this->get_submission_group($userid);
1703             if ($group) {
1704                 $groupid = $group->id;
1705             }
1706         }
1708         if ($create) {
1709             // Make sure there is a submission for this user.
1710             $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>0, 'userid'=>$userid);
1711             $submission = $DB->get_record('assign_submission', $params);
1713             if (!$submission) {
1714                 $submission = new stdClass();
1715                 $submission->assignment = $this->get_instance()->id;
1716                 $submission->userid = $userid;
1717                 $submission->groupid = 0;
1718                 $submission->timecreated = time();
1719                 $submission->timemodified = $submission->timecreated;
1721                 if ($this->get_instance()->submissiondrafts) {
1722                     $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
1723                 } else {
1724                     $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1725                 }
1726                 $DB->insert_record('assign_submission', $submission);
1727             }
1728         }
1729         // Now get the group submission.
1730         $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
1731         $submission = $DB->get_record('assign_submission', $params);
1733         if ($submission) {
1734             return $submission;
1735         }
1736         if ($create) {
1737             $submission = new stdClass();
1738             $submission->assignment = $this->get_instance()->id;
1739             $submission->userid = 0;
1740             $submission->groupid = $groupid;
1741             $submission->timecreated = time();
1742             $submission->timemodified = $submission->timecreated;
1744             if ($this->get_instance()->submissiondrafts) {
1745                 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
1746             } else {
1747                 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1748             }
1749             $sid = $DB->insert_record('assign_submission', $submission);
1750             $submission->id = $sid;
1751             return $submission;
1752         }
1753         return false;
1754     }
1756     /**
1757      * View a summary listing of all assignments in the current course.
1758      *
1759      * @return string
1760      */
1761     private function view_course_index() {
1762         global $USER;
1764         $o = '';
1766         $course = $this->get_course();
1767         $strplural = get_string('modulenameplural', 'assign');
1769         if (!$cms = get_coursemodules_in_course('assign', $course->id, 'm.duedate')) {
1770             $o .= $this->get_renderer()->notification(get_string('thereareno', 'moodle', $strplural));
1771             $o .= $this->get_renderer()->continue_button(new moodle_url('/course/view.php', array('id' => $course->id)));
1772             return $o;
1773         }
1775         $strsectionname  = get_string('sectionname', 'format_'.$course->format);
1776         $usesections = course_format_uses_sections($course->format);
1777         $modinfo = get_fast_modinfo($course);
1779         if ($usesections) {
1780             $sections = $modinfo->get_section_info_all();
1781         }
1782         $courseindexsummary = new assign_course_index_summary($usesections, $strsectionname);
1784         $timenow = time();
1786         $currentsection = '';
1787         foreach ($modinfo->instances['assign'] as $cm) {
1788             if (!$cm->uservisible) {
1789                 continue;
1790             }
1792             $timedue = $cms[$cm->id]->duedate;
1794             $sectionname = '';
1795             if ($usesections && $cm->sectionnum) {
1796                 $sectionname = get_section_name($course, $sections[$cm->sectionnum]);
1797             }
1799             $submitted = '';
1800             $context = context_module::instance($cm->id);
1802             $assignment = new assign($context, $cm, $course);
1804             if (has_capability('mod/assign:grade', $context)) {
1805                 $submitted = $assignment->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED);
1807             } else if (has_capability('mod/assign:submit', $context)) {
1808                 $usersubmission = $assignment->get_user_submission($USER->id, false);
1810                 if (!empty($usersubmission->status)) {
1811                     $submitted = get_string('submissionstatus_' . $usersubmission->status, 'assign');
1812                 } else {
1813                     $submitted = get_string('submissionstatus_', 'assign');
1814                 }
1815             }
1816             $grading_info = grade_get_grades($course->id, 'mod', 'assign', $cm->instance, $USER->id);
1817             if (isset($grading_info->items[0]->grades[$USER->id]) &&
1818                     !$grading_info->items[0]->grades[$USER->id]->hidden ) {
1819                 $grade = $grading_info->items[0]->grades[$USER->id]->str_grade;
1820             } else {
1821                 $grade = '-';
1822             }
1824             $courseindexsummary->add_assign_info($cm->id, $cm->name, $sectionname, $timedue, $submitted, $grade);
1826         }
1828         $o .= $this->get_renderer()->render($courseindexsummary);
1829         $o .= $this->view_footer();
1831         return $o;
1832     }
1834     /**
1835      * View a page rendered by a plugin.
1836      *
1837      * Uses url parameters 'pluginaction', 'pluginsubtype', 'plugin', and 'id'.
1838      *
1839      * @return string
1840      */
1841     protected function view_plugin_page() {
1842         global $USER;
1844         $o = '';
1846         $pluginsubtype = required_param('pluginsubtype', PARAM_ALPHA);
1847         $plugintype = required_param('plugin', PARAM_TEXT);
1848         $pluginaction = required_param('pluginaction', PARAM_ALPHA);
1850         $plugin = $this->get_plugin_by_type($pluginsubtype, $plugintype);
1851         if (!$plugin) {
1852             print_error('invalidformdata', '');
1853             return;
1854         }
1856         $o .= $plugin->view_page($pluginaction);
1858         return $o;
1859     }
1862     /**
1863      * This is used for team assignments to get the group for the specified user.
1864      * If the user is a member of multiple or no groups this will return false
1865      *
1866      * @param int $userid The id of the user whose submission we want
1867      * @return mixed The group or false
1868      */
1869     public function get_submission_group($userid) {
1870         $grouping = $this->get_instance()->teamsubmissiongroupingid;
1871         $groups = groups_get_all_groups($this->get_course()->id, $userid, $grouping);
1872         if (count($groups) != 1) {
1873             return false;
1874         }
1875         return array_pop($groups);
1876     }
1879     /**
1880      * Display the submission that is used by a plugin.
1881      *
1882      * Uses url parameters 'sid', 'gid' and 'plugin'.
1883      *
1884      * @param string $pluginsubtype
1885      * @return string
1886      */
1887     protected function view_plugin_content($pluginsubtype) {
1888         global $USER;
1890         $o = '';
1892         $submissionid = optional_param('sid', 0, PARAM_INT);
1893         $gradeid = optional_param('gid', 0, PARAM_INT);
1894         $plugintype = required_param('plugin', PARAM_TEXT);
1895         $item = null;
1896         if ($pluginsubtype == 'assignsubmission') {
1897             $plugin = $this->get_submission_plugin_by_type($plugintype);
1898             if ($submissionid <= 0) {
1899                 throw new coding_exception('Submission id should not be 0');
1900             }
1901             $item = $this->get_submission($submissionid);
1903             // Check permissions.
1904             if ($item->userid != $USER->id) {
1905                 require_capability('mod/assign:grade', $this->context);
1906             }
1907             $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
1908                                                               $this->get_context(),
1909                                                               $this->show_intro(),
1910                                                               $this->get_course_module()->id,
1911                                                               $plugin->get_name()));
1912             $o .= $this->get_renderer()->render(new assign_submission_plugin_submission($plugin,
1913                                                               $item,
1914                                                               assign_submission_plugin_submission::FULL,
1915                                                               $this->get_course_module()->id,
1916                                                               $this->get_return_action(),
1917                                                               $this->get_return_params()));
1919             $logmessage = get_string('viewsubmissionforuser', 'assign', $item->userid);
1920             $this->add_to_log('view submission', $logmessage);
1921         } else {
1922             $plugin = $this->get_feedback_plugin_by_type($plugintype);
1923             if ($gradeid <= 0) {
1924                 throw new coding_exception('Grade id should not be 0');
1925             }
1926             $item = $this->get_grade($gradeid);
1927             // Check permissions.
1928             if ($item->userid != $USER->id) {
1929                 require_capability('mod/assign:grade', $this->context);
1930             }
1931             $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
1932                                                               $this->get_context(),
1933                                                               $this->show_intro(),
1934                                                               $this->get_course_module()->id,
1935                                                               $plugin->get_name()));
1936             $o .= $this->get_renderer()->render(new assign_feedback_plugin_feedback($plugin,
1937                                                               $item,
1938                                                               assign_feedback_plugin_feedback::FULL,
1939                                                               $this->get_course_module()->id,
1940                                                               $this->get_return_action(),
1941                                                               $this->get_return_params()));
1942             $logmessage = get_string('viewfeedbackforuser', 'assign', $item->userid);
1943             $this->add_to_log('view feedback', $logmessage);
1944         }
1946         $o .= $this->view_return_links();
1948         $o .= $this->view_footer();
1949         return $o;
1950     }
1952     /**
1953      * Rewrite plugin file urls so they resolve correctly in an exported zip.
1954      *
1955      * @param stdClass $user - The user record
1956      * @param assign_plugin $plugin - The assignment plugin
1957      */
1958     public function download_rewrite_pluginfile_urls($text, $user, $plugin) {
1959         $groupmode = groups_get_activity_groupmode($this->get_course_module());
1960         $groupname = '';
1961         if ($groupmode) {
1962             $groupid = groups_get_activity_group($this->get_course_module(), true);
1963             $groupname = groups_get_group_name($groupid).'-';
1964         }
1966         if ($this->is_blind_marking()) {
1967             $prefix = $groupname . get_string('participant', 'assign');
1968             $prefix = str_replace('_', ' ', $prefix);
1969             $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
1970         } else {
1971             $prefix = $groupname . fullname($user);
1972             $prefix = str_replace('_', ' ', $prefix);
1973             $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
1974         }
1976         $subtype = $plugin->get_subtype();
1977         $type = $plugin->get_type();
1978         $prefix = $prefix . $subtype . '_' . $type . '_';
1980         $result = str_replace('@@PLUGINFILE@@/', $prefix, $text);
1982         return $result;
1983     }
1985     /**
1986      * Render the content in editor that is often used by plugin.
1987      *
1988      * @param string $filearea
1989      * @param int  $submissionid
1990      * @param string $plugintype
1991      * @param string $editor
1992      * @param string $component
1993      * @return string
1994      */
1995     public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
1996         global $CFG;
1998         $result = '';
2000         $plugin = $this->get_submission_plugin_by_type($plugintype);
2002         $text = $plugin->get_editor_text($editor, $submissionid);
2003         $format = $plugin->get_editor_format($editor, $submissionid);
2005         $finaltext = file_rewrite_pluginfile_urls($text,
2006                                                   'pluginfile.php',
2007                                                   $this->get_context()->id,
2008                                                   $component,
2009                                                   $filearea,
2010                                                   $submissionid);
2011         $params = array('overflowdiv' => true, 'context' => $this->get_context());
2012         $result .= format_text($finaltext, $format, $params);
2014         if ($CFG->enableportfolios) {
2015             require_once($CFG->libdir . '/portfoliolib.php');
2017             $button = new portfolio_add_button();
2018             $portfolioparams = array('cmid' => $this->get_course_module()->id,
2019                                      'sid' => $submissionid,
2020                                      'plugin' => $plugintype,
2021                                      'editor' => $editor,
2022                                      'area'=>$filearea);
2023             $button->set_callback_options('assign_portfolio_caller', $portfolioparams, 'mod_assign');
2024             $fs = get_file_storage();
2026             if ($files = $fs->get_area_files($this->context->id,
2027                                              $component,
2028                                              $filearea,
2029                                              $submissionid,
2030                                              'timemodified',
2031                                              false)) {
2032                 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
2033             } else {
2034                 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
2035             }
2036             $result .= $button->to_html();
2037         }
2038         return $result;
2039     }
2041     /**
2042      * Display a grading error.
2043      *
2044      * @param string $message - The description of the result
2045      * @return string
2046      */
2047     protected function view_quickgrading_result($message) {
2048         $o = '';
2049         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2050                                                       $this->get_context(),
2051                                                       $this->show_intro(),
2052                                                       $this->get_course_module()->id,
2053                                                       get_string('quickgradingresult', 'assign')));
2054         $gradingresult = new assign_quickgrading_result($message, $this->get_course_module()->id);
2055         $o .= $this->get_renderer()->render($gradingresult);
2056         $o .= $this->view_footer();
2057         return $o;
2058     }
2060     /**
2061      * Display the page footer.
2062      *
2063      * @return string
2064      */
2065     protected function view_footer() {
2066         return $this->get_renderer()->render_footer();
2067     }
2069     /**
2070      * Does this user have grade permission for this assignment?
2071      *
2072      * @return bool
2073      */
2074     protected function can_grade() {
2075         // Permissions check.
2076         if (!has_capability('mod/assign:grade', $this->context)) {
2077             return false;
2078         }
2080         return true;
2081     }
2083     /**
2084      * Download a zip file of all assignment submissions.
2085      *
2086      * @return void
2087      */
2088     protected function download_submissions() {
2089         global $CFG, $DB;
2091         // More efficient to load this here.
2092         require_once($CFG->libdir.'/filelib.php');
2094         // Load all users with submit.
2095         $students = get_enrolled_users($this->context, "mod/assign:submit");
2097         // Build a list of files to zip.
2098         $filesforzipping = array();
2099         $fs = get_file_storage();
2101         $groupmode = groups_get_activity_groupmode($this->get_course_module());
2102         // All users.
2103         $groupid = 0;
2104         $groupname = '';
2105         if ($groupmode) {
2106             $groupid = groups_get_activity_group($this->get_course_module(), true);
2107             $groupname = groups_get_group_name($groupid).'-';
2108         }
2110         // Construct the zip file name.
2111         $filename = clean_filename($this->get_course()->shortname . '-' .
2112                                    $this->get_instance()->name . '-' .
2113                                    $groupname.$this->get_course_module()->id . '.zip');
2115         // Get all the files for each student.
2116         foreach ($students as $student) {
2117             $userid = $student->id;
2119             if ((groups_is_member($groupid, $userid) or !$groupmode or !$groupid)) {
2120                 // Get the plugins to add their own files to the zip.
2122                 $submissiongroup = false;
2123                 $groupname = '';
2124                 if ($this->get_instance()->teamsubmission) {
2125                     $submission = $this->get_group_submission($userid, 0, false);
2126                     $submissiongroup = $this->get_submission_group($userid);
2127                     if ($submissiongroup) {
2128                         $groupname = $submissiongroup->name . '-';
2129                     } else {
2130                         $groupname = get_string('defaultteam', 'assign') . '-';
2131                     }
2132                 } else {
2133                     $submission = $this->get_user_submission($userid, false);
2134                 }
2136                 if ($this->is_blind_marking()) {
2137                     $prefix = str_replace('_', ' ', $groupname . get_string('participant', 'assign'));
2138                     $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2139                 } else {
2140                     $prefix = str_replace('_', ' ', $groupname . fullname($student));
2141                     $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2142                 }
2144                 if ($submission) {
2145                     foreach ($this->submissionplugins as $plugin) {
2146                         if ($plugin->is_enabled() && $plugin->is_visible()) {
2147                             $pluginfiles = $plugin->get_files($submission, $student);
2148                             foreach ($pluginfiles as $zipfilename => $file) {
2149                                 $subtype = $plugin->get_subtype();
2150                                 $type = $plugin->get_type();
2151                                 $prefixedfilename = clean_filename($prefix .
2152                                                                    $subtype .
2153                                                                    '_' .
2154                                                                    $type .
2155                                                                    '_' .
2156                                                                    $zipfilename);
2157                                 $filesforzipping[$prefixedfilename] = $file;
2158                             }
2159                         }
2160                     }
2161                 }
2162             }
2163         }
2164         $result = '';
2165         if (count($filesforzipping) == 0) {
2166             $header = new assign_header($this->get_instance(),
2167                                         $this->get_context(),
2168                                         '',
2169                                         $this->get_course_module()->id,
2170                                         get_string('downloadall', 'assign'));
2171             $result .= $this->get_renderer()->render($header);
2172             $result .= $this->get_renderer()->notification(get_string('nosubmission', 'assign'));
2173             $url = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id,
2174                                                                     'action'=>'grading'));
2175             $result .= $this->get_renderer()->continue_button($url);
2176             $result .= $this->view_footer();
2177         } else if ($zipfile = $this->pack_files($filesforzipping)) {
2178             $this->add_to_log('download all submissions', get_string('downloadall', 'assign'));
2179             // Send file and delete after sending.
2180             send_temp_file($zipfile, $filename);
2181             // We will not get here - send_temp_file calls exit.
2182         }
2183         return $result;
2184     }
2186     /**
2187      * Util function to add a message to the log.
2188      *
2189      * @param string $action The current action
2190      * @param string $info A detailed description of the change. But no more than 255 characters.
2191      * @param string $url The url to the assign module instance.
2192      * @return void
2193      */
2194     public function add_to_log($action = '', $info = '', $url='') {
2195         global $USER;
2197         $fullurl = 'view.php?id=' . $this->get_course_module()->id;
2198         if ($url != '') {
2199             $fullurl .= '&' . $url;
2200         }
2202         add_to_log($this->get_course()->id,
2203                    'assign',
2204                    $action,
2205                    $fullurl,
2206                    $info,
2207                    $this->get_course_module()->id,
2208                    $USER->id);
2209     }
2211     /**
2212      * Lazy load the page renderer and expose the renderer to plugins.
2213      *
2214      * @return assign_renderer
2215      */
2216     public function get_renderer() {
2217         global $PAGE;
2218         if ($this->output) {
2219             return $this->output;
2220         }
2221         $this->output = $PAGE->get_renderer('mod_assign');
2222         return $this->output;
2223     }
2225     /**
2226      * Load the submission object for a particular user, optionally creating it if required.
2227      *
2228      * For team assignments there are 2 submissions - the student submission and the team submission
2229      * All files are associated with the team submission but the status of the students contribution is
2230      * recorded separately.
2231      *
2232      * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
2233      * @param bool $create optional - defaults to false. If set to true a new submission object
2234      *                     will be created in the database.
2235      * @return stdClass The submission
2236      */
2237     public function get_user_submission($userid, $create) {
2238         global $DB, $USER;
2240         if (!$userid) {
2241             $userid = $USER->id;
2242         }
2243         // If the userid is not null then use userid.
2244         $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid, 'groupid'=>0);
2245         $submission = $DB->get_record('assign_submission', $params);
2247         if ($submission) {
2248             return $submission;
2249         }
2250         if ($create) {
2251             $submission = new stdClass();
2252             $submission->assignment   = $this->get_instance()->id;
2253             $submission->userid       = $userid;
2254             $submission->timecreated = time();
2255             $submission->timemodified = $submission->timecreated;
2256             $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
2257             $sid = $DB->insert_record('assign_submission', $submission);
2258             $submission->id = $sid;
2259             return $submission;
2260         }
2261         return false;
2262     }
2264     /**
2265      * Load the submission object from it's id.
2266      *
2267      * @param int $submissionid The id of the submission we want
2268      * @return stdClass The submission
2269      */
2270     protected function get_submission($submissionid) {
2271         global $DB;
2273         $params = array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid);
2274         return $DB->get_record('assign_submission', $params, '*', MUST_EXIST);
2275     }
2277     /**
2278      * This will retrieve a grade object from the db, optionally creating it if required.
2279      *
2280      * @param int $userid The user we are grading
2281      * @param bool $create If true the grade will be created if it does not exist
2282      * @return stdClass The grade record
2283      */
2284     public function get_user_grade($userid, $create) {
2285         global $DB, $USER;
2287         if (!$userid) {
2288             $userid = $USER->id;
2289         }
2291         // If the userid is not null then use userid.
2292         $grade = $DB->get_record('assign_grades', array('assignment'=>$this->get_instance()->id, 'userid'=>$userid));
2294         if ($grade) {
2295             return $grade;
2296         }
2297         if ($create) {
2298             $grade = new stdClass();
2299             $grade->assignment   = $this->get_instance()->id;
2300             $grade->userid       = $userid;
2301             $grade->timecreated = time();
2302             $grade->timemodified = $grade->timecreated;
2303             $grade->locked = 0;
2304             $grade->grade = -1;
2305             $grade->grader = $USER->id;
2306             $grade->extensionduedate = 0;
2308             // The mailed flag can be one of 3 values: 0 is unsent, 1 is sent and 2 is do not send yet.
2309             // This is because students only want to be notified about certain types of update (grades and feedback).
2310             $grade->mailed = 2;
2311             $gid = $DB->insert_record('assign_grades', $grade);
2312             $grade->id = $gid;
2313             return $grade;
2314         }
2315         return false;
2316     }
2318     /**
2319      * This will retrieve a grade object from the db.
2320      *
2321      * @param int $gradeid The id of the grade
2322      * @return stdClass The grade record
2323      */
2324     protected function get_grade($gradeid) {
2325         global $DB;
2327         $params = array('assignment'=>$this->get_instance()->id, 'id'=>$gradeid);
2328         return $DB->get_record('assign_grades', $params, '*', MUST_EXIST);
2329     }
2331     /**
2332      * Print the grading page for a single user submission.
2333      *
2334      * @param moodleform $mform
2335      * @param int $offset
2336      * @return string
2337      */
2338     protected function view_single_grade_page($mform, $offset=0) {
2339         global $DB, $CFG;
2341         $o = '';
2342         $instance = $this->get_instance();
2344         require_once($CFG->dirroot . '/mod/assign/gradeform.php');
2346         // Need submit permission to submit an assignment.
2347         require_capability('mod/assign:grade', $this->context);
2349         $header = new assign_header($instance,
2350                                     $this->get_context(),
2351                                     false,
2352                                     $this->get_course_module()->id,
2353                                     get_string('grading', 'assign'));
2354         $o .= $this->get_renderer()->render($header);
2356         $rownum = required_param('rownum', PARAM_INT) + $offset;
2357         $useridlist = optional_param('useridlist', '', PARAM_TEXT);
2358         if ($useridlist) {
2359             $useridlist = explode(',', $useridlist);
2360         } else {
2361             $useridlist = $this->get_grading_userid_list();
2362         }
2363         $last = false;
2364         $userid = $useridlist[$rownum];
2365         if ($rownum == count($useridlist) - 1) {
2366             $last = true;
2367         }
2368         if (!$userid) {
2369             throw new coding_exception('Row is out of bounds for the current grading table: ' . $rownum);
2370         }
2371         $user = $DB->get_record('user', array('id' => $userid));
2372         if ($user) {
2373             $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2374             $usersummary = new assign_user_summary($user,
2375                                                    $this->get_course()->id,
2376                                                    $viewfullnames,
2377                                                    $this->is_blind_marking(),
2378                                                    $this->get_uniqueid_for_user($user->id));
2379             $o .= $this->get_renderer()->render($usersummary);
2380         }
2381         $submission = $this->get_user_submission($userid, false);
2382         $submissiongroup = null;
2383         $submissiongroupmemberswhohavenotsubmitted = array();
2384         $teamsubmission = null;
2385         $notsubmitted = array();
2386         if ($instance->teamsubmission) {
2387             $teamsubmission = $this->get_group_submission($userid, 0, false);
2388             $submissiongroup = $this->get_submission_group($userid);
2389             $groupid = 0;
2390             if ($submissiongroup) {
2391                 $groupid = $submissiongroup->id;
2392             }
2393             $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
2395         }
2397         // Get the current grade.
2398         $grade = $this->get_user_grade($userid, false);
2399         if ($this->can_view_submission($userid)) {
2400             $gradelocked = ($grade && $grade->locked) || $this->grading_disabled($userid);
2401             $extensionduedate = null;
2402             if ($grade) {
2403                 $extensionduedate = $grade->extensionduedate;
2404             }
2405             $showedit = $this->submissions_open($userid) && ($this->is_any_submission_plugin_enabled());
2407             if ($teamsubmission) {
2408                 $showsubmit = $showedit &&
2409                               $teamsubmission &&
2410                               ($teamsubmission->status == ASSIGN_SUBMISSION_STATUS_DRAFT);
2411             } else {
2412                 $showsubmit = $showedit &&
2413                               $submission &&
2414                               ($submission->status == ASSIGN_SUBMISSION_STATUS_DRAFT);
2415             }
2416             if (!$this->get_instance()->submissiondrafts) {
2417                 $showsubmit = false;
2418             }
2419             $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2421             $submissionstatus = new assign_submission_status($instance->allowsubmissionsfromdate,
2422                                                              $instance->alwaysshowdescription,
2423                                                              $submission,
2424                                                              $instance->teamsubmission,
2425                                                              $teamsubmission,
2426                                                              $submissiongroup,
2427                                                              $notsubmitted,
2428                                                              $this->is_any_submission_plugin_enabled(),
2429                                                              $gradelocked,
2430                                                              $this->is_graded($userid),
2431                                                              $instance->duedate,
2432                                                              $instance->cutoffdate,
2433                                                              $this->get_submission_plugins(),
2434                                                              $this->get_return_action(),
2435                                                              $this->get_return_params(),
2436                                                              $this->get_course_module()->id,
2437                                                              $this->get_course()->id,
2438                                                              assign_submission_status::GRADER_VIEW,
2439                                                              $showedit,
2440                                                              $showsubmit,
2441                                                              $viewfullnames,
2442                                                              $extensionduedate,
2443                                                              $this->get_context(),
2444                                                              $this->is_blind_marking(),
2445                                                              '');
2446             $o .= $this->get_renderer()->render($submissionstatus);
2447         }
2448         if ($grade) {
2449             $data = new stdClass();
2450             if ($grade->grade !== null && $grade->grade >= 0) {
2451                 $data->grade = format_float($grade->grade, 2);
2452             }
2453         } else {
2454             $data = new stdClass();
2455             $data->grade = '';
2456         }
2458         // Now show the grading form.
2459         if (!$mform) {
2460             $pagination = array( 'rownum'=>$rownum, 'useridlist'=>$useridlist, 'last'=>$last);
2461             $formparams = array($this, $data, $pagination);
2462             $mform = new mod_assign_grade_form(null,
2463                                                $formparams,
2464                                                'post',
2465                                                '',
2466                                                array('class'=>'gradeform'));
2467         }
2468         $o .= $this->get_renderer()->render(new assign_form('gradingform', $mform));
2470         $msg = get_string('viewgradingformforstudent',
2471                           'assign',
2472                           array('id'=>$user->id, 'fullname'=>fullname($user)));
2473         $this->add_to_log('view grading form', $msg);
2475         $o .= $this->view_footer();
2476         return $o;
2477     }
2479     /**
2480      * Show a confirmation page to make sure they want to release student identities.
2481      *
2482      * @return string
2483      */
2484     protected function view_reveal_identities_confirm() {
2485         global $CFG, $USER;
2487         require_capability('mod/assign:revealidentities', $this->get_context());
2489         $o = '';
2490         $header = new assign_header($this->get_instance(),
2491                                     $this->get_context(),
2492                                     false,
2493                                     $this->get_course_module()->id);
2494         $o .= $this->get_renderer()->render($header);
2496         $urlparams = array('id'=>$this->get_course_module()->id,
2497                            'action'=>'revealidentitiesconfirm',
2498                            'sesskey'=>sesskey());
2499         $confirmurl = new moodle_url('/mod/assign/view.php', $urlparams);
2501         $urlparams = array('id'=>$this->get_course_module()->id,
2502                            'action'=>'grading');
2503         $cancelurl = new moodle_url('/mod/assign/view.php', $urlparams);
2505         $o .= $this->get_renderer()->confirm(get_string('revealidentitiesconfirm', 'assign'),
2506                                              $confirmurl,
2507                                              $cancelurl);
2508         $o .= $this->view_footer();
2509         $this->add_to_log('view', get_string('viewrevealidentitiesconfirm', 'assign'));
2510         return $o;
2511     }
2513     /**
2514      * View a link to go back to the previous page. Uses url parameters returnaction and returnparams.
2515      *
2516      * @return string
2517      */
2518     protected function view_return_links() {
2519         $returnaction = optional_param('returnaction', '', PARAM_ALPHA);
2520         $returnparams = optional_param('returnparams', '', PARAM_TEXT);
2522         $params = array();
2523         parse_str($returnparams, $params);
2524         $newparams = array('id' => $this->get_course_module()->id, 'action' => $returnaction);
2525         $params = array_merge($newparams, $params);
2527         $url = new moodle_url('/mod/assign/view.php', $params);
2528         return $this->get_renderer()->single_button($url, get_string('back'), 'get');
2529     }
2531     /**
2532      * View the grading table of all submissions for this assignment.
2533      *
2534      * @return string
2535      */
2536     protected function view_grading_table() {
2537         global $USER, $CFG;
2539         // Include grading options form.
2540         require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
2541         require_once($CFG->dirroot . '/mod/assign/quickgradingform.php');
2542         require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
2543         $o = '';
2544         $cmid = $this->get_course_module()->id;
2546         $links = array();
2547         if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
2548                 has_capability('moodle/grade:viewall', $this->get_course_context())) {
2549             $gradebookurl = '/grade/report/grader/index.php?id=' . $this->get_course()->id;
2550             $links[$gradebookurl] = get_string('viewgradebook', 'assign');
2551         }
2552         if ($this->is_any_submission_plugin_enabled() && $this->count_submissions()) {
2553             $downloadurl = '/mod/assign/view.php?id=' . $cmid . '&action=downloadall';
2554             $links[$downloadurl] = get_string('downloadall', 'assign');
2555         }
2556         if ($this->is_blind_marking() &&
2557                 has_capability('mod/assign:revealidentities', $this->get_context())) {
2558             $revealidentitiesurl = '/mod/assign/view.php?id=' . $cmid . '&action=revealidentities';
2559             $links[$revealidentitiesurl] = get_string('revealidentities', 'assign');
2560         }
2561         foreach ($this->get_feedback_plugins() as $plugin) {
2562             if ($plugin->is_enabled() && $plugin->is_visible()) {
2563                 foreach ($plugin->get_grading_actions() as $action => $description) {
2564                     $url = '/mod/assign/view.php' .
2565                            '?id=' .  $cmid .
2566                            '&plugin=' . $plugin->get_type() .
2567                            '&pluginsubtype=assignfeedback' .
2568                            '&action=viewpluginpage&pluginaction=' . $action;
2569                     $links[$url] = $description;
2570                 }
2571             }
2572         }
2574         $gradingactions = new url_select($links);
2575         $gradingactions->set_label(get_string('choosegradingaction', 'assign'));
2577         $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2579         $perpage = get_user_preferences('assign_perpage', 10);
2580         $filter = get_user_preferences('assign_filter', '');
2581         $controller = $gradingmanager->get_active_controller();
2582         $showquickgrading = empty($controller);
2583         if (optional_param('action', '', PARAM_ALPHA) == 'saveoptions') {
2584             $quickgrading = optional_param('quickgrading', false, PARAM_BOOL);
2585             set_user_preference('assign_quickgrading', $quickgrading);
2586         }
2587         $quickgrading = get_user_preferences('assign_quickgrading', false);
2589         // Print options for changing the filter and changing the number of results per page.
2590         $gradingoptionsformparams = array('cm'=>$cmid,
2591                                           'contextid'=>$this->context->id,
2592                                           'userid'=>$USER->id,
2593                                           'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
2594                                           'showquickgrading'=>$showquickgrading,
2595                                           'quickgrading'=>$quickgrading);
2597         $classoptions = array('class'=>'gradingoptionsform');
2598         $gradingoptionsform = new mod_assign_grading_options_form(null,
2599                                                                   $gradingoptionsformparams,
2600                                                                   'post',
2601                                                                   '',
2602                                                                   $classoptions);
2604         $batchformparams = array('cm'=>$cmid,
2605                                  'submissiondrafts'=>$this->get_instance()->submissiondrafts,
2606                                  'duedate'=>$this->get_instance()->duedate,
2607                                  'feedbackplugins'=>$this->get_feedback_plugins());
2608         $classoptions = array('class'=>'gradingbatchoperationsform');
2610         $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
2611                                                                                    $batchformparams,
2612                                                                                    'post',
2613                                                                                    '',
2614                                                                                    $classoptions);
2616         $gradingoptionsdata = new stdClass();
2617         $gradingoptionsdata->perpage = $perpage;
2618         $gradingoptionsdata->filter = $filter;
2619         $gradingoptionsform->set_data($gradingoptionsdata);
2621         $actionformtext = $this->get_renderer()->render($gradingactions);
2622         $header = new assign_header($this->get_instance(),
2623                                     $this->get_context(),
2624                                     false,
2625                                     $this->get_course_module()->id,
2626                                     get_string('grading', 'assign'),
2627                                     $actionformtext);
2628         $o .= $this->get_renderer()->render($header);
2630         $currenturl = $CFG->wwwroot .
2631                       '/mod/assign/view.php?id=' .
2632                       $this->get_course_module()->id .
2633                       '&action=grading';
2635         $o .= groups_print_activity_menu($this->get_course_module(), $currenturl, true);
2637         // Plagiarism update status apearring in the grading book.
2638         if (!empty($CFG->enableplagiarism)) {
2639             require_once($CFG->libdir . '/plagiarismlib.php');
2640             $o .= plagiarism_update_status($this->get_course(), $this->get_course_module());
2641         }
2643         // Load and print the table of submissions.
2644         if ($showquickgrading && $quickgrading) {
2645             $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, true);
2646             $table = $this->get_renderer()->render($gradingtable);
2647             $quickformparams = array('cm'=>$this->get_course_module()->id, 'gradingtable'=>$table);
2648             $quickgradingform = new mod_assign_quick_grading_form(null, $quickformparams);
2650             $o .= $this->get_renderer()->render(new assign_form('quickgradingform', $quickgradingform));
2651         } else {
2652             $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, false);
2653             $o .= $this->get_renderer()->render($gradingtable);
2654         }
2656         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
2657         $users = array_keys($this->list_participants($currentgroup, true));
2658         if (count($users) != 0) {
2659             // If no enrolled user in a course then don't display the batch operations feature.
2660             $assignform = new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform);
2661             $o .= $this->get_renderer()->render($assignform);
2662         }
2663         $assignform = new assign_form('gradingoptionsform',
2664                                       $gradingoptionsform,
2665                                       'M.mod_assign.init_grading_options');
2666         $o .= $this->get_renderer()->render($assignform);
2667         return $o;
2668     }
2670     /**
2671      * View entire grading page.
2672      *
2673      * @return string
2674      */
2675     protected function view_grading_page() {
2676         global $CFG;
2678         $o = '';
2679         // Need submit permission to submit an assignment.
2680         require_capability('mod/assign:grade', $this->context);
2681         require_once($CFG->dirroot . '/mod/assign/gradeform.php');
2683         // Only load this if it is.
2685         $o .= $this->view_grading_table();
2687         $o .= $this->view_footer();
2689         $logmessage = get_string('viewsubmissiongradingtable', 'assign');
2690         $this->add_to_log('view submission grading table', $logmessage);
2691         return $o;
2692     }
2694     /**
2695      * Capture the output of the plagiarism plugins disclosures and return it as a string.
2696      *
2697      * @return void
2698      */
2699     protected function plagiarism_print_disclosure() {
2700         global $CFG;
2701         $o = '';
2703         if (!empty($CFG->enableplagiarism)) {
2704             require_once($CFG->libdir . '/plagiarismlib.php');
2706             $o .= plagiarism_print_disclosure($this->get_course_module()->id);
2707         }
2709         return $o;
2710     }
2712     /**
2713      * Message for students when assignment submissions have been closed.
2714      *
2715      * @return string
2716      */
2717     protected function view_student_error_message() {
2718         global $CFG;
2720         $o = '';
2721         // Need submit permission to submit an assignment.
2722         require_capability('mod/assign:submit', $this->context);
2724         $header = new assign_header($this->get_instance(),
2725                                     $this->get_context(),
2726                                     $this->show_intro(),
2727                                     $this->get_course_module()->id,
2728                                     get_string('editsubmission', 'assign'));
2729         $o .= $this->get_renderer()->render($header);
2731         $o .= $this->get_renderer()->notification(get_string('submissionsclosed', 'assign'));
2733         $o .= $this->view_footer();
2735         return $o;
2737     }
2739     /**
2740      * View edit submissions page.
2741      *
2742      * @param moodleform $mform
2743      * @param array $notices A list of notices to display at the top of the
2744      *                       edit submission form (e.g. from plugins).
2745      * @return void
2746      */
2747     protected function view_edit_submission_page($mform, $notices) {
2748         global $CFG;
2750         $o = '';
2751         require_once($CFG->dirroot . '/mod/assign/submission_form.php');
2752         // Need submit permission to submit an assignment.
2753         require_capability('mod/assign:submit', $this->context);
2755         if (!$this->submissions_open()) {
2756             return $this->view_student_error_message();
2757         }
2758         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2759                                                       $this->get_context(),
2760                                                       $this->show_intro(),
2761                                                       $this->get_course_module()->id,
2762                                                       get_string('editsubmission', 'assign')));
2763         $o .= $this->plagiarism_print_disclosure();
2764         $data = new stdClass();
2766         if (!$mform) {
2767             $mform = new mod_assign_submission_form(null, array($this, $data));
2768         }
2770         foreach ($notices as $notice) {
2771             $o .= $this->get_renderer()->notification($notice);
2772         }
2774         $o .= $this->get_renderer()->render(new assign_form('editsubmissionform', $mform));
2776         $o .= $this->view_footer();
2777         $this->add_to_log('view submit assignment form', get_string('viewownsubmissionform', 'assign'));
2779         return $o;
2780     }
2782     /**
2783      * See if this assignment has a grade yet.
2784      *
2785      * @param int $userid
2786      * @return bool
2787      */
2788     protected function is_graded($userid) {
2789         $grade = $this->get_user_grade($userid, false);
2790         if ($grade) {
2791             return ($grade->grade !== null && $grade->grade >= 0);
2792         }
2793         return false;
2794     }
2796     /**
2797      * Perform an access check to see if the current $USER can view this group submission.
2798      *
2799      * @param int $groupid
2800      * @return bool
2801      */
2802     public function can_view_group_submission($groupid) {
2803         global $USER;
2805         if (!is_enrolled($this->get_course_context(), $USER->id)) {
2806             return false;
2807         }
2808         if (has_capability('mod/assign:grade', $this->context)) {
2809             return true;
2810         }
2811         $members = $this->get_submission_group_members($groupid, true);
2812         foreach ($members as $member) {
2813             if ($member->id == $USER->id) {
2814                 return true;
2815             }
2816         }
2817         return false;
2818     }
2820     /**
2821      * Perform an access check to see if the current $USER can view this users submission.
2822      *
2823      * @param int $userid
2824      * @return bool
2825      */
2826     public function can_view_submission($userid) {
2827         global $USER;
2829         if (!is_enrolled($this->get_course_context(), $userid)) {
2830             return false;
2831         }
2832         if ($userid == $USER->id && has_capability('mod/assign:submit', $this->context)) {
2833             return true;
2834         }
2835         if (has_capability('mod/assign:grade', $this->context)) {
2836             return true;
2837         }
2838         return false;
2839     }
2841     /**
2842      * Allows the plugin to show a batch grading operation page.
2843      *
2844      * @return none
2845      */
2846     protected function view_plugin_grading_batch_operation($mform) {
2847         require_capability('mod/assign:grade', $this->context);
2848         $prefix = 'plugingradingbatchoperation_';
2850         if ($data = $mform->get_data()) {
2851             $tail = substr($data->operation, strlen($prefix));
2852             list($plugintype, $action) = explode('_', $tail, 2);
2854             $plugin = $this->get_feedback_plugin_by_type($plugintype);
2855             if ($plugin) {
2856                 $users = $data->selectedusers;
2857                 $userlist = explode(',', $users);
2858                 echo $plugin->grading_batch_operation($action, $userlist);
2859                 return;
2860             }
2861         }
2862         print_error('invalidformdata', '');
2863     }
2865     /**
2866      * Ask the user to confirm they want to perform this batch operation
2867      *
2868      * @param moodleform $mform Set to a grading batch operations form
2869      * @return string - the page to view after processing these actions
2870      */
2871     protected function process_grading_batch_operation(& $mform) {
2872         global $CFG;
2873         require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
2874         require_sesskey();
2876         $batchformparams = array('cm'=>$this->get_course_module()->id,
2877                                  'submissiondrafts'=>$this->get_instance()->submissiondrafts,
2878                                  'duedate'=>$this->get_instance()->duedate,
2879                                  'feedbackplugins'=>$this->get_feedback_plugins());
2880         $formclasses = array('class'=>'gradingbatchoperationsform');
2881         $mform = new mod_assign_grading_batch_operations_form(null,
2882                                                               $batchformparams,
2883                                                               'post',
2884                                                               '',
2885                                                               $formclasses);
2887         if ($data = $mform->get_data()) {
2888             // Get the list of users.
2889             $users = $data->selectedusers;
2890             $userlist = explode(',', $users);
2892             $prefix = 'plugingradingbatchoperation_';
2894             if ($data->operation == 'grantextension') {
2895                 // Reset the form so the grant extension page will create the extension form.
2896                 $mform = null;
2897                 return 'grantextension';
2898             } else if (strpos($data->operation, $prefix) === 0) {
2899                 $tail = substr($data->operation, strlen($prefix));
2900                 list($plugintype, $action) = explode('_', $tail, 2);
2902                 $plugin = $this->get_feedback_plugin_by_type($plugintype);
2903                 if ($plugin) {
2904                     return 'plugingradingbatchoperation';
2905                 }
2906             }
2908             foreach ($userlist as $userid) {
2909                 if ($data->operation == 'lock') {
2910                     $this->process_lock($userid);
2911                 } else if ($data->operation == 'unlock') {
2912                     $this->process_unlock($userid);
2913                 } else if ($data->operation == 'reverttodraft') {
2914                     $this->process_revert_to_draft($userid);
2915                 }
2916             }
2917         }
2919         return 'grading';
2920     }
2922     /**
2923      * Ask the user to confirm they want to submit their work for grading.
2924      *
2925      * @param $mform moodleform - null unless form validation has failed
2926      * @return string
2927      */
2928     protected function check_submit_for_grading($mform) {
2929         global $USER, $CFG;
2931         require_once($CFG->dirroot . '/mod/assign/submissionconfirmform.php');
2933         // Check that all of the submission plugins are ready for this submission.
2934         $notifications = array();
2935         $submission = $this->get_user_submission($USER->id, false);
2936         $plugins = $this->get_submission_plugins();
2937         foreach ($plugins as $plugin) {
2938             if ($plugin->is_enabled() && $plugin->is_visible()) {
2939                 $check = $plugin->precheck_submission($submission);
2940                 if ($check !== true) {
2941                     $notifications[] = $check;
2942                 }
2943             }
2944         }
2946         $data = new stdClass();
2947         $adminconfig = $this->get_admin_config();
2948         $requiresubmissionstatement = (!empty($adminconfig->requiresubmissionstatement) ||
2949                                        $this->get_instance()->requiresubmissionstatement) &&
2950                                        !empty($adminconfig->submissionstatement);
2952         $submissionstatement = '';
2953         if (!empty($adminconfig->submissionstatement)) {
2954             $submissionstatement = $adminconfig->submissionstatement;
2955         }
2957         if ($mform == null) {
2958             $mform = new mod_assign_confirm_submission_form(null, array($requiresubmissionstatement,
2959                                                                         $submissionstatement,
2960                                                                         $this->get_course_module()->id,
2961                                                                         $data));
2962         }
2963         $o = '';
2964         $o .= $this->get_renderer()->header();
2965         $submitforgradingpage = new assign_submit_for_grading_page($notifications,
2966                                                                    $this->get_course_module()->id,
2967                                                                    $mform);
2968         $o .= $this->get_renderer()->render($submitforgradingpage);
2969         $o .= $this->view_footer();
2971         $logmessage = get_string('viewownsubmissionform', 'assign');
2972         $this->add_to_log('view confirm submit assignment form', $logmessage);
2974         return $o;
2975     }
2977     /**
2978      * Print 2 tables of information with no action links -
2979      * the submission summary and the grading summary.
2980      *
2981      * @param stdClass $user the user to print the report for
2982      * @param bool $showlinks - Return plain text or links to the profile
2983      * @return string - the html summary
2984      */
2985     public function view_student_summary($user, $showlinks) {
2986         global $CFG, $DB, $PAGE;
2988         $instance = $this->get_instance();
2989         $grade = $this->get_user_grade($user->id, false);
2990         $submission = $this->get_user_submission($user->id, false);
2991         $o = '';
2993         $teamsubmission = null;
2994         $submissiongroup = null;
2995         $notsubmitted = array();
2996         if ($instance->teamsubmission) {
2997             $teamsubmission = $this->get_group_submission($user->id, 0, false);
2998             $submissiongroup = $this->get_submission_group($user->id);
2999             $groupid = 0;
3000             if ($submissiongroup) {
3001                 $groupid = $submissiongroup->id;
3002             }
3003             $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
3004         }
3006         if ($this->can_view_submission($user->id)) {
3007             $showedit = has_capability('mod/assign:submit', $this->context) &&
3008                         $this->submissions_open($user->id) &&
3009                         ($this->is_any_submission_plugin_enabled()) &&
3010                         $showlinks;
3012             $gradelocked = ($grade && $grade->locked) || $this->grading_disabled($user->id);
3014             // Grading criteria preview.
3015             $gradingmanager = get_grading_manager($this->context, 'mod_assign', 'submissions');
3016             $gradingcontrollerpreview = '';
3017             if ($gradingmethod = $gradingmanager->get_active_method()) {
3018                 $controller = $gradingmanager->get_controller($gradingmethod);
3019                 if ($controller->is_form_defined()) {
3020                     $gradingcontrollerpreview = $controller->render_preview($PAGE);
3021                 }
3022             }
3024             $showsubmit = ($submission || $teamsubmission) && $showlinks;
3025             if ($teamsubmission && ($teamsubmission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED)) {
3026                 $showsubmit = false;
3027             }
3028             if ($submission && ($submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED)) {
3029                 $showsubmit = false;
3030             }
3031             if (!$this->get_instance()->submissiondrafts) {
3032                 $showsubmit = false;
3033             }
3034             $extensionduedate = null;
3035             if ($grade) {
3036                 $extensionduedate = $grade->extensionduedate;
3037             }
3038             $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
3040             $submissionstatus = new assign_submission_status($instance->allowsubmissionsfromdate,
3041                                                               $instance->alwaysshowdescription,
3042                                                               $submission,
3043                                                               $instance->teamsubmission,
3044                                                               $teamsubmission,
3045                                                               $submissiongroup,
3046                                                               $notsubmitted,
3047                                                               $this->is_any_submission_plugin_enabled(),
3048                                                               $gradelocked,
3049                                                               $this->is_graded($user->id),
3050                                                               $instance->duedate,
3051                                                               $instance->cutoffdate,
3052                                                               $this->get_submission_plugins(),
3053                                                               $this->get_return_action(),
3054                                                               $this->get_return_params(),
3055                                                               $this->get_course_module()->id,
3056                                                               $this->get_course()->id,
3057                                                               assign_submission_status::STUDENT_VIEW,
3058                                                               $showedit,
3059                                                               $showsubmit,
3060                                                               $viewfullnames,
3061                                                               $extensionduedate,
3062                                                               $this->get_context(),
3063                                                               $this->is_blind_marking(),
3064                                                               $gradingcontrollerpreview);
3065             $o .= $this->get_renderer()->render($submissionstatus);
3067             require_once($CFG->libdir.'/gradelib.php');
3068             require_once($CFG->dirroot.'/grade/grading/lib.php');
3070             $gradinginfo = grade_get_grades($this->get_course()->id,
3071                                         'mod',
3072                                         'assign',
3073                                         $instance->id,
3074                                         $user->id);
3076             $gradingitem = null;
3077             $gradebookgrade = null;
3078             if (isset($gradinginfo->items[0])) {
3079                 $gradingitem = $gradinginfo->items[0];
3080                 $gradebookgrade = $gradingitem->grades[$user->id];
3081             }
3083             // Check to see if all feedback plugins are empty.
3084             $emptyplugins = true;
3085             if ($grade) {
3086                 foreach ($this->get_feedback_plugins() as $plugin) {
3087                     if ($plugin->is_visible() && $plugin->is_enabled()) {
3088                         if (!$plugin->is_empty($grade)) {
3089                             $emptyplugins = false;
3090                         }
3091                     }
3092                 }
3093             }
3095             $cangrade = has_capability('mod/assign:grade', $this->get_context());
3096             // If there is feedback or a visible grade, show the summary.
3097             if ((!empty($gradebookgrade->grade) && ($cangrade || !$gradebookgrade->hidden)) ||
3098                     !$emptyplugins) {
3100                 $gradefordisplay = null;
3101                 $gradeddate = null;
3102                 $grader = null;
3103                 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
3105                 // Only show the grade if it is not hidden in gradebook.
3106                 if (!empty($gradebookgrade->grade) && ($cangrade || !$gradebookgrade->hidden)) {
3107                     if ($controller = $gradingmanager->get_active_controller()) {
3108                         $controller->set_grade_range(make_grades_menu($this->get_instance()->grade));
3109                         $gradefordisplay = $controller->render_grade($PAGE,
3110                                                                      $grade->id,
3111                                                                      $gradingitem,
3112                                                                      $gradebookgrade->str_long_grade,
3113                                                                      $cangrade);
3114                     } else {
3115                         $gradefordisplay = $this->display_grade($gradebookgrade->grade, false);
3116                     }
3117                     $gradeddate = $gradebookgrade->dategraded;
3118                     if (isset($grade->grader)) {
3119                         $grader = $DB->get_record('user', array('id'=>$grade->grader));
3120                     }
3121                 }
3123                 $feedbackstatus = new assign_feedback_status($gradefordisplay,
3124                                                       $gradeddate,
3125                                                       $grader,
3126                                                       $this->get_feedback_plugins(),
3127                                                       $grade,
3128                                                       $this->get_course_module()->id,
3129                                                       $this->get_return_action(),
3130                                                       $this->get_return_params());
3132                 $o .= $this->get_renderer()->render($feedbackstatus);
3133             }
3135         }
3136         return $o;
3137     }
3139     /**
3140      * View submissions page (contains details of current submission).
3141      *
3142      * @return string
3143      */
3144     protected function view_submission_page() {
3145         global $CFG, $DB, $USER, $PAGE;
3147         $instance = $this->get_instance();
3149         $o = '';
3150         $o .= $this->get_renderer()->render(new assign_header($instance,
3151                                                       $this->get_context(),
3152                                                       $this->show_intro(),
3153                                                       $this->get_course_module()->id));
3155         if ($this->can_grade()) {
3156             $draft = ASSIGN_SUBMISSION_STATUS_DRAFT;
3157             $submitted = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
3158             if ($instance->teamsubmission) {
3159                 $summary = new assign_grading_summary($this->count_teams(),
3160                                                       $instance->submissiondrafts,
3161                                                       $this->count_submissions_with_status($draft),
3162                                                       $this->is_any_submission_plugin_enabled(),
3163                                                       $this->count_submissions_with_status($submitted),
3164                                                       $instance->cutoffdate,
3165                                                       $instance->duedate,
3166                                                       $this->get_course_module()->id,
3167                                                       $this->count_submissions_need_grading(),
3168                                                       $instance->teamsubmission);
3169                 $o .= $this->get_renderer()->render($summary);
3170             } else {
3171                 $summary = new assign_grading_summary($this->count_participants(0),
3172                                                       $instance->submissiondrafts,
3173                                                       $this->count_submissions_with_status($draft),
3174                                                       $this->is_any_submission_plugin_enabled(),
3175                                                       $this->count_submissions_with_status($submitted),
3176                                                       $instance->cutoffdate,
3177                                                       $instance->duedate,
3178                                                       $this->get_course_module()->id,
3179                                                       $this->count_submissions_need_grading(),
3180                                                       $instance->teamsubmission);
3181                 $o .= $this->get_renderer()->render($summary);
3182             }
3183         }
3184         $grade = $this->get_user_grade($USER->id, false);
3185         $submission = $this->get_user_submission($USER->id, false);
3187         if ($this->can_view_submission($USER->id)) {
3188             $o .= $this->view_student_summary($USER, true);
3189         }
3191         $o .= $this->view_footer();
3192         $this->add_to_log('view', get_string('viewownsubmissionstatus', 'assign'));
3193         return $o;
3194     }
3196     /**
3197      * Convert the final raw grade(s) in the grading table for the gradebook.
3198      *
3199      * @param stdClass $grade
3200      * @return array
3201      */
3202     protected function convert_grade_for_gradebook(stdClass $grade) {
3203         $gradebookgrade = array();
3204         if ($grade->grade >= 0) {
3205             $gradebookgrade['rawgrade'] = $grade->grade;
3206         }
3207         $gradebookgrade['userid'] = $grade->userid;
3208         $gradebookgrade['usermodified'] = $grade->grader;
3209         $gradebookgrade['datesubmitted'] = null;
3210         $gradebookgrade['dategraded'] = $grade->timemodified;
3211         if (isset($grade->feedbackformat)) {
3212             $gradebookgrade['feedbackformat'] = $grade->feedbackformat;
3213         }
3214         if (isset($grade->feedbacktext)) {
3215             $gradebookgrade['feedback'] = $grade->feedbacktext;
3216         }
3218         return $gradebookgrade;
3219     }
3221     /**
3222      * Convert submission details for the gradebook.
3223      *
3224      * @param stdClass $submission
3225      * @return array
3226      */
3227     protected function convert_submission_for_gradebook(stdClass $submission) {
3228         $gradebookgrade = array();
3230         $gradebookgrade['userid'] = $submission->userid;
3231         $gradebookgrade['usermodified'] = $submission->userid;
3232     &n