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