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