MDL-41101 mod_assign: replaced 'grade submission' add_to_log call with an event
[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 require_once($CFG->libdir . '/accesslib.php');
60 require_once($CFG->libdir . '/formslib.php');
61 require_once($CFG->dirroot . '/repository/lib.php');
62 require_once($CFG->dirroot . '/mod/assign/mod_form.php');
63 require_once($CFG->libdir . '/gradelib.php');
64 require_once($CFG->dirroot . '/grade/grading/lib.php');
65 require_once($CFG->dirroot . '/mod/assign/feedbackplugin.php');
66 require_once($CFG->dirroot . '/mod/assign/submissionplugin.php');
67 require_once($CFG->dirroot . '/mod/assign/renderable.php');
68 require_once($CFG->dirroot . '/mod/assign/gradingtable.php');
69 require_once($CFG->libdir . '/eventslib.php');
70 require_once($CFG->libdir . '/portfolio/caller.php');
72 /**
73  * Standard base class for mod_assign (assignment types).
74  *
75  * @package   mod_assign
76  * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
77  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
78  */
79 class assign {
81     /** @var stdClass the assignment record that contains the global settings for this assign instance */
82     private $instance;
84     /** @var stdClass the grade_item record for this assign instance's primary grade item. */
85     private $gradeitem;
87     /** @var context the context of the course module for this assign instance
88      *               (or just the course if we are creating a new one)
89      */
90     private $context;
92     /** @var stdClass the course this assign instance belongs to */
93     private $course;
95     /** @var stdClass the admin config for all assign instances  */
96     private $adminconfig;
98     /** @var assign_renderer the custom renderer for this module */
99     private $output;
101     /** @var stdClass the course module for this assign instance */
102     private $coursemodule;
104     /** @var array cache for things like the coursemodule name or the scale menu -
105      *             only lives for a single request.
106      */
107     private $cache;
109     /** @var array list of the installed submission plugins */
110     private $submissionplugins;
112     /** @var array list of the installed feedback plugins */
113     private $feedbackplugins;
115     /** @var string action to be used to return to this page
116      *              (without repeating any form submissions etc).
117      */
118     private $returnaction = 'view';
120     /** @var array params to be used to return to this page */
121     private $returnparams = array();
123     /** @var string modulename prevents excessive calls to get_string */
124     private static $modulename = null;
126     /** @var string modulenameplural prevents excessive calls to get_string */
127     private static $modulenameplural = null;
129     /** @var array of marking workflow states for the current user */
130     private $markingworkflowstates = null;
132     /** @var bool whether to exclude users with inactive enrolment */
133     private $showonlyactiveenrol = null;
135     /** @var array list of suspended user IDs in form of ([id1] => id1) */
136     public $susers = 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      * @param mixed $coursemodulecontext context|null the course module context
145      *                                   (or the course context if the coursemodule has not been
146      *                                   created yet).
147      * @param mixed $coursemodule the current course module if it was already loaded,
148      *                            otherwise this class will load one from the context as required.
149      * @param mixed $course the current course  if it was already loaded,
150      *                      otherwise this class will load one from the context as required.
151      */
152     public function __construct($coursemodulecontext, $coursemodule, $course) {
153         $this->context = $coursemodulecontext;
154         $this->coursemodule = $coursemodule;
155         $this->course = $course;
157         // Temporary cache only lives for a single request - used to reduce db lookups.
158         $this->cache = array();
160         $this->submissionplugins = $this->load_plugins('assignsubmission');
161         $this->feedbackplugins = $this->load_plugins('assignfeedback');
162     }
164     /**
165      * Set the action and parameters that can be used to return to the current page.
166      *
167      * @param string $action The action for the current page
168      * @param array $params An array of name value pairs which form the parameters
169      *                      to return to the current page.
170      * @return void
171      */
172     public function register_return_link($action, $params) {
173         global $PAGE;
174         $params['action'] = $action;
175         $currenturl = $PAGE->url;
177         $currenturl->params($params);
178         $PAGE->set_url($currenturl);
179     }
181     /**
182      * Return an action that can be used to get back to the current page.
183      *
184      * @return string action
185      */
186     public function get_return_action() {
187         global $PAGE;
189         $params = $PAGE->url->params();
191         if (!empty($params['action'])) {
192             return $params['action'];
193         }
194         return '';
195     }
197     /**
198      * Based on the current assignment settings should we display the intro.
199      *
200      * @return bool showintro
201      */
202     protected function show_intro() {
203         if ($this->get_instance()->alwaysshowdescription ||
204                 time() > $this->get_instance()->allowsubmissionsfromdate) {
205             return true;
206         }
207         return false;
208     }
210     /**
211      * Return a list of parameters that can be used to get back to the current page.
212      *
213      * @return array params
214      */
215     public function get_return_params() {
216         global $PAGE;
218         $params = $PAGE->url->params();
219         unset($params['id']);
220         unset($params['action']);
221         return $params;
222     }
224     /**
225      * Set the submitted form data.
226      *
227      * @param stdClass $data The form data (instance)
228      */
229     public function set_instance(stdClass $data) {
230         $this->instance = $data;
231     }
233     /**
234      * Set the context.
235      *
236      * @param context $context The new context
237      */
238     public function set_context(context $context) {
239         $this->context = $context;
240     }
242     /**
243      * Set the course data.
244      *
245      * @param stdClass $course The course data
246      */
247     public function set_course(stdClass $course) {
248         $this->course = $course;
249     }
251     /**
252      * Get list of feedback plugins installed.
253      *
254      * @return array
255      */
256     public function get_feedback_plugins() {
257         return $this->feedbackplugins;
258     }
260     /**
261      * Get list of submission plugins installed.
262      *
263      * @return array
264      */
265     public function get_submission_plugins() {
266         return $this->submissionplugins;
267     }
269     /**
270      * Is blind marking enabled and reveal identities not set yet?
271      *
272      * @return bool
273      */
274     public function is_blind_marking() {
275         return $this->get_instance()->blindmarking && !$this->get_instance()->revealidentities;
276     }
278     /**
279      * Does an assignment have submission(s) or grade(s) already?
280      *
281      * @return bool
282      */
283     public function has_submissions_or_grades() {
284         $allgrades = $this->count_grades();
285         $allsubmissions = $this->count_submissions();
286         if (($allgrades == 0) && ($allsubmissions == 0)) {
287             return false;
288         }
289         return true;
290     }
292     /**
293      * Get a specific submission plugin by its type.
294      *
295      * @param string $subtype assignsubmission | assignfeedback
296      * @param string $type
297      * @return mixed assign_plugin|null
298      */
299     public function get_plugin_by_type($subtype, $type) {
300         $shortsubtype = substr($subtype, strlen('assign'));
301         $name = $shortsubtype . 'plugins';
302         if ($name != 'feedbackplugins' && $name != 'submissionplugins') {
303             return null;
304         }
305         $pluginlist = $this->$name;
306         foreach ($pluginlist as $plugin) {
307             if ($plugin->get_type() == $type) {
308                 return $plugin;
309             }
310         }
311         return null;
312     }
314     /**
315      * Get a feedback plugin by type.
316      *
317      * @param string $type - The type of plugin e.g comments
318      * @return mixed assign_feedback_plugin|null
319      */
320     public function get_feedback_plugin_by_type($type) {
321         return $this->get_plugin_by_type('assignfeedback', $type);
322     }
324     /**
325      * Get a submission plugin by type.
326      *
327      * @param string $type - The type of plugin e.g comments
328      * @return mixed assign_submission_plugin|null
329      */
330     public function get_submission_plugin_by_type($type) {
331         return $this->get_plugin_by_type('assignsubmission', $type);
332     }
334     /**
335      * Load the plugins from the sub folders under subtype.
336      *
337      * @param string $subtype - either submission or feedback
338      * @return array - The sorted list of plugins
339      */
340     protected function load_plugins($subtype) {
341         global $CFG;
342         $result = array();
344         $names = core_component::get_plugin_list($subtype);
346         foreach ($names as $name => $path) {
347             if (file_exists($path . '/locallib.php')) {
348                 require_once($path . '/locallib.php');
350                 $shortsubtype = substr($subtype, strlen('assign'));
351                 $pluginclass = 'assign_' . $shortsubtype . '_' . $name;
353                 $plugin = new $pluginclass($this, $name);
355                 if ($plugin instanceof assign_plugin) {
356                     $idx = $plugin->get_sort_order();
357                     while (array_key_exists($idx, $result)) {
358                         $idx +=1;
359                     }
360                     $result[$idx] = $plugin;
361                 }
362             }
363         }
364         ksort($result);
365         return $result;
366     }
368     /**
369      * Display the assignment, used by view.php
370      *
371      * The assignment is displayed differently depending on your role,
372      * the settings for the assignment and the status of the assignment.
373      *
374      * @param string $action The current action if any.
375      * @return string - The page output.
376      */
377     public function view($action='') {
379         $o = '';
380         $mform = null;
381         $notices = array();
382         $nextpageparams = array();
384         if (!empty($this->get_course_module()->id)) {
385             $nextpageparams['id'] = $this->get_course_module()->id;
386         }
388         // Handle form submissions first.
389         if ($action == 'savesubmission') {
390             $action = 'editsubmission';
391             if ($this->process_save_submission($mform, $notices)) {
392                 $action = 'redirect';
393                 $nextpageparams['action'] = 'view';
394             }
395         } else if ($action == 'editprevioussubmission') {
396             $action = 'editsubmission';
397             if ($this->process_copy_previous_attempt($notices)) {
398                 $action = 'redirect';
399                 $nextpageparams['action'] = 'editsubmission';
400             }
401         } else if ($action == 'lock') {
402             $this->process_lock_submission();
403             $action = 'redirect';
404             $nextpageparams['action'] = 'grading';
405         } else if ($action == 'addattempt') {
406             $this->process_add_attempt(required_param('userid', PARAM_INT));
407             $action = 'redirect';
408             $nextpageparams['action'] = 'grading';
409         } else if ($action == 'reverttodraft') {
410             $this->process_revert_to_draft();
411             $action = 'redirect';
412             $nextpageparams['action'] = 'grading';
413         } else if ($action == 'unlock') {
414             $this->process_unlock_submission();
415             $action = 'redirect';
416             $nextpageparams['action'] = 'grading';
417         } else if ($action == 'setbatchmarkingworkflowstate') {
418             $this->process_set_batch_marking_workflow_state();
419             $action = 'redirect';
420             $nextpageparams['action'] = 'grading';
421         } else if ($action == 'setbatchmarkingallocation') {
422             $this->process_set_batch_marking_allocation();
423             $action = 'redirect';
424             $nextpageparams['action'] = 'grading';
425         } else if ($action == 'confirmsubmit') {
426             $action = 'submit';
427             if ($this->process_submit_for_grading($mform, $notices)) {
428                 $action = 'redirect';
429                 $nextpageparams['action'] = 'view';
430             } else if ($notices) {
431                 $action = 'viewsubmitforgradingerror';
432             }
433         } else if ($action == 'submitotherforgrading') {
434             if ($this->process_submit_other_for_grading($mform, $notices)) {
435                 $action = 'redirect';
436                 $nextpageparams['action'] = 'grading';
437             } else {
438                 $action = 'viewsubmitforgradingerror';
439             }
440         } else if ($action == 'gradingbatchoperation') {
441             $action = $this->process_grading_batch_operation($mform);
442             if ($action == 'grading') {
443                 $action = 'redirect';
444                 $nextpageparams['action'] = 'grading';
445             }
446         } else if ($action == 'submitgrade') {
447             if (optional_param('saveandshownext', null, PARAM_RAW)) {
448                 // Save and show next.
449                 $action = 'grade';
450                 if ($this->process_save_grade($mform)) {
451                     $action = 'redirect';
452                     $nextpageparams['action'] = 'grade';
453                     $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) + 1;
454                     $nextpageparams['useridlistid'] = optional_param('useridlistid', time(), PARAM_INT);
455                 }
456             } else if (optional_param('nosaveandprevious', null, PARAM_RAW)) {
457                 $action = 'redirect';
458                 $nextpageparams['action'] = 'grade';
459                 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) - 1;
460                 $nextpageparams['useridlistid'] = optional_param('useridlistid', time(), PARAM_INT);
461             } else if (optional_param('nosaveandnext', 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('savegrade', null, PARAM_RAW)) {
467                 // Save changes button.
468                 $action = 'grade';
469                 if ($this->process_save_grade($mform)) {
470                     $action = 'redirect';
471                     $nextpageparams['action'] = 'savegradingresult';
472                 }
473             } else {
474                 // Cancel button.
475                 $action = 'redirect';
476                 $nextpageparams['action'] = 'grading';
477             }
478         } else if ($action == 'quickgrade') {
479             $message = $this->process_save_quick_grades();
480             $action = 'quickgradingresult';
481         } else if ($action == 'saveoptions') {
482             $this->process_save_grading_options();
483             $action = 'redirect';
484             $nextpageparams['action'] = 'grading';
485         } else if ($action == 'saveextension') {
486             $action = 'grantextension';
487             if ($this->process_save_extension($mform)) {
488                 $action = 'redirect';
489                 $nextpageparams['action'] = 'grading';
490             }
491         } else if ($action == 'revealidentitiesconfirm') {
492             $this->process_reveal_identities();
493             $action = 'redirect';
494             $nextpageparams['action'] = 'grading';
495         }
497         $returnparams = array('rownum'=>optional_param('rownum', 0, PARAM_INT),
498                               'useridlistid'=>optional_param('useridlistid', 0, PARAM_INT));
499         $this->register_return_link($action, $returnparams);
501         // Now show the right view page.
502         if ($action == 'redirect') {
503             $nextpageurl = new moodle_url('/mod/assign/view.php', $nextpageparams);
504             redirect($nextpageurl);
505             return;
506         } else if ($action == 'savegradingresult') {
507             $message = get_string('gradingchangessaved', 'assign');
508             $o .= $this->view_savegrading_result($message);
509         } else if ($action == 'quickgradingresult') {
510             $mform = null;
511             $o .= $this->view_quickgrading_result($message);
512         } else if ($action == 'grade') {
513             $o .= $this->view_single_grade_page($mform);
514         } else if ($action == 'viewpluginassignfeedback') {
515             $o .= $this->view_plugin_content('assignfeedback');
516         } else if ($action == 'viewpluginassignsubmission') {
517             $o .= $this->view_plugin_content('assignsubmission');
518         } else if ($action == 'editsubmission') {
519             $o .= $this->view_edit_submission_page($mform, $notices);
520         } else if ($action == 'grading') {
521             $o .= $this->view_grading_page();
522         } else if ($action == 'downloadall') {
523             $o .= $this->download_submissions();
524         } else if ($action == 'submit') {
525             $o .= $this->check_submit_for_grading($mform);
526         } else if ($action == 'grantextension') {
527             $o .= $this->view_grant_extension($mform);
528         } else if ($action == 'revealidentities') {
529             $o .= $this->view_reveal_identities_confirm($mform);
530         } else if ($action == 'plugingradingbatchoperation') {
531             $o .= $this->view_plugin_grading_batch_operation($mform);
532         } else if ($action == 'viewpluginpage') {
533              $o .= $this->view_plugin_page();
534         } else if ($action == 'viewcourseindex') {
535              $o .= $this->view_course_index();
536         } else if ($action == 'viewbatchsetmarkingworkflowstate') {
537              $o .= $this->view_batch_set_workflow_state($mform);
538         } else if ($action == 'viewbatchmarkingallocation') {
539             $o .= $this->view_batch_markingallocation($mform);
540         } else if ($action == 'viewsubmitforgradingerror') {
541             $o .= $this->view_error_page(get_string('submitforgrading', 'assign'), $notices);
542         } else {
543             $o .= $this->view_submission_page();
544         }
546         return $o;
547     }
549     /**
550      * Add this instance to the database.
551      *
552      * @param stdClass $formdata The data submitted from the form
553      * @param bool $callplugins This is used to skip the plugin code
554      *             when upgrading an old assignment to a new one (the plugins get called manually)
555      * @return mixed false if an error occurs or the int id of the new instance
556      */
557     public function add_instance(stdClass $formdata, $callplugins) {
558         global $DB;
559         $adminconfig = $this->get_admin_config();
561         $err = '';
563         // Add the database record.
564         $update = new stdClass();
565         $update->name = $formdata->name;
566         $update->timemodified = time();
567         $update->timecreated = time();
568         $update->course = $formdata->course;
569         $update->courseid = $formdata->course;
570         $update->intro = $formdata->intro;
571         $update->introformat = $formdata->introformat;
572         $update->alwaysshowdescription = !empty($formdata->alwaysshowdescription);
573         $update->submissiondrafts = $formdata->submissiondrafts;
574         $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
575         $update->sendnotifications = $formdata->sendnotifications;
576         $update->sendlatenotifications = $formdata->sendlatenotifications;
577         $update->sendstudentnotifications = $adminconfig->sendstudentnotifications;
578         if (isset($formdata->sendstudentnotifications)) {
579             $update->sendstudentnotifications = $formdata->sendstudentnotifications;
580         }
581         $update->duedate = $formdata->duedate;
582         $update->cutoffdate = $formdata->cutoffdate;
583         $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
584         $update->grade = $formdata->grade;
585         $update->completionsubmit = !empty($formdata->completionsubmit);
586         $update->teamsubmission = $formdata->teamsubmission;
587         $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
588         if (isset($formdata->teamsubmissiongroupingid)) {
589             $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
590         }
591         $update->blindmarking = $formdata->blindmarking;
592         $update->attemptreopenmethod = ASSIGN_ATTEMPT_REOPEN_METHOD_NONE;
593         if (!empty($formdata->attemptreopenmethod)) {
594             $update->attemptreopenmethod = $formdata->attemptreopenmethod;
595         }
596         if (!empty($formdata->maxattempts)) {
597             $update->maxattempts = $formdata->maxattempts;
598         }
599         $update->markingworkflow = $formdata->markingworkflow;
600         $update->markingallocation = $formdata->markingallocation;
602         $returnid = $DB->insert_record('assign', $update);
603         $this->instance = $DB->get_record('assign', array('id'=>$returnid), '*', MUST_EXIST);
604         // Cache the course record.
605         $this->course = $DB->get_record('course', array('id'=>$formdata->course), '*', MUST_EXIST);
607         if ($callplugins) {
608             // Call save_settings hook for submission plugins.
609             foreach ($this->submissionplugins as $plugin) {
610                 if (!$this->update_plugin_instance($plugin, $formdata)) {
611                     print_error($plugin->get_error());
612                     return false;
613                 }
614             }
615             foreach ($this->feedbackplugins as $plugin) {
616                 if (!$this->update_plugin_instance($plugin, $formdata)) {
617                     print_error($plugin->get_error());
618                     return false;
619                 }
620             }
622             // In the case of upgrades the coursemodule has not been set,
623             // so we need to wait before calling these two.
624             $this->update_calendar($formdata->coursemodule);
625             $this->update_gradebook(false, $formdata->coursemodule);
627         }
629         $update = new stdClass();
630         $update->id = $this->get_instance()->id;
631         $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
632         $DB->update_record('assign', $update);
634         return $returnid;
635     }
637     /**
638      * Delete all grades from the gradebook for this assignment.
639      *
640      * @return bool
641      */
642     protected function delete_grades() {
643         global $CFG;
645         $result = grade_update('mod/assign',
646                                $this->get_course()->id,
647                                'mod',
648                                'assign',
649                                $this->get_instance()->id,
650                                0,
651                                null,
652                                array('deleted'=>1));
653         return $result == GRADE_UPDATE_OK;
654     }
656     /**
657      * Delete this instance from the database.
658      *
659      * @return bool false if an error occurs
660      */
661     public function delete_instance() {
662         global $DB;
663         $result = true;
665         foreach ($this->submissionplugins as $plugin) {
666             if (!$plugin->delete_instance()) {
667                 print_error($plugin->get_error());
668                 $result = false;
669             }
670         }
671         foreach ($this->feedbackplugins as $plugin) {
672             if (!$plugin->delete_instance()) {
673                 print_error($plugin->get_error());
674                 $result = false;
675             }
676         }
678         // Delete files associated with this assignment.
679         $fs = get_file_storage();
680         if (! $fs->delete_area_files($this->context->id) ) {
681             $result = false;
682         }
684         // Delete_records will throw an exception if it fails - so no need for error checking here.
685         $DB->delete_records('assign_submission', array('assignment'=>$this->get_instance()->id));
686         $DB->delete_records('assign_grades', array('assignment'=>$this->get_instance()->id));
687         $DB->delete_records('assign_plugin_config', array('assignment'=>$this->get_instance()->id));
689         // Delete items from the gradebook.
690         if (! $this->delete_grades()) {
691             $result = false;
692         }
694         // Delete the instance.
695         $DB->delete_records('assign', array('id'=>$this->get_instance()->id));
697         return $result;
698     }
700     /**
701      * Actual implementation of the reset course functionality, delete all the
702      * assignment submissions for course $data->courseid.
703      *
704      * @param stdClass $data the data submitted from the reset course.
705      * @return array status array
706      */
707     public function reset_userdata($data) {
708         global $CFG, $DB;
710         $componentstr = get_string('modulenameplural', 'assign');
711         $status = array();
713         $fs = get_file_storage();
714         if (!empty($data->reset_assign_submissions)) {
715             // Delete files associated with this assignment.
716             foreach ($this->submissionplugins as $plugin) {
717                 $fileareas = array();
718                 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
719                 $fileareas = $plugin->get_file_areas();
720                 foreach ($fileareas as $filearea) {
721                     $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
722                 }
724                 if (!$plugin->delete_instance()) {
725                     $status[] = array('component'=>$componentstr,
726                                       'item'=>get_string('deleteallsubmissions', 'assign'),
727                                       'error'=>$plugin->get_error());
728                 }
729             }
731             foreach ($this->feedbackplugins as $plugin) {
732                 $fileareas = array();
733                 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
734                 $fileareas = $plugin->get_file_areas();
735                 foreach ($fileareas as $filearea) {
736                     $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
737                 }
739                 if (!$plugin->delete_instance()) {
740                     $status[] = array('component'=>$componentstr,
741                                       'item'=>get_string('deleteallsubmissions', 'assign'),
742                                       'error'=>$plugin->get_error());
743                 }
744             }
746             $assignssql = 'SELECT a.id
747                              FROM {assign} a
748                            WHERE a.course=:course';
749             $params = array('course'=>$data->courseid);
751             $DB->delete_records_select('assign_submission', "assignment IN ($assignssql)", $params);
753             $status[] = array('component'=>$componentstr,
754                               'item'=>get_string('deleteallsubmissions', 'assign'),
755                               'error'=>false);
757             if (!empty($data->reset_gradebook_grades)) {
758                 $DB->delete_records_select('assign_grades', "assignment IN ($assignssql)", $params);
759                 // Remove all grades from gradebook.
760                 require_once($CFG->dirroot.'/mod/assign/lib.php');
761                 assign_reset_gradebook($data->courseid);
762             }
763         }
764         // Updating dates - shift may be negative too.
765         if ($data->timeshift) {
766             shift_course_mod_dates('assign',
767                                     array('duedate', 'allowsubmissionsfromdate', 'cutoffdate'),
768                                     $data->timeshift,
769                                     $data->courseid, $this->get_instance()->id);
770             $status[] = array('component'=>$componentstr,
771                               'item'=>get_string('datechanged'),
772                               'error'=>false);
773         }
775         return $status;
776     }
778     /**
779      * Update the settings for a single plugin.
780      *
781      * @param assign_plugin $plugin The plugin to update
782      * @param stdClass $formdata The form data
783      * @return bool false if an error occurs
784      */
785     protected function update_plugin_instance(assign_plugin $plugin, stdClass $formdata) {
786         if ($plugin->is_visible()) {
787             $enabledname = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
788             if (!empty($formdata->$enabledname)) {
789                 $plugin->enable();
790                 if (!$plugin->save_settings($formdata)) {
791                     print_error($plugin->get_error());
792                     return false;
793                 }
794             } else {
795                 $plugin->disable();
796             }
797         }
798         return true;
799     }
801     /**
802      * Update the gradebook information for this assignment.
803      *
804      * @param bool $reset If true, will reset all grades in the gradbook for this assignment
805      * @param int $coursemoduleid This is required because it might not exist in the database yet
806      * @return bool
807      */
808     public function update_gradebook($reset, $coursemoduleid) {
809         global $CFG;
811         require_once($CFG->dirroot.'/mod/assign/lib.php');
812         $assign = clone $this->get_instance();
813         $assign->cmidnumber = $coursemoduleid;
815         // Set assign gradebook feedback plugin status (enabled and visible).
816         $assign->gradefeedbackenabled = $this->is_gradebook_feedback_enabled();
818         $param = null;
819         if ($reset) {
820             $param = 'reset';
821         }
823         return assign_grade_item_update($assign, $param);
824     }
826     /**
827      * Load and cache the admin config for this module.
828      *
829      * @return stdClass the plugin config
830      */
831     public function get_admin_config() {
832         if ($this->adminconfig) {
833             return $this->adminconfig;
834         }
835         $this->adminconfig = get_config('assign');
836         return $this->adminconfig;
837     }
839     /**
840      * Update the calendar entries for this assignment.
841      *
842      * @param int $coursemoduleid - Required to pass this in because it might
843      *                              not exist in the database yet.
844      * @return bool
845      */
846     public function update_calendar($coursemoduleid) {
847         global $DB, $CFG;
848         require_once($CFG->dirroot.'/calendar/lib.php');
850         // Special case for add_instance as the coursemodule has not been set yet.
851         $instance = $this->get_instance();
853         if ($instance->duedate) {
854             $event = new stdClass();
856             $params = array('modulename'=>'assign', 'instance'=>$instance->id);
857             $event->id = $DB->get_field('event', 'id', $params);
858             $event->name = $instance->name;
859             $event->timestart = $instance->duedate;
861             // Convert the links to pluginfile. It is a bit hacky but at this stage the files
862             // might not have been saved in the module area yet.
863             $intro = $instance->intro;
864             if ($draftid = file_get_submitted_draft_itemid('introeditor')) {
865                 $intro = file_rewrite_urls_to_pluginfile($intro, $draftid);
866             }
868             // We need to remove the links to files as the calendar is not ready
869             // to support module events with file areas.
870             $intro = strip_pluginfile_content($intro);
871             $event->description = array(
872                 'text' => $intro,
873                 'format' => $instance->introformat
874             );
876             if ($event->id) {
877                 $calendarevent = calendar_event::load($event->id);
878                 $calendarevent->update($event);
879             } else {
880                 unset($event->id);
881                 $event->courseid    = $instance->course;
882                 $event->groupid     = 0;
883                 $event->userid      = 0;
884                 $event->modulename  = 'assign';
885                 $event->instance    = $instance->id;
886                 $event->eventtype   = 'due';
887                 $event->timeduration = 0;
888                 calendar_event::create($event);
889             }
890         } else {
891             $DB->delete_records('event', array('modulename'=>'assign', 'instance'=>$instance->id));
892         }
893     }
896     /**
897      * Update this instance in the database.
898      *
899      * @param stdClass $formdata - the data submitted from the form
900      * @return bool false if an error occurs
901      */
902     public function update_instance($formdata) {
903         global $DB;
904         $adminconfig = $this->get_admin_config();
906         $update = new stdClass();
907         $update->id = $formdata->instance;
908         $update->name = $formdata->name;
909         $update->timemodified = time();
910         $update->course = $formdata->course;
911         $update->intro = $formdata->intro;
912         $update->introformat = $formdata->introformat;
913         $update->alwaysshowdescription = !empty($formdata->alwaysshowdescription);
914         $update->submissiondrafts = $formdata->submissiondrafts;
915         $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
916         $update->sendnotifications = $formdata->sendnotifications;
917         $update->sendlatenotifications = $formdata->sendlatenotifications;
918         $update->sendstudentnotifications = $adminconfig->sendstudentnotifications;
919         if (isset($formdata->sendstudentnotifications)) {
920             $update->sendstudentnotifications = $formdata->sendstudentnotifications;
921         }
922         $update->duedate = $formdata->duedate;
923         $update->cutoffdate = $formdata->cutoffdate;
924         $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
925         $update->grade = $formdata->grade;
926         if (!empty($formdata->completionunlocked)) {
927             $update->completionsubmit = !empty($formdata->completionsubmit);
928         }
929         $update->teamsubmission = $formdata->teamsubmission;
930         $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
931         if (isset($formdata->teamsubmissiongroupingid)) {
932             $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
933         }
934         $update->blindmarking = $formdata->blindmarking;
935         $update->attemptreopenmethod = ASSIGN_ATTEMPT_REOPEN_METHOD_NONE;
936         if (!empty($formdata->attemptreopenmethod)) {
937             $update->attemptreopenmethod = $formdata->attemptreopenmethod;
938         }
939         if (!empty($formdata->maxattempts)) {
940             $update->maxattempts = $formdata->maxattempts;
941         }
942         $update->markingworkflow = $formdata->markingworkflow;
943         $update->markingallocation = $formdata->markingallocation;
945         $result = $DB->update_record('assign', $update);
946         $this->instance = $DB->get_record('assign', array('id'=>$update->id), '*', MUST_EXIST);
948         // Load the assignment so the plugins have access to it.
950         // Call save_settings hook for submission plugins.
951         foreach ($this->submissionplugins as $plugin) {
952             if (!$this->update_plugin_instance($plugin, $formdata)) {
953                 print_error($plugin->get_error());
954                 return false;
955             }
956         }
957         foreach ($this->feedbackplugins as $plugin) {
958             if (!$this->update_plugin_instance($plugin, $formdata)) {
959                 print_error($plugin->get_error());
960                 return false;
961             }
962         }
964         $this->update_calendar($this->get_course_module()->id);
965         $this->update_gradebook(false, $this->get_course_module()->id);
967         $update = new stdClass();
968         $update->id = $this->get_instance()->id;
969         $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
970         $DB->update_record('assign', $update);
972         return $result;
973     }
975     /**
976      * Add elements in grading plugin form.
977      *
978      * @param mixed $grade stdClass|null
979      * @param MoodleQuickForm $mform
980      * @param stdClass $data
981      * @param int $userid - The userid we are grading
982      * @return void
983      */
984     protected function add_plugin_grade_elements($grade, MoodleQuickForm $mform, stdClass $data, $userid) {
985         foreach ($this->feedbackplugins as $plugin) {
986             if ($plugin->is_enabled() && $plugin->is_visible()) {
987                 $plugin->get_form_elements_for_user($grade, $mform, $data, $userid);
988             }
989         }
990     }
994     /**
995      * Add one plugins settings to edit plugin form.
996      *
997      * @param assign_plugin $plugin The plugin to add the settings from
998      * @param MoodleQuickForm $mform The form to add the configuration settings to.
999      *                               This form is modified directly (not returned).
1000      * @param array $pluginsenabled A list of form elements to be added to a group.
1001      *                              The new element is added to this array by this function.
1002      * @return void
1003      */
1004     protected function add_plugin_settings(assign_plugin $plugin, MoodleQuickForm $mform, & $pluginsenabled) {
1005         global $CFG;
1006         if ($plugin->is_visible() && !$plugin->is_configurable() && $plugin->is_enabled()) {
1007             $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
1008             $pluginsenabled[] = $mform->createElement('hidden', $name, 1);
1009             $mform->setType($name, PARAM_BOOL);
1010             $plugin->get_settings($mform);
1011         } else if ($plugin->is_visible() && $plugin->is_configurable()) {
1012             $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
1013             $label = $plugin->get_name();
1014             $label .= ' ' . $this->get_renderer()->help_icon('enabled', $plugin->get_subtype() . '_' . $plugin->get_type());
1015             $pluginsenabled[] = $mform->createElement('checkbox', $name, '', $label);
1017             $default = get_config($plugin->get_subtype() . '_' . $plugin->get_type(), 'default');
1018             if ($plugin->get_config('enabled') !== false) {
1019                 $default = $plugin->is_enabled();
1020             }
1021             $mform->setDefault($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $default);
1023             $plugin->get_settings($mform);
1025         }
1026     }
1028     /**
1029      * Add settings to edit plugin form.
1030      *
1031      * @param MoodleQuickForm $mform The form to add the configuration settings to.
1032      *                               This form is modified directly (not returned).
1033      * @return void
1034      */
1035     public function add_all_plugin_settings(MoodleQuickForm $mform) {
1036         $mform->addElement('header', 'submissiontypes', get_string('submissiontypes', 'assign'));
1038         $submissionpluginsenabled = array();
1039         $group = $mform->addGroup(array(), 'submissionplugins', get_string('submissiontypes', 'assign'), array(' '), false);
1040         foreach ($this->submissionplugins as $plugin) {
1041             $this->add_plugin_settings($plugin, $mform, $submissionpluginsenabled);
1042         }
1043         $group->setElements($submissionpluginsenabled);
1045         $mform->addElement('header', 'feedbacktypes', get_string('feedbacktypes', 'assign'));
1046         $feedbackpluginsenabled = array();
1047         $group = $mform->addGroup(array(), 'feedbackplugins', get_string('feedbacktypes', 'assign'), array(' '), false);
1048         foreach ($this->feedbackplugins as $plugin) {
1049             $this->add_plugin_settings($plugin, $mform, $feedbackpluginsenabled);
1050         }
1051         $group->setElements($feedbackpluginsenabled);
1052         $mform->setExpanded('submissiontypes');
1053     }
1055     /**
1056      * Allow each plugin an opportunity to update the defaultvalues
1057      * passed in to the settings form (needed to set up draft areas for
1058      * editor and filemanager elements)
1059      *
1060      * @param array $defaultvalues
1061      */
1062     public function plugin_data_preprocessing(&$defaultvalues) {
1063         foreach ($this->submissionplugins as $plugin) {
1064             if ($plugin->is_visible()) {
1065                 $plugin->data_preprocessing($defaultvalues);
1066             }
1067         }
1068         foreach ($this->feedbackplugins as $plugin) {
1069             if ($plugin->is_visible()) {
1070                 $plugin->data_preprocessing($defaultvalues);
1071             }
1072         }
1073     }
1075     /**
1076      * Get the name of the current module.
1077      *
1078      * @return string the module name (Assignment)
1079      */
1080     protected function get_module_name() {
1081         if (isset(self::$modulename)) {
1082             return self::$modulename;
1083         }
1084         self::$modulename = get_string('modulename', 'assign');
1085         return self::$modulename;
1086     }
1088     /**
1089      * Get the plural name of the current module.
1090      *
1091      * @return string the module name plural (Assignments)
1092      */
1093     protected function get_module_name_plural() {
1094         if (isset(self::$modulenameplural)) {
1095             return self::$modulenameplural;
1096         }
1097         self::$modulenameplural = get_string('modulenameplural', 'assign');
1098         return self::$modulenameplural;
1099     }
1101     /**
1102      * Has this assignment been constructed from an instance?
1103      *
1104      * @return bool
1105      */
1106     public function has_instance() {
1107         return $this->instance || $this->get_course_module();
1108     }
1110     /**
1111      * Get the settings for the current instance of this assignment
1112      *
1113      * @return stdClass The settings
1114      */
1115     public function get_instance() {
1116         global $DB;
1117         if ($this->instance) {
1118             return $this->instance;
1119         }
1120         if ($this->get_course_module()) {
1121             $params = array('id' => $this->get_course_module()->instance);
1122             $this->instance = $DB->get_record('assign', $params, '*', MUST_EXIST);
1123         }
1124         if (!$this->instance) {
1125             throw new coding_exception('Improper use of the assignment class. ' .
1126                                        'Cannot load the assignment record.');
1127         }
1128         return $this->instance;
1129     }
1131     /**
1132      * Get the primary grade item for this assign instance.
1133      *
1134      * @return stdClass The grade_item record
1135      */
1136     public function get_grade_item() {
1137         if ($this->gradeitem) {
1138             return $this->gradeitem;
1139         }
1140         $instance = $this->get_instance();
1141         $params = array('itemtype' => 'mod',
1142                         'itemmodule' => 'assign',
1143                         'iteminstance' => $instance->id,
1144                         'courseid' => $instance->course,
1145                         'itemnumber' => 0);
1146         $this->gradeitem = grade_item::fetch($params);
1147         if (!$this->gradeitem) {
1148             throw new coding_exception('Improper use of the assignment class. ' .
1149                                        'Cannot load the grade item.');
1150         }
1151         return $this->gradeitem;
1152     }
1154     /**
1155      * Get the context of the current course.
1156      *
1157      * @return mixed context|null The course context
1158      */
1159     public function get_course_context() {
1160         if (!$this->context && !$this->course) {
1161             throw new coding_exception('Improper use of the assignment class. ' .
1162                                        'Cannot load the course context.');
1163         }
1164         if ($this->context) {
1165             return $this->context->get_course_context();
1166         } else {
1167             return context_course::instance($this->course->id);
1168         }
1169     }
1172     /**
1173      * Get the current course module.
1174      *
1175      * @return mixed stdClass|null The course module
1176      */
1177     public function get_course_module() {
1178         if ($this->coursemodule) {
1179             return $this->coursemodule;
1180         }
1181         if (!$this->context) {
1182             return null;
1183         }
1185         if ($this->context->contextlevel == CONTEXT_MODULE) {
1186             $this->coursemodule = get_coursemodule_from_id('assign',
1187                                                            $this->context->instanceid,
1188                                                            0,
1189                                                            false,
1190                                                            MUST_EXIST);
1191             return $this->coursemodule;
1192         }
1193         return null;
1194     }
1196     /**
1197      * Get context module.
1198      *
1199      * @return context
1200      */
1201     public function get_context() {
1202         return $this->context;
1203     }
1205     /**
1206      * Get the current course.
1207      *
1208      * @return mixed stdClass|null The course
1209      */
1210     public function get_course() {
1211         global $DB;
1213         if ($this->course) {
1214             return $this->course;
1215         }
1217         if (!$this->context) {
1218             return null;
1219         }
1220         $params = array('id' => $this->get_course_context()->instanceid);
1221         $this->course = $DB->get_record('course', $params, '*', MUST_EXIST);
1223         return $this->course;
1224     }
1226     /**
1227      * Return a grade in user-friendly form, whether it's a scale or not.
1228      *
1229      * @param mixed $grade int|null
1230      * @param boolean $editing Are we allowing changes to this grade?
1231      * @param int $userid The user id the grade belongs to
1232      * @param int $modified Timestamp from when the grade was last modified
1233      * @return string User-friendly representation of grade
1234      */
1235     public function display_grade($grade, $editing, $userid=0, $modified=0) {
1236         global $DB;
1238         static $scalegrades = array();
1240         $o = '';
1242         if ($this->get_instance()->grade >= 0) {
1243             // Normal number.
1244             if ($editing && $this->get_instance()->grade > 0) {
1245                 if ($grade < 0) {
1246                     $displaygrade = '';
1247                 } else {
1248                     $displaygrade = format_float($grade, 2);
1249                 }
1250                 $o .= '<label class="accesshide" for="quickgrade_' . $userid . '">' .
1251                        get_string('usergrade', 'assign') .
1252                        '</label>';
1253                 $o .= '<input type="text"
1254                               id="quickgrade_' . $userid . '"
1255                               name="quickgrade_' . $userid . '"
1256                               value="' .  $displaygrade . '"
1257                               size="6"
1258                               maxlength="10"
1259                               class="quickgrade"/>';
1260                 $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade, 2);
1261                 return $o;
1262             } else {
1263                 if ($grade == -1 || $grade === null) {
1264                     $o .= '-';
1265                 } else {
1266                     $item = $this->get_grade_item();
1267                     $o .= grade_format_gradevalue($grade, $item);
1268                     if ($item->get_displaytype() == GRADE_DISPLAY_TYPE_REAL) {
1269                         // If displaying the raw grade, also display the total value.
1270                         $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade, 2);
1271                     }
1272                 }
1273                 return $o;
1274             }
1276         } else {
1277             // Scale.
1278             if (empty($this->cache['scale'])) {
1279                 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
1280                     $this->cache['scale'] = make_menu_from_list($scale->scale);
1281                 } else {
1282                     $o .= '-';
1283                     return $o;
1284                 }
1285             }
1286             if ($editing) {
1287                 $o .= '<label class="accesshide"
1288                               for="quickgrade_' . $userid . '">' .
1289                       get_string('usergrade', 'assign') .
1290                       '</label>';
1291                 $o .= '<select name="quickgrade_' . $userid . '" class="quickgrade">';
1292                 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
1293                 foreach ($this->cache['scale'] as $optionid => $option) {
1294                     $selected = '';
1295                     if ($grade == $optionid) {
1296                         $selected = 'selected="selected"';
1297                     }
1298                     $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
1299                 }
1300                 $o .= '</select>';
1301                 return $o;
1302             } else {
1303                 $scaleid = (int)$grade;
1304                 if (isset($this->cache['scale'][$scaleid])) {
1305                     $o .= $this->cache['scale'][$scaleid];
1306                     return $o;
1307                 }
1308                 $o .= '-';
1309                 return $o;
1310             }
1311         }
1312     }
1314     /**
1315      * Load a list of users enrolled in the current course with the specified permission and group.
1316      * 0 for no group.
1317      *
1318      * @param int $currentgroup
1319      * @param bool $idsonly
1320      * @return array List of user records
1321      */
1322     public function list_participants($currentgroup, $idsonly) {
1323         $key = $this->context->id . '-' . $currentgroup . '-' . $this->show_only_active_users();
1324         if (!isset($this->participants[$key])) {
1325             $users = get_enrolled_users($this->context, 'mod/assign:submit', $currentgroup, 'u.*', null, null, null,
1326                     $this->show_only_active_users());
1328             $cm = $this->get_course_module();
1329             $users = groups_filter_users_by_course_module_visible($cm, $users);
1331             $this->participants[$key] = $users;
1332         }
1334         if ($idsonly) {
1335             $idslist = array();
1336             foreach ($this->participants[$key] as $id => $user) {
1337                 $idslist[$id] = new stdClass();
1338                 $idslist[$id]->id = $id;
1339             }
1340             return $idslist;
1341         }
1342         return $this->participants[$key];
1343     }
1345     /**
1346      * Load a count of valid teams for this assignment.
1347      *
1348      * @return int number of valid teams
1349      */
1350     public function count_teams() {
1352         $groups = groups_get_all_groups($this->get_course()->id,
1353                                         0,
1354                                         $this->get_instance()->teamsubmissiongroupingid,
1355                                         'g.id');
1356         $count = count($groups);
1358         // See if there are any users in the default group.
1359         $defaultusers = $this->get_submission_group_members(0, true);
1360         if (count($defaultusers) > 0) {
1361             $count += 1;
1362         }
1363         return $count;
1364     }
1366     /**
1367      * Load a count of active users enrolled in the current course with the specified permission and group.
1368      * 0 for no group.
1369      *
1370      * @param int $currentgroup
1371      * @return int number of matching users
1372      */
1373     public function count_participants($currentgroup) {
1374         return count($this->list_participants($currentgroup, true));
1375     }
1377     /**
1378      * Load a count of active users submissions in the current module that require grading
1379      * This means the submission modification time is more recent than the
1380      * grading modification time and the status is SUBMITTED.
1381      *
1382      * @return int number of matching submissions
1383      */
1384     public function count_submissions_need_grading() {
1385         global $DB;
1387         if ($this->get_instance()->teamsubmission) {
1388             // This does not make sense for group assignment because the submission is shared.
1389             return 0;
1390         }
1392         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1393         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1395         $submissionmaxattempt = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt
1396                                  FROM {assign_submission} mxs
1397                                  WHERE mxs.assignment = :assignid2 GROUP BY mxs.userid';
1398         $grademaxattempt = 'SELECT mxg.userid, MAX(mxg.attemptnumber) AS maxattempt
1399                             FROM {assign_grades} mxg
1400                             WHERE mxg.assignment = :assignid3 GROUP BY mxg.userid';
1402         $params['assignid'] = $this->get_instance()->id;
1403         $params['assignid2'] = $this->get_instance()->id;
1404         $params['assignid3'] = $this->get_instance()->id;
1405         $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1407         $sql = 'SELECT COUNT(s.userid)
1408                    FROM {assign_submission} s
1409                    LEFT JOIN ( ' . $submissionmaxattempt . ' ) smx ON s.userid = smx.userid
1410                    LEFT JOIN ( ' . $grademaxattempt . ' ) gmx ON s.userid = gmx.userid
1411                    LEFT JOIN {assign_grades} g ON
1412                         s.assignment = g.assignment AND
1413                         s.userid = g.userid AND
1414                         g.attemptnumber = gmx.maxattempt
1415                    JOIN(' . $esql . ') e ON e.id = s.userid
1416                    WHERE
1417                         s.attemptnumber = smx.maxattempt AND
1418                         s.assignment = :assignid AND
1419                         s.timemodified IS NOT NULL AND
1420                         s.status = :submitted AND
1421                         (s.timemodified > g.timemodified OR g.timemodified IS NULL)';
1423         return $DB->count_records_sql($sql, $params);
1424     }
1426     /**
1427      * Load a count of grades.
1428      *
1429      * @return int number of grades
1430      */
1431     public function count_grades() {
1432         global $DB;
1434         if (!$this->has_instance()) {
1435             return 0;
1436         }
1438         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1439         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1441         $params['assignid'] = $this->get_instance()->id;
1443         $sql = 'SELECT COUNT(g.userid)
1444                    FROM {assign_grades} g
1445                    JOIN(' . $esql . ') e ON e.id = g.userid
1446                    WHERE g.assignment = :assignid';
1448         return $DB->count_records_sql($sql, $params);
1449     }
1451     /**
1452      * Load a count of submissions.
1453      *
1454      * @return int number of submissions
1455      */
1456     public function count_submissions() {
1457         global $DB;
1459         if (!$this->has_instance()) {
1460             return 0;
1461         }
1463         $params = array();
1465         if ($this->get_instance()->teamsubmission) {
1466             // We cannot join on the enrolment tables for group submissions (no userid).
1467             $sql = 'SELECT COUNT(DISTINCT s.groupid)
1468                         FROM {assign_submission} s
1469                         WHERE
1470                             s.assignment = :assignid AND
1471                             s.timemodified IS NOT NULL AND
1472                             s.userid = :groupuserid';
1474             $params['assignid'] = $this->get_instance()->id;
1475             $params['groupuserid'] = 0;
1476         } else {
1477             $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1478             list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1480             $params['assignid'] = $this->get_instance()->id;
1482             $sql = 'SELECT COUNT(DISTINCT s.userid)
1483                        FROM {assign_submission} s
1484                        JOIN(' . $esql . ') e ON e.id = s.userid
1485                        WHERE
1486                             s.assignment = :assignid AND
1487                             s.timemodified IS NOT NULL';
1489         }
1491         return $DB->count_records_sql($sql, $params);
1492     }
1494     /**
1495      * Load a count of submissions with a specified status.
1496      *
1497      * @param string $status The submission status - should match one of the constants
1498      * @return int number of matching submissions
1499      */
1500     public function count_submissions_with_status($status) {
1501         global $DB;
1503         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1504         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1506         $params['assignid'] = $this->get_instance()->id;
1507         $params['assignid2'] = $this->get_instance()->id;
1508         $params['submissionstatus'] = $status;
1510         if ($this->get_instance()->teamsubmission) {
1511             $maxattemptsql = 'SELECT mxs.groupid, MAX(mxs.attemptnumber) AS maxattempt
1512                               FROM {assign_submission} mxs
1513                               WHERE mxs.assignment = :assignid2 GROUP BY mxs.groupid';
1515             $sql = 'SELECT COUNT(s.groupid)
1516                         FROM {assign_submission} s
1517                         JOIN(' . $maxattemptsql . ') smx ON s.groupid = smx.groupid
1518                         WHERE
1519                             s.attemptnumber = smx.maxattempt AND
1520                             s.assignment = :assignid AND
1521                             s.timemodified IS NOT NULL AND
1522                             s.userid = :groupuserid AND
1523                             s.status = :submissionstatus';
1524             $params['groupuserid'] = 0;
1525         } else {
1526             $maxattemptsql = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt
1527                               FROM {assign_submission} mxs
1528                               WHERE mxs.assignment = :assignid2 GROUP BY mxs.userid';
1530             $sql = 'SELECT COUNT(s.userid)
1531                         FROM {assign_submission} s
1532                         JOIN(' . $esql . ') e ON e.id = s.userid
1533                         JOIN(' . $maxattemptsql . ') smx ON s.userid = smx.userid
1534                         WHERE
1535                             s.attemptnumber = smx.maxattempt AND
1536                             s.assignment = :assignid AND
1537                             s.timemodified IS NOT NULL AND
1538                             s.status = :submissionstatus';
1540         }
1542         return $DB->count_records_sql($sql, $params);
1543     }
1545     /**
1546      * Utility function to get the userid for every row in the grading table
1547      * so the order can be frozen while we iterate it.
1548      *
1549      * @return array An array of userids
1550      */
1551     protected function get_grading_userid_list() {
1552         $filter = get_user_preferences('assign_filter', '');
1553         $table = new assign_grading_table($this, 0, $filter, 0, false);
1555         $useridlist = $table->get_column_data('userid');
1557         return $useridlist;
1558     }
1560     /**
1561      * Generate zip file from array of given files.
1562      *
1563      * @param array $filesforzipping - array of files to pass into archive_to_pathname.
1564      *                                 This array is indexed by the final file name and each
1565      *                                 element in the array is an instance of a stored_file object.
1566      * @return path of temp file - note this returned file does
1567      *         not have a .zip extension - it is a temp file.
1568      */
1569     protected function pack_files($filesforzipping) {
1570         global $CFG;
1571         // Create path for new zip file.
1572         $tempzip = tempnam($CFG->tempdir . '/', 'assignment_');
1573         // Zip files.
1574         $zipper = new zip_packer();
1575         if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
1576             return $tempzip;
1577         }
1578         return false;
1579     }
1581     /**
1582      * Finds all assignment notifications that have yet to be mailed out, and mails them.
1583      *
1584      * Cron function to be run periodically according to the moodle cron.
1585      *
1586      * @return bool
1587      */
1588     public static function cron() {
1589         global $DB;
1591         // Only ever send a max of one days worth of updates.
1592         $yesterday = time() - (24 * 3600);
1593         $timenow   = time();
1595         // Collect all submissions from the past 24 hours that require mailing.
1596         $sql = 'SELECT g.id as gradeid, a.course, a.name, a.blindmarking, a.revealidentities,
1597                        g.*, g.timemodified as lastmodified
1598                  FROM {assign} a
1599                  JOIN {assign_grades} g ON g.assignment = a.id
1600                  LEFT JOIN {assign_user_flags} uf ON uf.assignment = a.id AND uf.userid = g.userid
1601                 WHERE g.timemodified >= :yesterday AND
1602                       g.timemodified <= :today AND
1603                       uf.mailed = 0';
1605         $params = array('yesterday' => $yesterday, 'today' => $timenow);
1606         $submissions = $DB->get_records_sql($sql, $params);
1608         if (empty($submissions)) {
1609             return true;
1610         }
1612         mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
1614         // Preload courses we are going to need those.
1615         $courseids = array();
1616         foreach ($submissions as $submission) {
1617             $courseids[] = $submission->course;
1618         }
1620         // Filter out duplicates.
1621         $courseids = array_unique($courseids);
1622         $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1623         list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
1624         $sql = 'SELECT c.*, ' . $ctxselect .
1625                   ' FROM {course} c
1626              LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
1627                  WHERE c.id ' . $courseidsql;
1629         $params['contextlevel'] = CONTEXT_COURSE;
1630         $courses = $DB->get_records_sql($sql, $params);
1632         // Clean up... this could go on for a while.
1633         unset($courseids);
1634         unset($ctxselect);
1635         unset($courseidsql);
1636         unset($params);
1638         // Simple array we'll use for caching modules.
1639         $modcache = array();
1641         // Message students about new feedback.
1642         foreach ($submissions as $submission) {
1644             mtrace("Processing assignment submission $submission->id ...");
1646             // Do not cache user lookups - could be too many.
1647             if (!$user = $DB->get_record('user', array('id'=>$submission->userid))) {
1648                 mtrace('Could not find user ' . $submission->userid);
1649                 continue;
1650             }
1652             // Use a cache to prevent the same DB queries happening over and over.
1653             if (!array_key_exists($submission->course, $courses)) {
1654                 mtrace('Could not find course ' . $submission->course);
1655                 continue;
1656             }
1657             $course = $courses[$submission->course];
1658             if (isset($course->ctxid)) {
1659                 // Context has not yet been preloaded. Do so now.
1660                 context_helper::preload_from_record($course);
1661             }
1663             // Override the language and timezone of the "current" user, so that
1664             // mail is customised for the receiver.
1665             cron_setup_user($user, $course);
1667             // Context lookups are already cached.
1668             $coursecontext = context_course::instance($course->id);
1669             if (!is_enrolled($coursecontext, $user->id)) {
1670                 $courseshortname = format_string($course->shortname,
1671                                                  true,
1672                                                  array('context' => $coursecontext));
1673                 mtrace(fullname($user) . ' not an active participant in ' . $courseshortname);
1674                 continue;
1675             }
1677             if (!$grader = $DB->get_record('user', array('id'=>$submission->grader))) {
1678                 mtrace('Could not find grader ' . $submission->grader);
1679                 continue;
1680             }
1682             if (!array_key_exists($submission->assignment, $modcache)) {
1683                 $mod = get_coursemodule_from_instance('assign', $submission->assignment, $course->id);
1684                 if (empty($mod)) {
1685                     mtrace('Could not find course module for assignment id ' . $submission->assignment);
1686                     continue;
1687                 }
1688                 $modcache[$submission->assignment] = $mod;
1689             } else {
1690                 $mod = $modcache[$submission->assignment];
1691             }
1692             // Context lookups are already cached.
1693             $contextmodule = context_module::instance($mod->id);
1695             if (!$mod->visible) {
1696                 // Hold mail notification for hidden assignments until later.
1697                 continue;
1698             }
1700             // Need to send this to the student.
1701             $messagetype = 'feedbackavailable';
1702             $eventtype = 'assign_notification';
1703             $updatetime = $submission->lastmodified;
1704             $modulename = get_string('modulename', 'assign');
1706             $uniqueid = 0;
1707             if ($submission->blindmarking && !$submission->revealidentities) {
1708                 $uniqueid = self::get_uniqueid_for_user_static($submission->assignment, $user->id);
1709             }
1710             $showusers = $submission->blindmarking && !$submission->revealidentities;
1711             self::send_assignment_notification($grader,
1712                                                $user,
1713                                                $messagetype,
1714                                                $eventtype,
1715                                                $updatetime,
1716                                                $mod,
1717                                                $contextmodule,
1718                                                $course,
1719                                                $modulename,
1720                                                $submission->name,
1721                                                $showusers,
1722                                                $uniqueid);
1724             $flags = $DB->get_record('assign_user_flags', array('userid'=>$user->id, 'assignment'=>$submission->assignment));
1725             if ($flags) {
1726                 $flags->mailed = 1;
1727                 $DB->update_record('assign_user_flags', $flags);
1728             } else {
1729                 $flags = new stdClass();
1730                 $flags->userid = $user->id;
1731                 $flags->assignment = $submission->assignment;
1732                 $flags->mailed = 1;
1733                 $DB->insert_record('assign_user_flags', $flags);
1734             }
1736             mtrace('Done');
1737         }
1738         mtrace('Done processing ' . count($submissions) . ' assignment submissions');
1740         cron_setup_user();
1742         // Free up memory just to be sure.
1743         unset($courses);
1744         unset($modcache);
1746         return true;
1747     }
1749     /**
1750      * Mark in the database that this grade record should have an update notification sent by cron.
1751      *
1752      * @param stdClass $grade a grade record keyed on id
1753      * @return bool true for success
1754      */
1755     public function notify_grade_modified($grade) {
1756         global $DB;
1758         $flags = $this->get_user_flags($grade->userid, true);
1759         if ($flags->mailed != 1) {
1760             $flags->mailed = 0;
1761         }
1763         return $this->update_user_flags($flags);
1764     }
1766     /**
1767      * Update user flags for this user in this assignment.
1768      *
1769      * @param stdClass $flags a flags record keyed on id
1770      * @return bool true for success
1771      */
1772     public function update_user_flags($flags) {
1773         global $DB;
1774         if ($flags->userid <= 0 || $flags->assignment <= 0 || $flags->id <= 0) {
1775             return false;
1776         }
1778         $result = $DB->update_record('assign_user_flags', $flags);
1779         return $result;
1780     }
1782     /**
1783      * Update a grade in the grade table for the assignment and in the gradebook.
1784      *
1785      * @param stdClass $grade a grade record keyed on id
1786      * @return bool true for success
1787      */
1788     public function update_grade($grade) {
1789         global $DB;
1791         $grade->timemodified = time();
1793         if (!empty($grade->workflowstate)) {
1794             $validstates = $this->get_marking_workflow_states_for_current_user();
1795             if (!array_key_exists($grade->workflowstate, $validstates)) {
1796                 return false;
1797             }
1798         }
1800         if ($grade->grade && $grade->grade != -1) {
1801             if ($this->get_instance()->grade > 0) {
1802                 if (!is_numeric($grade->grade)) {
1803                     return false;
1804                 } else if ($grade->grade > $this->get_instance()->grade) {
1805                     return false;
1806                 } else if ($grade->grade < 0) {
1807                     return false;
1808                 }
1809             } else {
1810                 // This is a scale.
1811                 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
1812                     $scaleoptions = make_menu_from_list($scale->scale);
1813                     if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
1814                         return false;
1815                     }
1816                 }
1817             }
1818         }
1820         if (empty($grade->attemptnumber)) {
1821             // Set it to the default.
1822             $grade->attemptnumber = 0;
1823         }
1824         $result = $DB->update_record('assign_grades', $grade);
1826         // Only push to gradebook if the update is for the latest attempt.
1827         $submission = null;
1828         if ($this->get_instance()->teamsubmission) {
1829             $submission = $this->get_group_submission($grade->userid, 0, false);
1830         } else {
1831             $submission = $this->get_user_submission($grade->userid, false);
1832         }
1833         // Not the latest attempt.
1834         if ($submission && $submission->attemptnumber != $grade->attemptnumber) {
1835             return true;
1836         }
1838         if ($result) {
1839             $this->gradebook_item_update(null, $grade);
1841             $params = array(
1842                 'context' => $this->context,
1843                 'objectid' => $grade->id,
1844                 'relateduserid' => $grade->userid
1845             );
1846             $event = \mod_assign\event\submission_graded::create($params);
1847             $event->set_legacy_logdata('grade submission', $this->format_grade_for_log($grade));
1848             $event->trigger();
1849         }
1850         return $result;
1851     }
1853     /**
1854      * View the grant extension date page.
1855      *
1856      * Uses url parameters 'userid'
1857      * or from parameter 'selectedusers'
1858      *
1859      * @param moodleform $mform - Used for validation of the submitted data
1860      * @return string
1861      */
1862     protected function view_grant_extension($mform) {
1863         global $DB, $CFG;
1864         require_once($CFG->dirroot . '/mod/assign/extensionform.php');
1866         $o = '';
1867         $batchusers = optional_param('selectedusers', '', PARAM_SEQUENCE);
1868         $data = new stdClass();
1869         $data->extensionduedate = null;
1870         $userid = 0;
1871         if (!$batchusers) {
1872             $userid = required_param('userid', PARAM_INT);
1874             $grade = $this->get_user_grade($userid, false);
1876             $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
1878             if ($grade) {
1879                 $data->extensionduedate = $grade->extensionduedate;
1880             }
1881             $data->userid = $userid;
1882         } else {
1883             $data->batchusers = $batchusers;
1884         }
1885         $header = new assign_header($this->get_instance(),
1886                                     $this->get_context(),
1887                                     $this->show_intro(),
1888                                     $this->get_course_module()->id,
1889                                     get_string('grantextension', 'assign'));
1890         $o .= $this->get_renderer()->render($header);
1892         if (!$mform) {
1893             $formparams = array($this->get_course_module()->id,
1894                                 $userid,
1895                                 $batchusers,
1896                                 $this->get_instance(),
1897                                 $data);
1898             $mform = new mod_assign_extension_form(null, $formparams);
1899         }
1900         $o .= $this->get_renderer()->render(new assign_form('extensionform', $mform));
1901         $o .= $this->view_footer();
1902         return $o;
1903     }
1905     /**
1906      * Get a list of the users in the same group as this user.
1907      *
1908      * @param int $groupid The id of the group whose members we want or 0 for the default group
1909      * @param bool $onlyids Whether to retrieve only the user id's
1910      * @return array The users (possibly id's only)
1911      */
1912     public function get_submission_group_members($groupid, $onlyids) {
1913         $members = array();
1914         if ($groupid != 0) {
1915             if ($onlyids) {
1916                 $allusers = groups_get_members($groupid, 'u.id');
1917             } else {
1918                 $allusers = groups_get_members($groupid);
1919             }
1920             foreach ($allusers as $user) {
1921                 if ($this->get_submission_group($user->id)) {
1922                     $members[] = $user;
1923                 }
1924             }
1925         } else {
1926             $allusers = $this->list_participants(null, $onlyids);
1927             foreach ($allusers as $user) {
1928                 if ($this->get_submission_group($user->id) == null) {
1929                     $members[] = $user;
1930                 }
1931             }
1932         }
1933         // Exclude suspended users, if user can't see them.
1934         if (!has_capability('moodle/course:viewsuspendedusers', $this->context)) {
1935             foreach ($members as $key => $member) {
1936                 if (!$this->is_active_user($member->id)) {
1937                     unset($members[$key]);
1938                 }
1939             }
1940         }
1941         return $members;
1942     }
1944     /**
1945      * Get a list of the users in the same group as this user that have not submitted the assignment.
1946      *
1947      * @param int $groupid The id of the group whose members we want or 0 for the default group
1948      * @param bool $onlyids Whether to retrieve only the user id's
1949      * @return array The users (possibly id's only)
1950      */
1951     public function get_submission_group_members_who_have_not_submitted($groupid, $onlyids) {
1952         $instance = $this->get_instance();
1953         if (!$instance->teamsubmission || !$instance->requireallteammemberssubmit) {
1954             return array();
1955         }
1956         $members = $this->get_submission_group_members($groupid, $onlyids);
1958         foreach ($members as $id => $member) {
1959             $submission = $this->get_user_submission($member->id, false);
1960             if ($submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
1961                 unset($members[$id]);
1962             } else {
1963                 if ($this->is_blind_marking()) {
1964                     $members[$id]->alias = get_string('hiddenuser', 'assign') .
1965                                            $this->get_uniqueid_for_user($id);
1966                 }
1967             }
1968         }
1969         return $members;
1970     }
1972     /**
1973      * Load the group submission object for a particular user, optionally creating it if required.
1974      *
1975      * @param int $userid The id of the user whose submission we want
1976      * @param int $groupid The id of the group for this user - may be 0 in which
1977      *                     case it is determined from the userid.
1978      * @param bool $create If set to true a new submission object will be created in the database
1979      * @param int $attemptnumber - -1 means the latest attempt
1980      * @return stdClass The submission
1981      */
1982     public function get_group_submission($userid, $groupid, $create, $attemptnumber=-1) {
1983         global $DB;
1985         if ($groupid == 0) {
1986             $group = $this->get_submission_group($userid);
1987             if ($group) {
1988                 $groupid = $group->id;
1989             }
1990         }
1992         // Now get the group submission.
1993         $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
1994         if ($attemptnumber >= 0) {
1995             $params['attemptnumber'] = $attemptnumber;
1996         }
1998         // Only return the row with the highest attemptnumber.
1999         $submission = null;
2000         $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
2001         if ($submissions) {
2002             $submission = reset($submissions);
2003         }
2005         if ($submission) {
2006             return $submission;
2007         }
2008         if ($create) {
2009             $submission = new stdClass();
2010             $submission->assignment = $this->get_instance()->id;
2011             $submission->userid = 0;
2012             $submission->groupid = $groupid;
2013             $submission->timecreated = time();
2014             $submission->timemodified = $submission->timecreated;
2015             if ($attemptnumber >= 0) {
2016                 $submission->attemptnumber = $attemptnumber;
2017             } else {
2018                 $submission->attemptnumber = 0;
2019             }
2021             $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
2022             $sid = $DB->insert_record('assign_submission', $submission);
2023             $submission->id = $sid;
2024             return $submission;
2025         }
2026         return false;
2027     }
2029     /**
2030      * View a summary listing of all assignments in the current course.
2031      *
2032      * @return string
2033      */
2034     private function view_course_index() {
2035         global $USER;
2037         $o = '';
2039         $course = $this->get_course();
2040         $strplural = get_string('modulenameplural', 'assign');
2042         if (!$cms = get_coursemodules_in_course('assign', $course->id, 'm.duedate')) {
2043             $o .= $this->get_renderer()->notification(get_string('thereareno', 'moodle', $strplural));
2044             $o .= $this->get_renderer()->continue_button(new moodle_url('/course/view.php', array('id' => $course->id)));
2045             return $o;
2046         }
2048         $strsectionname = '';
2049         $usesections = course_format_uses_sections($course->format);
2050         $modinfo = get_fast_modinfo($course);
2052         if ($usesections) {
2053             $strsectionname = get_string('sectionname', 'format_'.$course->format);
2054             $sections = $modinfo->get_section_info_all();
2055         }
2056         $courseindexsummary = new assign_course_index_summary($usesections, $strsectionname);
2058         $timenow = time();
2060         $currentsection = '';
2061         foreach ($modinfo->instances['assign'] as $cm) {
2062             if (!$cm->uservisible) {
2063                 continue;
2064             }
2066             $timedue = $cms[$cm->id]->duedate;
2068             $sectionname = '';
2069             if ($usesections && $cm->sectionnum) {
2070                 $sectionname = get_section_name($course, $sections[$cm->sectionnum]);
2071             }
2073             $submitted = '';
2074             $context = context_module::instance($cm->id);
2076             $assignment = new assign($context, $cm, $course);
2078             if (has_capability('mod/assign:grade', $context)) {
2079                 $submitted = $assignment->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED);
2081             } else if (has_capability('mod/assign:submit', $context)) {
2082                 $usersubmission = $assignment->get_user_submission($USER->id, false);
2084                 if (!empty($usersubmission->status)) {
2085                     $submitted = get_string('submissionstatus_' . $usersubmission->status, 'assign');
2086                 } else {
2087                     $submitted = get_string('submissionstatus_', 'assign');
2088                 }
2089             }
2090             $gradinginfo = grade_get_grades($course->id, 'mod', 'assign', $cm->instance, $USER->id);
2091             if (isset($gradinginfo->items[0]->grades[$USER->id]) &&
2092                     !$gradinginfo->items[0]->grades[$USER->id]->hidden ) {
2093                 $grade = $gradinginfo->items[0]->grades[$USER->id]->str_grade;
2094             } else {
2095                 $grade = '-';
2096             }
2098             $courseindexsummary->add_assign_info($cm->id, $cm->name, $sectionname, $timedue, $submitted, $grade);
2100         }
2102         $o .= $this->get_renderer()->render($courseindexsummary);
2103         $o .= $this->view_footer();
2105         return $o;
2106     }
2108     /**
2109      * View a page rendered by a plugin.
2110      *
2111      * Uses url parameters 'pluginaction', 'pluginsubtype', 'plugin', and 'id'.
2112      *
2113      * @return string
2114      */
2115     protected function view_plugin_page() {
2116         global $USER;
2118         $o = '';
2120         $pluginsubtype = required_param('pluginsubtype', PARAM_ALPHA);
2121         $plugintype = required_param('plugin', PARAM_TEXT);
2122         $pluginaction = required_param('pluginaction', PARAM_ALPHA);
2124         $plugin = $this->get_plugin_by_type($pluginsubtype, $plugintype);
2125         if (!$plugin) {
2126             print_error('invalidformdata', '');
2127             return;
2128         }
2130         $o .= $plugin->view_page($pluginaction);
2132         return $o;
2133     }
2136     /**
2137      * This is used for team assignments to get the group for the specified user.
2138      * If the user is a member of multiple or no groups this will return false
2139      *
2140      * @param int $userid The id of the user whose submission we want
2141      * @return mixed The group or false
2142      */
2143     public function get_submission_group($userid) {
2144         $grouping = $this->get_instance()->teamsubmissiongroupingid;
2145         $groups = groups_get_all_groups($this->get_course()->id, $userid, $grouping);
2146         if (count($groups) != 1) {
2147             return false;
2148         }
2149         return array_pop($groups);
2150     }
2153     /**
2154      * Display the submission that is used by a plugin.
2155      *
2156      * Uses url parameters 'sid', 'gid' and 'plugin'.
2157      *
2158      * @param string $pluginsubtype
2159      * @return string
2160      */
2161     protected function view_plugin_content($pluginsubtype) {
2162         $o = '';
2164         $submissionid = optional_param('sid', 0, PARAM_INT);
2165         $gradeid = optional_param('gid', 0, PARAM_INT);
2166         $plugintype = required_param('plugin', PARAM_TEXT);
2167         $item = null;
2168         if ($pluginsubtype == 'assignsubmission') {
2169             $plugin = $this->get_submission_plugin_by_type($plugintype);
2170             if ($submissionid <= 0) {
2171                 throw new coding_exception('Submission id should not be 0');
2172             }
2173             $item = $this->get_submission($submissionid);
2175             // Check permissions.
2176             $this->require_view_submission($item->userid);
2177             $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2178                                                               $this->get_context(),
2179                                                               $this->show_intro(),
2180                                                               $this->get_course_module()->id,
2181                                                               $plugin->get_name()));
2182             $o .= $this->get_renderer()->render(new assign_submission_plugin_submission($plugin,
2183                                                               $item,
2184                                                               assign_submission_plugin_submission::FULL,
2185                                                               $this->get_course_module()->id,
2186                                                               $this->get_return_action(),
2187                                                               $this->get_return_params()));
2189             // Trigger event for viewing a submission.
2190             $logmessage = new lang_string('viewsubmissionforuser', 'assign', $item->userid);
2191             $event = \mod_assign\event\submission_viewed::create(array(
2192                 'objectid' => $item->id,
2193                 'relateduserid' => $item->userid,
2194                 'context' => $this->get_context(),
2195                 'other' => array(
2196                     'assignid' => $this->get_instance()->id
2197                 )
2198             ));
2199             $event->set_legacy_logdata('view submission', $logmessage);
2200             $event->trigger();
2201         } else {
2202             $plugin = $this->get_feedback_plugin_by_type($plugintype);
2203             if ($gradeid <= 0) {
2204                 throw new coding_exception('Grade id should not be 0');
2205             }
2206             $item = $this->get_grade($gradeid);
2207             // Check permissions.
2208             $this->require_view_submission($item->userid);
2209             $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2210                                                               $this->get_context(),
2211                                                               $this->show_intro(),
2212                                                               $this->get_course_module()->id,
2213                                                               $plugin->get_name()));
2214             $o .= $this->get_renderer()->render(new assign_feedback_plugin_feedback($plugin,
2215                                                               $item,
2216                                                               assign_feedback_plugin_feedback::FULL,
2217                                                               $this->get_course_module()->id,
2218                                                               $this->get_return_action(),
2219                                                               $this->get_return_params()));
2221             // Trigger event for viewing feedback.
2222             $logmessage = new lang_string('viewfeedbackforuser', 'assign', $item->userid);
2223             $event = \mod_assign\event\feedback_viewed::create(array(
2224                 'objectid' => $item->id,
2225                 'relateduserid' => $item->userid,
2226                 'context' => $this->get_context(),
2227                 'other' => array(
2228                     'assignid' => $this->get_instance()->id
2229                 )
2230             ));
2231             $event->set_legacy_logdata('view feedback', $logmessage);
2232             $event->trigger();
2233         }
2235         $o .= $this->view_return_links();
2237         $o .= $this->view_footer();
2239         return $o;
2240     }
2242     /**
2243      * Rewrite plugin file urls so they resolve correctly in an exported zip.
2244      *
2245      * @param string $text - The replacement text
2246      * @param stdClass $user - The user record
2247      * @param assign_plugin $plugin - The assignment plugin
2248      */
2249     public function download_rewrite_pluginfile_urls($text, $user, $plugin) {
2250         $groupmode = groups_get_activity_groupmode($this->get_course_module());
2251         $groupname = '';
2252         if ($groupmode) {
2253             $groupid = groups_get_activity_group($this->get_course_module(), true);
2254             $groupname = groups_get_group_name($groupid).'-';
2255         }
2257         if ($this->is_blind_marking()) {
2258             $prefix = $groupname . get_string('participant', 'assign');
2259             $prefix = str_replace('_', ' ', $prefix);
2260             $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2261         } else {
2262             $prefix = $groupname . fullname($user);
2263             $prefix = str_replace('_', ' ', $prefix);
2264             $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2265         }
2267         $subtype = $plugin->get_subtype();
2268         $type = $plugin->get_type();
2269         $prefix = $prefix . $subtype . '_' . $type . '_';
2271         $result = str_replace('@@PLUGINFILE@@/', $prefix, $text);
2273         return $result;
2274     }
2276     /**
2277      * Render the content in editor that is often used by plugin.
2278      *
2279      * @param string $filearea
2280      * @param int  $submissionid
2281      * @param string $plugintype
2282      * @param string $editor
2283      * @param string $component
2284      * @return string
2285      */
2286     public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
2287         global $CFG;
2289         $result = '';
2291         $plugin = $this->get_submission_plugin_by_type($plugintype);
2293         $text = $plugin->get_editor_text($editor, $submissionid);
2294         $format = $plugin->get_editor_format($editor, $submissionid);
2296         $finaltext = file_rewrite_pluginfile_urls($text,
2297                                                   'pluginfile.php',
2298                                                   $this->get_context()->id,
2299                                                   $component,
2300                                                   $filearea,
2301                                                   $submissionid);
2302         $params = array('overflowdiv' => true, 'context' => $this->get_context());
2303         $result .= format_text($finaltext, $format, $params);
2305         if ($CFG->enableportfolios) {
2306             require_once($CFG->libdir . '/portfoliolib.php');
2308             $button = new portfolio_add_button();
2309             $portfolioparams = array('cmid' => $this->get_course_module()->id,
2310                                      'sid' => $submissionid,
2311                                      'plugin' => $plugintype,
2312                                      'editor' => $editor,
2313                                      'area'=>$filearea);
2314             $button->set_callback_options('assign_portfolio_caller', $portfolioparams, 'mod_assign');
2315             $fs = get_file_storage();
2317             if ($files = $fs->get_area_files($this->context->id,
2318                                              $component,
2319                                              $filearea,
2320                                              $submissionid,
2321                                              'timemodified',
2322                                              false)) {
2323                 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
2324             } else {
2325                 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
2326             }
2327             $result .= $button->to_html();
2328         }
2329         return $result;
2330     }
2332     /**
2333      * Display a continue page.
2334      *
2335      * @param string $message - The message to display
2336      * @return string
2337      */
2338     protected function view_savegrading_result($message) {
2339         $o = '';
2340         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2341                                                       $this->get_context(),
2342                                                       $this->show_intro(),
2343                                                       $this->get_course_module()->id,
2344                                                       get_string('savegradingresult', 'assign')));
2345         $gradingresult = new assign_gradingmessage(get_string('savegradingresult', 'assign'),
2346                                                    $message,
2347                                                    $this->get_course_module()->id);
2348         $o .= $this->get_renderer()->render($gradingresult);
2349         $o .= $this->view_footer();
2350         return $o;
2351     }
2352     /**
2353      * Display a grading error.
2354      *
2355      * @param string $message - The description of the result
2356      * @return string
2357      */
2358     protected function view_quickgrading_result($message) {
2359         $o = '';
2360         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2361                                                       $this->get_context(),
2362                                                       $this->show_intro(),
2363                                                       $this->get_course_module()->id,
2364                                                       get_string('quickgradingresult', 'assign')));
2365         $gradingresult = new assign_gradingmessage(get_string('quickgradingresult', 'assign'),
2366                                                    $message,
2367                                                    $this->get_course_module()->id);
2368         $o .= $this->get_renderer()->render($gradingresult);
2369         $o .= $this->view_footer();
2370         return $o;
2371     }
2373     /**
2374      * Display the page footer.
2375      *
2376      * @return string
2377      */
2378     protected function view_footer() {
2379         // When viewing the footer during PHPUNIT tests a set_state error is thrown.
2380         if (!PHPUNIT_TEST) {
2381             return $this->get_renderer()->render_footer();
2382         }
2384         return '';
2385     }
2387     /**
2388      * Throw an error if the permissions to view this users submission are missing.
2389      *
2390      * @throws required_capability_exception
2391      * @return none
2392      */
2393     public function require_view_submission($userid) {
2394         if (!$this->can_view_submission($userid)) {
2395             throw new required_capability_exception($this->context, 'mod/assign:viewgrades', 'nopermission', '');
2396         }
2397     }
2399     /**
2400      * Throw an error if the permissions to view grades in this assignment are missing.
2401      *
2402      * @throws required_capability_exception
2403      * @return none
2404      */
2405     public function require_view_grades() {
2406         if (!$this->can_view_grades()) {
2407             throw new required_capability_exception($this->context, 'mod/assign:viewgrades', 'nopermission', '');
2408         }
2409     }
2411     /**
2412      * Does this user have view grade or grade permission for this assignment?
2413      *
2414      * @return bool
2415      */
2416     public function can_view_grades() {
2417         // Permissions check.
2418         if (!has_any_capability(array('mod/assign:viewgrades', 'mod/assign:grade'), $this->context)) {
2419             return false;
2420         }
2422         return true;
2423     }
2425     /**
2426      * Does this user have grade permission for this assignment?
2427      *
2428      * @return bool
2429      */
2430     public function can_grade() {
2431         // Permissions check.
2432         if (!has_capability('mod/assign:grade', $this->context)) {
2433             return false;
2434         }
2436         return true;
2437     }
2439     /**
2440      * Download a zip file of all assignment submissions.
2441      *
2442      * @return string - If an error occurs, this will contain the error page.
2443      */
2444     protected function download_submissions() {
2445         global $CFG, $DB;
2447         // More efficient to load this here.
2448         require_once($CFG->libdir.'/filelib.php');
2450         $this->require_view_grades();
2452         // Load all users with submit.
2453         $students = get_enrolled_users($this->context, "mod/assign:submit", null, 'u.*', null, null, null,
2454                         $this->show_only_active_users());
2456         // Build a list of files to zip.
2457         $filesforzipping = array();
2458         $fs = get_file_storage();
2460         $groupmode = groups_get_activity_groupmode($this->get_course_module());
2461         // All users.
2462         $groupid = 0;
2463         $groupname = '';
2464         if ($groupmode) {
2465             $groupid = groups_get_activity_group($this->get_course_module(), true);
2466             $groupname = groups_get_group_name($groupid).'-';
2467         }
2469         // Construct the zip file name.
2470         $filename = clean_filename($this->get_course()->shortname . '-' .
2471                                    $this->get_instance()->name . '-' .
2472                                    $groupname.$this->get_course_module()->id . '.zip');
2474         // Get all the files for each student.
2475         foreach ($students as $student) {
2476             $userid = $student->id;
2478             if ((groups_is_member($groupid, $userid) or !$groupmode or !$groupid)) {
2479                 // Get the plugins to add their own files to the zip.
2481                 $submissiongroup = false;
2482                 $groupname = '';
2483                 if ($this->get_instance()->teamsubmission) {
2484                     $submission = $this->get_group_submission($userid, 0, false);
2485                     $submissiongroup = $this->get_submission_group($userid);
2486                     if ($submissiongroup) {
2487                         $groupname = $submissiongroup->name . '-';
2488                     } else {
2489                         $groupname = get_string('defaultteam', 'assign') . '-';
2490                     }
2491                 } else {
2492                     $submission = $this->get_user_submission($userid, false);
2493                 }
2495                 if ($this->is_blind_marking()) {
2496                     $prefix = str_replace('_', ' ', $groupname . get_string('participant', 'assign'));
2497                     $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2498                 } else {
2499                     $prefix = str_replace('_', ' ', $groupname . fullname($student));
2500                     $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2501                 }
2503                 if ($submission) {
2504                     foreach ($this->submissionplugins as $plugin) {
2505                         if ($plugin->is_enabled() && $plugin->is_visible()) {
2506                             $pluginfiles = $plugin->get_files($submission, $student);
2507                             foreach ($pluginfiles as $zipfilename => $file) {
2508                                 $subtype = $plugin->get_subtype();
2509                                 $type = $plugin->get_type();
2510                                 $prefixedfilename = clean_filename($prefix .
2511                                                                    $subtype .
2512                                                                    '_' .
2513                                                                    $type .
2514                                                                    '_' .
2515                                                                    $zipfilename);
2516                                 $filesforzipping[$prefixedfilename] = $file;
2517                             }
2518                         }
2519                     }
2520                 }
2521             }
2522         }
2523         $result = '';
2524         if (count($filesforzipping) == 0) {
2525             $header = new assign_header($this->get_instance(),
2526                                         $this->get_context(),
2527                                         '',
2528                                         $this->get_course_module()->id,
2529                                         get_string('downloadall', 'assign'));
2530             $result .= $this->get_renderer()->render($header);
2531             $result .= $this->get_renderer()->notification(get_string('nosubmission', 'assign'));
2532             $url = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id,
2533                                                                     'action'=>'grading'));
2534             $result .= $this->get_renderer()->continue_button($url);
2535             $result .= $this->view_footer();
2536         } else if ($zipfile = $this->pack_files($filesforzipping)) {
2537             $params = array(
2538                 'context' => $this->context,
2539                 'objectid' => $this->get_instance()->id
2540             );
2541             $event = \mod_assign\event\all_submissions_downloaded::create($params);
2542             $event->set_legacy_logdata('download all submissions', new lang_string('downloadall', 'assign'));
2543             $event->trigger();
2544             // Send file and delete after sending.
2545             send_temp_file($zipfile, $filename);
2546             // We will not get here - send_temp_file calls exit.
2547         }
2548         return $result;
2549     }
2551     /**
2552      * Util function to add a message to the log.
2553      *
2554      * @deprecated since 2.7 - Use new events system instead.
2555      *             (see http://docs.moodle.org/dev/Migrating_logging_calls_in_plugins).
2556      *
2557      * @param string $action The current action
2558      * @param string $info A detailed description of the change. But no more than 255 characters.
2559      * @param string $url The url to the assign module instance.
2560      * @param bool $return If true, returns the arguments, else adds to log. The purpose of this is to
2561      *                     retrieve the arguments to use them with the new event system (Event 2).
2562      * @return void|array
2563      */
2564     public function add_to_log($action = '', $info = '', $url='', $return = false) {
2565         global $USER;
2567         $fullurl = 'view.php?id=' . $this->get_course_module()->id;
2568         if ($url != '') {
2569             $fullurl .= '&' . $url;
2570         }
2572         $args = array(
2573             $this->get_course()->id,
2574             'assign',
2575             $action,
2576             $fullurl,
2577             $info,
2578             $this->get_course_module()->id
2579         );
2581         if ($return) {
2582             // We only need to call debugging when returning a value. This is because the call to
2583             // call_user_func_array('add_to_log', $args) will trigger a debugging message of it's own.
2584             debugging('The mod_assign add_to_log() function is now deprecated.', DEBUG_DEVELOPER);
2585             return $args;
2586         }
2587         call_user_func_array('add_to_log', $args);
2588     }
2590     /**
2591      * Lazy load the page renderer and expose the renderer to plugins.
2592      *
2593      * @return assign_renderer
2594      */
2595     public function get_renderer() {
2596         global $PAGE;
2597         if ($this->output) {
2598             return $this->output;
2599         }
2600         $this->output = $PAGE->get_renderer('mod_assign');
2601         return $this->output;
2602     }
2604     /**
2605      * Load the submission object for a particular user, optionally creating it if required.
2606      *
2607      * For team assignments there are 2 submissions - the student submission and the team submission
2608      * All files are associated with the team submission but the status of the students contribution is
2609      * recorded separately.
2610      *
2611      * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
2612      * @param bool $create optional - defaults to false. If set to true a new submission object
2613      *                     will be created in the database.
2614      * @param int $attemptnumber - -1 means the latest attempt
2615      * @return stdClass The submission
2616      */
2617     public function get_user_submission($userid, $create, $attemptnumber=-1) {
2618         global $DB, $USER;
2620         if (!$userid) {
2621             $userid = $USER->id;
2622         }
2623         // If the userid is not null then use userid.
2624         $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid, 'groupid'=>0);
2625         if ($attemptnumber >= 0) {
2626             $params['attemptnumber'] = $attemptnumber;
2627         }
2629         // Only return the row with the highest attemptnumber.
2630         $submission = null;
2631         $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
2632         if ($submissions) {
2633             $submission = reset($submissions);
2634         }
2636         if ($submission) {
2637             return $submission;
2638         }
2639         if ($create) {
2640             $submission = new stdClass();
2641             $submission->assignment   = $this->get_instance()->id;
2642             $submission->userid       = $userid;
2643             $submission->timecreated = time();
2644             $submission->timemodified = $submission->timecreated;
2645             $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
2646             if ($attemptnumber >= 0) {
2647                 $submission->attemptnumber = $attemptnumber;
2648             } else {
2649                 $submission->attemptnumber = 0;
2650             }
2651             $sid = $DB->insert_record('assign_submission', $submission);
2652             $submission->id = $sid;
2653             return $submission;
2654         }
2655         return false;
2656     }
2658     /**
2659      * Load the submission object from it's id.
2660      *
2661      * @param int $submissionid The id of the submission we want
2662      * @return stdClass The submission
2663      */
2664     protected function get_submission($submissionid) {
2665         global $DB;
2667         $params = array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid);
2668         return $DB->get_record('assign_submission', $params, '*', MUST_EXIST);
2669     }
2671     /**
2672      * This will retrieve a user flags object from the db optionally creating it if required.
2673      * The user flags was split from the user_grades table in 2.5.
2674      *
2675      * @param int $userid The user we are getting the flags for.
2676      * @param bool $create If true the flags record will be created if it does not exist
2677      * @return stdClass The flags record
2678      */
2679     public function get_user_flags($userid, $create) {
2680         global $DB, $USER;
2682         // If the userid is not null then use userid.
2683         if (!$userid) {
2684             $userid = $USER->id;
2685         }
2687         $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
2689         $flags = $DB->get_record('assign_user_flags', $params);
2691         if ($flags) {
2692             return $flags;
2693         }
2694         if ($create) {
2695             $flags = new stdClass();
2696             $flags->assignment = $this->get_instance()->id;
2697             $flags->userid = $userid;
2698             $flags->locked = 0;
2699             $flags->extensionduedate = 0;
2700             $flags->workflowstate = '';
2701             $flags->allocatedmarker = 0;
2703             // The mailed flag can be one of 3 values: 0 is unsent, 1 is sent and 2 is do not send yet.
2704             // This is because students only want to be notified about certain types of update (grades and feedback).
2705             $flags->mailed = 2;
2707             $fid = $DB->insert_record('assign_user_flags', $flags);
2708             $flags->id = $fid;
2709             return $flags;
2710         }
2711         return false;
2712     }
2714     /**
2715      * This will retrieve a grade object from the db, optionally creating it if required.
2716      *
2717      * @param int $userid The user we are grading
2718      * @param bool $create If true the grade will be created if it does not exist
2719      * @param int $attemptnumber The attempt number to retrieve the grade for. -1 means the latest submission.
2720      * @return stdClass The grade record
2721      */
2722     public function get_user_grade($userid, $create, $attemptnumber=-1) {
2723         global $DB, $USER;
2725         // If the userid is not null then use userid.
2726         if (!$userid) {
2727             $userid = $USER->id;
2728         }
2730         $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
2731         if ($attemptnumber < 0) {
2732             // Make sure this grade matches the latest submission attempt.
2733             if ($this->get_instance()->teamsubmission) {
2734                 $submission = $this->get_group_submission($userid, 0, false);
2735             } else {
2736                 $submission = $this->get_user_submission($userid, false);
2737             }
2738             if ($submission) {
2739                 $attemptnumber = $submission->attemptnumber;
2740             }
2741         }
2743         if ($attemptnumber >= 0) {
2744             $params['attemptnumber'] = $attemptnumber;
2745         }
2747         $grades = $DB->get_records('assign_grades', $params, 'attemptnumber DESC', '*', 0, 1);
2749         if ($grades) {
2750             return reset($grades);
2751         }
2752         if ($create) {
2753             $grade = new stdClass();
2754             $grade->assignment   = $this->get_instance()->id;
2755             $grade->userid       = $userid;
2756             $grade->timecreated = time();
2757             $grade->timemodified = $grade->timecreated;
2758             $grade->grade = -1;
2759             $grade->grader = $USER->id;
2760             if ($attemptnumber >= 0) {
2761                 $grade->attemptnumber = $attemptnumber;
2762             }
2764             $gid = $DB->insert_record('assign_grades', $grade);
2765             $grade->id = $gid;
2766             return $grade;
2767         }
2768         return false;
2769     }
2771     /**
2772      * This will retrieve a grade object from the db.
2773      *
2774      * @param int $gradeid The id of the grade
2775      * @return stdClass The grade record
2776      */
2777     protected function get_grade($gradeid) {
2778         global $DB;
2780         $params = array('assignment'=>$this->get_instance()->id, 'id'=>$gradeid);
2781         return $DB->get_record('assign_grades', $params, '*', MUST_EXIST);
2782     }
2784     /**
2785      * Print the grading page for a single user submission.
2786      *
2787      * @param moodleform $mform
2788      * @return string
2789      */
2790     protected function view_single_grade_page($mform) {
2791         global $DB, $CFG;
2793         $o = '';
2794         $instance = $this->get_instance();
2796         require_once($CFG->dirroot . '/mod/assign/gradeform.php');
2798         // Need submit permission to submit an assignment.
2799         require_capability('mod/assign:grade', $this->context);
2801         $header = new assign_header($instance,
2802                                     $this->get_context(),
2803                                     false,
2804                                     $this->get_course_module()->id,
2805                                     get_string('grading', 'assign'));
2806         $o .= $this->get_renderer()->render($header);
2808         // If userid is passed - we are only grading a single student.
2809         $rownum = required_param('rownum', PARAM_INT);
2810         $useridlistid = optional_param('useridlistid', time(), PARAM_INT);
2811         $userid = optional_param('userid', 0, PARAM_INT);
2812         $attemptnumber = optional_param('attemptnumber', -1, PARAM_INT);
2814         $cache = cache::make_from_params(cache_store::MODE_SESSION, 'mod_assign', 'useridlist');
2815         if (!$userid) {
2816             if (!$useridlist = $cache->get($this->get_course_module()->id . '_' . $useridlistid)) {
2817                 $useridlist = $this->get_grading_userid_list();
2818             }
2819             $cache->set($this->get_course_module()->id . '_' . $useridlistid, $useridlist);
2820         } else {
2821             $rownum = 0;
2822             $useridlist = array($userid);
2823         }
2825         if ($rownum < 0 || $rownum > count($useridlist)) {
2826             throw new coding_exception('Row is out of bounds for the current grading table: ' . $rownum);
2827         }
2829         $last = false;
2830         $userid = $useridlist[$rownum];
2831         if ($rownum == count($useridlist) - 1) {
2832             $last = true;
2833         }
2834         $user = $DB->get_record('user', array('id' => $userid));
2835         if ($user) {
2836             $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2837             $usersummary = new assign_user_summary($user,
2838                                                    $this->get_course()->id,
2839                                                    $viewfullnames,
2840                                                    $this->is_blind_marking(),
2841                                                    $this->get_uniqueid_for_user($user->id),
2842                                                    get_extra_user_fields($this->get_context()),
2843                                                    !$this->is_active_user($userid));
2844             $o .= $this->get_renderer()->render($usersummary);
2845         }
2846         $submission = $this->get_user_submission($userid, false, $attemptnumber);
2847         $submissiongroup = null;
2848         $teamsubmission = null;
2849         $notsubmitted = array();
2850         if ($instance->teamsubmission) {
2851             $teamsubmission = $this->get_group_submission($userid, 0, false, $attemptnumber);
2852             $submissiongroup = $this->get_submission_group($userid);
2853             $groupid = 0;
2854             if ($submissiongroup) {
2855                 $groupid = $submissiongroup->id;
2856             }
2857             $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
2859         }
2861         // Get the requested grade.
2862         $grade = $this->get_user_grade($userid, false, $attemptnumber);
2863         $flags = $this->get_user_flags($userid, false);
2864         if ($this->can_view_submission($userid)) {
2865             $gradelocked = ($flags && $flags->locked) || $this->grading_disabled($userid);
2866             $extensionduedate = null;
2867             if ($flags) {
2868                 $extensionduedate = $flags->extensionduedate;
2869             }
2870             $showedit = $this->submissions_open($userid) && ($this->is_any_submission_plugin_enabled());
2871             $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2873             $submissionstatus = new assign_submission_status($instance->allowsubmissionsfromdate,
2874                                                              $instance->alwaysshowdescription,
2875                                                              $submission,
2876                                                              $instance->teamsubmission,
2877                                                              $teamsubmission,
2878                                                              $submissiongroup,
2879                                                              $notsubmitted,
2880                                                              $this->is_any_submission_plugin_enabled(),
2881                                                              $gradelocked,
2882                                                              $this->is_graded($userid),
2883                                                              $instance->duedate,
2884                                                              $instance->cutoffdate,
2885                                                              $this->get_submission_plugins(),
2886                                                              $this->get_return_action(),
2887                                                              $this->get_return_params(),
2888                                                              $this->get_course_module()->id,
2889                                                              $this->get_course()->id,
2890                                                              assign_submission_status::GRADER_VIEW,
2891                                                              $showedit,
2892                                                              false,
2893                                                              $viewfullnames,
2894                                                              $extensionduedate,
2895                                                              $this->get_context(),
2896                                                              $this->is_blind_marking(),
2897                                                              '',
2898                                                              $instance->attemptreopenmethod,
2899                                                              $instance->maxattempts);
2900             $o .= $this->get_renderer()->render($submissionstatus);
2901         }
2903         if ($grade) {
2904             $data = new stdClass();
2905             if ($grade->grade !== null && $grade->grade >= 0) {
2906                 $data->grade = format_float($grade->grade, 2);
2907             }
2908             if (!empty($flags->workflowstate)) {
2909                 $data->workflowstate = $flags->workflowstate;
2910             }
2911             if (!empty($flags->allocatedmarker)) {
2912                 $data->allocatedmarker = $flags->allocatedmarker;
2913             }
2914         } else {
2915             $data = new stdClass();
2916             $data->grade = '';
2917         }
2918         // Warning if required.
2919         $allsubmissions = $this->get_all_submissions($userid);
2921         if ($attemptnumber != -1) {
2922             $params = array('attemptnumber'=>$attemptnumber + 1,
2923                             'totalattempts'=>count($allsubmissions));
2924             $message = get_string('editingpreviousfeedbackwarning', 'assign', $params);
2925             $o .= $this->get_renderer()->notification($message);
2926         }
2928         // Now show the grading form.
2929         if (!$mform) {
2930             $pagination = array('rownum'=>$rownum,
2931                                 'useridlistid'=>$useridlistid,
2932                                 'last'=>$last,
2933                                 'userid'=>optional_param('userid', 0, PARAM_INT),
2934                                 'attemptnumber'=>$attemptnumber);
2935             $formparams = array($this, $data, $pagination);
2936             $mform = new mod_assign_grade_form(null,
2937                                                $formparams,
2938                                                'post',
2939                                                '',
2940                                                array('class'=>'gradeform'));
2941         }
2942         $o .= $this->get_renderer()->heading(get_string('grade'), 3);
2943         $o .= $this->get_renderer()->render(new assign_form('gradingform', $mform));
2945         if (count($allsubmissions) > 1 && $attemptnumber == -1) {
2946             $allgrades = $this->get_all_grades($userid);
2947             $history = new assign_attempt_history($allsubmissions,
2948                                                   $allgrades,
2949                                                   $this->get_submission_plugins(),
2950                                                   $this->get_feedback_plugins(),
2951                                                   $this->get_course_module()->id,
2952                                                   $this->get_return_action(),
2953                                                   $this->get_return_params(),
2954                                                   true,
2955                                                   $useridlistid,
2956                                                   $rownum);
2958             $o .= $this->get_renderer()->render($history);
2959         }
2961         $msg = new lang_string('viewgradingformforstudent',
2962                           'assign',
2963                           array('id'=>$user->id, 'fullname'=>fullname($user)));
2964         $event = \mod_assign\event\grading_form_viewed::create(array(
2965             'relateduserid' => $user->id,
2966             'context' => $this->get_context(),
2967             'other' => array(
2968                 'assignid' => $this->get_instance()->id
2969             )
2970         ));
2971         $event->set_legacy_logdata('view grading form', $msg);
2972         $event->trigger();
2974         $o .= $this->view_footer();
2975         return $o;
2976     }
2978     /**
2979      * Show a confirmation page to make sure they want to release student identities.
2980      *
2981      * @return string
2982      */
2983     protected function view_reveal_identities_confirm() {
2984         require_capability('mod/assign:revealidentities', $this->get_context());
2986         $o = '';
2987         $header = new assign_header($this->get_instance(),
2988                                     $this->get_context(),
2989                                     false,
2990                                     $this->get_course_module()->id);
2991         $o .= $this->get_renderer()->render($header);
2993         $urlparams = array('id'=>$this->get_course_module()->id,
2994                            'action'=>'revealidentitiesconfirm',
2995                            'sesskey'=>sesskey());
2996         $confirmurl = new moodle_url('/mod/assign/view.php', $urlparams);
2998         $urlparams = array('id'=>$this->get_course_module()->id,
2999                            'action'=>'grading');
3000         $cancelurl = new moodle_url('/mod/assign/view.php', $urlparams);
3002         $o .= $this->get_renderer()->confirm(get_string('revealidentitiesconfirm', 'assign'),
3003                                              $confirmurl,
3004                                              $cancelurl);
3005         $o .= $this->view_footer();
3007         $event = \mod_assign\event\reveal_identities_confirmation_page_viewed::create(array(
3008             'context' => $this->get_context(),
3009             'other' => array(
3010                 'assignid' => $this->get_instance()->id
3011             )
3012         ));
3013         $event->set_legacy_logdata('view', new lang_string('viewrevealidentitiesconfirm', 'assign'));
3014         $event->trigger();
3016         return $o;
3017     }
3019     /**
3020      * View a link to go back to the previous page. Uses url parameters returnaction and returnparams.
3021      *
3022      * @return string
3023      */
3024     protected function view_return_links() {
3025         $returnaction = optional_param('returnaction', '', PARAM_ALPHA);
3026         $returnparams = optional_param('returnparams', '', PARAM_TEXT);
3028         $params = array();
3029         $returnparams = str_replace('&amp;', '&', $returnparams);
3030         parse_str($returnparams, $params);
3031         $newparams = array('id' => $this->get_course_module()->id, 'action' => $returnaction);
3032         $params = array_merge($newparams, $params);
3034         $url = new moodle_url('/mod/assign/view.php', $params);
3035         return $this->get_renderer()->single_button($url, get_string('back'), 'get');
3036     }
3038     /**
3039      * View the grading table of all submissions for this assignment.
3040      *
3041      * @return string
3042      */
3043     protected function view_grading_table() {
3044         global $USER, $CFG;
3046         // Include grading options form.
3047         require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
3048         require_once($CFG->dirroot . '/mod/assign/quickgradingform.php');
3049         require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
3050         $o = '';
3051         $cmid = $this->get_course_module()->id;
3053         $links = array();
3054         if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
3055                 has_capability('moodle/grade:viewall', $this->get_course_context())) {
3056             $gradebookurl = '/grade/report/grader/index.php?id=' . $this->get_course()->id;
3057             $links[$gradebookurl] = get_string('viewgradebook', 'assign');
3058         }
3059         if ($this->is_any_submission_plugin_enabled() && $this->count_submissions()) {
3060             $downloadurl = '/mod/assign/view.php?id=' . $cmid . '&action=downloadall';
3061             $links[$downloadurl] = get_string('downloadall', 'assign');
3062         }
3063         if ($this->is_blind_marking() &&
3064                 has_capability('mod/assign:revealidentities', $this->get_context())) {
3065             $revealidentitiesurl = '/mod/assign/view.php?id=' . $cmid . '&action=revealidentities';
3066             $links[$revealidentitiesurl] = get_string('revealidentities', 'assign');
3067         }
3068         foreach ($this->get_feedback_plugins() as $plugin) {
3069             if ($plugin->is_enabled() && $plugin->is_visible()) {
3070                 foreach ($plugin->get_grading_actions() as $action => $description) {
3071                     $url = '/mod/assign/view.php' .
3072                            '?id=' .  $cmid .
3073                            '&plugin=' . $plugin->get_type() .
3074                            '&pluginsubtype=assignfeedback' .
3075                            '&action=viewpluginpage&pluginaction=' . $action;
3076                     $links[$url] = $description;
3077                 }
3078             }
3079         }
3081         // Sort links alphabetically based on the link description.
3082         core_collator::asort($links);
3084         $gradingactions = new url_select($links);
3085         $gradingactions->set_label(get_string('choosegradingaction', 'assign'));
3087         $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
3089         $perpage = get_user_preferences('assign_perpage', 10);
3090         $filter = get_user_preferences('assign_filter', '');
3091         $markerfilter = get_user_preferences('assign_markerfilter', '');
3092         $workflowfilter = get_user_preferences('assign_workflowfilter', '');
3093         $controller = $gradingmanager->get_active_controller();
3094         $showquickgrading = empty($controller) && $this->can_grade();
3095         $quickgrading = get_user_preferences('assign_quickgrading', false);
3096         $showonlyactiveenrolopt = has_capability('moodle/course:viewsuspendedusers', $this->context);
3098         $markingallocation = $this->get_instance()->markingallocation &&
3099             has_capability('mod/assign:manageallocations', $this->context);
3100         // Get markers to use in drop lists.
3101         $markingallocationoptions = array();
3102         if ($markingallocation) {
3103             $markers = get_users_by_capability($this->context, 'mod/assign:grade');
3104             $markingallocationoptions[''] = get_string('filternone', 'assign');
3105             $markingallocationoptions[ASSIGN_MARKER_FILTER_NO_MARKER] = get_string('markerfilternomarker', 'assign');
3106             foreach ($markers as $marker) {
3107                 $markingallocationoptions[$marker->id] = fullname($marker);
3108             }
3109         }
3111         $markingworkflow = $this->get_instance()->markingworkflow;
3112         // Get marking states to show in form.
3113         $markingworkflowoptions = array();
3114         if ($markingworkflow) {
3115             $notmarked = get_string('markingworkflowstatenotmarked', 'assign');
3116             $markingworkflowoptions[''] = get_string('filternone', 'assign');
3117             $markingworkflowoptions[ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED] = $notmarked;
3118             $markingworkflowoptions = array_merge($markingworkflowoptions, $this->get_marking_workflow_states_for_current_user());
3119         }
3121         // Print options for changing the filter and changing the number of results per page.
3122         $gradingoptionsformparams = array('cm'=>$cmid,
3123                                           'contextid'=>$this->context->id,
3124                                           'userid'=>$USER->id,
3125                                           'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
3126                                           'showquickgrading'=>$showquickgrading,
3127                                           'quickgrading'=>$quickgrading,
3128                                           'markingworkflowopt'=>$markingworkflowoptions,
3129                                           'markingallocationopt'=>$markingallocationoptions,
3130                                           'showonlyactiveenrolopt'=>$showonlyactiveenrolopt,
3131                                           'showonlyactiveenrol'=>$this->show_only_active_users());
3133         $classoptions = array('class'=>'gradingoptionsform');
3134         $gradingoptionsform = new mod_assign_grading_options_form(null,
3135                                                                   $gradingoptionsformparams,
3136                                                                   'post',
3137                                                                   '',
3138                                                                   $classoptions);
3140         $batchformparams = array('cm'=>$cmid,
3141                                  'submissiondrafts'=>$this->get_instance()->submissiondrafts,
3142                                  'duedate'=>$this->get_instance()->duedate,
3143                                  'attemptreopenmethod'=>$this->get_instance()->attemptreopenmethod,
3144                                  'feedbackplugins'=>$this->get_feedback_plugins(),
3145                                  'context'=>$this->get_context(),
3146                                  'markingworkflow'=>$markingworkflow,
3147                                  'markingallocation'=>$markingallocation);
3148         $classoptions = array('class'=>'gradingbatchoperationsform');
3150         $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
3151                                                                                    $batchformparams,
3152                                                                                    'post',
3153                                                                                    '',
3154                                                                                    $classoptions);
3156         $gradingoptionsdata = new stdClass();
3157         $gradingoptionsdata->perpage = $perpage;
3158         $gradingoptionsdata->filter = $filter;
3159         $gradingoptionsdata->markerfilter = $markerfilter;
3160         $gradingoptionsdata->workflowfilter = $workflowfilter;
3161         $gradingoptionsform->set_data($gradingoptionsdata);
3163         $actionformtext = $this->get_renderer()->render($gradingactions);
3164         $header = new assign_header($this->get_instance(),
3165                                     $this->get_context(),
3166                                     false,
3167                                     $this->get_course_module()->id,
3168                                     get_string('grading', 'assign'),
3169                                     $actionformtext);
3170         $o .= $this->get_renderer()->render($header);
3172         $currenturl = $CFG->wwwroot .
3173                       '/mod/assign/view.php?id=' .
3174                       $this->get_course_module()->id .
3175                       '&action=grading';
3177         $o .= groups_print_activity_menu($this->get_course_module(), $currenturl, true);
3179         // Plagiarism update status apearring in the grading book.
3180         if (!empty($CFG->enableplagiarism)) {
3181             require_once($CFG->libdir . '/plagiarismlib.php');
3182             $o .= plagiarism_update_status($this->get_course(), $this->get_course_module());
3183         }
3185         // Load and print the table of submissions.
3186         if ($showquickgrading && $quickgrading) {
3187             $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, true);
3188             $table = $this->get_renderer()->render($gradingtable);
3189             $quickformparams = array('cm'=>$this->get_course_module()->id,
3190                                      'gradingtable'=>$table,
3191                                      'sendstudentnotifications'=>$this->get_instance()->sendstudentnotifications);
3192             $quickgradingform = new mod_assign_quick_grading_form(null, $quickformparams);
3194             $o .= $this->get_renderer()->render(new assign_form('quickgradingform', $quickgradingform));
3195         } else {
3196             $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, false);
3197             $o .= $this->get_renderer()->render($gradingtable);
3198         }
3200         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
3201         $users = array_keys($this->list_participants($currentgroup, true));
3202         if (count($users) != 0 && $this->can_grade()) {
3203             // If no enrolled user in a course then don't display the batch operations feature.
3204             $assignform = new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform);
3205             $o .= $this->get_renderer()->render($assignform);
3206         }
3207         $assignform = new assign_form('gradingoptionsform',
3208                                       $gradingoptionsform,
3209                                       'M.mod_assign.init_grading_options');
3210         $o .= $this->get_renderer()->render($assignform);
3211         return $o;
3212     }
3214     /**
3215      * View entire grading page.
3216      *
3217      * @return string
3218      */
3219     protected function view_grading_page() {
3220         global $CFG;
3222         $o = '';
3223         // Need submit permission to submit an assignment.
3224         $this->require_view_grades();
3225         require_once($CFG->dirroot . '/mod/assign/gradeform.php');
3227         // Only load this if it is.
3229         $o .= $this->view_grading_table();
3231         $o .= $this->view_footer();
3233         $logmessage = new lang_string('viewsubmissiongradingtable', 'assign');
3234         $event = \mod_assign\event\grading_table_viewed::create(array(
3235             'context' => $this->get_context(),
3236             'other' => array(
3237                 'assignid' => $this->get_instance()->id
3238             )
3239         ));
3240         $event->set_legacy_logdata('view submission grading table', $logmessage);
3241         $event->trigger();
3243         return $o;
3244     }
3246     /**
3247      * Capture the output of the plagiarism plugins disclosures and return it as a string.
3248      *
3249      * @return void
3250      */
3251     protected function plagiarism_print_disclosure() {
3252         global $CFG;
3253         $o = '';
3255         if (!empty($CFG->enableplagiarism)) {
3256             require_once($CFG->libdir . '/plagiarismlib.php');
3258             $o .= plagiarism_print_disclosure($this->get_course_module()->id);