7566973882c11e4ee2db5e955514f50588e57af3
[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_NOT_SUBMITTED', 'notsubmitted');
37 define('ASSIGN_FILTER_SINGLE_USER', 'singleuser');
38 define('ASSIGN_FILTER_REQUIRE_GRADING', 'require_grading');
40 // Marker filter for grading page.
41 define('ASSIGN_MARKER_FILTER_NO_MARKER', -1);
43 // Reopen attempt methods.
44 define('ASSIGN_ATTEMPT_REOPEN_METHOD_NONE', 'none');
45 define('ASSIGN_ATTEMPT_REOPEN_METHOD_MANUAL', 'manual');
46 define('ASSIGN_ATTEMPT_REOPEN_METHOD_UNTILPASS', 'untilpass');
48 // Special value means allow unlimited attempts.
49 define('ASSIGN_UNLIMITED_ATTEMPTS', -1);
51 // Marking workflow states.
52 define('ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED', 'notmarked');
53 define('ASSIGN_MARKING_WORKFLOW_STATE_INMARKING', 'inmarking');
54 define('ASSIGN_MARKING_WORKFLOW_STATE_READYFORREVIEW', 'readyforreview');
55 define('ASSIGN_MARKING_WORKFLOW_STATE_INREVIEW', 'inreview');
56 define('ASSIGN_MARKING_WORKFLOW_STATE_READYFORRELEASE', 'readyforrelease');
57 define('ASSIGN_MARKING_WORKFLOW_STATE_RELEASED', 'released');
59 // Name of file area for intro attachments.
60 define('ASSIGN_INTROATTACHMENT_FILEAREA', 'introattachment');
62 require_once($CFG->libdir . '/accesslib.php');
63 require_once($CFG->libdir . '/formslib.php');
64 require_once($CFG->dirroot . '/repository/lib.php');
65 require_once($CFG->dirroot . '/mod/assign/mod_form.php');
66 require_once($CFG->libdir . '/gradelib.php');
67 require_once($CFG->dirroot . '/grade/grading/lib.php');
68 require_once($CFG->dirroot . '/mod/assign/feedbackplugin.php');
69 require_once($CFG->dirroot . '/mod/assign/submissionplugin.php');
70 require_once($CFG->dirroot . '/mod/assign/renderable.php');
71 require_once($CFG->dirroot . '/mod/assign/gradingtable.php');
72 require_once($CFG->libdir . '/eventslib.php');
73 require_once($CFG->libdir . '/portfolio/caller.php');
75 /**
76  * Standard base class for mod_assign (assignment types).
77  *
78  * @package   mod_assign
79  * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
80  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
81  */
82 class assign {
84     /** @var stdClass the assignment record that contains the global settings for this assign instance */
85     private $instance;
87     /** @var stdClass the grade_item record for this assign instance's primary grade item. */
88     private $gradeitem;
90     /** @var context the context of the course module for this assign instance
91      *               (or just the course if we are creating a new one)
92      */
93     private $context;
95     /** @var stdClass the course this assign instance belongs to */
96     private $course;
98     /** @var stdClass the admin config for all assign instances  */
99     private $adminconfig;
101     /** @var assign_renderer the custom renderer for this module */
102     private $output;
104     /** @var cm_info the course module for this assign instance */
105     private $coursemodule;
107     /** @var array cache for things like the coursemodule name or the scale menu -
108      *             only lives for a single request.
109      */
110     private $cache;
112     /** @var array list of the installed submission plugins */
113     private $submissionplugins;
115     /** @var array list of the installed feedback plugins */
116     private $feedbackplugins;
118     /** @var string action to be used to return to this page
119      *              (without repeating any form submissions etc).
120      */
121     private $returnaction = 'view';
123     /** @var array params to be used to return to this page */
124     private $returnparams = array();
126     /** @var string modulename prevents excessive calls to get_string */
127     private static $modulename = null;
129     /** @var string modulenameplural prevents excessive calls to get_string */
130     private static $modulenameplural = null;
132     /** @var array of marking workflow states for the current user */
133     private $markingworkflowstates = null;
135     /** @var bool whether to exclude users with inactive enrolment */
136     private $showonlyactiveenrol = null;
138     /** @var array cached list of participants for this assignment. The cache key will be group, showactive and the context id */
139     private $participants = array();
141     /**
142      * Constructor for the base assign class.
143      *
144      * Note: For $coursemodule you can supply a stdclass if you like, but it
145      * will be more efficient to supply a cm_info object.
146      *
147      * @param mixed $coursemodulecontext context|null the course module context
148      *                                   (or the course context if the coursemodule has not been
149      *                                   created yet).
150      * @param mixed $coursemodule the current course module if it was already loaded,
151      *                            otherwise this class will load one from the context as required.
152      * @param mixed $course the current course  if it was already loaded,
153      *                      otherwise this class will load one from the context as required.
154      */
155     public function __construct($coursemodulecontext, $coursemodule, $course) {
156         $this->context = $coursemodulecontext;
157         $this->course = $course;
159         // Ensure that $this->coursemodule is a cm_info object (or null).
160         $this->coursemodule = cm_info::create($coursemodule);
162         // Temporary cache only lives for a single request - used to reduce db lookups.
163         $this->cache = array();
165         $this->submissionplugins = $this->load_plugins('assignsubmission');
166         $this->feedbackplugins = $this->load_plugins('assignfeedback');
167     }
169     /**
170      * Set the action and parameters that can be used to return to the current page.
171      *
172      * @param string $action The action for the current page
173      * @param array $params An array of name value pairs which form the parameters
174      *                      to return to the current page.
175      * @return void
176      */
177     public function register_return_link($action, $params) {
178         global $PAGE;
179         $params['action'] = $action;
180         $currenturl = $PAGE->url;
182         $currenturl->params($params);
183         $PAGE->set_url($currenturl);
184     }
186     /**
187      * Return an action that can be used to get back to the current page.
188      *
189      * @return string action
190      */
191     public function get_return_action() {
192         global $PAGE;
194         $params = $PAGE->url->params();
196         if (!empty($params['action'])) {
197             return $params['action'];
198         }
199         return '';
200     }
202     /**
203      * Based on the current assignment settings should we display the intro.
204      *
205      * @return bool showintro
206      */
207     public function show_intro() {
208         if ($this->get_instance()->alwaysshowdescription ||
209                 time() > $this->get_instance()->allowsubmissionsfromdate) {
210             return true;
211         }
212         return false;
213     }
215     /**
216      * Return a list of parameters that can be used to get back to the current page.
217      *
218      * @return array params
219      */
220     public function get_return_params() {
221         global $PAGE;
223         $params = $PAGE->url->params();
224         unset($params['id']);
225         unset($params['action']);
226         return $params;
227     }
229     /**
230      * Set the submitted form data.
231      *
232      * @param stdClass $data The form data (instance)
233      */
234     public function set_instance(stdClass $data) {
235         $this->instance = $data;
236     }
238     /**
239      * Set the context.
240      *
241      * @param context $context The new context
242      */
243     public function set_context(context $context) {
244         $this->context = $context;
245     }
247     /**
248      * Set the course data.
249      *
250      * @param stdClass $course The course data
251      */
252     public function set_course(stdClass $course) {
253         $this->course = $course;
254     }
256     /**
257      * Get list of feedback plugins installed.
258      *
259      * @return array
260      */
261     public function get_feedback_plugins() {
262         return $this->feedbackplugins;
263     }
265     /**
266      * Get list of submission plugins installed.
267      *
268      * @return array
269      */
270     public function get_submission_plugins() {
271         return $this->submissionplugins;
272     }
274     /**
275      * Is blind marking enabled and reveal identities not set yet?
276      *
277      * @return bool
278      */
279     public function is_blind_marking() {
280         return $this->get_instance()->blindmarking && !$this->get_instance()->revealidentities;
281     }
283     /**
284      * Does an assignment have submission(s) or grade(s) already?
285      *
286      * @return bool
287      */
288     public function has_submissions_or_grades() {
289         $allgrades = $this->count_grades();
290         $allsubmissions = $this->count_submissions();
291         if (($allgrades == 0) && ($allsubmissions == 0)) {
292             return false;
293         }
294         return true;
295     }
297     /**
298      * Get a specific submission plugin by its type.
299      *
300      * @param string $subtype assignsubmission | assignfeedback
301      * @param string $type
302      * @return mixed assign_plugin|null
303      */
304     public function get_plugin_by_type($subtype, $type) {
305         $shortsubtype = substr($subtype, strlen('assign'));
306         $name = $shortsubtype . 'plugins';
307         if ($name != 'feedbackplugins' && $name != 'submissionplugins') {
308             return null;
309         }
310         $pluginlist = $this->$name;
311         foreach ($pluginlist as $plugin) {
312             if ($plugin->get_type() == $type) {
313                 return $plugin;
314             }
315         }
316         return null;
317     }
319     /**
320      * Get a feedback plugin by type.
321      *
322      * @param string $type - The type of plugin e.g comments
323      * @return mixed assign_feedback_plugin|null
324      */
325     public function get_feedback_plugin_by_type($type) {
326         return $this->get_plugin_by_type('assignfeedback', $type);
327     }
329     /**
330      * Get a submission plugin by type.
331      *
332      * @param string $type - The type of plugin e.g comments
333      * @return mixed assign_submission_plugin|null
334      */
335     public function get_submission_plugin_by_type($type) {
336         return $this->get_plugin_by_type('assignsubmission', $type);
337     }
339     /**
340      * Load the plugins from the sub folders under subtype.
341      *
342      * @param string $subtype - either submission or feedback
343      * @return array - The sorted list of plugins
344      */
345     protected function load_plugins($subtype) {
346         global $CFG;
347         $result = array();
349         $names = core_component::get_plugin_list($subtype);
351         foreach ($names as $name => $path) {
352             if (file_exists($path . '/locallib.php')) {
353                 require_once($path . '/locallib.php');
355                 $shortsubtype = substr($subtype, strlen('assign'));
356                 $pluginclass = 'assign_' . $shortsubtype . '_' . $name;
358                 $plugin = new $pluginclass($this, $name);
360                 if ($plugin instanceof assign_plugin) {
361                     $idx = $plugin->get_sort_order();
362                     while (array_key_exists($idx, $result)) {
363                         $idx +=1;
364                     }
365                     $result[$idx] = $plugin;
366                 }
367             }
368         }
369         ksort($result);
370         return $result;
371     }
373     /**
374      * Display the assignment, used by view.php
375      *
376      * The assignment is displayed differently depending on your role,
377      * the settings for the assignment and the status of the assignment.
378      *
379      * @param string $action The current action if any.
380      * @return string - The page output.
381      */
382     public function view($action='') {
384         $o = '';
385         $mform = null;
386         $notices = array();
387         $nextpageparams = array();
389         if (!empty($this->get_course_module()->id)) {
390             $nextpageparams['id'] = $this->get_course_module()->id;
391         }
393         // Handle form submissions first.
394         if ($action == 'savesubmission') {
395             $action = 'editsubmission';
396             if ($this->process_save_submission($mform, $notices)) {
397                 $action = 'redirect';
398                 $nextpageparams['action'] = 'view';
399             }
400         } else if ($action == 'editprevioussubmission') {
401             $action = 'editsubmission';
402             if ($this->process_copy_previous_attempt($notices)) {
403                 $action = 'redirect';
404                 $nextpageparams['action'] = 'editsubmission';
405             }
406         } else if ($action == 'lock') {
407             $this->process_lock_submission();
408             $action = 'redirect';
409             $nextpageparams['action'] = 'grading';
410         } else if ($action == 'addattempt') {
411             $this->process_add_attempt(required_param('userid', PARAM_INT));
412             $action = 'redirect';
413             $nextpageparams['action'] = 'grading';
414         } else if ($action == 'reverttodraft') {
415             $this->process_revert_to_draft();
416             $action = 'redirect';
417             $nextpageparams['action'] = 'grading';
418         } else if ($action == 'unlock') {
419             $this->process_unlock_submission();
420             $action = 'redirect';
421             $nextpageparams['action'] = 'grading';
422         } else if ($action == 'setbatchmarkingworkflowstate') {
423             $this->process_set_batch_marking_workflow_state();
424             $action = 'redirect';
425             $nextpageparams['action'] = 'grading';
426         } else if ($action == 'setbatchmarkingallocation') {
427             $this->process_set_batch_marking_allocation();
428             $action = 'redirect';
429             $nextpageparams['action'] = 'grading';
430         } else if ($action == 'confirmsubmit') {
431             $action = 'submit';
432             if ($this->process_submit_for_grading($mform, $notices)) {
433                 $action = 'redirect';
434                 $nextpageparams['action'] = 'view';
435             } else if ($notices) {
436                 $action = 'viewsubmitforgradingerror';
437             }
438         } else if ($action == 'submitotherforgrading') {
439             if ($this->process_submit_other_for_grading($mform, $notices)) {
440                 $action = 'redirect';
441                 $nextpageparams['action'] = 'grading';
442             } else {
443                 $action = 'viewsubmitforgradingerror';
444             }
445         } else if ($action == 'gradingbatchoperation') {
446             $action = $this->process_grading_batch_operation($mform);
447             if ($action == 'grading') {
448                 $action = 'redirect';
449                 $nextpageparams['action'] = 'grading';
450             }
451         } else if ($action == 'submitgrade') {
452             if (optional_param('saveandshownext', null, PARAM_RAW)) {
453                 // Save and show next.
454                 $action = 'grade';
455                 if ($this->process_save_grade($mform)) {
456                     $action = 'redirect';
457                     $nextpageparams['action'] = 'grade';
458                     $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) + 1;
459                     $nextpageparams['useridlistid'] = optional_param('useridlistid', time(), PARAM_INT);
460                 }
461             } else if (optional_param('nosaveandprevious', null, PARAM_RAW)) {
462                 $action = 'redirect';
463                 $nextpageparams['action'] = 'grade';
464                 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) - 1;
465                 $nextpageparams['useridlistid'] = optional_param('useridlistid', time(), PARAM_INT);
466             } else if (optional_param('nosaveandnext', null, PARAM_RAW)) {
467                 $action = 'redirect';
468                 $nextpageparams['action'] = 'grade';
469                 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) + 1;
470                 $nextpageparams['useridlistid'] = optional_param('useridlistid', time(), PARAM_INT);
471             } else if (optional_param('savegrade', null, PARAM_RAW)) {
472                 // Save changes button.
473                 $action = 'grade';
474                 if ($this->process_save_grade($mform)) {
475                     $action = 'redirect';
476                     $nextpageparams['action'] = 'savegradingresult';
477                 }
478             } else {
479                 // Cancel button.
480                 $action = 'redirect';
481                 $nextpageparams['action'] = 'grading';
482             }
483         } else if ($action == 'quickgrade') {
484             $message = $this->process_save_quick_grades();
485             $action = 'quickgradingresult';
486         } else if ($action == 'saveoptions') {
487             $this->process_save_grading_options();
488             $action = 'redirect';
489             $nextpageparams['action'] = 'grading';
490         } else if ($action == 'saveextension') {
491             $action = 'grantextension';
492             if ($this->process_save_extension($mform)) {
493                 $action = 'redirect';
494                 $nextpageparams['action'] = 'grading';
495             }
496         } else if ($action == 'revealidentitiesconfirm') {
497             $this->process_reveal_identities();
498             $action = 'redirect';
499             $nextpageparams['action'] = 'grading';
500         }
502         $returnparams = array('rownum'=>optional_param('rownum', 0, PARAM_INT),
503                               'useridlistid'=>optional_param('useridlistid', 0, PARAM_INT));
504         $this->register_return_link($action, $returnparams);
506         // Now show the right view page.
507         if ($action == 'redirect') {
508             $nextpageurl = new moodle_url('/mod/assign/view.php', $nextpageparams);
509             redirect($nextpageurl);
510             return;
511         } else if ($action == 'savegradingresult') {
512             $message = get_string('gradingchangessaved', 'assign');
513             $o .= $this->view_savegrading_result($message);
514         } else if ($action == 'quickgradingresult') {
515             $mform = null;
516             $o .= $this->view_quickgrading_result($message);
517         } else if ($action == 'grade') {
518             $o .= $this->view_single_grade_page($mform);
519         } else if ($action == 'viewpluginassignfeedback') {
520             $o .= $this->view_plugin_content('assignfeedback');
521         } else if ($action == 'viewpluginassignsubmission') {
522             $o .= $this->view_plugin_content('assignsubmission');
523         } else if ($action == 'editsubmission') {
524             $o .= $this->view_edit_submission_page($mform, $notices);
525         } else if ($action == 'grading') {
526             $o .= $this->view_grading_page();
527         } else if ($action == 'downloadall') {
528             $o .= $this->download_submissions();
529         } else if ($action == 'submit') {
530             $o .= $this->check_submit_for_grading($mform);
531         } else if ($action == 'grantextension') {
532             $o .= $this->view_grant_extension($mform);
533         } else if ($action == 'revealidentities') {
534             $o .= $this->view_reveal_identities_confirm($mform);
535         } else if ($action == 'plugingradingbatchoperation') {
536             $o .= $this->view_plugin_grading_batch_operation($mform);
537         } else if ($action == 'viewpluginpage') {
538              $o .= $this->view_plugin_page();
539         } else if ($action == 'viewcourseindex') {
540              $o .= $this->view_course_index();
541         } else if ($action == 'viewbatchsetmarkingworkflowstate') {
542              $o .= $this->view_batch_set_workflow_state($mform);
543         } else if ($action == 'viewbatchmarkingallocation') {
544             $o .= $this->view_batch_markingallocation($mform);
545         } else if ($action == 'viewsubmitforgradingerror') {
546             $o .= $this->view_error_page(get_string('submitforgrading', 'assign'), $notices);
547         } else {
548             $o .= $this->view_submission_page();
549         }
551         return $o;
552     }
554     /**
555      * Add this instance to the database.
556      *
557      * @param stdClass $formdata The data submitted from the form
558      * @param bool $callplugins This is used to skip the plugin code
559      *             when upgrading an old assignment to a new one (the plugins get called manually)
560      * @return mixed false if an error occurs or the int id of the new instance
561      */
562     public function add_instance(stdClass $formdata, $callplugins) {
563         global $DB;
564         $adminconfig = $this->get_admin_config();
566         $err = '';
568         // Add the database record.
569         $update = new stdClass();
570         $update->name = $formdata->name;
571         $update->timemodified = time();
572         $update->timecreated = time();
573         $update->course = $formdata->course;
574         $update->courseid = $formdata->course;
575         $update->intro = $formdata->intro;
576         $update->introformat = $formdata->introformat;
577         $update->alwaysshowdescription = !empty($formdata->alwaysshowdescription);
578         $update->submissiondrafts = $formdata->submissiondrafts;
579         $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
580         $update->sendnotifications = $formdata->sendnotifications;
581         $update->sendlatenotifications = $formdata->sendlatenotifications;
582         $update->sendstudentnotifications = $adminconfig->sendstudentnotifications;
583         if (isset($formdata->sendstudentnotifications)) {
584             $update->sendstudentnotifications = $formdata->sendstudentnotifications;
585         }
586         $update->duedate = $formdata->duedate;
587         $update->cutoffdate = $formdata->cutoffdate;
588         $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
589         $update->grade = $formdata->grade;
590         $update->completionsubmit = !empty($formdata->completionsubmit);
591         $update->teamsubmission = $formdata->teamsubmission;
592         $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
593         if (isset($formdata->teamsubmissiongroupingid)) {
594             $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
595         }
596         $update->blindmarking = $formdata->blindmarking;
597         $update->attemptreopenmethod = ASSIGN_ATTEMPT_REOPEN_METHOD_NONE;
598         if (!empty($formdata->attemptreopenmethod)) {
599             $update->attemptreopenmethod = $formdata->attemptreopenmethod;
600         }
601         if (!empty($formdata->maxattempts)) {
602             $update->maxattempts = $formdata->maxattempts;
603         }
604         $update->markingworkflow = $formdata->markingworkflow;
605         $update->markingallocation = $formdata->markingallocation;
606         if (empty($update->markingworkflow)) { // If marking workflow is disabled, make sure allocation is disabled.
607             $update->markingallocation = 0;
608         }
610         $returnid = $DB->insert_record('assign', $update);
611         $this->instance = $DB->get_record('assign', array('id'=>$returnid), '*', MUST_EXIST);
612         // Cache the course record.
613         $this->course = $DB->get_record('course', array('id'=>$formdata->course), '*', MUST_EXIST);
615         $this->save_intro_draft_files($formdata);
617         if ($callplugins) {
618             // Call save_settings hook for submission plugins.
619             foreach ($this->submissionplugins as $plugin) {
620                 if (!$this->update_plugin_instance($plugin, $formdata)) {
621                     print_error($plugin->get_error());
622                     return false;
623                 }
624             }
625             foreach ($this->feedbackplugins as $plugin) {
626                 if (!$this->update_plugin_instance($plugin, $formdata)) {
627                     print_error($plugin->get_error());
628                     return false;
629                 }
630             }
632             // In the case of upgrades the coursemodule has not been set,
633             // so we need to wait before calling these two.
634             $this->update_calendar($formdata->coursemodule);
635             $this->update_gradebook(false, $formdata->coursemodule);
637         }
639         $update = new stdClass();
640         $update->id = $this->get_instance()->id;
641         $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
642         $DB->update_record('assign', $update);
644         return $returnid;
645     }
647     /**
648      * Delete all grades from the gradebook for this assignment.
649      *
650      * @return bool
651      */
652     protected function delete_grades() {
653         global $CFG;
655         $result = grade_update('mod/assign',
656                                $this->get_course()->id,
657                                'mod',
658                                'assign',
659                                $this->get_instance()->id,
660                                0,
661                                null,
662                                array('deleted'=>1));
663         return $result == GRADE_UPDATE_OK;
664     }
666     /**
667      * Delete this instance from the database.
668      *
669      * @return bool false if an error occurs
670      */
671     public function delete_instance() {
672         global $DB;
673         $result = true;
675         foreach ($this->submissionplugins as $plugin) {
676             if (!$plugin->delete_instance()) {
677                 print_error($plugin->get_error());
678                 $result = false;
679             }
680         }
681         foreach ($this->feedbackplugins as $plugin) {
682             if (!$plugin->delete_instance()) {
683                 print_error($plugin->get_error());
684                 $result = false;
685             }
686         }
688         // Delete files associated with this assignment.
689         $fs = get_file_storage();
690         if (! $fs->delete_area_files($this->context->id) ) {
691             $result = false;
692         }
694         // Delete_records will throw an exception if it fails - so no need for error checking here.
695         $DB->delete_records('assign_submission', array('assignment'=>$this->get_instance()->id));
696         $DB->delete_records('assign_grades', array('assignment'=>$this->get_instance()->id));
697         $DB->delete_records('assign_plugin_config', array('assignment'=>$this->get_instance()->id));
699         // Delete items from the gradebook.
700         if (! $this->delete_grades()) {
701             $result = false;
702         }
704         // Delete the instance.
705         $DB->delete_records('assign', array('id'=>$this->get_instance()->id));
707         return $result;
708     }
710     /**
711      * Actual implementation of the reset course functionality, delete all the
712      * assignment submissions for course $data->courseid.
713      *
714      * @param stdClass $data the data submitted from the reset course.
715      * @return array status array
716      */
717     public function reset_userdata($data) {
718         global $CFG, $DB;
720         $componentstr = get_string('modulenameplural', 'assign');
721         $status = array();
723         $fs = get_file_storage();
724         if (!empty($data->reset_assign_submissions)) {
725             // Delete files associated with this assignment.
726             foreach ($this->submissionplugins as $plugin) {
727                 $fileareas = array();
728                 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
729                 $fileareas = $plugin->get_file_areas();
730                 foreach ($fileareas as $filearea) {
731                     $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
732                 }
734                 if (!$plugin->delete_instance()) {
735                     $status[] = array('component'=>$componentstr,
736                                       'item'=>get_string('deleteallsubmissions', 'assign'),
737                                       'error'=>$plugin->get_error());
738                 }
739             }
741             foreach ($this->feedbackplugins as $plugin) {
742                 $fileareas = array();
743                 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
744                 $fileareas = $plugin->get_file_areas();
745                 foreach ($fileareas as $filearea) {
746                     $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
747                 }
749                 if (!$plugin->delete_instance()) {
750                     $status[] = array('component'=>$componentstr,
751                                       'item'=>get_string('deleteallsubmissions', 'assign'),
752                                       'error'=>$plugin->get_error());
753                 }
754             }
756             $assignssql = 'SELECT a.id
757                              FROM {assign} a
758                            WHERE a.course=:course';
759             $params = array('course'=>$data->courseid);
761             $DB->delete_records_select('assign_submission', "assignment IN ($assignssql)", $params);
763             $status[] = array('component'=>$componentstr,
764                               'item'=>get_string('deleteallsubmissions', 'assign'),
765                               'error'=>false);
767             if (!empty($data->reset_gradebook_grades)) {
768                 $DB->delete_records_select('assign_grades', "assignment IN ($assignssql)", $params);
769                 // Remove all grades from gradebook.
770                 require_once($CFG->dirroot.'/mod/assign/lib.php');
771                 assign_reset_gradebook($data->courseid);
772             }
773         }
774         // Updating dates - shift may be negative too.
775         if ($data->timeshift) {
776             shift_course_mod_dates('assign',
777                                     array('duedate', 'allowsubmissionsfromdate', 'cutoffdate'),
778                                     $data->timeshift,
779                                     $data->courseid, $this->get_instance()->id);
780             $status[] = array('component'=>$componentstr,
781                               'item'=>get_string('datechanged'),
782                               'error'=>false);
783         }
785         return $status;
786     }
788     /**
789      * Update the settings for a single plugin.
790      *
791      * @param assign_plugin $plugin The plugin to update
792      * @param stdClass $formdata The form data
793      * @return bool false if an error occurs
794      */
795     protected function update_plugin_instance(assign_plugin $plugin, stdClass $formdata) {
796         if ($plugin->is_visible()) {
797             $enabledname = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
798             if (!empty($formdata->$enabledname)) {
799                 $plugin->enable();
800                 if (!$plugin->save_settings($formdata)) {
801                     print_error($plugin->get_error());
802                     return false;
803                 }
804             } else {
805                 $plugin->disable();
806             }
807         }
808         return true;
809     }
811     /**
812      * Update the gradebook information for this assignment.
813      *
814      * @param bool $reset If true, will reset all grades in the gradbook for this assignment
815      * @param int $coursemoduleid This is required because it might not exist in the database yet
816      * @return bool
817      */
818     public function update_gradebook($reset, $coursemoduleid) {
819         global $CFG;
821         require_once($CFG->dirroot.'/mod/assign/lib.php');
822         $assign = clone $this->get_instance();
823         $assign->cmidnumber = $coursemoduleid;
825         // Set assign gradebook feedback plugin status (enabled and visible).
826         $assign->gradefeedbackenabled = $this->is_gradebook_feedback_enabled();
828         $param = null;
829         if ($reset) {
830             $param = 'reset';
831         }
833         return assign_grade_item_update($assign, $param);
834     }
836     /**
837      * Load and cache the admin config for this module.
838      *
839      * @return stdClass the plugin config
840      */
841     public function get_admin_config() {
842         if ($this->adminconfig) {
843             return $this->adminconfig;
844         }
845         $this->adminconfig = get_config('assign');
846         return $this->adminconfig;
847     }
849     /**
850      * Update the calendar entries for this assignment.
851      *
852      * @param int $coursemoduleid - Required to pass this in because it might
853      *                              not exist in the database yet.
854      * @return bool
855      */
856     public function update_calendar($coursemoduleid) {
857         global $DB, $CFG;
858         require_once($CFG->dirroot.'/calendar/lib.php');
860         // Special case for add_instance as the coursemodule has not been set yet.
861         $instance = $this->get_instance();
863         if ($instance->duedate) {
864             $event = new stdClass();
866             $params = array('modulename'=>'assign', 'instance'=>$instance->id);
867             $event->id = $DB->get_field('event', 'id', $params);
868             $event->name = $instance->name;
869             $event->timestart = $instance->duedate;
871             // Convert the links to pluginfile. It is a bit hacky but at this stage the files
872             // might not have been saved in the module area yet.
873             $intro = $instance->intro;
874             if ($draftid = file_get_submitted_draft_itemid('introeditor')) {
875                 $intro = file_rewrite_urls_to_pluginfile($intro, $draftid);
876             }
878             // We need to remove the links to files as the calendar is not ready
879             // to support module events with file areas.
880             $intro = strip_pluginfile_content($intro);
881             if ($this->show_intro()) {
882                 $event->description = array(
883                     'text' => $intro,
884                     'format' => $instance->introformat
885                 );
886             } else {
887                 $event->description = array(
888                     'text' => '',
889                     'format' => $instance->introformat
890                 );
891             }
893             if ($event->id) {
894                 $calendarevent = calendar_event::load($event->id);
895                 $calendarevent->update($event);
896             } else {
897                 unset($event->id);
898                 $event->courseid    = $instance->course;
899                 $event->groupid     = 0;
900                 $event->userid      = 0;
901                 $event->modulename  = 'assign';
902                 $event->instance    = $instance->id;
903                 $event->eventtype   = 'due';
904                 $event->timeduration = 0;
905                 calendar_event::create($event);
906             }
907         } else {
908             $DB->delete_records('event', array('modulename'=>'assign', 'instance'=>$instance->id));
909         }
910     }
913     /**
914      * Update this instance in the database.
915      *
916      * @param stdClass $formdata - the data submitted from the form
917      * @return bool false if an error occurs
918      */
919     public function update_instance($formdata) {
920         global $DB;
921         $adminconfig = $this->get_admin_config();
923         $update = new stdClass();
924         $update->id = $formdata->instance;
925         $update->name = $formdata->name;
926         $update->timemodified = time();
927         $update->course = $formdata->course;
928         $update->intro = $formdata->intro;
929         $update->introformat = $formdata->introformat;
930         $update->alwaysshowdescription = !empty($formdata->alwaysshowdescription);
931         $update->submissiondrafts = $formdata->submissiondrafts;
932         $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
933         $update->sendnotifications = $formdata->sendnotifications;
934         $update->sendlatenotifications = $formdata->sendlatenotifications;
935         $update->sendstudentnotifications = $adminconfig->sendstudentnotifications;
936         if (isset($formdata->sendstudentnotifications)) {
937             $update->sendstudentnotifications = $formdata->sendstudentnotifications;
938         }
939         $update->duedate = $formdata->duedate;
940         $update->cutoffdate = $formdata->cutoffdate;
941         $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
942         $update->grade = $formdata->grade;
943         if (!empty($formdata->completionunlocked)) {
944             $update->completionsubmit = !empty($formdata->completionsubmit);
945         }
946         $update->teamsubmission = $formdata->teamsubmission;
947         $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
948         if (isset($formdata->teamsubmissiongroupingid)) {
949             $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
950         }
951         $update->blindmarking = $formdata->blindmarking;
952         $update->attemptreopenmethod = ASSIGN_ATTEMPT_REOPEN_METHOD_NONE;
953         if (!empty($formdata->attemptreopenmethod)) {
954             $update->attemptreopenmethod = $formdata->attemptreopenmethod;
955         }
956         if (!empty($formdata->maxattempts)) {
957             $update->maxattempts = $formdata->maxattempts;
958         }
959         $update->markingworkflow = $formdata->markingworkflow;
960         $update->markingallocation = $formdata->markingallocation;
961         if (empty($update->markingworkflow)) { // If marking workflow is disabled, make sure allocation is disabled.
962             $update->markingallocation = 0;
963         }
965         $result = $DB->update_record('assign', $update);
966         $this->instance = $DB->get_record('assign', array('id'=>$update->id), '*', MUST_EXIST);
968         $this->save_intro_draft_files($formdata);
970         // Load the assignment so the plugins have access to it.
972         // Call save_settings hook for submission plugins.
973         foreach ($this->submissionplugins as $plugin) {
974             if (!$this->update_plugin_instance($plugin, $formdata)) {
975                 print_error($plugin->get_error());
976                 return false;
977             }
978         }
979         foreach ($this->feedbackplugins as $plugin) {
980             if (!$this->update_plugin_instance($plugin, $formdata)) {
981                 print_error($plugin->get_error());
982                 return false;
983             }
984         }
986         $this->update_calendar($this->get_course_module()->id);
987         $this->update_gradebook(false, $this->get_course_module()->id);
989         $update = new stdClass();
990         $update->id = $this->get_instance()->id;
991         $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
992         $DB->update_record('assign', $update);
994         return $result;
995     }
997     /**
998      * Save the attachments in the draft areas.
999      *
1000      * @param stdClass $formdata
1001      */
1002     protected function save_intro_draft_files($formdata) {
1003         if (isset($formdata->introattachments)) {
1004             file_save_draft_area_files($formdata->introattachments, $this->get_context()->id,
1005                                        'mod_assign', ASSIGN_INTROATTACHMENT_FILEAREA, 0);
1006         }
1007     }
1009     /**
1010      * Add elements in grading plugin form.
1011      *
1012      * @param mixed $grade stdClass|null
1013      * @param MoodleQuickForm $mform
1014      * @param stdClass $data
1015      * @param int $userid - The userid we are grading
1016      * @return void
1017      */
1018     protected function add_plugin_grade_elements($grade, MoodleQuickForm $mform, stdClass $data, $userid) {
1019         foreach ($this->feedbackplugins as $plugin) {
1020             if ($plugin->is_enabled() && $plugin->is_visible()) {
1021                 $plugin->get_form_elements_for_user($grade, $mform, $data, $userid);
1022             }
1023         }
1024     }
1028     /**
1029      * Add one plugins settings to edit plugin form.
1030      *
1031      * @param assign_plugin $plugin The plugin to add the settings from
1032      * @param MoodleQuickForm $mform The form to add the configuration settings to.
1033      *                               This form is modified directly (not returned).
1034      * @param array $pluginsenabled A list of form elements to be added to a group.
1035      *                              The new element is added to this array by this function.
1036      * @return void
1037      */
1038     protected function add_plugin_settings(assign_plugin $plugin, MoodleQuickForm $mform, & $pluginsenabled) {
1039         global $CFG;
1040         if ($plugin->is_visible() && !$plugin->is_configurable() && $plugin->is_enabled()) {
1041             $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
1042             $pluginsenabled[] = $mform->createElement('hidden', $name, 1);
1043             $mform->setType($name, PARAM_BOOL);
1044             $plugin->get_settings($mform);
1045         } else if ($plugin->is_visible() && $plugin->is_configurable()) {
1046             $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
1047             $label = $plugin->get_name();
1048             $label .= ' ' . $this->get_renderer()->help_icon('enabled', $plugin->get_subtype() . '_' . $plugin->get_type());
1049             $pluginsenabled[] = $mform->createElement('checkbox', $name, '', $label);
1051             $default = get_config($plugin->get_subtype() . '_' . $plugin->get_type(), 'default');
1052             if ($plugin->get_config('enabled') !== false) {
1053                 $default = $plugin->is_enabled();
1054             }
1055             $mform->setDefault($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $default);
1057             $plugin->get_settings($mform);
1059         }
1060     }
1062     /**
1063      * Add settings to edit plugin form.
1064      *
1065      * @param MoodleQuickForm $mform The form to add the configuration settings to.
1066      *                               This form is modified directly (not returned).
1067      * @return void
1068      */
1069     public function add_all_plugin_settings(MoodleQuickForm $mform) {
1070         $mform->addElement('header', 'submissiontypes', get_string('submissiontypes', 'assign'));
1072         $submissionpluginsenabled = array();
1073         $group = $mform->addGroup(array(), 'submissionplugins', get_string('submissiontypes', 'assign'), array(' '), false);
1074         foreach ($this->submissionplugins as $plugin) {
1075             $this->add_plugin_settings($plugin, $mform, $submissionpluginsenabled);
1076         }
1077         $group->setElements($submissionpluginsenabled);
1079         $mform->addElement('header', 'feedbacktypes', get_string('feedbacktypes', 'assign'));
1080         $feedbackpluginsenabled = array();
1081         $group = $mform->addGroup(array(), 'feedbackplugins', get_string('feedbacktypes', 'assign'), array(' '), false);
1082         foreach ($this->feedbackplugins as $plugin) {
1083             $this->add_plugin_settings($plugin, $mform, $feedbackpluginsenabled);
1084         }
1085         $group->setElements($feedbackpluginsenabled);
1086         $mform->setExpanded('submissiontypes');
1087     }
1089     /**
1090      * Allow each plugin an opportunity to update the defaultvalues
1091      * passed in to the settings form (needed to set up draft areas for
1092      * editor and filemanager elements)
1093      *
1094      * @param array $defaultvalues
1095      */
1096     public function plugin_data_preprocessing(&$defaultvalues) {
1097         foreach ($this->submissionplugins as $plugin) {
1098             if ($plugin->is_visible()) {
1099                 $plugin->data_preprocessing($defaultvalues);
1100             }
1101         }
1102         foreach ($this->feedbackplugins as $plugin) {
1103             if ($plugin->is_visible()) {
1104                 $plugin->data_preprocessing($defaultvalues);
1105             }
1106         }
1107     }
1109     /**
1110      * Get the name of the current module.
1111      *
1112      * @return string the module name (Assignment)
1113      */
1114     protected function get_module_name() {
1115         if (isset(self::$modulename)) {
1116             return self::$modulename;
1117         }
1118         self::$modulename = get_string('modulename', 'assign');
1119         return self::$modulename;
1120     }
1122     /**
1123      * Get the plural name of the current module.
1124      *
1125      * @return string the module name plural (Assignments)
1126      */
1127     protected function get_module_name_plural() {
1128         if (isset(self::$modulenameplural)) {
1129             return self::$modulenameplural;
1130         }
1131         self::$modulenameplural = get_string('modulenameplural', 'assign');
1132         return self::$modulenameplural;
1133     }
1135     /**
1136      * Has this assignment been constructed from an instance?
1137      *
1138      * @return bool
1139      */
1140     public function has_instance() {
1141         return $this->instance || $this->get_course_module();
1142     }
1144     /**
1145      * Get the settings for the current instance of this assignment
1146      *
1147      * @return stdClass The settings
1148      */
1149     public function get_instance() {
1150         global $DB;
1151         if ($this->instance) {
1152             return $this->instance;
1153         }
1154         if ($this->get_course_module()) {
1155             $params = array('id' => $this->get_course_module()->instance);
1156             $this->instance = $DB->get_record('assign', $params, '*', MUST_EXIST);
1157         }
1158         if (!$this->instance) {
1159             throw new coding_exception('Improper use of the assignment class. ' .
1160                                        'Cannot load the assignment record.');
1161         }
1162         return $this->instance;
1163     }
1165     /**
1166      * Get the primary grade item for this assign instance.
1167      *
1168      * @return stdClass The grade_item record
1169      */
1170     public function get_grade_item() {
1171         if ($this->gradeitem) {
1172             return $this->gradeitem;
1173         }
1174         $instance = $this->get_instance();
1175         $params = array('itemtype' => 'mod',
1176                         'itemmodule' => 'assign',
1177                         'iteminstance' => $instance->id,
1178                         'courseid' => $instance->course,
1179                         'itemnumber' => 0);
1180         $this->gradeitem = grade_item::fetch($params);
1181         if (!$this->gradeitem) {
1182             throw new coding_exception('Improper use of the assignment class. ' .
1183                                        'Cannot load the grade item.');
1184         }
1185         return $this->gradeitem;
1186     }
1188     /**
1189      * Get the context of the current course.
1190      *
1191      * @return mixed context|null The course context
1192      */
1193     public function get_course_context() {
1194         if (!$this->context && !$this->course) {
1195             throw new coding_exception('Improper use of the assignment class. ' .
1196                                        'Cannot load the course context.');
1197         }
1198         if ($this->context) {
1199             return $this->context->get_course_context();
1200         } else {
1201             return context_course::instance($this->course->id);
1202         }
1203     }
1206     /**
1207      * Get the current course module.
1208      *
1209      * @return cm_info|null The course module or null if not known
1210      */
1211     public function get_course_module() {
1212         if ($this->coursemodule) {
1213             return $this->coursemodule;
1214         }
1215         if (!$this->context) {
1216             return null;
1217         }
1219         if ($this->context->contextlevel == CONTEXT_MODULE) {
1220             $modinfo = get_fast_modinfo($this->get_course());
1221             $this->coursemodule = $modinfo->get_cm($this->context->instanceid);
1222             return $this->coursemodule;
1223         }
1224         return null;
1225     }
1227     /**
1228      * Get context module.
1229      *
1230      * @return context
1231      */
1232     public function get_context() {
1233         return $this->context;
1234     }
1236     /**
1237      * Get the current course.
1238      *
1239      * @return mixed stdClass|null The course
1240      */
1241     public function get_course() {
1242         global $DB;
1244         if ($this->course) {
1245             return $this->course;
1246         }
1248         if (!$this->context) {
1249             return null;
1250         }
1251         $params = array('id' => $this->get_course_context()->instanceid);
1252         $this->course = $DB->get_record('course', $params, '*', MUST_EXIST);
1254         return $this->course;
1255     }
1257     /**
1258      * Count the number of intro attachments.
1259      *
1260      * @return int
1261      */
1262     protected function count_attachments() {
1264         $fs = get_file_storage();
1265         $files = $fs->get_area_files($this->get_context()->id, 'mod_assign', ASSIGN_INTROATTACHMENT_FILEAREA,
1266                         0, 'id', false);
1268         return count($files);
1269     }
1271     /**
1272      * Are there any intro attachments to display?
1273      *
1274      * @return boolean
1275      */
1276     protected function has_visible_attachments() {
1277         return ($this->count_attachments() > 0);
1278     }
1280     /**
1281      * Return a grade in user-friendly form, whether it's a scale or not.
1282      *
1283      * @param mixed $grade int|null
1284      * @param boolean $editing Are we allowing changes to this grade?
1285      * @param int $userid The user id the grade belongs to
1286      * @param int $modified Timestamp from when the grade was last modified
1287      * @return string User-friendly representation of grade
1288      */
1289     public function display_grade($grade, $editing, $userid=0, $modified=0) {
1290         global $DB;
1292         static $scalegrades = array();
1294         $o = '';
1296         if ($this->get_instance()->grade >= 0) {
1297             // Normal number.
1298             if ($editing && $this->get_instance()->grade > 0) {
1299                 if ($grade < 0) {
1300                     $displaygrade = '';
1301                 } else {
1302                     $displaygrade = format_float($grade, 2);
1303                 }
1304                 $o .= '<label class="accesshide" for="quickgrade_' . $userid . '">' .
1305                        get_string('usergrade', 'assign') .
1306                        '</label>';
1307                 $o .= '<input type="text"
1308                               id="quickgrade_' . $userid . '"
1309                               name="quickgrade_' . $userid . '"
1310                               value="' .  $displaygrade . '"
1311                               size="6"
1312                               maxlength="10"
1313                               class="quickgrade"/>';
1314                 $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade, 2);
1315                 return $o;
1316             } else {
1317                 if ($grade == -1 || $grade === null) {
1318                     $o .= '-';
1319                 } else {
1320                     $item = $this->get_grade_item();
1321                     $o .= grade_format_gradevalue($grade, $item);
1322                     if ($item->get_displaytype() == GRADE_DISPLAY_TYPE_REAL) {
1323                         // If displaying the raw grade, also display the total value.
1324                         $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade, 2);
1325                     }
1326                 }
1327                 return $o;
1328             }
1330         } else {
1331             // Scale.
1332             if (empty($this->cache['scale'])) {
1333                 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
1334                     $this->cache['scale'] = make_menu_from_list($scale->scale);
1335                 } else {
1336                     $o .= '-';
1337                     return $o;
1338                 }
1339             }
1340             if ($editing) {
1341                 $o .= '<label class="accesshide"
1342                               for="quickgrade_' . $userid . '">' .
1343                       get_string('usergrade', 'assign') .
1344                       '</label>';
1345                 $o .= '<select name="quickgrade_' . $userid . '" class="quickgrade">';
1346                 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
1347                 foreach ($this->cache['scale'] as $optionid => $option) {
1348                     $selected = '';
1349                     if ($grade == $optionid) {
1350                         $selected = 'selected="selected"';
1351                     }
1352                     $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
1353                 }
1354                 $o .= '</select>';
1355                 return $o;
1356             } else {
1357                 $scaleid = (int)$grade;
1358                 if (isset($this->cache['scale'][$scaleid])) {
1359                     $o .= $this->cache['scale'][$scaleid];
1360                     return $o;
1361                 }
1362                 $o .= '-';
1363                 return $o;
1364             }
1365         }
1366     }
1368     /**
1369      * Load a list of users enrolled in the current course with the specified permission and group.
1370      * 0 for no group.
1371      *
1372      * @param int $currentgroup
1373      * @param bool $idsonly
1374      * @return array List of user records
1375      */
1376     public function list_participants($currentgroup, $idsonly) {
1377         $key = $this->context->id . '-' . $currentgroup . '-' . $this->show_only_active_users();
1378         if (!isset($this->participants[$key])) {
1379             $users = get_enrolled_users($this->context, 'mod/assign:submit', $currentgroup, 'u.*', null, null, null,
1380                     $this->show_only_active_users());
1382             $cm = $this->get_course_module();
1383             $info = new \core_availability\info_module($cm);
1384             $users = $info->filter_user_list($users);
1386             $this->participants[$key] = $users;
1387         }
1389         if ($idsonly) {
1390             $idslist = array();
1391             foreach ($this->participants[$key] as $id => $user) {
1392                 $idslist[$id] = new stdClass();
1393                 $idslist[$id]->id = $id;
1394             }
1395             return $idslist;
1396         }
1397         return $this->participants[$key];
1398     }
1400     /**
1401      * Load a count of valid teams for this assignment.
1402      *
1403      * @return int number of valid teams
1404      */
1405     public function count_teams() {
1407         $groups = groups_get_all_groups($this->get_course()->id,
1408                                         0,
1409                                         $this->get_instance()->teamsubmissiongroupingid,
1410                                         'g.id');
1411         $count = count($groups);
1413         // See if there are any users in the default group.
1414         $defaultusers = $this->get_submission_group_members(0, true);
1415         if (count($defaultusers) > 0) {
1416             $count += 1;
1417         }
1418         return $count;
1419     }
1421     /**
1422      * Load a count of active users enrolled in the current course with the specified permission and group.
1423      * 0 for no group.
1424      *
1425      * @param int $currentgroup
1426      * @return int number of matching users
1427      */
1428     public function count_participants($currentgroup) {
1429         return count($this->list_participants($currentgroup, true));
1430     }
1432     /**
1433      * Load a count of active users submissions in the current module that require grading
1434      * This means the submission modification time is more recent than the
1435      * grading modification time and the status is SUBMITTED.
1436      *
1437      * @return int number of matching submissions
1438      */
1439     public function count_submissions_need_grading() {
1440         global $DB;
1442         if ($this->get_instance()->teamsubmission) {
1443             // This does not make sense for group assignment because the submission is shared.
1444             return 0;
1445         }
1447         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1448         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1450         $submissionmaxattempt = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt
1451                                  FROM {assign_submission} mxs
1452                                  WHERE mxs.assignment = :assignid2 GROUP BY mxs.userid';
1453         $grademaxattempt = 'SELECT mxg.userid, MAX(mxg.attemptnumber) AS maxattempt
1454                             FROM {assign_grades} mxg
1455                             WHERE mxg.assignment = :assignid3 GROUP BY mxg.userid';
1457         $params['assignid'] = $this->get_instance()->id;
1458         $params['assignid2'] = $this->get_instance()->id;
1459         $params['assignid3'] = $this->get_instance()->id;
1460         $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1462         $sql = 'SELECT COUNT(s.userid)
1463                    FROM {assign_submission} s
1464                    LEFT JOIN ( ' . $submissionmaxattempt . ' ) smx ON s.userid = smx.userid
1465                    LEFT JOIN ( ' . $grademaxattempt . ' ) gmx ON s.userid = gmx.userid
1466                    LEFT JOIN {assign_grades} g ON
1467                         s.assignment = g.assignment AND
1468                         s.userid = g.userid AND
1469                         g.attemptnumber = gmx.maxattempt
1470                    JOIN(' . $esql . ') e ON e.id = s.userid
1471                    WHERE
1472                         s.attemptnumber = smx.maxattempt AND
1473                         s.assignment = :assignid AND
1474                         s.timemodified IS NOT NULL AND
1475                         s.status = :submitted AND
1476                         (s.timemodified > g.timemodified OR g.timemodified IS NULL)';
1478         return $DB->count_records_sql($sql, $params);
1479     }
1481     /**
1482      * Load a count of grades.
1483      *
1484      * @return int number of grades
1485      */
1486     public function count_grades() {
1487         global $DB;
1489         if (!$this->has_instance()) {
1490             return 0;
1491         }
1493         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1494         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1496         $params['assignid'] = $this->get_instance()->id;
1498         $sql = 'SELECT COUNT(g.userid)
1499                    FROM {assign_grades} g
1500                    JOIN(' . $esql . ') e ON e.id = g.userid
1501                    WHERE g.assignment = :assignid';
1503         return $DB->count_records_sql($sql, $params);
1504     }
1506     /**
1507      * Load a count of submissions.
1508      *
1509      * @return int number of submissions
1510      */
1511     public function count_submissions() {
1512         global $DB;
1514         if (!$this->has_instance()) {
1515             return 0;
1516         }
1518         $params = array();
1520         if ($this->get_instance()->teamsubmission) {
1521             // We cannot join on the enrolment tables for group submissions (no userid).
1522             $sql = 'SELECT COUNT(DISTINCT s.groupid)
1523                         FROM {assign_submission} s
1524                         WHERE
1525                             s.assignment = :assignid AND
1526                             s.timemodified IS NOT NULL AND
1527                             s.userid = :groupuserid';
1529             $params['assignid'] = $this->get_instance()->id;
1530             $params['groupuserid'] = 0;
1531         } else {
1532             $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1533             list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1535             $params['assignid'] = $this->get_instance()->id;
1537             $sql = 'SELECT COUNT(DISTINCT s.userid)
1538                        FROM {assign_submission} s
1539                        JOIN(' . $esql . ') e ON e.id = s.userid
1540                        WHERE
1541                             s.assignment = :assignid AND
1542                             s.timemodified IS NOT NULL';
1544         }
1546         return $DB->count_records_sql($sql, $params);
1547     }
1549     /**
1550      * Load a count of submissions with a specified status.
1551      *
1552      * @param string $status The submission status - should match one of the constants
1553      * @return int number of matching submissions
1554      */
1555     public function count_submissions_with_status($status) {
1556         global $DB;
1558         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1559         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1561         $params['assignid'] = $this->get_instance()->id;
1562         $params['assignid2'] = $this->get_instance()->id;
1563         $params['submissionstatus'] = $status;
1565         if ($this->get_instance()->teamsubmission) {
1566             $maxattemptsql = 'SELECT mxs.groupid, MAX(mxs.attemptnumber) AS maxattempt
1567                               FROM {assign_submission} mxs
1568                               WHERE mxs.assignment = :assignid2 GROUP BY mxs.groupid';
1570             $sql = 'SELECT COUNT(s.groupid)
1571                         FROM {assign_submission} s
1572                         JOIN(' . $maxattemptsql . ') smx ON s.groupid = smx.groupid
1573                         WHERE
1574                             s.attemptnumber = smx.maxattempt AND
1575                             s.assignment = :assignid AND
1576                             s.timemodified IS NOT NULL AND
1577                             s.userid = :groupuserid AND
1578                             s.status = :submissionstatus';
1579             $params['groupuserid'] = 0;
1580         } else {
1581             $maxattemptsql = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt
1582                               FROM {assign_submission} mxs
1583                               WHERE mxs.assignment = :assignid2 GROUP BY mxs.userid';
1585             $sql = 'SELECT COUNT(s.userid)
1586                         FROM {assign_submission} s
1587                         JOIN(' . $esql . ') e ON e.id = s.userid
1588                         JOIN(' . $maxattemptsql . ') smx ON s.userid = smx.userid
1589                         WHERE
1590                             s.attemptnumber = smx.maxattempt AND
1591                             s.assignment = :assignid AND
1592                             s.timemodified IS NOT NULL AND
1593                             s.status = :submissionstatus';
1595         }
1597         return $DB->count_records_sql($sql, $params);
1598     }
1600     /**
1601      * Utility function to get the userid for every row in the grading table
1602      * so the order can be frozen while we iterate it.
1603      *
1604      * @return array An array of userids
1605      */
1606     protected function get_grading_userid_list() {
1607         $filter = get_user_preferences('assign_filter', '');
1608         $table = new assign_grading_table($this, 0, $filter, 0, false);
1610         $useridlist = $table->get_column_data('userid');
1612         return $useridlist;
1613     }
1615     /**
1616      * Generate zip file from array of given files.
1617      *
1618      * @param array $filesforzipping - array of files to pass into archive_to_pathname.
1619      *                                 This array is indexed by the final file name and each
1620      *                                 element in the array is an instance of a stored_file object.
1621      * @return path of temp file - note this returned file does
1622      *         not have a .zip extension - it is a temp file.
1623      */
1624     protected function pack_files($filesforzipping) {
1625         global $CFG;
1626         // Create path for new zip file.
1627         $tempzip = tempnam($CFG->tempdir . '/', 'assignment_');
1628         // Zip files.
1629         $zipper = new zip_packer();
1630         if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
1631             return $tempzip;
1632         }
1633         return false;
1634     }
1636     /**
1637      * Finds all assignment notifications that have yet to be mailed out, and mails them.
1638      *
1639      * Cron function to be run periodically according to the moodle cron.
1640      *
1641      * @return bool
1642      */
1643     public static function cron() {
1644         global $DB;
1646         // Only ever send a max of one days worth of updates.
1647         $yesterday = time() - (24 * 3600);
1648         $timenow   = time();
1649         $lastcron = $DB->get_field('modules', 'lastcron', array('name' => 'assign'));
1651         // Collect all submissions from the past 24 hours that require mailing.
1652         // Submissions are excluded if the assignment is hidden in the gradebook.
1653         $sql = "SELECT g.id as gradeid, a.course, a.name, a.blindmarking, a.revealidentities,
1654                        g.*, g.timemodified as lastmodified, cm.id as cmid
1655                  FROM {assign} a
1656                  JOIN {assign_grades} g ON g.assignment = a.id
1657             LEFT JOIN {assign_user_flags} uf ON uf.assignment = a.id AND uf.userid = g.userid
1658                  JOIN {course_modules} cm ON cm.course = a.course AND cm.instance = a.id
1659                  JOIN {modules} md ON md.id = cm.module AND md.name = 'assign'
1660                  JOIN {grade_items} gri ON gri.iteminstance = a.id AND gri.courseid = a.course AND gri.itemmodule = md.name
1661                  WHERE g.timemodified >= :yesterday AND
1662                        g.timemodified <= :today AND
1663                        uf.mailed = 0 AND gri.hidden = 0
1664               ORDER BY a.course, cm.id";
1666         $params = array('yesterday' => $yesterday, 'today' => $timenow);
1667         $submissions = $DB->get_records_sql($sql, $params);
1669         if (!empty($submissions)) {
1671             mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
1673             // Preload courses we are going to need those.
1674             $courseids = array();
1675             foreach ($submissions as $submission) {
1676                 $courseids[] = $submission->course;
1677             }
1679             // Filter out duplicates.
1680             $courseids = array_unique($courseids);
1681             $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1682             list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
1683             $sql = 'SELECT c.*, ' . $ctxselect .
1684                       ' FROM {course} c
1685                  LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
1686                      WHERE c.id ' . $courseidsql;
1688             $params['contextlevel'] = CONTEXT_COURSE;
1689             $courses = $DB->get_records_sql($sql, $params);
1691             // Clean up... this could go on for a while.
1692             unset($courseids);
1693             unset($ctxselect);
1694             unset($courseidsql);
1695             unset($params);
1697             // Message students about new feedback.
1698             foreach ($submissions as $submission) {
1700                 mtrace("Processing assignment submission $submission->id ...");
1702                 // Do not cache user lookups - could be too many.
1703                 if (!$user = $DB->get_record('user', array('id'=>$submission->userid))) {
1704                     mtrace('Could not find user ' . $submission->userid);
1705                     continue;
1706                 }
1708                 // Use a cache to prevent the same DB queries happening over and over.
1709                 if (!array_key_exists($submission->course, $courses)) {
1710                     mtrace('Could not find course ' . $submission->course);
1711                     continue;
1712                 }
1713                 $course = $courses[$submission->course];
1714                 if (isset($course->ctxid)) {
1715                     // Context has not yet been preloaded. Do so now.
1716                     context_helper::preload_from_record($course);
1717                 }
1719                 // Override the language and timezone of the "current" user, so that
1720                 // mail is customised for the receiver.
1721                 cron_setup_user($user, $course);
1723                 // Context lookups are already cached.
1724                 $coursecontext = context_course::instance($course->id);
1725                 if (!is_enrolled($coursecontext, $user->id)) {
1726                     $courseshortname = format_string($course->shortname,
1727                                                      true,
1728                                                      array('context' => $coursecontext));
1729                     mtrace(fullname($user) . ' not an active participant in ' . $courseshortname);
1730                     continue;
1731                 }
1733                 if (!$grader = $DB->get_record('user', array('id'=>$submission->grader))) {
1734                     mtrace('Could not find grader ' . $submission->grader);
1735                     continue;
1736                 }
1738                 $modinfo = get_fast_modinfo($course, $user->id);
1739                 $cm = $modinfo->get_cm($submission->cmid);
1740                 // Context lookups are already cached.
1741                 $contextmodule = context_module::instance($cm->id);
1743                 if (!$cm->uservisible) {
1744                     // Hold mail notification for assignments the user cannot access until later.
1745                     continue;
1746                 }
1748                 // Need to send this to the student.
1749                 $messagetype = 'feedbackavailable';
1750                 $eventtype = 'assign_notification';
1751                 $updatetime = $submission->lastmodified;
1752                 $modulename = get_string('modulename', 'assign');
1754                 $uniqueid = 0;
1755                 if ($submission->blindmarking && !$submission->revealidentities) {
1756                     $uniqueid = self::get_uniqueid_for_user_static($submission->assignment, $user->id);
1757                 }
1758                 $showusers = $submission->blindmarking && !$submission->revealidentities;
1759                 self::send_assignment_notification($grader,
1760                                                    $user,
1761                                                    $messagetype,
1762                                                    $eventtype,
1763                                                    $updatetime,
1764                                                    $cm,
1765                                                    $contextmodule,
1766                                                    $course,
1767                                                    $modulename,
1768                                                    $submission->name,
1769                                                    $showusers,
1770                                                    $uniqueid);
1772                 $flags = $DB->get_record('assign_user_flags', array('userid'=>$user->id, 'assignment'=>$submission->assignment));
1773                 if ($flags) {
1774                     $flags->mailed = 1;
1775                     $DB->update_record('assign_user_flags', $flags);
1776                 } else {
1777                     $flags = new stdClass();
1778                     $flags->userid = $user->id;
1779                     $flags->assignment = $submission->assignment;
1780                     $flags->mailed = 1;
1781                     $DB->insert_record('assign_user_flags', $flags);
1782                 }
1784                 mtrace('Done');
1785             }
1786             mtrace('Done processing ' . count($submissions) . ' assignment submissions');
1788             cron_setup_user();
1790             // Free up memory just to be sure.
1791             unset($courses);
1792         }
1794         // Update calendar events to provide a description.
1795         $sql = 'SELECT id
1796                     FROM {assign}
1797                     WHERE
1798                         allowsubmissionsfromdate >= :lastcron AND
1799                         allowsubmissionsfromdate <= :timenow AND
1800                         alwaysshowdescription = 0';
1801         $params = array('lastcron' => $lastcron, 'timenow' => $timenow);
1802         $newlyavailable = $DB->get_records_sql($sql, $params);
1803         foreach ($newlyavailable as $record) {
1804             $cm = get_coursemodule_from_instance('assign', $record->id, 0, false, MUST_EXIST);
1805             $context = context_module::instance($cm->id);
1807             $assignment = new assign($context, null, null);
1808             $assignment->update_calendar($cm->id);
1809         }
1811         return true;
1812     }
1814     /**
1815      * Mark in the database that this grade record should have an update notification sent by cron.
1816      *
1817      * @param stdClass $grade a grade record keyed on id
1818      * @return bool true for success
1819      */
1820     public function notify_grade_modified($grade) {
1821         global $DB;
1823         $flags = $this->get_user_flags($grade->userid, true);
1824         if ($flags->mailed != 1) {
1825             $flags->mailed = 0;
1826         }
1828         return $this->update_user_flags($flags);
1829     }
1831     /**
1832      * Update user flags for this user in this assignment.
1833      *
1834      * @param stdClass $flags a flags record keyed on id
1835      * @return bool true for success
1836      */
1837     public function update_user_flags($flags) {
1838         global $DB;
1839         if ($flags->userid <= 0 || $flags->assignment <= 0 || $flags->id <= 0) {
1840             return false;
1841         }
1843         $result = $DB->update_record('assign_user_flags', $flags);
1844         return $result;
1845     }
1847     /**
1848      * Update a grade in the grade table for the assignment and in the gradebook.
1849      *
1850      * @param stdClass $grade a grade record keyed on id
1851      * @param bool $reopenattempt If the attempt reopen method is manual, allow another attempt at this assignment.
1852      * @return bool true for success
1853      */
1854     public function update_grade($grade, $reopenattempt = false) {
1855         global $DB;
1857         $grade->timemodified = time();
1859         if (!empty($grade->workflowstate)) {
1860             $validstates = $this->get_marking_workflow_states_for_current_user();
1861             if (!array_key_exists($grade->workflowstate, $validstates)) {
1862                 return false;
1863             }
1864         }
1866         if ($grade->grade && $grade->grade != -1) {
1867             if ($this->get_instance()->grade > 0) {
1868                 if (!is_numeric($grade->grade)) {
1869                     return false;
1870                 } else if ($grade->grade > $this->get_instance()->grade) {
1871                     return false;
1872                 } else if ($grade->grade < 0) {
1873                     return false;
1874                 }
1875             } else {
1876                 // This is a scale.
1877                 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
1878                     $scaleoptions = make_menu_from_list($scale->scale);
1879                     if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
1880                         return false;
1881                     }
1882                 }
1883             }
1884         }
1886         if (empty($grade->attemptnumber)) {
1887             // Set it to the default.
1888             $grade->attemptnumber = 0;
1889         }
1890         $result = $DB->update_record('assign_grades', $grade);
1892         // If the conditions are met, allow another attempt.
1893         $submission = null;
1894         if ($this->get_instance()->teamsubmission) {
1895             $submission = $this->get_group_submission($grade->userid, 0, false);
1896         } else {
1897             $submission = $this->get_user_submission($grade->userid, false);
1898         }
1899         if ($submission && $submission->attemptnumber == $grade->attemptnumber) {
1900             $this->reopen_submission_if_required($grade->userid,
1901                                                  $submission,
1902                                                  $reopenattempt);
1903         }
1905         // Only push to gradebook if the update is for the latest attempt.
1906         // Not the latest attempt.
1907         if ($submission && $submission->attemptnumber != $grade->attemptnumber) {
1908             return true;
1909         }
1911         if ($result) {
1912             $this->gradebook_item_update(null, $grade);
1913             \mod_assign\event\submission_graded::create_from_grade($this, $grade)->trigger();
1914         }
1915         return $result;
1916     }
1918     /**
1919      * View the grant extension date page.
1920      *
1921      * Uses url parameters 'userid'
1922      * or from parameter 'selectedusers'
1923      *
1924      * @param moodleform $mform - Used for validation of the submitted data
1925      * @return string
1926      */
1927     protected function view_grant_extension($mform) {
1928         global $DB, $CFG;
1929         require_once($CFG->dirroot . '/mod/assign/extensionform.php');
1931         $o = '';
1932         $batchusers = optional_param('selectedusers', '', PARAM_SEQUENCE);
1933         $data = new stdClass();
1934         $data->extensionduedate = null;
1935         $userid = 0;
1936         if (!$batchusers) {
1937             $userid = required_param('userid', PARAM_INT);
1939             $flags = $this->get_user_flags($userid, false);
1941             $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
1943             if ($flags) {
1944                 $data->extensionduedate = $flags->extensionduedate;
1945             }
1946             $data->userid = $userid;
1947         } else {
1948             $data->batchusers = $batchusers;
1949         }
1950         $header = new assign_header($this->get_instance(),
1951                                     $this->get_context(),
1952                                     $this->show_intro(),
1953                                     $this->get_course_module()->id,
1954                                     get_string('grantextension', 'assign'));
1955         $o .= $this->get_renderer()->render($header);
1957         if (!$mform) {
1958             $formparams = array($this->get_course_module()->id,
1959                                 $userid,
1960                                 $batchusers,
1961                                 $this->get_instance(),
1962                                 $data);
1963             $mform = new mod_assign_extension_form(null, $formparams);
1964         }
1965         $o .= $this->get_renderer()->render(new assign_form('extensionform', $mform));
1966         $o .= $this->view_footer();
1967         return $o;
1968     }
1970     /**
1971      * Get a list of the users in the same group as this user.
1972      *
1973      * @param int $groupid The id of the group whose members we want or 0 for the default group
1974      * @param bool $onlyids Whether to retrieve only the user id's
1975      * @return array The users (possibly id's only)
1976      */
1977     public function get_submission_group_members($groupid, $onlyids) {
1978         $members = array();
1979         if ($groupid != 0) {
1980             if ($onlyids) {
1981                 $allusers = groups_get_members($groupid, 'u.id');
1982             } else {
1983                 $allusers = groups_get_members($groupid);
1984             }
1985             foreach ($allusers as $user) {
1986                 if ($this->get_submission_group($user->id)) {
1987                     $members[] = $user;
1988                 }
1989             }
1990         } else {
1991             $allusers = $this->list_participants(null, $onlyids);
1992             foreach ($allusers as $user) {
1993                 if ($this->get_submission_group($user->id) == null) {
1994                     $members[] = $user;
1995                 }
1996             }
1997         }
1998         // Exclude suspended users, if user can't see them.
1999         if (!has_capability('moodle/course:viewsuspendedusers', $this->context)) {
2000             foreach ($members as $key => $member) {
2001                 if (!$this->is_active_user($member->id)) {
2002                     unset($members[$key]);
2003                 }
2004             }
2005         }
2006         return $members;
2007     }
2009     /**
2010      * Get a list of the users in the same group as this user that have not submitted the assignment.
2011      *
2012      * @param int $groupid The id of the group whose members we want or 0 for the default group
2013      * @param bool $onlyids Whether to retrieve only the user id's
2014      * @return array The users (possibly id's only)
2015      */
2016     public function get_submission_group_members_who_have_not_submitted($groupid, $onlyids) {
2017         $instance = $this->get_instance();
2018         if (!$instance->teamsubmission || !$instance->requireallteammemberssubmit) {
2019             return array();
2020         }
2021         $members = $this->get_submission_group_members($groupid, $onlyids);
2023         foreach ($members as $id => $member) {
2024             $submission = $this->get_user_submission($member->id, false);
2025             if ($submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
2026                 unset($members[$id]);
2027             } else {
2028                 if ($this->is_blind_marking()) {
2029                     $members[$id]->alias = get_string('hiddenuser', 'assign') .
2030                                            $this->get_uniqueid_for_user($id);
2031                 }
2032             }
2033         }
2034         return $members;
2035     }
2037     /**
2038      * Load the group submission object for a particular user, optionally creating it if required.
2039      *
2040      * @param int $userid The id of the user whose submission we want
2041      * @param int $groupid The id of the group for this user - may be 0 in which
2042      *                     case it is determined from the userid.
2043      * @param bool $create If set to true a new submission object will be created in the database
2044      * @param int $attemptnumber - -1 means the latest attempt
2045      * @return stdClass The submission
2046      */
2047     public function get_group_submission($userid, $groupid, $create, $attemptnumber=-1) {
2048         global $DB;
2050         if ($groupid == 0) {
2051             $group = $this->get_submission_group($userid);
2052             if ($group) {
2053                 $groupid = $group->id;
2054             }
2055         }
2057         // Now get the group submission.
2058         $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
2059         if ($attemptnumber >= 0) {
2060             $params['attemptnumber'] = $attemptnumber;
2061         }
2063         // Only return the row with the highest attemptnumber.
2064         $submission = null;
2065         $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
2066         if ($submissions) {
2067             $submission = reset($submissions);
2068         }
2070         if ($submission) {
2071             return $submission;
2072         }
2073         if ($create) {
2074             $submission = new stdClass();
2075             $submission->assignment = $this->get_instance()->id;
2076             $submission->userid = 0;
2077             $submission->groupid = $groupid;
2078             $submission->timecreated = time();
2079             $submission->timemodified = $submission->timecreated;
2080             if ($attemptnumber >= 0) {
2081                 $submission->attemptnumber = $attemptnumber;
2082             } else {
2083                 $submission->attemptnumber = 0;
2084             }
2086             $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
2087             $sid = $DB->insert_record('assign_submission', $submission);
2088             return $DB->get_record('assign_submission', array('id' => $sid));
2089         }
2090         return false;
2091     }
2093     /**
2094      * View a summary listing of all assignments in the current course.
2095      *
2096      * @return string
2097      */
2098     private function view_course_index() {
2099         global $USER;
2101         $o = '';
2103         $course = $this->get_course();
2104         $strplural = get_string('modulenameplural', 'assign');
2106         if (!$cms = get_coursemodules_in_course('assign', $course->id, 'm.duedate')) {
2107             $o .= $this->get_renderer()->notification(get_string('thereareno', 'moodle', $strplural));
2108             $o .= $this->get_renderer()->continue_button(new moodle_url('/course/view.php', array('id' => $course->id)));
2109             return $o;
2110         }
2112         $strsectionname = '';
2113         $usesections = course_format_uses_sections($course->format);
2114         $modinfo = get_fast_modinfo($course);
2116         if ($usesections) {
2117             $strsectionname = get_string('sectionname', 'format_'.$course->format);
2118             $sections = $modinfo->get_section_info_all();
2119         }
2120         $courseindexsummary = new assign_course_index_summary($usesections, $strsectionname);
2122         $timenow = time();
2124         $currentsection = '';
2125         foreach ($modinfo->instances['assign'] as $cm) {
2126             if (!$cm->uservisible) {
2127                 continue;
2128             }
2130             $timedue = $cms[$cm->id]->duedate;
2132             $sectionname = '';
2133             if ($usesections && $cm->sectionnum) {
2134                 $sectionname = get_section_name($course, $sections[$cm->sectionnum]);
2135             }
2137             $submitted = '';
2138             $context = context_module::instance($cm->id);
2140             $assignment = new assign($context, $cm, $course);
2142             if (has_capability('mod/assign:grade', $context)) {
2143                 $submitted = $assignment->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED);
2145             } else if (has_capability('mod/assign:submit', $context)) {
2146                 $usersubmission = $assignment->get_user_submission($USER->id, false);
2148                 if (!empty($usersubmission->status)) {
2149                     $submitted = get_string('submissionstatus_' . $usersubmission->status, 'assign');
2150                 } else {
2151                     $submitted = get_string('submissionstatus_', 'assign');
2152                 }
2153             }
2154             $gradinginfo = grade_get_grades($course->id, 'mod', 'assign', $cm->instance, $USER->id);
2155             if (isset($gradinginfo->items[0]->grades[$USER->id]) &&
2156                     !$gradinginfo->items[0]->grades[$USER->id]->hidden ) {
2157                 $grade = $gradinginfo->items[0]->grades[$USER->id]->str_grade;
2158             } else {
2159                 $grade = '-';
2160             }
2162             $courseindexsummary->add_assign_info($cm->id, $cm->name, $sectionname, $timedue, $submitted, $grade);
2164         }
2166         $o .= $this->get_renderer()->render($courseindexsummary);
2167         $o .= $this->view_footer();
2169         return $o;
2170     }
2172     /**
2173      * View a page rendered by a plugin.
2174      *
2175      * Uses url parameters 'pluginaction', 'pluginsubtype', 'plugin', and 'id'.
2176      *
2177      * @return string
2178      */
2179     protected function view_plugin_page() {
2180         global $USER;
2182         $o = '';
2184         $pluginsubtype = required_param('pluginsubtype', PARAM_ALPHA);
2185         $plugintype = required_param('plugin', PARAM_TEXT);
2186         $pluginaction = required_param('pluginaction', PARAM_ALPHA);
2188         $plugin = $this->get_plugin_by_type($pluginsubtype, $plugintype);
2189         if (!$plugin) {
2190             print_error('invalidformdata', '');
2191             return;
2192         }
2194         $o .= $plugin->view_page($pluginaction);
2196         return $o;
2197     }
2200     /**
2201      * This is used for team assignments to get the group for the specified user.
2202      * If the user is a member of multiple or no groups this will return false
2203      *
2204      * @param int $userid The id of the user whose submission we want
2205      * @return mixed The group or false
2206      */
2207     public function get_submission_group($userid) {
2208         $grouping = $this->get_instance()->teamsubmissiongroupingid;
2209         $groups = groups_get_all_groups($this->get_course()->id, $userid, $grouping);
2210         if (count($groups) != 1) {
2211             return false;
2212         }
2213         return array_pop($groups);
2214     }
2217     /**
2218      * Display the submission that is used by a plugin.
2219      *
2220      * Uses url parameters 'sid', 'gid' and 'plugin'.
2221      *
2222      * @param string $pluginsubtype
2223      * @return string
2224      */
2225     protected function view_plugin_content($pluginsubtype) {
2226         $o = '';
2228         $submissionid = optional_param('sid', 0, PARAM_INT);
2229         $gradeid = optional_param('gid', 0, PARAM_INT);
2230         $plugintype = required_param('plugin', PARAM_TEXT);
2231         $item = null;
2232         if ($pluginsubtype == 'assignsubmission') {
2233             $plugin = $this->get_submission_plugin_by_type($plugintype);
2234             if ($submissionid <= 0) {
2235                 throw new coding_exception('Submission id should not be 0');
2236             }
2237             $item = $this->get_submission($submissionid);
2239             // Check permissions.
2240             $this->require_view_submission($item->userid);
2241             $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2242                                                               $this->get_context(),
2243                                                               $this->show_intro(),
2244                                                               $this->get_course_module()->id,
2245                                                               $plugin->get_name()));
2246             $o .= $this->get_renderer()->render(new assign_submission_plugin_submission($plugin,
2247                                                               $item,
2248                                                               assign_submission_plugin_submission::FULL,
2249                                                               $this->get_course_module()->id,
2250                                                               $this->get_return_action(),
2251                                                               $this->get_return_params()));
2253             // Trigger event for viewing a submission.
2254             \mod_assign\event\submission_viewed::create_from_submission($this, $item)->trigger();
2256         } else {
2257             $plugin = $this->get_feedback_plugin_by_type($plugintype);
2258             if ($gradeid <= 0) {
2259                 throw new coding_exception('Grade id should not be 0');
2260             }
2261             $item = $this->get_grade($gradeid);
2262             // Check permissions.
2263             $this->require_view_submission($item->userid);
2264             $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2265                                                               $this->get_context(),
2266                                                               $this->show_intro(),
2267                                                               $this->get_course_module()->id,
2268                                                               $plugin->get_name()));
2269             $o .= $this->get_renderer()->render(new assign_feedback_plugin_feedback($plugin,
2270                                                               $item,
2271                                                               assign_feedback_plugin_feedback::FULL,
2272                                                               $this->get_course_module()->id,
2273                                                               $this->get_return_action(),
2274                                                               $this->get_return_params()));
2276             // Trigger event for viewing feedback.
2277             \mod_assign\event\feedback_viewed::create_from_grade($this, $item)->trigger();
2278         }
2280         $o .= $this->view_return_links();
2282         $o .= $this->view_footer();
2284         return $o;
2285     }
2287     /**
2288      * Rewrite plugin file urls so they resolve correctly in an exported zip.
2289      *
2290      * @param string $text - The replacement text
2291      * @param stdClass $user - The user record
2292      * @param assign_plugin $plugin - The assignment plugin
2293      */
2294     public function download_rewrite_pluginfile_urls($text, $user, $plugin) {
2295         $groupmode = groups_get_activity_groupmode($this->get_course_module());
2296         $groupname = '';
2297         if ($groupmode) {
2298             $groupid = groups_get_activity_group($this->get_course_module(), true);
2299             $groupname = groups_get_group_name($groupid).'-';
2300         }
2302         if ($this->is_blind_marking()) {
2303             $prefix = $groupname . get_string('participant', 'assign');
2304             $prefix = str_replace('_', ' ', $prefix);
2305             $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2306         } else {
2307             $prefix = $groupname . fullname($user);
2308             $prefix = str_replace('_', ' ', $prefix);
2309             $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2310         }
2312         $subtype = $plugin->get_subtype();
2313         $type = $plugin->get_type();
2314         $prefix = $prefix . $subtype . '_' . $type . '_';
2316         $result = str_replace('@@PLUGINFILE@@/', $prefix, $text);
2318         return $result;
2319     }
2321     /**
2322      * Render the content in editor that is often used by plugin.
2323      *
2324      * @param string $filearea
2325      * @param int  $submissionid
2326      * @param string $plugintype
2327      * @param string $editor
2328      * @param string $component
2329      * @return string
2330      */
2331     public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
2332         global $CFG;
2334         $result = '';
2336         $plugin = $this->get_submission_plugin_by_type($plugintype);
2338         $text = $plugin->get_editor_text($editor, $submissionid);
2339         $format = $plugin->get_editor_format($editor, $submissionid);
2341         $finaltext = file_rewrite_pluginfile_urls($text,
2342                                                   'pluginfile.php',
2343                                                   $this->get_context()->id,
2344                                                   $component,
2345                                                   $filearea,
2346                                                   $submissionid);
2347         $params = array('overflowdiv' => true, 'context' => $this->get_context());
2348         $result .= format_text($finaltext, $format, $params);
2350         if ($CFG->enableportfolios) {
2351             require_once($CFG->libdir . '/portfoliolib.php');
2353             $button = new portfolio_add_button();
2354             $portfolioparams = array('cmid' => $this->get_course_module()->id,
2355                                      'sid' => $submissionid,
2356                                      'plugin' => $plugintype,
2357                                      'editor' => $editor,
2358                                      'area'=>$filearea);
2359             $button->set_callback_options('assign_portfolio_caller', $portfolioparams, 'mod_assign');
2360             $fs = get_file_storage();
2362             if ($files = $fs->get_area_files($this->context->id,
2363                                              $component,
2364                                              $filearea,
2365                                              $submissionid,
2366                                              'timemodified',
2367                                              false)) {
2368                 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
2369             } else {
2370                 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
2371             }
2372             $result .= $button->to_html();
2373         }
2374         return $result;
2375     }
2377     /**
2378      * Display a continue page after grading.
2379      *
2380      * @param string $message - The message to display.
2381      * @return string
2382      */
2383     protected function view_savegrading_result($message) {
2384         $o = '';
2385         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2386                                                       $this->get_context(),
2387                                                       $this->show_intro(),
2388                                                       $this->get_course_module()->id,
2389                                                       get_string('savegradingresult', 'assign')));
2390         $gradingresult = new assign_gradingmessage(get_string('savegradingresult', 'assign'),
2391                                                    $message,
2392                                                    $this->get_course_module()->id);
2393         $o .= $this->get_renderer()->render($gradingresult);
2394         $o .= $this->view_footer();
2395         return $o;
2396     }
2397     /**
2398      * Display a continue page after quickgrading.
2399      *
2400      * @param string $message - The message to display.
2401      * @return string
2402      */
2403     protected function view_quickgrading_result($message) {
2404         $o = '';
2405         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2406                                                       $this->get_context(),
2407                                                       $this->show_intro(),
2408                                                       $this->get_course_module()->id,
2409                                                       get_string('quickgradingresult', 'assign')));
2410         $lastpage = optional_param('lastpage', null, PARAM_INT);
2411         $gradingresult = new assign_gradingmessage(get_string('quickgradingresult', 'assign'),
2412                                                    $message,
2413                                                    $this->get_course_module()->id,
2414                                                    false,
2415                                                    $lastpage);
2416         $o .= $this->get_renderer()->render($gradingresult);
2417         $o .= $this->view_footer();
2418         return $o;
2419     }
2421     /**
2422      * Display the page footer.
2423      *
2424      * @return string
2425      */
2426     protected function view_footer() {
2427         // When viewing the footer during PHPUNIT tests a set_state error is thrown.
2428         if (!PHPUNIT_TEST) {
2429             return $this->get_renderer()->render_footer();
2430         }
2432         return '';
2433     }
2435     /**
2436      * Throw an error if the permissions to view this users submission are missing.
2437      *
2438      * @throws required_capability_exception
2439      * @return none
2440      */
2441     public function require_view_submission($userid) {
2442         if (!$this->can_view_submission($userid)) {
2443             throw new required_capability_exception($this->context, 'mod/assign:viewgrades', 'nopermission', '');
2444         }
2445     }
2447     /**
2448      * Throw an error if the permissions to view grades in this assignment are missing.
2449      *
2450      * @throws required_capability_exception
2451      * @return none
2452      */
2453     public function require_view_grades() {
2454         if (!$this->can_view_grades()) {
2455             throw new required_capability_exception($this->context, 'mod/assign:viewgrades', 'nopermission', '');
2456         }
2457     }
2459     /**
2460      * Does this user have view grade or grade permission for this assignment?
2461      *
2462      * @return bool
2463      */
2464     public function can_view_grades() {
2465         // Permissions check.
2466         if (!has_any_capability(array('mod/assign:viewgrades', 'mod/assign:grade'), $this->context)) {
2467             return false;
2468         }
2470         return true;
2471     }
2473     /**
2474      * Does this user have grade permission for this assignment?
2475      *
2476      * @return bool
2477      */
2478     public function can_grade() {
2479         // Permissions check.
2480         if (!has_capability('mod/assign:grade', $this->context)) {
2481             return false;
2482         }
2484         return true;
2485     }
2487     /**
2488      * Download a zip file of all assignment submissions.
2489      *
2490      * @return string - If an error occurs, this will contain the error page.
2491      */
2492     protected function download_submissions() {
2493         global $CFG, $DB;
2495         // More efficient to load this here.
2496         require_once($CFG->libdir.'/filelib.php');
2498         $this->require_view_grades();
2500         // Load all users with submit.
2501         $students = get_enrolled_users($this->context, "mod/assign:submit", null, 'u.*', null, null, null,
2502                         $this->show_only_active_users());
2504         // Build a list of files to zip.
2505         $filesforzipping = array();
2506         $fs = get_file_storage();
2508         $groupmode = groups_get_activity_groupmode($this->get_course_module());
2509         // All users.
2510         $groupid = 0;
2511         $groupname = '';
2512         if ($groupmode) {
2513             $groupid = groups_get_activity_group($this->get_course_module(), true);
2514             $groupname = groups_get_group_name($groupid).'-';
2515         }
2517         // Construct the zip file name.
2518         $filename = clean_filename($this->get_course()->shortname . '-' .
2519                                    $this->get_instance()->name . '-' .
2520                                    $groupname.$this->get_course_module()->id . '.zip');
2522         // Get all the files for each student.
2523         foreach ($students as $student) {
2524             $userid = $student->id;
2526             if ((groups_is_member($groupid, $userid) or !$groupmode or !$groupid)) {
2527                 // Get the plugins to add their own files to the zip.
2529                 $submissiongroup = false;
2530                 $groupname = '';
2531                 if ($this->get_instance()->teamsubmission) {
2532                     $submission = $this->get_group_submission($userid, 0, false);
2533                     $submissiongroup = $this->get_submission_group($userid);
2534                     if ($submissiongroup) {
2535                         $groupname = $submissiongroup->name . '-';
2536                     } else {
2537                         $groupname = get_string('defaultteam', 'assign') . '-';
2538                     }
2539                 } else {
2540                     $submission = $this->get_user_submission($userid, false);
2541                 }
2543                 if ($this->is_blind_marking()) {
2544                     $prefix = str_replace('_', ' ', $groupname . get_string('participant', 'assign'));
2545                     $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2546                 } else {
2547                     $prefix = str_replace('_', ' ', $groupname . fullname($student));
2548                     $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2549                 }
2551                 if ($submission) {
2552                     foreach ($this->submissionplugins as $plugin) {
2553                         if ($plugin->is_enabled() && $plugin->is_visible()) {
2554                             $pluginfiles = $plugin->get_files($submission, $student);
2555                             foreach ($pluginfiles as $zipfilename => $file) {
2556                                 $subtype = $plugin->get_subtype();
2557                                 $type = $plugin->get_type();
2558                                 $prefixedfilename = clean_filename($prefix .
2559                                                                    $subtype .
2560                                                                    '_' .
2561                                                                    $type .
2562                                                                    '_' .
2563                                                                    $zipfilename);
2564                                 $filesforzipping[$prefixedfilename] = $file;
2565                             }
2566                         }
2567                     }
2568                 }
2569             }
2570         }
2571         $result = '';
2572         if (count($filesforzipping) == 0) {
2573             $header = new assign_header($this->get_instance(),
2574                                         $this->get_context(),
2575                                         '',
2576                                         $this->get_course_module()->id,
2577                                         get_string('downloadall', 'assign'));
2578             $result .= $this->get_renderer()->render($header);
2579             $result .= $this->get_renderer()->notification(get_string('nosubmission', 'assign'));
2580             $url = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id,
2581                                                                     'action'=>'grading'));
2582             $result .= $this->get_renderer()->continue_button($url);
2583             $result .= $this->view_footer();
2584         } else if ($zipfile = $this->pack_files($filesforzipping)) {
2585             \mod_assign\event\all_submissions_downloaded::create_from_assign($this)->trigger();
2586             // Send file and delete after sending.
2587             send_temp_file($zipfile, $filename);
2588             // We will not get here - send_temp_file calls exit.
2589         }
2590         return $result;
2591     }
2593     /**
2594      * Util function to add a message to the log.
2595      *
2596      * @deprecated since 2.7 - Use new events system instead.
2597      *             (see http://docs.moodle.org/dev/Migrating_logging_calls_in_plugins).
2598      *
2599      * @param string $action The current action
2600      * @param string $info A detailed description of the change. But no more than 255 characters.
2601      * @param string $url The url to the assign module instance.
2602      * @param bool $return If true, returns the arguments, else adds to log. The purpose of this is to
2603      *                     retrieve the arguments to use them with the new event system (Event 2).
2604      * @return void|array
2605      */
2606     public function add_to_log($action = '', $info = '', $url='', $return = false) {
2607         global $USER;
2609         $fullurl = 'view.php?id=' . $this->get_course_module()->id;
2610         if ($url != '') {
2611             $fullurl .= '&' . $url;
2612         }
2614         $args = array(
2615             $this->get_course()->id,
2616             'assign',
2617             $action,
2618             $fullurl,
2619             $info,
2620             $this->get_course_module()->id
2621         );
2623         if ($return) {
2624             // We only need to call debugging when returning a value. This is because the call to
2625             // call_user_func_array('add_to_log', $args) will trigger a debugging message of it's own.
2626             debugging('The mod_assign add_to_log() function is now deprecated.', DEBUG_DEVELOPER);
2627             return $args;
2628         }
2629         call_user_func_array('add_to_log', $args);
2630     }
2632     /**
2633      * Lazy load the page renderer and expose the renderer to plugins.
2634      *
2635      * @return assign_renderer
2636      */
2637     public function get_renderer() {
2638         global $PAGE;
2639         if ($this->output) {
2640             return $this->output;
2641         }
2642         $this->output = $PAGE->get_renderer('mod_assign');
2643         return $this->output;
2644     }
2646     /**
2647      * Load the submission object for a particular user, optionally creating it if required.
2648      *
2649      * For team assignments there are 2 submissions - the student submission and the team submission
2650      * All files are associated with the team submission but the status of the students contribution is
2651      * recorded separately.
2652      *
2653      * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
2654      * @param bool $create optional - defaults to false. If set to true a new submission object
2655      *                     will be created in the database.
2656      * @param int $attemptnumber - -1 means the latest attempt
2657      * @return stdClass The submission
2658      */
2659     public function get_user_submission($userid, $create, $attemptnumber=-1) {
2660         global $DB, $USER;
2662         if (!$userid) {
2663             $userid = $USER->id;
2664         }
2665         // If the userid is not null then use userid.
2666         $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid, 'groupid'=>0);
2667         if ($attemptnumber >= 0) {
2668             $params['attemptnumber'] = $attemptnumber;
2669         }
2671         // Only return the row with the highest attemptnumber.
2672         $submission = null;
2673         $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
2674         if ($submissions) {
2675             $submission = reset($submissions);
2676         }
2678         if ($submission) {
2679             return $submission;
2680         }
2681         if ($create) {
2682             $submission = new stdClass();
2683             $submission->assignment   = $this->get_instance()->id;
2684             $submission->userid       = $userid;
2685             $submission->timecreated = time();
2686             $submission->timemodified = $submission->timecreated;
2687             $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
2688             if ($attemptnumber >= 0) {
2689                 $submission->attemptnumber = $attemptnumber;
2690             } else {
2691                 $submission->attemptnumber = 0;
2692             }
2693             $sid = $DB->insert_record('assign_submission', $submission);
2694             return $DB->get_record('assign_submission', array('id' => $sid));
2695         }
2696         return false;
2697     }
2699     /**
2700      * Load the submission object from it's id.
2701      *
2702      * @param int $submissionid The id of the submission we want
2703      * @return stdClass The submission
2704      */
2705     protected function get_submission($submissionid) {
2706         global $DB;
2708         $params = array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid);
2709         return $DB->get_record('assign_submission', $params, '*', MUST_EXIST);
2710     }
2712     /**
2713      * This will retrieve a user flags object from the db optionally creating it if required.
2714      * The user flags was split from the user_grades table in 2.5.
2715      *
2716      * @param int $userid The user we are getting the flags for.
2717      * @param bool $create If true the flags record will be created if it does not exist
2718      * @return stdClass The flags record
2719      */
2720     public function get_user_flags($userid, $create) {
2721         global $DB, $USER;
2723         // If the userid is not null then use userid.
2724         if (!$userid) {
2725             $userid = $USER->id;
2726         }
2728         $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
2730         $flags = $DB->get_record('assign_user_flags', $params);
2732         if ($flags) {
2733             return $flags;
2734         }
2735         if ($create) {
2736             $flags = new stdClass();
2737             $flags->assignment = $this->get_instance()->id;
2738             $flags->userid = $userid;
2739             $flags->locked = 0;
2740             $flags->extensionduedate = 0;
2741             $flags->workflowstate = '';
2742             $flags->allocatedmarker = 0;
2744             // The mailed flag can be one of 3 values: 0 is unsent, 1 is sent and 2 is do not send yet.
2745             // This is because students only want to be notified about certain types of update (grades and feedback).
2746             $flags->mailed = 2;
2748             $fid = $DB->insert_record('assign_user_flags', $flags);
2749             $flags->id = $fid;
2750             return $flags;
2751         }
2752         return false;
2753     }
2755     /**
2756      * This will retrieve a grade object from the db, optionally creating it if required.
2757      *
2758      * @param int $userid The user we are grading
2759      * @param bool $create If true the grade will be created if it does not exist
2760      * @param int $attemptnumber The attempt number to retrieve the grade for. -1 means the latest submission.
2761      * @return stdClass The grade record
2762      */
2763     public function get_user_grade($userid, $create, $attemptnumber=-1) {
2764         global $DB, $USER;
2766         // If the userid is not null then use userid.
2767         if (!$userid) {
2768             $userid = $USER->id;
2769         }
2771         $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
2772         if ($attemptnumber < 0) {
2773             // Make sure this grade matches the latest submission attempt.
2774             if ($this->get_instance()->teamsubmission) {
2775                 $submission = $this->get_group_submission($userid, 0, false);
2776             } else {
2777                 $submission = $this->get_user_submission($userid, false);
2778             }
2779             if ($submission) {
2780                 $attemptnumber = $submission->attemptnumber;
2781             }
2782         }
2784         if ($attemptnumber >= 0) {
2785             $params['attemptnumber'] = $attemptnumber;
2786         }
2788         $grades = $DB->get_records('assign_grades', $params, 'attemptnumber DESC', '*', 0, 1);
2790         if ($grades) {
2791             return reset($grades);
2792         }
2793         if ($create) {
2794             $grade = new stdClass();
2795             $grade->assignment   = $this->get_instance()->id;
2796             $grade->userid       = $userid;
2797             $grade->timecreated = time();
2798             $grade->timemodified = $grade->timecreated;
2799             $grade->grade = -1;
2800             $grade->grader = $USER->id;
2801             if ($attemptnumber >= 0) {
2802                 $grade->attemptnumber = $attemptnumber;
2803             }
2805             $gid = $DB->insert_record('assign_grades', $grade);
2806             $grade->id = $gid;
2807             return $grade;
2808         }
2809         return false;
2810     }
2812     /**
2813      * This will retrieve a grade object from the db.
2814      *
2815      * @param int $gradeid The id of the grade
2816      * @return stdClass The grade record
2817      */
2818     protected function get_grade($gradeid) {
2819         global $DB;
2821         $params = array('assignment'=>$this->get_instance()->id, 'id'=>$gradeid);
2822         return $DB->get_record('assign_grades', $params, '*', MUST_EXIST);
2823     }
2825     /**
2826      * Print the grading page for a single user submission.
2827      *
2828      * @param moodleform $mform
2829      * @return string
2830      */
2831     protected function view_single_grade_page($mform) {
2832         global $DB, $CFG;
2834         $o = '';
2835         $instance = $this->get_instance();
2837         require_once($CFG->dirroot . '/mod/assign/gradeform.php');
2839         // Need submit permission to submit an assignment.
2840         require_capability('mod/assign:grade', $this->context);
2842         $header = new assign_header($instance,
2843                                     $this->get_context(),
2844                                     false,
2845                                     $this->get_course_module()->id,
2846                                     get_string('grading', 'assign'));
2847         $o .= $this->get_renderer()->render($header);
2849         // If userid is passed - we are only grading a single student.
2850         $rownum = required_param('rownum', PARAM_INT);
2851         $useridlistid = optional_param('useridlistid', time(), PARAM_INT);
2852         $userid = optional_param('userid', 0, PARAM_INT);
2853         $attemptnumber = optional_param('attemptnumber', -1, PARAM_INT);
2855         $cache = cache::make_from_params(cache_store::MODE_SESSION, 'mod_assign', 'useridlist');
2856         if (!$userid) {
2857             if (!$useridlist = $cache->get($this->get_course_module()->id . '_' . $useridlistid)) {
2858                 $useridlist = $this->get_grading_userid_list();
2859             }
2860             $cache->set($this->get_course_module()->id . '_' . $useridlistid, $useridlist);
2861         } else {
2862             $rownum = 0;
2863             $useridlist = array($userid);
2864         }
2866         if ($rownum < 0 || $rownum > count($useridlist)) {
2867             throw new coding_exception('Row is out of bounds for the current grading table: ' . $rownum);
2868         }
2870         $last = false;
2871         $userid = $useridlist[$rownum];
2872         if ($rownum == count($useridlist) - 1) {
2873             $last = true;
2874         }
2875         $user = $DB->get_record('user', array('id' => $userid));
2876         if ($user) {
2877             $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2878             $usersummary = new assign_user_summary($user,
2879                                                    $this->get_course()->id,
2880                                                    $viewfullnames,
2881                                                    $this->is_blind_marking(),
2882                                                    $this->get_uniqueid_for_user($user->id),
2883                                                    get_extra_user_fields($this->get_context()),
2884                                                    !$this->is_active_user($userid));
2885             $o .= $this->get_renderer()->render($usersummary);
2886         }
2887         $submission = $this->get_user_submission($userid, false, $attemptnumber);
2888         $submissiongroup = null;
2889         $teamsubmission = null;
2890         $notsubmitted = array();
2891         if ($instance->teamsubmission) {
2892             $teamsubmission = $this->get_group_submission($userid, 0, false, $attemptnumber);
2893             $submissiongroup = $this->get_submission_group($userid);
2894             $groupid = 0;
2895             if ($submissiongroup) {
2896                 $groupid = $submissiongroup->id;
2897             }
2898             $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
2900         }
2902         // Get the requested grade.
2903         $grade = $this->get_user_grade($userid, false, $attemptnumber);
2904         $flags = $this->get_user_flags($userid, false);
2905         if ($this->can_view_submission($userid)) {
2906             $gradelocked = ($flags && $flags->locked) || $this->grading_disabled($userid);
2907             $extensionduedate = null;
2908             if ($flags) {
2909                 $extensionduedate = $flags->extensionduedate;
2910             }
2911             $showedit = $this->submissions_open($userid) && ($this->is_any_submission_plugin_enabled());
2912             $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2914             $submissionstatus = new assign_submission_status($instance->allowsubmissionsfromdate,
2915                                                              $instance->alwaysshowdescription,
2916                                                              $submission,
2917                                                              $instance->teamsubmission,
2918                                                              $teamsubmission,
2919                                                              $submissiongroup,
2920                                                              $notsubmitted,
2921                                                              $this->is_any_submission_plugin_enabled(),
2922                                                              $gradelocked,
2923                                                              $this->is_graded($userid),
2924                                                              $instance->duedate,
2925                                                              $instance->cutoffdate,
2926                                                              $this->get_submission_plugins(),
2927                                                              $this->get_return_action(),
2928                                                              $this->get_return_params(),
2929                                                              $this->get_course_module()->id,
2930                                                              $this->get_course()->id,
2931                                                              assign_submission_status::GRADER_VIEW,
2932                                                              $showedit,
2933                                                              false,
2934                                                              $viewfullnames,
2935                                                              $extensionduedate,
2936                                                              $this->get_context(),
2937                                                              $this->is_blind_marking(),
2938                                                              '',
2939                                                              $instance->attemptreopenmethod,
2940                                                              $instance->maxattempts);
2941             $o .= $this->get_renderer()->render($submissionstatus);
2942         }
2944         if ($grade) {
2945             $data = new stdClass();
2946             if ($grade->grade !== null && $grade->grade >= 0) {
2947                 $data->grade = format_float($grade->grade, 2);
2948             }
2949             if (!empty($flags->workflowstate)) {
2950                 $data->workflowstate = $flags->workflowstate;
2951             }
2952             if (!empty($flags->allocatedmarker)) {
2953                 $data->allocatedmarker = $flags->allocatedmarker;
2954             }
2955         } else {
2956             $data = new stdClass();
2957             $data->grade = '';
2958         }
2959         // Warning if required.
2960         $allsubmissions = $this->get_all_submissions($userid);
2962         if ($attemptnumber != -1) {
2963             $params = array('attemptnumber'=>$attemptnumber + 1,
2964                             'totalattempts'=>count($allsubmissions));
2965             $message = get_string('editingpreviousfeedbackwarning', 'assign', $params);
2966             $o .= $this->get_renderer()->notification($message);
2967         }
2969         // Now show the grading form.
2970         if (!$mform) {
2971             $pagination = array('rownum'=>$rownum,
2972                                 'useridlistid'=>$useridlistid,
2973                                 'last'=>$last,
2974                                 'userid'=>optional_param('userid', 0, PARAM_INT),
2975                                 'attemptnumber'=>$attemptnumber);
2976             $formparams = array($this, $data, $pagination);
2977             $mform = new mod_assign_grade_form(null,
2978                                                $formparams,
2979                                                'post',
2980                                                '',
2981                                                array('class'=>'gradeform'));
2982         }
2983         $o .= $this->get_renderer()->heading(get_string('grade'), 3);
2984         $o .= $this->get_renderer()->render(new assign_form('gradingform', $mform));
2986         if (count($allsubmissions) > 1 && $attemptnumber == -1) {
2987             $allgrades = $this->get_all_grades($userid);
2988             $history = new assign_attempt_history($allsubmissions,
2989                                                   $allgrades,
2990                                                   $this->get_submission_plugins(),
2991                                                   $this->get_feedback_plugins(),
2992                                                   $this->get_course_module()->id,
2993                                                   $this->get_return_action(),
2994                                                   $this->get_return_params(),
2995                                                   true,
2996                                                   $useridlistid,
2997                                                   $rownum);
2999             $o .= $this->get_renderer()->render($history);
3000         }
3002         \mod_assign\event\grading_form_viewed::create_from_user($this, $user)->trigger();
3004         $o .= $this->view_footer();
3005         return $o;
3006     }
3008     /**
3009      * Show a confirmation page to make sure they want to release student identities.
3010      *
3011      * @return string
3012      */
3013     protected function view_reveal_identities_confirm() {
3014         require_capability('mod/assign:revealidentities', $this->get_context());
3016         $o = '';
3017         $header = new assign_header($this->get_instance(),
3018                                     $this->get_context(),
3019                                     false,
3020                                     $this->get_course_module()->id);
3021         $o .= $this->get_renderer()->render($header);
3023         $urlparams = array('id'=>$this->get_course_module()->id,
3024                            'action'=>'revealidentitiesconfirm',
3025                            'sesskey'=>sesskey());
3026         $confirmurl = new moodle_url('/mod/assign/view.php', $urlparams);
3028         $urlparams = array('id'=>$this->get_course_module()->id,
3029                            'action'=>'grading');
3030         $cancelurl = new moodle_url('/mod/assign/view.php', $urlparams);
3032         $o .= $this->get_renderer()->confirm(get_string('revealidentitiesconfirm', 'assign'),
3033                                              $confirmurl,
3034                                              $cancelurl);
3035         $o .= $this->view_footer();
3037         \mod_assign\event\reveal_identities_confirmation_page_viewed::create_from_assign($this)->trigger();
3039         return $o;
3040     }
3042     /**
3043      * View a link to go back to the previous page. Uses url parameters returnaction and returnparams.
3044      *
3045      * @return string
3046      */
3047     protected function view_return_links() {
3048         $returnaction = optional_param('returnaction', '', PARAM_ALPHA);
3049         $returnparams = optional_param('returnparams', '', PARAM_TEXT);
3051         $params = array();
3052         $returnparams = str_replace('&amp;', '&', $returnparams);
3053         parse_str($returnparams, $params);
3054         $newparams = array('id' => $this->get_course_module()->id, 'action' => $returnaction);
3055         $params = array_merge($newparams, $params);
3057         $url = new moodle_url('/mod/assign/view.php', $params);
3058         return $this->get_renderer()->single_button($url, get_string('back'), 'get');
3059     }
3061     /**
3062      * View the grading table of all submissions for this assignment.
3063      *
3064      * @return string
3065      */
3066     protected function view_grading_table() {
3067         global $USER, $CFG;
3069         // Include grading options form.
3070         require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
3071         require_once($CFG->dirroot . '/mod/assign/quickgradingform.php');
3072         require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
3073         $o = '';
3074         $cmid = $this->get_course_module()->id;
3076         $links = array();
3077         if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
3078                 has_capability('moodle/grade:viewall', $this->get_course_context())) {
3079             $gradebookurl = '/grade/report/grader/index.php?id=' . $this->get_course()->id;
3080             $links[$gradebookurl] = get_string('viewgradebook', 'assign');
3081         }
3082         if ($this->is_any_submission_plugin_enabled() && $this->count_submissions()) {
3083             $downloadurl = '/mod/assign/view.php?id=' . $cmid . '&action=downloadall';
3084             $links[$downloadurl] = get_string('downloadall', 'assign');
3085         }
3086         if ($this->is_blind_marking() &&
3087                 has_capability('mod/assign:revealidentities', $this->get_context())) {
3088             $revealidentitiesurl = '/mod/assign/view.php?id=' . $cmid . '&action=revealidentities';
3089             $links[$revealidentitiesurl] = get_string('revealidentities', 'assign');
3090         }
3091         foreach ($this->get_feedback_plugins() as $plugin) {
3092             if ($plugin->is_enabled() && $plugin->is_visible()) {
3093                 foreach ($plugin->get_grading_actions() as $action => $description) {
3094                     $url = '/mod/assign/view.php' .
3095                            '?id=' .  $cmid .
3096                            '&plugin=' . $plugin->get_type() .
3097                            '&pluginsubtype=assignfeedback' .
3098                            '&action=viewpluginpage&pluginaction=' . $action;
3099                     $links[$url] = $description;
3100                 }
3101             }
3102         }
3104         // Sort links alphabetically based on the link description.
3105         core_collator::asort($links);
3107         $gradingactions = new url_select($links);
3108         $gradingactions->set_label(get_string('choosegradingaction', 'assign'));
3110         $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
3112         $perpage = get_user_preferences('assign_perpage', 10);
3113         $filter = get_user_preferences('assign_filter', '');
3114         $markerfilter = get_user_preferences('assign_markerfilter', '');
3115         $workflowfilter = get_user_preferences('assign_workflowfilter', '');
3116         $controller = $gradingmanager->get_active_controller();
3117         $showquickgrading = empty($controller) && $this->can_grade();
3118         $quickgrading = get_user_preferences('assign_quickgrading', false);
3119         $showonlyactiveenrolopt = has_capability('moodle/course:viewsuspendedusers', $this->context);
3121         $markingallocation = $this->get_instance()->markingworkflow &&
3122             $this->get_instance()->markingallocation &&
3123             has_capability('mod/assign:manageallocations', $this->context);
3124         // Get markers to use in drop lists.
3125         $markingallocationoptions = array();
3126         if ($markingallocation) {
3127             $markers = get_users_by_capability($this->context, 'mod/assign:grade');
3128             $markingallocationoptions[''] = get_string('filternone', 'assign');
3129             $markingallocationoptions[ASSIGN_MARKER_FILTER_NO_MARKER] = get_string('markerfilternomarker', 'assign');
3130             foreach ($markers as $marker) {
3131                 $markingallocationoptions[$marker->id] = fullname($marker);
3132             }
3133         }
3135         $markingworkflow = $this->get_instance()->markingworkflow;
3136         // Get marking states to show in form.
3137         $markingworkflowoptions = array();
3138         if ($markingworkflow) {
3139             $notmarked = get_string('markingworkflowstatenotmarked', 'assign');
3140             $markingworkflowoptions[''] = get_string('filternone', 'assign');
3141             $markingworkflowoptions[ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED] = $notmarked;
3142             $markingworkflowoptions = array_merge($markingworkflowoptions, $this->get_marking_workflow_states_for_current_user());
3143         }
3145         // Print options for changing the filter and changing the number of results per page.
3146         $gradingoptionsformparams = array('cm'=>$cmid,
3147                                           'contextid'=>$this->context->id,
3148                                           'userid'=>$USER->id,
3149                                           'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
3150                                           'showquickgrading'=>$showquickgrading,
3151                                           'quickgrading'=>$quickgrading,
3152                                           'markingworkflowopt'=>$markingworkflowoptions,
3153                                           'markingallocationopt'=>$markingallocationoptions,
3154                                           'showonlyactiveenrolopt'=>$showonlyactiveenrolopt,
3155                                           'showonlyactiveenrol'=>$this->show_only_active_users());
3157         $classoptions = array('class'=>'gradingoptionsform');
3158         $gradingoptionsform = new mod_assign_grading_options_form(null,
3159                                                                   $gradingoptionsformparams,
3160                                                                   'post',
3161                                                                   '',
3162                                                                   $classoptions);
3164         $batchformparams = array('cm'=>$cmid,
3165                                  'submissiondrafts'=>$this->get_instance()->submissiondrafts,
3166                                  'duedate'=>$this->get_instance()->duedate,
3167                                  'attemptreopenmethod'=>$this->get_instance()->attemptreopenmethod,
3168                                  'feedbackplugins'=>$this->get_feedback_plugins(),
3169                                  'context'=>$this->get_context(),
3170                                  'markingworkflow'=>$markingworkflow,
3171                                  'markingallocation'=>$markingallocation);
3172         $classoptions = array('class'=>'gradingbatchoperationsform');
3174         $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
3175                                                                                    $batchformparams,
3176                                                                                    'post',
3177                                                                                    '',
3178                                                                                    $classoptions);
3180         $gradingoptionsdata = new stdClass();
3181         $gradingoptionsdata->perpage = $perpage;
3182         $gradingoptionsdata->filter = $filter;
3183         $gradingoptionsdata->markerfilter = $markerfilter;
3184         $gradingoptionsdata->workflowfilter = $workflowfilter;
3185         $gradingoptionsform->set_data($gradingoptionsdata);
3187         $actionformtext = $this->get_renderer()->render($gradingactions);
3188         $header = new assign_header($this->get_instance(),
3189                                     $this->get_context(),
3190                                     false,
3191                                     $this->get_course_module()->id,
3192                                     get_string('grading', 'assign'),
3193                                     $actionformtext);
3194         $o .= $this->get_renderer()->render($header);
3196         $currenturl = $CFG->wwwroot .
3197                       '/mod/assign/view.php?id=' .
3198                       $this->get_course_module()->id .
3199                       '&action=grading';
3201         $o .= groups_print_activity_menu($this->get_course_module(), $currenturl, true);
3203         // Plagiarism update status apearring in the grading book.
3204         if (!empty($CFG->enableplagiarism)) {
3205             require_once($CFG->libdir . '/plagiarismlib.php');
3206             $o .= plagiarism_update_status($this->get_course(), $this->get_course_module());
3207         }
3209         // Load and print the table of submissions.
3210         if ($showquickgrading && $quickgrading) {
3211             $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, true);
3212             $table = $this->get_renderer()->render($gradingtable);
3213             $page = optional_param('page', null, PARAM_INT);
3214             $quickformparams = array('cm'=>$this->get_course_module()->id,
3215                                      'gradingtable'=>$table,
3216                                      'sendstudentnotifications' => $this->get_instance()->sendstudentnotifications,
3217                                      'page' => $page);
3218             $quickgradingform = new mod_assign_quick_grading_form(null, $quickformparams);
3220             $o .= $this->get_renderer()->render(new assign_form('quickgradingform', $quickgradingform));
3221         } else {
3222             $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, false);
3223             $o .= $this->get_renderer()->render($gradingtable);
3224         }
3226         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
3227         $users = array_keys($this->list_participants($currentgroup, true));
3228         if (count($users) != 0 && $this->can_grade()) {
3229             // If no enrolled user in a course then don't display the batch operations feature.
3230             $assignform = new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform);
3231             $o .= $this->get_renderer()->render($assignform);
3232         }
3233         $assignform = new assign_form('gradingoptionsform',
3234                                       $gradingoptionsform,
3235                                       'M.mod_assign.init_grading_options');
3236         $o .= $this->get_renderer()->render($assignform);
3237         return $o;
3238     }
3240     /**
3241      * View entire grading page.
3242      *
3243      * @return string
3244      */
3245     protected function view_grading_page() {
3246         global $CFG;
3248         $o = '';
3249         // Need submit permission to submit an assignment.
3250         $this->require_view_grades();
3251         require_once($CFG->dirroot . '/mod/assign/gradeform.php');
3253         // Only load this if it is.
3255         $o .= $this->view_grading_table();
3257         $o .= $this->view_footer();
3259         \mod_assign\event\grading_table_viewed::create_from_assign($this)->trigger();
3261         return $o;
3262     }
3264     /**
3265      * Capture the output of the plagiarism plugins disclosures and return it as a string.
3266      *
3267      * @return string
3268      */
3269     protected function plagiarism_print_disclosure() {
3270         global $CFG;
3271         $o = '';
3273         if (!empty($CFG->enableplagiarism)) {
3274             require_once($CFG->libdir . '/plagiarismlib.php');
3276             $o .= plagiarism_print_disclosure($this->get_course_module()->id);
3277         }
3279         return $o;
3280     }
3282     /**
3283      * Message for students when assignment submissions have been closed.
3284      *
3285      * @param string $title The page title
3286      * @param array $notices The array of notices to show.
3287      * @return string
3288      */
3289     protected function view_notices($title, $notices) {
3290         global $CFG;
3292         $o = '';
3294         $header = new assign_header($this->get_instance(),
3295                                     $this->get_context(),
3296                                     $this->show_intro(),
3297                                     $this->get_course_module()->id,
3298                                     $title);
3299         $o .= $this->get_renderer()->render($header);
3301         foreach ($notices as $notice) {
3302             $o .= $this->get_renderer()->notification($notice);
3303         }
3305         $url = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id, 'action'=>'view'));
3306         $o .= $this->get_renderer()->continue_button($url);
3308         $o .= $this->view_footer();
3310         return $o;
3311     }
3313     /**
3314      * Get the name for a user - hiding their real name if blind marking is on.
3315      *
3316      * @param stdClass $user The user record as required by fullname()
3317      * @return string The name.
3318      */
3319     public function fullname($user) {
3320         if ($this->is_blind_marking()) {
3321             $hasviewblind = has_capability('mod/assign:viewblinddetails', $this->get_context());
3322             if ($hasviewblind) {
3323                 return fullname($user);
3324             } else {
3325                 $uniqueid = $this->get_uniqueid_for_user($user->id);
3326                 return get_string('participant', 'assign') . ' ' . $uniqueid;
3327             }
3328         } else {
3329             return fullname($user);
3330         }
3331     }
3333     /**
3334      * View edit submissions page.
3335      *
3336      * @param moodleform $mform
3337      * @param array $notices A list of notices to display at the top of the
3338      *                       edit submission form (e.g. from plugins).
3339      * @return string The page output.
3340      */
3341     protected function view_edit_submission_page($mform, $notices) {
3342         global $CFG, $USER, $DB;
3344         $o = '';
3345         require_once($CFG->dirroot . '/mod/assign/submission_form.php');
3346         // Need submit permission to submit an assignment.
3347         $userid = optional_param('userid', $USER->id, PARAM_INT);
3348         $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
3349         if ($userid == $USER->id) {
3350             // User is editing their own submission.
3351             require_capability('mod/assign:submit', $this->context);
3352             $title = get_string('editsubmission', 'assign');
3353         } else {
3354             // User is editing another user's submission.
3355             if (!$this->can_edit_submission($userid, $USER->id)) {
3356                 print_error('nopermission');
3357             }
3359             $name = $this->fullname($user);
3360             $title = get_string('editsubmissionother', 'assign', $name);
3361         }
3363         if (!$this->submissions_open($userid)) {
3364             $message = array(get_string('submissionsclosed', 'assign'));
3365             return $this->view_notices($title, $message);
3366         }
3368         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
3369                                                       $this->get_context(),
3370                                                       $this->show_intro(),
3371                                                       $this->get_course_module()->id,
3372                                                       $title));
3373         if ($userid == $USER->id) {
3374             // We only show this if it their submission.
3375             $o .= $this->plagiarism_print_disclosure();
3376         }
3377         $data = new stdClass();
3378         $data->userid = $userid;
3379         if (!$mform) {
3380             $mform = new mod_assign_submission_form(null, array($this, $data));
3381         }
3383         foreach ($notices as $notice) {
3384             $o .= $this->get_renderer()->notification($notice);
3385         }
3387         $o .= $this->get_renderer()->render(new assign_form('editsubmissionform', $mform));
3389         $o .= $this->view_footer();
3391         \mod_assign\event\submission_form_viewed::create_from_user($this, $user)->trigger();
3393         return $o;
3394     }
3396     /**
3397      * See if this assignment has a grade yet.
3398      *
3399      * @param int $userid
3400      * @return bool
3401      */
3402     protected function is_graded($userid) {
3403         $grade = $this->get_user_grade($userid, false);
3404         if ($grade) {
3405             return ($grade->grade !== null && $grade->grade >= 0);
3406         }
3407         return false;
3408     }
3410     /**
3411      * Perform an access check to see if the current $USER can view this group submission.
3412      *
3413      * @param int $groupid
3414      * @return bool
3415      */
3416     public function can_view_group_submission($groupid) {
3417         global $USER;
3419         if (has_capability('mod/assign:grade', $this->context)) {
3420             return true;
3421         }
3422         if (!is_enrolled($this->get_course_context(), $USER->id)) {
3423             return false;
3424         }
3425         $members = $this->get_submission_group_members($groupid, true);
3426         foreach ($members as $member) {
3427             if ($member->id == $USER->id) {
3428                 return true;
3429             }
3430         }
3431         return false;
3432     }
3434     /**
3435      * Perform an access check to see if the current $USER can view this users submission.
3436      *
3437      * @param int $userid
3438      * @return bool
3439      */
3440     public function can_view_submission($userid) {
3441         global $USER;
3443         if (!$this->is_active_user($userid) && !has_capability('moodle/course:viewsuspendedusers', $this->context)) {
3444             return false;
3445         }
3446         if (has_any_capability(array('mod/assign:viewgrades', 'mod/assign:grade'), $this->context)) {
3447             return true;
3448         }
3449         if (!is_enrolled($this->get_course_context(), $userid)) {
3450             return false;
3451         }
3452         if ($userid == $USER->id && has_capability('mod/assign:submit', $this->context)) {
3453             return true;
3454         }
3455         return false;
3456     }
3458     /**
3459      * Allows the plugin to show a batch grading operation page.
3460      *
3461      * @param moodleform $mform
3462      * @return none
3463      */
3464     protected function view_plugin_grading_batch_operation($mform) {
3465         require_capability('mod/assign:grade', $this->context);
3466         $prefix = 'plugingradingbatchoperation_';
3468         if ($data = $mform->get_data()) {
3469             $tail = substr($data->operation, strlen($prefix));
3470             list($plugintype, $action) = explode('_', $tail, 2);
3472             $plugin = $this->get_feedback_plugin_by_type($plugintype);
3473             if ($plugin) {
3474                 $users = $data->selectedusers;
3475                 $userlist = explode(',', $users);
3476                 echo $plugin->grading_batch_operation($action, $userlist);
3477                 return;
3478             }
3479         }
3480         print_error('invalidformdata', '');
3481     }
3483     /**
3484      * Ask the user to confirm they want to perform this batch operation
3485      *
3486      * @param moodleform $mform Set to a grading batch operations form
3487      * @return string - the page to view after processing these actions
3488      */
3489     protected function process_grading_batch_operation(& $mform) {
3490         global $CFG;
3491         require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
3492         require_sesskey();
3494         $markingallocation = $this->get_instance()->markingworkflow &&
3495             $this->get_instance()->markingallocation &&
3496             has_capability('mod/assign:manageallocations', $this->context);
3498         $batchformparams = array('cm'=>$this->get_course_module()->id,
3499                                  'submissiondrafts'=>$this->get_instance()->submissiondrafts,
3500                                  'duedate'=>$this->get_instance()->duedate,
3501                                  'attemptreopenmethod'=>$this->get_instance()->attemptreopenmethod,
3502                                  'feedbackplugins'=>$this->get_feedback_plugins(),
3503                                  'context'=>$this->get_context(),
3504                                  'markingworkflow'=>$this->get_instance()->markingworkflow,
3505                                  'markingallocation'=>$markingallocation);
3506         $formclasses = array('class'=>'gradingbatchoperationsform');
3507         $mform = new mod_assign_grading_batch_operations_form(null,
3508                                                               $batchformparams,
3509                                                               'post',
3510                                                               '',
3511                                                               $formclasses);
3513         if ($data = $mform->get_data()) {
3514             // Get the list of users.
3515             $users = $data->selectedusers;
3516             $userlist = explode(',', $users);
3518             $prefix = 'plugingradingbatchoperation_';
3520             if ($data->operation == 'grantextension') {
3521                 // Reset the form so the grant extension page will create the extension form.
3522                 $mform = null;
3523                 return 'grantextension';
3524             } else if ($data->operation == 'setmarkingworkflowstate') {
3525                 return 'viewbatchsetmarkingworkflowstate';
3526             } else if ($data->operation == 'setmarkingallocation') {
3527                 return 'viewbatchmarkingallocation';
3528             } else if (strpos($data->operation, $prefix) === 0) {
3529                 $tail = substr($data->operation, strlen($prefix));
3530                 list($plugintype, $action) = explode('_', $tail, 2);
3532                 $plugin = $this->get_feedback_plugin_by_type($plugintype);
3533                 if ($plugin) {
3534                     return 'plugingradingbatchoperation';
3535                 }
3536             }
3538             foreach ($userlist as $userid) {
3539                 if ($data->operation == 'lock') {
3540                     $this->process_lock_submission($userid);
3541                 } else if ($data->operation == 'unlock') {
3542                     $this->process_unlock_submission($userid);
3543                 } else if ($data->operation == 'reverttodraft') {
3544                     $this->process_revert_to_draft($userid);
3545                 } else if ($data->operation == 'addattempt') {
3546                     if (!$this->get_instance()->teamsubmission) {
3547                         $this->process_add_attempt($userid);
3548                     }
3549                 }
3550             }
3551             if ($this->get_instance()->teamsubmission && $data->operation == 'addattempt') {
3552                 // This needs to be handled separately so that each team submission is only re-opened one time.
3553                 $this->process_add_attempt_group($userlist);
3554             }
3555         }
3557         return 'grading';
3558     }
3560     /**
3561      * Shows a form that allows the workflow state for selected submissions to be changed.
3562      *
3563      * @param moodleform $mform Set to a grading batch operations form
3564      * @return string - the page to view after processing these actions
3565      */
3566     protected function view_batch_set_workflow_state($mform) {
3567         global $CFG, $DB;
3569         require_once($CFG->dirroot . '/mod/assign/batchsetmarkingworkflowstateform.php');
3571         $o = '';
3573         $submitteddata = $mform->get_data();
3574         $users = $submitteddata->selectedusers;
3575         $userlist = explode(',', $users);
3577         $formdata = array('id' => $this->get_course_module()->id,
3578                           'selectedusers' => $users);
3580         $usershtml = '';
3582         $usercount = 0;
3583         $extrauserfields = get_extra_user_fields($this->get_context());
3584         foreach ($userlist as $userid) {
3585             if ($usercount >= 5) {
3586                 $usershtml .= get_string('moreusers', 'assign', count($userlist) - 5);
3587                 break;
3588             }
3589             $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
3591             $usershtml .= $this->get_renderer()->render(new assign_user_summary($user,
3592                                                                 $this->get_course()->id,
3593                                                                 has_capability('moodle/site:viewfullnames',
3594                                                                 $this->get_course_context()),
3595                                                                 $this->is_blind_marking(),
3596                                                                 $this->get_uniqueid_for_user($user->id),
3597                                                                 $extrauserfields,
3598                                                                 !$this->is_active_user($userid)));
3599             $usercount += 1;
3600         }
3602         $formparams = array(
3603             'userscount' => count($userlist),
3604             'usershtml' => $usershtml,
3605             'markingworkflowstates' => $this->get_marking_workflow_states_for_current_user()
3606         );
3608         $mform = new mod_assign_batch_set_marking_workflow_state_form(null, $formparams);
3609         $mform->set_data($formdata);    // Initialises the hidden elements.
3610         $o .= $this->get_renderer()->header();
3611         $o .= $this->get_renderer()->render(new assign_form('setworkflowstate', $mform));
3612         $o .= $this->view_footer();
3614         \mod_assign\event\batch_set_workflow_state_viewed::create_from_assign($this)->trigger();
3616         return $o;
3617     }
3619     /**
3620      * Shows a form that allows the allocated marker for selected submissions to be changed.
3621      *
3622      * @param moodleform $mform Set to a grading batch operations form
3623      * @return string - the page to view after processing these actions
3624      */
3625     public function view_batch_markingallocation($mform) {
3626         global $CFG, $DB;
3628         require_once($CFG->dirroot . '/mod/assign/batchsetallocatedmarkerform.php');
3630         $o = '';
3632         $submitteddata = $mform->get_data();
3633         $users = $submitteddata->selectedusers;
3634         $userlist = explode(',', $users);
3636         $formdata = array('id' => $this->get_course_module()->id,
3637                           'selectedusers' => $users);
3639         $usershtml = '';
3641         $usercount = 0;
3642         $extrauserfields = get_extra_user_fields($this->get_context());
3643         foreach ($userlist as $userid) {
3644             if ($usercount >= 5) {
3645                 $usershtml .= get_string('moreusers', 'assign', count($userlist) - 5);
3646                 break;
3647             }
3648             $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
3650             $usershtml .= $this->get_renderer()->render(new assign_user_summary($user,
3651                 $this->get_course()->id,
3652                 has_capability('moodle/site:viewfullnames',
3653                 $this->get_course_context()),
3654                 $this->is_blind_marking(),
3655                 $this->get_uniqueid_for_user($user->id),
3656                 $extrauserfields,
3657                 !$this->is_active_user($userid)));
3658             $usercount += 1;
3659         }
3661         $formparams = array(
3662             'userscount' => count($userlist),
3663             'usershtml' => $usershtml,
3664         );
3666         $markers = get_users_by_capability($this->get_context(), 'mod/assign:grade');
3667         $markerlist = array();
3668         foreach ($markers as $marker) {
3669             $markerlist[$marker->id] = fullname($marker);
3670         }
3672         $formparams['markers'] = $markerlist;
3674         $mform = new mod_assign_batch_set_allocatedmarker_form(null, $formparams);
3675         $mform->set_data($formdata);    // Initialises the hidden elements.
3676         $o .= $this->get_renderer()->header();
3677         $o .= $this->get_renderer()->render(new assign_form('setworkflowstate', $mform));
3678         $o .= $this->view_footer();
3680         \mod_assign\event\batch_set_marker_allocation_viewed::create_from_assign($this)->trigger();
3682         return $o;
3683     }
3685     /**
3686      * Ask the user to confirm they want to submit their work for grading.
3687      *
3688      * @param moodleform $mform - null unless form validation has failed
3689      * @return string
3690      */
3691     protected function check_submit_for_grading($mform) {
3692         global $USER, $CFG;
3694         require_once($CFG->dirroot . '/mod/assign/submissionconfirmform.php');
3696         // Check that all of the submission plugins are ready for this submission.
3697         $notifications = array();
3698         $submission = $this->get_user_submission($USER->id, false);
3699         $plugins = $this->get_submission_plugins();
3700         foreach ($plugins as $plugin) {
3701             if ($plugin->is_enabled() && $plugin->is_visible()) {
3702                 $check = $plugin->precheck_submission($submission);
3703                 if ($check !== true) {
3704                     $notifications[] = $check;
3705                 }
3706             }
3707         }
3709         $data = new stdClass();
3710         $adminconfig = $this->get_admin_config();
3711         $requiresubmissionstatement = $this->get_instance()->requiresubmissionstatement &&
3712                                        !empty($adminconfig->submissionstatement);
3714         $submissionstatement = '';
3715         if (!empty($adminconfig->submissionstatement)) {
3716             $submissionstatement = $adminconfig->submissionstatement;
3717         }
3719         if ($mform == null) {
3720             $mform = new mod_assign_confirm_submission_form(null, array($requiresubmissionstatement,
3721                                                                         $submissionstatement,
3722                                                                         $this->get_course_module()->id,
3723                                                                         $data));
3724         }
3725         $o = '';
3726         $o .= $this->get_renderer()->header();
3727         $submitforgradingpage = new assign_submit_for_grading_page($notifications,
3728                                                                    $this->get_course_module()->id,
3729                                                                    $mform);
3730         $o .= $this->get_renderer()->render($submitforgradingpage);
3731         $o .= $this->view_footer();
3733         \mod_assign\event\submission_confirmation_form_viewed::create_from_assign($this)->trigger();
3735         return $o;
3736     }
3738     /**
3739      * Print 2 tables of information with no action links -
3740      * the submission summary and the grading summary.
3741      *
3742      * @param stdClass $user the user to print the report for
3743      * @param bool $showlinks - Return plain text or links to the profile
3744      * @return string - the html summary
3745      */
3746     public function view_student_summary($user, $showlinks) {
3747         global $CFG, $DB, $PAGE;
3749         $instance = $this->get_instance();
3750         $grade = $this->get_user_grade($user->id, false);
3751         $flags = $this->get_user_flags($user->id, false);
3752         $submission = $this->get_user_submission($user->id, false);
3753         $o = '';
3755         $teamsubmission = null;
3756         $submissiongroup = null;
3757         $notsubmitted = array();
3758         if ($instance->teamsubmission) {
3759             $teamsubmission = $this->get_group_submission($user->id, 0, false);
3760             $submissiongroup = $this->get_submission_group($user->id);
3761             $groupid = 0;
3762             if ($submissiongroup) {
3763                 $groupid = $submissiongroup->id;
3764             }
3765             $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
3766         }
3768         if ($this->can_view_submission($user->id)) {
3769             $showedit = $showlinks &&
3770                         ($this->is_any_submission_plugin_enabled()) &&
3771                         $this->can_edit_submission($user->id);
3773             $gradelocked = ($flags && $flags->locked) || $this->grading_disabled($user->id, false);
3775             // Grading criteria preview.
3776             $gradingmanager = get_grading_manager($this->context, 'mod_assign', 'submissions');
3777             $gradingcontrollerpreview = '';
3778             if ($gradingmethod = $gradingmanager->get_active_method()) {
3779                 $controller = $gradingmanager->get_controller($gradingmethod);
3780                 if ($controller->is_form_defined()) {
3781                     $gradingcontrollerpreview = $controller->render_preview($PAGE);
3782                 }
3783