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