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