46404bc7eb3975dd7b09b7aaa66c4b78e6d0dc85
[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;
599         $returnid = $DB->insert_record('assign', $update);
600         $this->instance = $DB->get_record('assign', array('id'=>$returnid), '*', MUST_EXIST);
601         // Cache the course record.
602         $this->course = $DB->get_record('course', array('id'=>$formdata->course), '*', MUST_EXIST);
604         if ($callplugins) {
605             // Call save_settings hook for submission plugins.
606             foreach ($this->submissionplugins as $plugin) {
607                 if (!$this->update_plugin_instance($plugin, $formdata)) {
608                     print_error($plugin->get_error());
609                     return false;
610                 }
611             }
612             foreach ($this->feedbackplugins as $plugin) {
613                 if (!$this->update_plugin_instance($plugin, $formdata)) {
614                     print_error($plugin->get_error());
615                     return false;
616                 }
617             }
619             // In the case of upgrades the coursemodule has not been set,
620             // so we need to wait before calling these two.
621             $this->update_calendar($formdata->coursemodule);
622             $this->update_gradebook(false, $formdata->coursemodule);
624         }
626         $update = new stdClass();
627         $update->id = $this->get_instance()->id;
628         $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
629         $DB->update_record('assign', $update);
631         return $returnid;
632     }
634     /**
635      * Delete all grades from the gradebook for this assignment.
636      *
637      * @return bool
638      */
639     protected function delete_grades() {
640         global $CFG;
642         $result = grade_update('mod/assign',
643                                $this->get_course()->id,
644                                'mod',
645                                'assign',
646                                $this->get_instance()->id,
647                                0,
648                                null,
649                                array('deleted'=>1));
650         return $result == GRADE_UPDATE_OK;
651     }
653     /**
654      * Delete this instance from the database.
655      *
656      * @return bool false if an error occurs
657      */
658     public function delete_instance() {
659         global $DB;
660         $result = true;
662         foreach ($this->submissionplugins as $plugin) {
663             if (!$plugin->delete_instance()) {
664                 print_error($plugin->get_error());
665                 $result = false;
666             }
667         }
668         foreach ($this->feedbackplugins as $plugin) {
669             if (!$plugin->delete_instance()) {
670                 print_error($plugin->get_error());
671                 $result = false;
672             }
673         }
675         // Delete files associated with this assignment.
676         $fs = get_file_storage();
677         if (! $fs->delete_area_files($this->context->id) ) {
678             $result = false;
679         }
681         // Delete_records will throw an exception if it fails - so no need for error checking here.
682         $DB->delete_records('assign_submission', array('assignment'=>$this->get_instance()->id));
683         $DB->delete_records('assign_grades', array('assignment'=>$this->get_instance()->id));
684         $DB->delete_records('assign_plugin_config', array('assignment'=>$this->get_instance()->id));
686         // Delete items from the gradebook.
687         if (! $this->delete_grades()) {
688             $result = false;
689         }
691         // Delete the instance.
692         $DB->delete_records('assign', array('id'=>$this->get_instance()->id));
694         return $result;
695     }
697     /**
698      * Actual implementation of the reset course functionality, delete all the
699      * assignment submissions for course $data->courseid.
700      *
701      * @param stdClass $data the data submitted from the reset course.
702      * @return array status array
703      */
704     public function reset_userdata($data) {
705         global $CFG, $DB;
707         $componentstr = get_string('modulenameplural', 'assign');
708         $status = array();
710         $fs = get_file_storage();
711         if (!empty($data->reset_assign_submissions)) {
712             // Delete files associated with this assignment.
713             foreach ($this->submissionplugins as $plugin) {
714                 $fileareas = array();
715                 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
716                 $fileareas = $plugin->get_file_areas();
717                 foreach ($fileareas as $filearea) {
718                     $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
719                 }
721                 if (!$plugin->delete_instance()) {
722                     $status[] = array('component'=>$componentstr,
723                                       'item'=>get_string('deleteallsubmissions', 'assign'),
724                                       'error'=>$plugin->get_error());
725                 }
726             }
728             foreach ($this->feedbackplugins as $plugin) {
729                 $fileareas = array();
730                 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
731                 $fileareas = $plugin->get_file_areas();
732                 foreach ($fileareas as $filearea) {
733                     $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
734                 }
736                 if (!$plugin->delete_instance()) {
737                     $status[] = array('component'=>$componentstr,
738                                       'item'=>get_string('deleteallsubmissions', 'assign'),
739                                       'error'=>$plugin->get_error());
740                 }
741             }
743             $assignssql = 'SELECT a.id
744                              FROM {assign} a
745                            WHERE a.course=:course';
746             $params = array('course'=>$data->courseid);
748             $DB->delete_records_select('assign_submission', "assignment IN ($assignssql)", $params);
750             $status[] = array('component'=>$componentstr,
751                               'item'=>get_string('deleteallsubmissions', 'assign'),
752                               'error'=>false);
754             if (!empty($data->reset_gradebook_grades)) {
755                 $DB->delete_records_select('assign_grades', "assignment IN ($assignssql)", $params);
756                 // Remove all grades from gradebook.
757                 require_once($CFG->dirroot.'/mod/assign/lib.php');
758                 assign_reset_gradebook($data->courseid);
759             }
760         }
761         // Updating dates - shift may be negative too.
762         if ($data->timeshift) {
763             shift_course_mod_dates('assign',
764                                     array('duedate', 'allowsubmissionsfromdate', 'cutoffdate'),
765                                     $data->timeshift,
766                                     $data->courseid, $this->get_instance()->id);
767             $status[] = array('component'=>$componentstr,
768                               'item'=>get_string('datechanged'),
769                               'error'=>false);
770         }
772         return $status;
773     }
775     /**
776      * Update the settings for a single plugin.
777      *
778      * @param assign_plugin $plugin The plugin to update
779      * @param stdClass $formdata The form data
780      * @return bool false if an error occurs
781      */
782     protected function update_plugin_instance(assign_plugin $plugin, stdClass $formdata) {
783         if ($plugin->is_visible()) {
784             $enabledname = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
785             if (!empty($formdata->$enabledname)) {
786                 $plugin->enable();
787                 if (!$plugin->save_settings($formdata)) {
788                     print_error($plugin->get_error());
789                     return false;
790                 }
791             } else {
792                 $plugin->disable();
793             }
794         }
795         return true;
796     }
798     /**
799      * Update the gradebook information for this assignment.
800      *
801      * @param bool $reset If true, will reset all grades in the gradbook for this assignment
802      * @param int $coursemoduleid This is required because it might not exist in the database yet
803      * @return bool
804      */
805     public function update_gradebook($reset, $coursemoduleid) {
806         global $CFG;
808         require_once($CFG->dirroot.'/mod/assign/lib.php');
809         $assign = clone $this->get_instance();
810         $assign->cmidnumber = $coursemoduleid;
812         // Set assign gradebook feedback plugin status (enabled and visible).
813         $assign->gradefeedbackenabled = $this->is_gradebook_feedback_enabled();
815         $param = null;
816         if ($reset) {
817             $param = 'reset';
818         }
820         return assign_grade_item_update($assign, $param);
821     }
823     /**
824      * Load and cache the admin config for this module.
825      *
826      * @return stdClass the plugin config
827      */
828     public function get_admin_config() {
829         if ($this->adminconfig) {
830             return $this->adminconfig;
831         }
832         $this->adminconfig = get_config('assign');
833         return $this->adminconfig;
834     }
836     /**
837      * Update the calendar entries for this assignment.
838      *
839      * @param int $coursemoduleid - Required to pass this in because it might
840      *                              not exist in the database yet.
841      * @return bool
842      */
843     public function update_calendar($coursemoduleid) {
844         global $DB, $CFG;
845         require_once($CFG->dirroot.'/calendar/lib.php');
847         // Special case for add_instance as the coursemodule has not been set yet.
848         $instance = $this->get_instance();
850         if ($instance->duedate) {
851             $event = new stdClass();
853             $params = array('modulename'=>'assign', 'instance'=>$instance->id);
854             $event->id = $DB->get_field('event', 'id', $params);
855             $event->name = $instance->name;
856             $event->timestart = $instance->duedate;
858             // Convert the links to pluginfile. It is a bit hacky but at this stage the files
859             // might not have been saved in the module area yet.
860             $intro = $instance->intro;
861             if ($draftid = file_get_submitted_draft_itemid('introeditor')) {
862                 $intro = file_rewrite_urls_to_pluginfile($intro, $draftid);
863             }
865             // We need to remove the links to files as the calendar is not ready
866             // to support module events with file areas.
867             $intro = strip_pluginfile_content($intro);
868             if ($this->show_intro()) {
869                 $event->description = array(
870                     'text' => $intro,
871                     'format' => $instance->introformat
872                 );
873             } else {
874                 $event->description = array(
875                     'text' => '',
876                     'format' => $instance->introformat
877                 );
878             }
880             if ($event->id) {
881                 $calendarevent = calendar_event::load($event->id);
882                 $calendarevent->update($event);
883             } else {
884                 unset($event->id);
885                 $event->courseid    = $instance->course;
886                 $event->groupid     = 0;
887                 $event->userid      = 0;
888                 $event->modulename  = 'assign';
889                 $event->instance    = $instance->id;
890                 $event->eventtype   = 'due';
891                 $event->timeduration = 0;
892                 calendar_event::create($event);
893             }
894         } else {
895             $DB->delete_records('event', array('modulename'=>'assign', 'instance'=>$instance->id));
896         }
897     }
900     /**
901      * Update this instance in the database.
902      *
903      * @param stdClass $formdata - the data submitted from the form
904      * @return bool false if an error occurs
905      */
906     public function update_instance($formdata) {
907         global $DB;
908         $adminconfig = $this->get_admin_config();
910         $update = new stdClass();
911         $update->id = $formdata->instance;
912         $update->name = $formdata->name;
913         $update->timemodified = time();
914         $update->course = $formdata->course;
915         $update->intro = $formdata->intro;
916         $update->introformat = $formdata->introformat;
917         $update->alwaysshowdescription = !empty($formdata->alwaysshowdescription);
918         $update->submissiondrafts = $formdata->submissiondrafts;
919         $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
920         $update->sendnotifications = $formdata->sendnotifications;
921         $update->sendlatenotifications = $formdata->sendlatenotifications;
922         $update->sendstudentnotifications = $adminconfig->sendstudentnotifications;
923         if (isset($formdata->sendstudentnotifications)) {
924             $update->sendstudentnotifications = $formdata->sendstudentnotifications;
925         }
926         $update->duedate = $formdata->duedate;
927         $update->cutoffdate = $formdata->cutoffdate;
928         $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
929         $update->grade = $formdata->grade;
930         if (!empty($formdata->completionunlocked)) {
931             $update->completionsubmit = !empty($formdata->completionsubmit);
932         }
933         $update->teamsubmission = $formdata->teamsubmission;
934         $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
935         if (isset($formdata->teamsubmissiongroupingid)) {
936             $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
937         }
938         $update->blindmarking = $formdata->blindmarking;
939         $update->attemptreopenmethod = ASSIGN_ATTEMPT_REOPEN_METHOD_NONE;
940         if (!empty($formdata->attemptreopenmethod)) {
941             $update->attemptreopenmethod = $formdata->attemptreopenmethod;
942         }
943         if (!empty($formdata->maxattempts)) {
944             $update->maxattempts = $formdata->maxattempts;
945         }
946         $update->markingworkflow = $formdata->markingworkflow;
947         $update->markingallocation = $formdata->markingallocation;
949         $result = $DB->update_record('assign', $update);
950         $this->instance = $DB->get_record('assign', array('id'=>$update->id), '*', MUST_EXIST);
952         // Load the assignment so the plugins have access to it.
954         // Call save_settings hook for submission plugins.
955         foreach ($this->submissionplugins as $plugin) {
956             if (!$this->update_plugin_instance($plugin, $formdata)) {
957                 print_error($plugin->get_error());
958                 return false;
959             }
960         }
961         foreach ($this->feedbackplugins as $plugin) {
962             if (!$this->update_plugin_instance($plugin, $formdata)) {
963                 print_error($plugin->get_error());
964                 return false;
965             }
966         }
968         $this->update_calendar($this->get_course_module()->id);
969         $this->update_gradebook(false, $this->get_course_module()->id);
971         $update = new stdClass();
972         $update->id = $this->get_instance()->id;
973         $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
974         $DB->update_record('assign', $update);
976         return $result;
977     }
979     /**
980      * Add elements in grading plugin form.
981      *
982      * @param mixed $grade stdClass|null
983      * @param MoodleQuickForm $mform
984      * @param stdClass $data
985      * @param int $userid - The userid we are grading
986      * @return void
987      */
988     protected function add_plugin_grade_elements($grade, MoodleQuickForm $mform, stdClass $data, $userid) {
989         foreach ($this->feedbackplugins as $plugin) {
990             if ($plugin->is_enabled() && $plugin->is_visible()) {
991                 $plugin->get_form_elements_for_user($grade, $mform, $data, $userid);
992             }
993         }
994     }
998     /**
999      * Add one plugins settings to edit plugin form.
1000      *
1001      * @param assign_plugin $plugin The plugin to add the settings from
1002      * @param MoodleQuickForm $mform The form to add the configuration settings to.
1003      *                               This form is modified directly (not returned).
1004      * @param array $pluginsenabled A list of form elements to be added to a group.
1005      *                              The new element is added to this array by this function.
1006      * @return void
1007      */
1008     protected function add_plugin_settings(assign_plugin $plugin, MoodleQuickForm $mform, & $pluginsenabled) {
1009         global $CFG;
1010         if ($plugin->is_visible() && !$plugin->is_configurable() && $plugin->is_enabled()) {
1011             $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
1012             $pluginsenabled[] = $mform->createElement('hidden', $name, 1);
1013             $mform->setType($name, PARAM_BOOL);
1014             $plugin->get_settings($mform);
1015         } else if ($plugin->is_visible() && $plugin->is_configurable()) {
1016             $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
1017             $label = $plugin->get_name();
1018             $label .= ' ' . $this->get_renderer()->help_icon('enabled', $plugin->get_subtype() . '_' . $plugin->get_type());
1019             $pluginsenabled[] = $mform->createElement('checkbox', $name, '', $label);
1021             $default = get_config($plugin->get_subtype() . '_' . $plugin->get_type(), 'default');
1022             if ($plugin->get_config('enabled') !== false) {
1023                 $default = $plugin->is_enabled();
1024             }
1025             $mform->setDefault($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $default);
1027             $plugin->get_settings($mform);
1029         }
1030     }
1032     /**
1033      * Add settings to edit plugin form.
1034      *
1035      * @param MoodleQuickForm $mform The form to add the configuration settings to.
1036      *                               This form is modified directly (not returned).
1037      * @return void
1038      */
1039     public function add_all_plugin_settings(MoodleQuickForm $mform) {
1040         $mform->addElement('header', 'submissiontypes', get_string('submissiontypes', 'assign'));
1042         $submissionpluginsenabled = array();
1043         $group = $mform->addGroup(array(), 'submissionplugins', get_string('submissiontypes', 'assign'), array(' '), false);
1044         foreach ($this->submissionplugins as $plugin) {
1045             $this->add_plugin_settings($plugin, $mform, $submissionpluginsenabled);
1046         }
1047         $group->setElements($submissionpluginsenabled);
1049         $mform->addElement('header', 'feedbacktypes', get_string('feedbacktypes', 'assign'));
1050         $feedbackpluginsenabled = array();
1051         $group = $mform->addGroup(array(), 'feedbackplugins', get_string('feedbacktypes', 'assign'), array(' '), false);
1052         foreach ($this->feedbackplugins as $plugin) {
1053             $this->add_plugin_settings($plugin, $mform, $feedbackpluginsenabled);
1054         }
1055         $group->setElements($feedbackpluginsenabled);
1056         $mform->setExpanded('submissiontypes');
1057     }
1059     /**
1060      * Allow each plugin an opportunity to update the defaultvalues
1061      * passed in to the settings form (needed to set up draft areas for
1062      * editor and filemanager elements)
1063      *
1064      * @param array $defaultvalues
1065      */
1066     public function plugin_data_preprocessing(&$defaultvalues) {
1067         foreach ($this->submissionplugins as $plugin) {
1068             if ($plugin->is_visible()) {
1069                 $plugin->data_preprocessing($defaultvalues);
1070             }
1071         }
1072         foreach ($this->feedbackplugins as $plugin) {
1073             if ($plugin->is_visible()) {
1074                 $plugin->data_preprocessing($defaultvalues);
1075             }
1076         }
1077     }
1079     /**
1080      * Get the name of the current module.
1081      *
1082      * @return string the module name (Assignment)
1083      */
1084     protected function get_module_name() {
1085         if (isset(self::$modulename)) {
1086             return self::$modulename;
1087         }
1088         self::$modulename = get_string('modulename', 'assign');
1089         return self::$modulename;
1090     }
1092     /**
1093      * Get the plural name of the current module.
1094      *
1095      * @return string the module name plural (Assignments)
1096      */
1097     protected function get_module_name_plural() {
1098         if (isset(self::$modulenameplural)) {
1099             return self::$modulenameplural;
1100         }
1101         self::$modulenameplural = get_string('modulenameplural', 'assign');
1102         return self::$modulenameplural;
1103     }
1105     /**
1106      * Has this assignment been constructed from an instance?
1107      *
1108      * @return bool
1109      */
1110     public function has_instance() {
1111         return $this->instance || $this->get_course_module();
1112     }
1114     /**
1115      * Get the settings for the current instance of this assignment
1116      *
1117      * @return stdClass The settings
1118      */
1119     public function get_instance() {
1120         global $DB;
1121         if ($this->instance) {
1122             return $this->instance;
1123         }
1124         if ($this->get_course_module()) {
1125             $params = array('id' => $this->get_course_module()->instance);
1126             $this->instance = $DB->get_record('assign', $params, '*', MUST_EXIST);
1127         }
1128         if (!$this->instance) {
1129             throw new coding_exception('Improper use of the assignment class. ' .
1130                                        'Cannot load the assignment record.');
1131         }
1132         return $this->instance;
1133     }
1135     /**
1136      * Get the primary grade item for this assign instance.
1137      *
1138      * @return stdClass The grade_item record
1139      */
1140     public function get_grade_item() {
1141         if ($this->gradeitem) {
1142             return $this->gradeitem;
1143         }
1144         $instance = $this->get_instance();
1145         $params = array('itemtype' => 'mod',
1146                         'itemmodule' => 'assign',
1147                         'iteminstance' => $instance->id,
1148                         'courseid' => $instance->course,
1149                         'itemnumber' => 0);
1150         $this->gradeitem = grade_item::fetch($params);
1151         if (!$this->gradeitem) {
1152             throw new coding_exception('Improper use of the assignment class. ' .
1153                                        'Cannot load the grade item.');
1154         }
1155         return $this->gradeitem;
1156     }
1158     /**
1159      * Get the context of the current course.
1160      *
1161      * @return mixed context|null The course context
1162      */
1163     public function get_course_context() {
1164         if (!$this->context && !$this->course) {
1165             throw new coding_exception('Improper use of the assignment class. ' .
1166                                        'Cannot load the course context.');
1167         }
1168         if ($this->context) {
1169             return $this->context->get_course_context();
1170         } else {
1171             return context_course::instance($this->course->id);
1172         }
1173     }
1176     /**
1177      * Get the current course module.
1178      *
1179      * @return mixed stdClass|null The course module
1180      */
1181     public function get_course_module() {
1182         if ($this->coursemodule) {
1183             return $this->coursemodule;
1184         }
1185         if (!$this->context) {
1186             return null;
1187         }
1189         if ($this->context->contextlevel == CONTEXT_MODULE) {
1190             $this->coursemodule = get_coursemodule_from_id('assign',
1191                                                            $this->context->instanceid,
1192                                                            0,
1193                                                            false,
1194                                                            MUST_EXIST);
1195             return $this->coursemodule;
1196         }
1197         return null;
1198     }
1200     /**
1201      * Get context module.
1202      *
1203      * @return context
1204      */
1205     public function get_context() {
1206         return $this->context;
1207     }
1209     /**
1210      * Get the current course.
1211      *
1212      * @return mixed stdClass|null The course
1213      */
1214     public function get_course() {
1215         global $DB;
1217         if ($this->course) {
1218             return $this->course;
1219         }
1221         if (!$this->context) {
1222             return null;
1223         }
1224         $params = array('id' => $this->get_course_context()->instanceid);
1225         $this->course = $DB->get_record('course', $params, '*', MUST_EXIST);
1227         return $this->course;
1228     }
1230     /**
1231      * Return a grade in user-friendly form, whether it's a scale or not.
1232      *
1233      * @param mixed $grade int|null
1234      * @param boolean $editing Are we allowing changes to this grade?
1235      * @param int $userid The user id the grade belongs to
1236      * @param int $modified Timestamp from when the grade was last modified
1237      * @return string User-friendly representation of grade
1238      */
1239     public function display_grade($grade, $editing, $userid=0, $modified=0) {
1240         global $DB;
1242         static $scalegrades = array();
1244         $o = '';
1246         if ($this->get_instance()->grade >= 0) {
1247             // Normal number.
1248             if ($editing && $this->get_instance()->grade > 0) {
1249                 if ($grade < 0) {
1250                     $displaygrade = '';
1251                 } else {
1252                     $displaygrade = format_float($grade, 2);
1253                 }
1254                 $o .= '<label class="accesshide" for="quickgrade_' . $userid . '">' .
1255                        get_string('usergrade', 'assign') .
1256                        '</label>';
1257                 $o .= '<input type="text"
1258                               id="quickgrade_' . $userid . '"
1259                               name="quickgrade_' . $userid . '"
1260                               value="' .  $displaygrade . '"
1261                               size="6"
1262                               maxlength="10"
1263                               class="quickgrade"/>';
1264                 $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade, 2);
1265                 return $o;
1266             } else {
1267                 if ($grade == -1 || $grade === null) {
1268                     $o .= '-';
1269                 } else {
1270                     $item = $this->get_grade_item();
1271                     $o .= grade_format_gradevalue($grade, $item);
1272                     if ($item->get_displaytype() == GRADE_DISPLAY_TYPE_REAL) {
1273                         // If displaying the raw grade, also display the total value.
1274                         $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade, 2);
1275                     }
1276                 }
1277                 return $o;
1278             }
1280         } else {
1281             // Scale.
1282             if (empty($this->cache['scale'])) {
1283                 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
1284                     $this->cache['scale'] = make_menu_from_list($scale->scale);
1285                 } else {
1286                     $o .= '-';
1287                     return $o;
1288                 }
1289             }
1290             if ($editing) {
1291                 $o .= '<label class="accesshide"
1292                               for="quickgrade_' . $userid . '">' .
1293                       get_string('usergrade', 'assign') .
1294                       '</label>';
1295                 $o .= '<select name="quickgrade_' . $userid . '" class="quickgrade">';
1296                 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
1297                 foreach ($this->cache['scale'] as $optionid => $option) {
1298                     $selected = '';
1299                     if ($grade == $optionid) {
1300                         $selected = 'selected="selected"';
1301                     }
1302                     $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
1303                 }
1304                 $o .= '</select>';
1305                 return $o;
1306             } else {
1307                 $scaleid = (int)$grade;
1308                 if (isset($this->cache['scale'][$scaleid])) {
1309                     $o .= $this->cache['scale'][$scaleid];
1310                     return $o;
1311                 }
1312                 $o .= '-';
1313                 return $o;
1314             }
1315         }
1316     }
1318     /**
1319      * Load a list of users enrolled in the current course with the specified permission and group.
1320      * 0 for no group.
1321      *
1322      * @param int $currentgroup
1323      * @param bool $idsonly
1324      * @return array List of user records
1325      */
1326     public function list_participants($currentgroup, $idsonly) {
1327         $key = $this->context->id . '-' . $currentgroup . '-' . $this->show_only_active_users();
1328         if (!isset($this->participants[$key])) {
1329             $users = get_enrolled_users($this->context, 'mod/assign:submit', $currentgroup, 'u.*', null, null, null,
1330                     $this->show_only_active_users());
1332             $cm = $this->get_course_module();
1333             $users = groups_filter_users_by_course_module_visible($cm, $users);
1335             $this->participants[$key] = $users;
1336         }
1338         if ($idsonly) {
1339             $idslist = array();
1340             foreach ($this->participants[$key] as $id => $user) {
1341                 $idslist[$id] = new stdClass();
1342                 $idslist[$id]->id = $id;
1343             }
1344             return $idslist;
1345         }
1346         return $this->participants[$key];
1347     }
1349     /**
1350      * Load a count of valid teams for this assignment.
1351      *
1352      * @return int number of valid teams
1353      */
1354     public function count_teams() {
1356         $groups = groups_get_all_groups($this->get_course()->id,
1357                                         0,
1358                                         $this->get_instance()->teamsubmissiongroupingid,
1359                                         'g.id');
1360         $count = count($groups);
1362         // See if there are any users in the default group.
1363         $defaultusers = $this->get_submission_group_members(0, true);
1364         if (count($defaultusers) > 0) {
1365             $count += 1;
1366         }
1367         return $count;
1368     }
1370     /**
1371      * Load a count of active users enrolled in the current course with the specified permission and group.
1372      * 0 for no group.
1373      *
1374      * @param int $currentgroup
1375      * @return int number of matching users
1376      */
1377     public function count_participants($currentgroup) {
1378         return count($this->list_participants($currentgroup, true));
1379     }
1381     /**
1382      * Load a count of active users submissions in the current module that require grading
1383      * This means the submission modification time is more recent than the
1384      * grading modification time and the status is SUBMITTED.
1385      *
1386      * @return int number of matching submissions
1387      */
1388     public function count_submissions_need_grading() {
1389         global $DB;
1391         if ($this->get_instance()->teamsubmission) {
1392             // This does not make sense for group assignment because the submission is shared.
1393             return 0;
1394         }
1396         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1397         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1399         $submissionmaxattempt = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt
1400                                  FROM {assign_submission} mxs
1401                                  WHERE mxs.assignment = :assignid2 GROUP BY mxs.userid';
1402         $grademaxattempt = 'SELECT mxg.userid, MAX(mxg.attemptnumber) AS maxattempt
1403                             FROM {assign_grades} mxg
1404                             WHERE mxg.assignment = :assignid3 GROUP BY mxg.userid';
1406         $params['assignid'] = $this->get_instance()->id;
1407         $params['assignid2'] = $this->get_instance()->id;
1408         $params['assignid3'] = $this->get_instance()->id;
1409         $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1411         $sql = 'SELECT COUNT(s.userid)
1412                    FROM {assign_submission} s
1413                    LEFT JOIN ( ' . $submissionmaxattempt . ' ) smx ON s.userid = smx.userid
1414                    LEFT JOIN ( ' . $grademaxattempt . ' ) gmx ON s.userid = gmx.userid
1415                    LEFT JOIN {assign_grades} g ON
1416                         s.assignment = g.assignment AND
1417                         s.userid = g.userid AND
1418                         g.attemptnumber = gmx.maxattempt
1419                    JOIN(' . $esql . ') e ON e.id = s.userid
1420                    WHERE
1421                         s.attemptnumber = smx.maxattempt AND
1422                         s.assignment = :assignid AND
1423                         s.timemodified IS NOT NULL AND
1424                         s.status = :submitted AND
1425                         (s.timemodified > g.timemodified OR g.timemodified IS NULL)';
1427         return $DB->count_records_sql($sql, $params);
1428     }
1430     /**
1431      * Load a count of grades.
1432      *
1433      * @return int number of grades
1434      */
1435     public function count_grades() {
1436         global $DB;
1438         if (!$this->has_instance()) {
1439             return 0;
1440         }
1442         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1443         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1445         $params['assignid'] = $this->get_instance()->id;
1447         $sql = 'SELECT COUNT(g.userid)
1448                    FROM {assign_grades} g
1449                    JOIN(' . $esql . ') e ON e.id = g.userid
1450                    WHERE g.assignment = :assignid';
1452         return $DB->count_records_sql($sql, $params);
1453     }
1455     /**
1456      * Load a count of submissions.
1457      *
1458      * @return int number of submissions
1459      */
1460     public function count_submissions() {
1461         global $DB;
1463         if (!$this->has_instance()) {
1464             return 0;
1465         }
1467         $params = array();
1469         if ($this->get_instance()->teamsubmission) {
1470             // We cannot join on the enrolment tables for group submissions (no userid).
1471             $sql = 'SELECT COUNT(DISTINCT s.groupid)
1472                         FROM {assign_submission} s
1473                         WHERE
1474                             s.assignment = :assignid AND
1475                             s.timemodified IS NOT NULL AND
1476                             s.userid = :groupuserid';
1478             $params['assignid'] = $this->get_instance()->id;
1479             $params['groupuserid'] = 0;
1480         } else {
1481             $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1482             list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1484             $params['assignid'] = $this->get_instance()->id;
1486             $sql = 'SELECT COUNT(DISTINCT s.userid)
1487                        FROM {assign_submission} s
1488                        JOIN(' . $esql . ') e ON e.id = s.userid
1489                        WHERE
1490                             s.assignment = :assignid AND
1491                             s.timemodified IS NOT NULL';
1493         }
1495         return $DB->count_records_sql($sql, $params);
1496     }
1498     /**
1499      * Load a count of submissions with a specified status.
1500      *
1501      * @param string $status The submission status - should match one of the constants
1502      * @return int number of matching submissions
1503      */
1504     public function count_submissions_with_status($status) {
1505         global $DB;
1507         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1508         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1510         $params['assignid'] = $this->get_instance()->id;
1511         $params['assignid2'] = $this->get_instance()->id;
1512         $params['submissionstatus'] = $status;
1514         if ($this->get_instance()->teamsubmission) {
1515             $maxattemptsql = 'SELECT mxs.groupid, MAX(mxs.attemptnumber) AS maxattempt
1516                               FROM {assign_submission} mxs
1517                               WHERE mxs.assignment = :assignid2 GROUP BY mxs.groupid';
1519             $sql = 'SELECT COUNT(s.groupid)
1520                         FROM {assign_submission} s
1521                         JOIN(' . $maxattemptsql . ') smx ON s.groupid = smx.groupid
1522                         WHERE
1523                             s.attemptnumber = smx.maxattempt AND
1524                             s.assignment = :assignid AND
1525                             s.timemodified IS NOT NULL AND
1526                             s.userid = :groupuserid AND
1527                             s.status = :submissionstatus';
1528             $params['groupuserid'] = 0;
1529         } else {
1530             $maxattemptsql = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt
1531                               FROM {assign_submission} mxs
1532                               WHERE mxs.assignment = :assignid2 GROUP BY mxs.userid';
1534             $sql = 'SELECT COUNT(s.userid)
1535                         FROM {assign_submission} s
1536                         JOIN(' . $esql . ') e ON e.id = s.userid
1537                         JOIN(' . $maxattemptsql . ') smx ON s.userid = smx.userid
1538                         WHERE
1539                             s.attemptnumber = smx.maxattempt AND
1540                             s.assignment = :assignid AND
1541                             s.timemodified IS NOT NULL AND
1542                             s.status = :submissionstatus';
1544         }
1546         return $DB->count_records_sql($sql, $params);
1547     }
1549     /**
1550      * Utility function to get the userid for every row in the grading table
1551      * so the order can be frozen while we iterate it.
1552      *
1553      * @return array An array of userids
1554      */
1555     protected function get_grading_userid_list() {
1556         $filter = get_user_preferences('assign_filter', '');
1557         $table = new assign_grading_table($this, 0, $filter, 0, false);
1559         $useridlist = $table->get_column_data('userid');
1561         return $useridlist;
1562     }
1564     /**
1565      * Generate zip file from array of given files.
1566      *
1567      * @param array $filesforzipping - array of files to pass into archive_to_pathname.
1568      *                                 This array is indexed by the final file name and each
1569      *                                 element in the array is an instance of a stored_file object.
1570      * @return path of temp file - note this returned file does
1571      *         not have a .zip extension - it is a temp file.
1572      */
1573     protected function pack_files($filesforzipping) {
1574         global $CFG;
1575         // Create path for new zip file.
1576         $tempzip = tempnam($CFG->tempdir . '/', 'assignment_');
1577         // Zip files.
1578         $zipper = new zip_packer();
1579         if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
1580             return $tempzip;
1581         }
1582         return false;
1583     }
1585     /**
1586      * Finds all assignment notifications that have yet to be mailed out, and mails them.
1587      *
1588      * Cron function to be run periodically according to the moodle cron.
1589      *
1590      * @return bool
1591      */
1592     public static function cron() {
1593         global $DB;
1595         // Only ever send a max of one days worth of updates.
1596         $yesterday = time() - (24 * 3600);
1597         $timenow   = time();
1598         $lastcron = $DB->get_field('modules', 'lastcron', array('name'=>'mod_assign'));
1600         // Collect all submissions from the past 24 hours that require mailing.
1601         // Submissions are excluded if the assignment is hidden in the gradebook.
1602         $sql = 'SELECT g.id as gradeid, a.course, a.name, a.blindmarking, a.revealidentities,
1603                        g.*, g.timemodified as lastmodified
1604                  FROM {assign} a
1605                  JOIN {assign_grades} g ON g.assignment = a.id
1606             LEFT JOIN {assign_user_flags} uf ON uf.assignment = a.id AND uf.userid = g.userid
1607                  JOIN {course_modules} cm ON cm.course = a.course
1608                  JOIN {modules} md ON md.id = cm.module
1609                  JOIN {grade_items} gri ON gri.iteminstance = a.id AND gri.courseid = a.course AND gri.itemmodule = md.name
1610                  WHERE g.timemodified >= :yesterday AND
1611                        g.timemodified <= :today AND
1612                        uf.mailed = 0 AND gri.hidden = 0';
1614         $params = array('yesterday' => $yesterday, 'today' => $timenow);
1615         $submissions = $DB->get_records_sql($sql, $params);
1617         if (!empty($submissions)) {
1619             mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
1621             // Preload courses we are going to need those.
1622             $courseids = array();
1623             foreach ($submissions as $submission) {
1624                 $courseids[] = $submission->course;
1625             }
1627             // Filter out duplicates.
1628             $courseids = array_unique($courseids);
1629             $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1630             list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
1631             $sql = 'SELECT c.*, ' . $ctxselect .
1632                       ' FROM {course} c
1633                  LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
1634                      WHERE c.id ' . $courseidsql;
1636             $params['contextlevel'] = CONTEXT_COURSE;
1637             $courses = $DB->get_records_sql($sql, $params);
1639             // Clean up... this could go on for a while.
1640             unset($courseids);
1641             unset($ctxselect);
1642             unset($courseidsql);
1643             unset($params);
1645             // Simple array we'll use for caching modules.
1646             $modcache = array();
1648             // Message students about new feedback.
1649             foreach ($submissions as $submission) {
1651                 mtrace("Processing assignment submission $submission->id ...");
1653                 // Do not cache user lookups - could be too many.
1654                 if (!$user = $DB->get_record('user', array('id'=>$submission->userid))) {
1655                     mtrace('Could not find user ' . $submission->userid);
1656                     continue;
1657                 }
1659                 // Use a cache to prevent the same DB queries happening over and over.
1660                 if (!array_key_exists($submission->course, $courses)) {
1661                     mtrace('Could not find course ' . $submission->course);
1662                     continue;
1663                 }
1664                 $course = $courses[$submission->course];
1665                 if (isset($course->ctxid)) {
1666                     // Context has not yet been preloaded. Do so now.
1667                     context_helper::preload_from_record($course);
1668                 }
1670                 // Override the language and timezone of the "current" user, so that
1671                 // mail is customised for the receiver.
1672                 cron_setup_user($user, $course);
1674                 // Context lookups are already cached.
1675                 $coursecontext = context_course::instance($course->id);
1676                 if (!is_enrolled($coursecontext, $user->id)) {
1677                     $courseshortname = format_string($course->shortname,
1678                                                      true,
1679                                                      array('context' => $coursecontext));
1680                     mtrace(fullname($user) . ' not an active participant in ' . $courseshortname);
1681                     continue;
1682                 }
1684                 if (!$grader = $DB->get_record('user', array('id'=>$submission->grader))) {
1685                     mtrace('Could not find grader ' . $submission->grader);
1686                     continue;
1687                 }
1689                 if (!array_key_exists($submission->assignment, $modcache)) {
1690                     $mod = get_coursemodule_from_instance('assign', $submission->assignment, $course->id);
1691                     if (empty($mod)) {
1692                         mtrace('Could not find course module for assignment id ' . $submission->assignment);
1693                         continue;
1694                     }
1695                     $modcache[$submission->assignment] = $mod;
1696                 } else {
1697                     $mod = $modcache[$submission->assignment];
1698                 }
1699                 // Context lookups are already cached.
1700                 $contextmodule = context_module::instance($mod->id);
1702                 if (!$mod->visible) {
1703                     // Hold mail notification for hidden assignments until later.
1704                     continue;
1705                 }
1707                 // Need to send this to the student.
1708                 $messagetype = 'feedbackavailable';
1709                 $eventtype = 'assign_notification';
1710                 $updatetime = $submission->lastmodified;
1711                 $modulename = get_string('modulename', 'assign');
1713                 $uniqueid = 0;
1714                 if ($submission->blindmarking && !$submission->revealidentities) {
1715                     $uniqueid = self::get_uniqueid_for_user_static($submission->assignment, $user->id);
1716                 }
1717                 $showusers = $submission->blindmarking && !$submission->revealidentities;
1718                 self::send_assignment_notification($grader,
1719                                                    $user,
1720                                                    $messagetype,
1721                                                    $eventtype,
1722                                                    $updatetime,
1723                                                    $mod,
1724                                                    $contextmodule,
1725                                                    $course,
1726                                                    $modulename,
1727                                                    $submission->name,
1728                                                    $showusers,
1729                                                    $uniqueid);
1731                 $flags = $DB->get_record('assign_user_flags', array('userid'=>$user->id, 'assignment'=>$submission->assignment));
1732                 if ($flags) {
1733                     $flags->mailed = 1;
1734                     $DB->update_record('assign_user_flags', $flags);
1735                 } else {
1736                     $flags = new stdClass();
1737                     $flags->userid = $user->id;
1738                     $flags->assignment = $submission->assignment;
1739                     $flags->mailed = 1;
1740                     $DB->insert_record('assign_user_flags', $flags);
1741                 }
1743                 mtrace('Done');
1744             }
1745             mtrace('Done processing ' . count($submissions) . ' assignment submissions');
1747             cron_setup_user();
1749             // Free up memory just to be sure.
1750             unset($courses);
1751             unset($modcache);
1752         }
1754         // Update calendar events to provide a description.
1755         $sql = 'SELECT id
1756                     FROM {assign}
1757                     WHERE
1758                         allowsubmissionsfromdate >= :lastcron AND
1759                         allowsubmissionsfromdate <= :timenow AND
1760                         alwaysshowdescription = 0';
1761         $params = array('lastcron' => $lastcron, 'timenow' => $timenow);
1762         $newlyavailable = $DB->get_records_sql($sql, $params);
1763         foreach ($newlyavailable as $record) {
1764             $cm = get_coursemodule_from_instance('assign', $record->id, 0, false, MUST_EXIST);
1765             $context = context_module::instance($cm->id);
1767             $assignment = new assign($context, null, null);
1768             $assignment->update_calendar($cm->id);
1769         }
1771         return true;
1772     }
1774     /**
1775      * Mark in the database that this grade record should have an update notification sent by cron.
1776      *
1777      * @param stdClass $grade a grade record keyed on id
1778      * @return bool true for success
1779      */
1780     public function notify_grade_modified($grade) {
1781         global $DB;
1783         $flags = $this->get_user_flags($grade->userid, true);
1784         if ($flags->mailed != 1) {
1785             $flags->mailed = 0;
1786         }
1788         return $this->update_user_flags($flags);
1789     }
1791     /**
1792      * Update user flags for this user in this assignment.
1793      *
1794      * @param stdClass $flags a flags record keyed on id
1795      * @return bool true for success
1796      */
1797     public function update_user_flags($flags) {
1798         global $DB;
1799         if ($flags->userid <= 0 || $flags->assignment <= 0 || $flags->id <= 0) {
1800             return false;
1801         }
1803         $result = $DB->update_record('assign_user_flags', $flags);
1804         return $result;
1805     }
1807     /**
1808      * Update a grade in the grade table for the assignment and in the gradebook.
1809      *
1810      * @param stdClass $grade a grade record keyed on id
1811      * @return bool true for success
1812      */
1813     public function update_grade($grade) {
1814         global $DB;
1816         $grade->timemodified = time();
1818         if (!empty($grade->workflowstate)) {
1819             $validstates = $this->get_marking_workflow_states_for_current_user();
1820             if (!array_key_exists($grade->workflowstate, $validstates)) {
1821                 return false;
1822             }
1823         }
1825         if ($grade->grade && $grade->grade != -1) {
1826             if ($this->get_instance()->grade > 0) {
1827                 if (!is_numeric($grade->grade)) {
1828                     return false;
1829                 } else if ($grade->grade > $this->get_instance()->grade) {
1830                     return false;
1831                 } else if ($grade->grade < 0) {
1832                     return false;
1833                 }
1834             } else {
1835                 // This is a scale.
1836                 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
1837                     $scaleoptions = make_menu_from_list($scale->scale);
1838                     if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
1839                         return false;
1840                     }
1841                 }
1842             }
1843         }
1845         if (empty($grade->attemptnumber)) {
1846             // Set it to the default.
1847             $grade->attemptnumber = 0;
1848         }
1849         $result = $DB->update_record('assign_grades', $grade);
1851         // Only push to gradebook if the update is for the latest attempt.
1852         $submission = null;
1853         if ($this->get_instance()->teamsubmission) {
1854             $submission = $this->get_group_submission($grade->userid, 0, false);
1855         } else {
1856             $submission = $this->get_user_submission($grade->userid, false);
1857         }
1858         // Not the latest attempt.
1859         if ($submission && $submission->attemptnumber != $grade->attemptnumber) {
1860             return true;
1861         }
1863         if ($result) {
1864             $this->gradebook_item_update(null, $grade);
1865             \mod_assign\event\submission_graded::create_from_grade($this, $grade)->trigger();
1866         }
1867         return $result;
1868     }
1870     /**
1871      * View the grant extension date page.
1872      *
1873      * Uses url parameters 'userid'
1874      * or from parameter 'selectedusers'
1875      *
1876      * @param moodleform $mform - Used for validation of the submitted data
1877      * @return string
1878      */
1879     protected function view_grant_extension($mform) {
1880         global $DB, $CFG;
1881         require_once($CFG->dirroot . '/mod/assign/extensionform.php');
1883         $o = '';
1884         $batchusers = optional_param('selectedusers', '', PARAM_SEQUENCE);
1885         $data = new stdClass();
1886         $data->extensionduedate = null;
1887         $userid = 0;
1888         if (!$batchusers) {
1889             $userid = required_param('userid', PARAM_INT);
1891             $flags = $this->get_user_flags($userid, false);
1893             $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
1895             if ($flags) {
1896                 $data->extensionduedate = $flags->extensionduedate;
1897             }
1898             $data->userid = $userid;
1899         } else {
1900             $data->batchusers = $batchusers;
1901         }
1902         $header = new assign_header($this->get_instance(),
1903                                     $this->get_context(),
1904                                     $this->show_intro(),
1905                                     $this->get_course_module()->id,
1906                                     get_string('grantextension', 'assign'));
1907         $o .= $this->get_renderer()->render($header);
1909         if (!$mform) {
1910             $formparams = array($this->get_course_module()->id,
1911                                 $userid,
1912                                 $batchusers,
1913                                 $this->get_instance(),
1914                                 $data);
1915             $mform = new mod_assign_extension_form(null, $formparams);
1916         }
1917         $o .= $this->get_renderer()->render(new assign_form('extensionform', $mform));
1918         $o .= $this->view_footer();
1919         return $o;
1920     }
1922     /**
1923      * Get a list of the users in the same group as this user.
1924      *
1925      * @param int $groupid The id of the group whose members we want or 0 for the default group
1926      * @param bool $onlyids Whether to retrieve only the user id's
1927      * @return array The users (possibly id's only)
1928      */
1929     public function get_submission_group_members($groupid, $onlyids) {
1930         $members = array();
1931         if ($groupid != 0) {
1932             if ($onlyids) {
1933                 $allusers = groups_get_members($groupid, 'u.id');
1934             } else {
1935                 $allusers = groups_get_members($groupid);
1936             }
1937             foreach ($allusers as $user) {
1938                 if ($this->get_submission_group($user->id)) {
1939                     $members[] = $user;
1940                 }
1941             }
1942         } else {
1943             $allusers = $this->list_participants(null, $onlyids);
1944             foreach ($allusers as $user) {
1945                 if ($this->get_submission_group($user->id) == null) {
1946                     $members[] = $user;
1947                 }
1948             }
1949         }
1950         // Exclude suspended users, if user can't see them.
1951         if (!has_capability('moodle/course:viewsuspendedusers', $this->context)) {
1952             foreach ($members as $key => $member) {
1953                 if (!$this->is_active_user($member->id)) {
1954                     unset($members[$key]);
1955                 }
1956             }
1957         }
1958         return $members;
1959     }
1961     /**
1962      * Get a list of the users in the same group as this user that have not submitted the assignment.
1963      *
1964      * @param int $groupid The id of the group whose members we want or 0 for the default group
1965      * @param bool $onlyids Whether to retrieve only the user id's
1966      * @return array The users (possibly id's only)
1967      */
1968     public function get_submission_group_members_who_have_not_submitted($groupid, $onlyids) {
1969         $instance = $this->get_instance();
1970         if (!$instance->teamsubmission || !$instance->requireallteammemberssubmit) {
1971             return array();
1972         }
1973         $members = $this->get_submission_group_members($groupid, $onlyids);
1975         foreach ($members as $id => $member) {
1976             $submission = $this->get_user_submission($member->id, false);
1977             if ($submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
1978                 unset($members[$id]);
1979             } else {
1980                 if ($this->is_blind_marking()) {
1981                     $members[$id]->alias = get_string('hiddenuser', 'assign') .
1982                                            $this->get_uniqueid_for_user($id);
1983                 }
1984             }
1985         }
1986         return $members;
1987     }
1989     /**
1990      * Load the group submission object for a particular user, optionally creating it if required.
1991      *
1992      * @param int $userid The id of the user whose submission we want
1993      * @param int $groupid The id of the group for this user - may be 0 in which
1994      *                     case it is determined from the userid.
1995      * @param bool $create If set to true a new submission object will be created in the database
1996      * @param int $attemptnumber - -1 means the latest attempt
1997      * @return stdClass The submission
1998      */
1999     public function get_group_submission($userid, $groupid, $create, $attemptnumber=-1) {
2000         global $DB;
2002         if ($groupid == 0) {
2003             $group = $this->get_submission_group($userid);
2004             if ($group) {
2005                 $groupid = $group->id;
2006             }
2007         }
2009         // Now get the group submission.
2010         $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
2011         if ($attemptnumber >= 0) {
2012             $params['attemptnumber'] = $attemptnumber;
2013         }
2015         // Only return the row with the highest attemptnumber.
2016         $submission = null;
2017         $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
2018         if ($submissions) {
2019             $submission = reset($submissions);
2020         }
2022         if ($submission) {
2023             return $submission;
2024         }
2025         if ($create) {
2026             $submission = new stdClass();
2027             $submission->assignment = $this->get_instance()->id;
2028             $submission->userid = 0;
2029             $submission->groupid = $groupid;
2030             $submission->timecreated = time();
2031             $submission->timemodified = $submission->timecreated;
2032             if ($attemptnumber >= 0) {
2033                 $submission->attemptnumber = $attemptnumber;
2034             } else {
2035                 $submission->attemptnumber = 0;
2036             }
2038             $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
2039             $sid = $DB->insert_record('assign_submission', $submission);
2040             return $DB->get_record('assign_submission', array('id' => $sid));
2041         }
2042         return false;
2043     }
2045     /**
2046      * View a summary listing of all assignments in the current course.
2047      *
2048      * @return string
2049      */
2050     private function view_course_index() {
2051         global $USER;
2053         $o = '';
2055         $course = $this->get_course();
2056         $strplural = get_string('modulenameplural', 'assign');
2058         if (!$cms = get_coursemodules_in_course('assign', $course->id, 'm.duedate')) {
2059             $o .= $this->get_renderer()->notification(get_string('thereareno', 'moodle', $strplural));
2060             $o .= $this->get_renderer()->continue_button(new moodle_url('/course/view.php', array('id' => $course->id)));
2061             return $o;
2062         }
2064         $strsectionname = '';
2065         $usesections = course_format_uses_sections($course->format);
2066         $modinfo = get_fast_modinfo($course);
2068         if ($usesections) {
2069             $strsectionname = get_string('sectionname', 'format_'.$course->format);
2070             $sections = $modinfo->get_section_info_all();
2071         }
2072         $courseindexsummary = new assign_course_index_summary($usesections, $strsectionname);
2074         $timenow = time();
2076         $currentsection = '';
2077         foreach ($modinfo->instances['assign'] as $cm) {
2078             if (!$cm->uservisible) {
2079                 continue;
2080             }
2082             $timedue = $cms[$cm->id]->duedate;
2084             $sectionname = '';
2085             if ($usesections && $cm->sectionnum) {
2086                 $sectionname = get_section_name($course, $sections[$cm->sectionnum]);
2087             }
2089             $submitted = '';
2090             $context = context_module::instance($cm->id);
2092             $assignment = new assign($context, $cm, $course);
2094             if (has_capability('mod/assign:grade', $context)) {
2095                 $submitted = $assignment->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED);
2097             } else if (has_capability('mod/assign:submit', $context)) {
2098                 $usersubmission = $assignment->get_user_submission($USER->id, false);
2100                 if (!empty($usersubmission->status)) {
2101                     $submitted = get_string('submissionstatus_' . $usersubmission->status, 'assign');
2102                 } else {
2103                     $submitted = get_string('submissionstatus_', 'assign');
2104                 }
2105             }
2106             $gradinginfo = grade_get_grades($course->id, 'mod', 'assign', $cm->instance, $USER->id);
2107             if (isset($gradinginfo->items[0]->grades[$USER->id]) &&
2108                     !$gradinginfo->items[0]->grades[$USER->id]->hidden ) {
2109                 $grade = $gradinginfo->items[0]->grades[$USER->id]->str_grade;
2110             } else {
2111                 $grade = '-';
2112             }
2114             $courseindexsummary->add_assign_info($cm->id, $cm->name, $sectionname, $timedue, $submitted, $grade);
2116         }
2118         $o .= $this->get_renderer()->render($courseindexsummary);
2119         $o .= $this->view_footer();
2121         return $o;
2122     }
2124     /**
2125      * View a page rendered by a plugin.
2126      *
2127      * Uses url parameters 'pluginaction', 'pluginsubtype', 'plugin', and 'id'.
2128      *
2129      * @return string
2130      */
2131     protected function view_plugin_page() {
2132         global $USER;
2134         $o = '';
2136         $pluginsubtype = required_param('pluginsubtype', PARAM_ALPHA);
2137         $plugintype = required_param('plugin', PARAM_TEXT);
2138         $pluginaction = required_param('pluginaction', PARAM_ALPHA);
2140         $plugin = $this->get_plugin_by_type($pluginsubtype, $plugintype);
2141         if (!$plugin) {
2142             print_error('invalidformdata', '');
2143             return;
2144         }
2146         $o .= $plugin->view_page($pluginaction);
2148         return $o;
2149     }
2152     /**
2153      * This is used for team assignments to get the group for the specified user.
2154      * If the user is a member of multiple or no groups this will return false
2155      *
2156      * @param int $userid The id of the user whose submission we want
2157      * @return mixed The group or false
2158      */
2159     public function get_submission_group($userid) {
2160         $grouping = $this->get_instance()->teamsubmissiongroupingid;
2161         $groups = groups_get_all_groups($this->get_course()->id, $userid, $grouping);
2162         if (count($groups) != 1) {
2163             return false;
2164         }
2165         return array_pop($groups);
2166     }
2169     /**
2170      * Display the submission that is used by a plugin.
2171      *
2172      * Uses url parameters 'sid', 'gid' and 'plugin'.
2173      *
2174      * @param string $pluginsubtype
2175      * @return string
2176      */
2177     protected function view_plugin_content($pluginsubtype) {
2178         $o = '';
2180         $submissionid = optional_param('sid', 0, PARAM_INT);
2181         $gradeid = optional_param('gid', 0, PARAM_INT);
2182         $plugintype = required_param('plugin', PARAM_TEXT);
2183         $item = null;
2184         if ($pluginsubtype == 'assignsubmission') {
2185             $plugin = $this->get_submission_plugin_by_type($plugintype);
2186             if ($submissionid <= 0) {
2187                 throw new coding_exception('Submission id should not be 0');
2188             }
2189             $item = $this->get_submission($submissionid);
2191             // Check permissions.
2192             $this->require_view_submission($item->userid);
2193             $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2194                                                               $this->get_context(),
2195                                                               $this->show_intro(),
2196                                                               $this->get_course_module()->id,
2197                                                               $plugin->get_name()));
2198             $o .= $this->get_renderer()->render(new assign_submission_plugin_submission($plugin,
2199                                                               $item,
2200                                                               assign_submission_plugin_submission::FULL,
2201                                                               $this->get_course_module()->id,
2202                                                               $this->get_return_action(),
2203                                                               $this->get_return_params()));
2205             // Trigger event for viewing a submission.
2206             \mod_assign\event\submission_viewed::create_from_submission($this, $item)->trigger();
2208         } else {
2209             $plugin = $this->get_feedback_plugin_by_type($plugintype);
2210             if ($gradeid <= 0) {
2211                 throw new coding_exception('Grade id should not be 0');
2212             }
2213             $item = $this->get_grade($gradeid);
2214             // Check permissions.
2215             $this->require_view_submission($item->userid);
2216             $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2217                                                               $this->get_context(),
2218                                                               $this->show_intro(),
2219                                                               $this->get_course_module()->id,
2220                                                               $plugin->get_name()));
2221             $o .= $this->get_renderer()->render(new assign_feedback_plugin_feedback($plugin,
2222                                                               $item,
2223                                                               assign_feedback_plugin_feedback::FULL,
2224                                                               $this->get_course_module()->id,
2225                                                               $this->get_return_action(),
2226                                                               $this->get_return_params()));
2228             // Trigger event for viewing feedback.
2229             \mod_assign\event\feedback_viewed::create_from_grade($this, $item)->trigger();
2230         }
2232         $o .= $this->view_return_links();
2234         $o .= $this->view_footer();
2236         return $o;
2237     }
2239     /**
2240      * Rewrite plugin file urls so they resolve correctly in an exported zip.
2241      *
2242      * @param string $text - The replacement text
2243      * @param stdClass $user - The user record
2244      * @param assign_plugin $plugin - The assignment plugin
2245      */
2246     public function download_rewrite_pluginfile_urls($text, $user, $plugin) {
2247         $groupmode = groups_get_activity_groupmode($this->get_course_module());
2248         $groupname = '';
2249         if ($groupmode) {
2250             $groupid = groups_get_activity_group($this->get_course_module(), true);
2251             $groupname = groups_get_group_name($groupid).'-';
2252         }
2254         if ($this->is_blind_marking()) {
2255             $prefix = $groupname . get_string('participant', 'assign');
2256             $prefix = str_replace('_', ' ', $prefix);
2257             $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2258         } else {
2259             $prefix = $groupname . fullname($user);
2260             $prefix = str_replace('_', ' ', $prefix);
2261             $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2262         }
2264         $subtype = $plugin->get_subtype();
2265         $type = $plugin->get_type();
2266         $prefix = $prefix . $subtype . '_' . $type . '_';
2268         $result = str_replace('@@PLUGINFILE@@/', $prefix, $text);
2270         return $result;
2271     }
2273     /**
2274      * Render the content in editor that is often used by plugin.
2275      *
2276      * @param string $filearea
2277      * @param int  $submissionid
2278      * @param string $plugintype
2279      * @param string $editor
2280      * @param string $component
2281      * @return string
2282      */
2283     public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
2284         global $CFG;
2286         $result = '';
2288         $plugin = $this->get_submission_plugin_by_type($plugintype);
2290         $text = $plugin->get_editor_text($editor, $submissionid);
2291         $format = $plugin->get_editor_format($editor, $submissionid);
2293         $finaltext = file_rewrite_pluginfile_urls($text,
2294                                                   'pluginfile.php',
2295                                                   $this->get_context()->id,
2296                                                   $component,
2297                                                   $filearea,
2298                                                   $submissionid);
2299         $params = array('overflowdiv' => true, 'context' => $this->get_context());
2300         $result .= format_text($finaltext, $format, $params);
2302         if ($CFG->enableportfolios) {
2303             require_once($CFG->libdir . '/portfoliolib.php');
2305             $button = new portfolio_add_button();
2306             $portfolioparams = array('cmid' => $this->get_course_module()->id,
2307                                      'sid' => $submissionid,
2308                                      'plugin' => $plugintype,
2309                                      'editor' => $editor,
2310                                      'area'=>$filearea);
2311             $button->set_callback_options('assign_portfolio_caller', $portfolioparams, 'mod_assign');
2312             $fs = get_file_storage();
2314             if ($files = $fs->get_area_files($this->context->id,
2315                                              $component,
2316                                              $filearea,
2317                                              $submissionid,
2318                                              'timemodified',
2319                                              false)) {
2320                 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
2321             } else {
2322                 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
2323             }
2324             $result .= $button->to_html();
2325         }
2326         return $result;
2327     }
2329     /**
2330      * Display a continue page after grading.
2331      *
2332      * @param string $message - The message to display.
2333      * @return string
2334      */
2335     protected function view_savegrading_result($message) {
2336         $o = '';
2337         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2338                                                       $this->get_context(),
2339                                                       $this->show_intro(),
2340                                                       $this->get_course_module()->id,
2341                                                       get_string('savegradingresult', 'assign')));
2342         $gradingresult = new assign_gradingmessage(get_string('savegradingresult', 'assign'),
2343                                                    $message,
2344                                                    $this->get_course_module()->id);
2345         $o .= $this->get_renderer()->render($gradingresult);
2346         $o .= $this->view_footer();
2347         return $o;
2348     }
2349     /**
2350      * Display a continue page after quickgrading.
2351      *
2352      * @param string $message - The message to display.
2353      * @return string
2354      */
2355     protected function view_quickgrading_result($message) {
2356         $o = '';
2357         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2358                                                       $this->get_context(),
2359                                                       $this->show_intro(),
2360                                                       $this->get_course_module()->id,
2361                                                       get_string('quickgradingresult', 'assign')));
2362         $gradingresult = new assign_gradingmessage(get_string('quickgradingresult', 'assign'),
2363                                                    $message,
2364                                                    $this->get_course_module()->id);
2365         $o .= $this->get_renderer()->render($gradingresult);
2366         $o .= $this->view_footer();
2367         return $o;
2368     }
2370     /**
2371      * Display the page footer.
2372      *
2373      * @return string
2374      */
2375     protected function view_footer() {
2376         // When viewing the footer during PHPUNIT tests a set_state error is thrown.
2377         if (!PHPUNIT_TEST) {
2378             return $this->get_renderer()->render_footer();
2379         }
2381         return '';
2382     }
2384     /**
2385      * Throw an error if the permissions to view this users submission are missing.
2386      *
2387      * @throws required_capability_exception
2388      * @return none
2389      */
2390     public function require_view_submission($userid) {
2391         if (!$this->can_view_submission($userid)) {
2392             throw new required_capability_exception($this->context, 'mod/assign:viewgrades', 'nopermission', '');
2393         }
2394     }
2396     /**
2397      * Throw an error if the permissions to view grades in this assignment are missing.
2398      *
2399      * @throws required_capability_exception
2400      * @return none
2401      */
2402     public function require_view_grades() {
2403         if (!$this->can_view_grades()) {
2404             throw new required_capability_exception($this->context, 'mod/assign:viewgrades', 'nopermission', '');
2405         }
2406     }
2408     /**
2409      * Does this user have view grade or grade permission for this assignment?
2410      *
2411      * @return bool
2412      */
2413     public function can_view_grades() {
2414         // Permissions check.
2415         if (!has_any_capability(array('mod/assign:viewgrades', 'mod/assign:grade'), $this->context)) {
2416             return false;
2417         }
2419         return true;
2420     }
2422     /**
2423      * Does this user have grade permission for this assignment?
2424      *
2425      * @return bool
2426      */
2427     public function can_grade() {
2428         // Permissions check.
2429         if (!has_capability('mod/assign:grade', $this->context)) {
2430             return false;
2431         }
2433         return true;
2434     }
2436     /**
2437      * Download a zip file of all assignment submissions.
2438      *
2439      * @return string - If an error occurs, this will contain the error page.
2440      */
2441     protected function download_submissions() {
2442         global $CFG, $DB;
2444         // More efficient to load this here.
2445         require_once($CFG->libdir.'/filelib.php');
2447         $this->require_view_grades();
2449         // Load all users with submit.
2450         $students = get_enrolled_users($this->context, "mod/assign:submit", null, 'u.*', null, null, null,
2451                         $this->show_only_active_users());
2453         // Build a list of files to zip.
2454         $filesforzipping = array();
2455         $fs = get_file_storage();
2457         $groupmode = groups_get_activity_groupmode($this->get_course_module());
2458         // All users.
2459         $groupid = 0;
2460         $groupname = '';
2461         if ($groupmode) {
2462             $groupid = groups_get_activity_group($this->get_course_module(), true);
2463             $groupname = groups_get_group_name($groupid).'-';
2464         }
2466         // Construct the zip file name.
2467         $filename = clean_filename($this->get_course()->shortname . '-' .
2468                                    $this->get_instance()->name . '-' .
2469                                    $groupname.$this->get_course_module()->id . '.zip');
2471         // Get all the files for each student.
2472         foreach ($students as $student) {
2473             $userid = $student->id;
2475             if ((groups_is_member($groupid, $userid) or !$groupmode or !$groupid)) {
2476                 // Get the plugins to add their own files to the zip.
2478                 $submissiongroup = false;
2479                 $groupname = '';
2480                 if ($this->get_instance()->teamsubmission) {
2481                     $submission = $this->get_group_submission($userid, 0, false);
2482                     $submissiongroup = $this->get_submission_group($userid);
2483                     if ($submissiongroup) {
2484                         $groupname = $submissiongroup->name . '-';
2485                     } else {
2486                         $groupname = get_string('defaultteam', 'assign') . '-';
2487                     }
2488                 } else {
2489                     $submission = $this->get_user_submission($userid, false);
2490                 }
2492                 if ($this->is_blind_marking()) {
2493                     $prefix = str_replace('_', ' ', $groupname . get_string('participant', 'assign'));
2494                     $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2495                 } else {
2496                     $prefix = str_replace('_', ' ', $groupname . fullname($student));
2497                     $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2498                 }
2500                 if ($submission) {
2501                     foreach ($this->submissionplugins as $plugin) {
2502                         if ($plugin->is_enabled() && $plugin->is_visible()) {
2503                             $pluginfiles = $plugin->get_files($submission, $student);
2504                             foreach ($pluginfiles as $zipfilename => $file) {
2505                                 $subtype = $plugin->get_subtype();
2506                                 $type = $plugin->get_type();
2507                                 $prefixedfilename = clean_filename($prefix .
2508                                                                    $subtype .
2509                                                                    '_' .
2510                                                                    $type .
2511                                                                    '_' .
2512                                                                    $zipfilename);
2513                                 $filesforzipping[$prefixedfilename] = $file;
2514                             }
2515                         }
2516                     }
2517                 }
2518             }
2519         }
2520         $result = '';
2521         if (count($filesforzipping) == 0) {
2522             $header = new assign_header($this->get_instance(),
2523                                         $this->get_context(),
2524                                         '',
2525                                         $this->get_course_module()->id,
2526                                         get_string('downloadall', 'assign'));
2527             $result .= $this->get_renderer()->render($header);
2528             $result .= $this->get_renderer()->notification(get_string('nosubmission', 'assign'));
2529             $url = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id,
2530                                                                     'action'=>'grading'));
2531             $result .= $this->get_renderer()->continue_button($url);
2532             $result .= $this->view_footer();
2533         } else if ($zipfile = $this->pack_files($filesforzipping)) {
2534             \mod_assign\event\all_submissions_downloaded::create_from_assign($this)->trigger();
2535             // Send file and delete after sending.
2536             send_temp_file($zipfile, $filename);
2537             // We will not get here - send_temp_file calls exit.
2538         }
2539         return $result;
2540     }
2542     /**
2543      * Util function to add a message to the log.
2544      *
2545      * @deprecated since 2.7 - Use new events system instead.
2546      *             (see http://docs.moodle.org/dev/Migrating_logging_calls_in_plugins).
2547      *
2548      * @param string $action The current action
2549      * @param string $info A detailed description of the change. But no more than 255 characters.
2550      * @param string $url The url to the assign module instance.
2551      * @param bool $return If true, returns the arguments, else adds to log. The purpose of this is to
2552      *                     retrieve the arguments to use them with the new event system (Event 2).
2553      * @return void|array
2554      */
2555     public function add_to_log($action = '', $info = '', $url='', $return = false) {
2556         global $USER;
2558         $fullurl = 'view.php?id=' . $this->get_course_module()->id;
2559         if ($url != '') {
2560             $fullurl .= '&' . $url;
2561         }
2563         $args = array(
2564             $this->get_course()->id,
2565             'assign',
2566             $action,
2567             $fullurl,
2568             $info,
2569             $this->get_course_module()->id
2570         );
2572         if ($return) {
2573             // We only need to call debugging when returning a value. This is because the call to
2574             // call_user_func_array('add_to_log', $args) will trigger a debugging message of it's own.
2575             debugging('The mod_assign add_to_log() function is now deprecated.', DEBUG_DEVELOPER);
2576             return $args;
2577         }
2578         call_user_func_array('add_to_log', $args);
2579     }
2581     /**
2582      * Lazy load the page renderer and expose the renderer to plugins.
2583      *
2584      * @return assign_renderer
2585      */
2586     public function get_renderer() {
2587         global $PAGE;
2588         if ($this->output) {
2589             return $this->output;
2590         }
2591         $this->output = $PAGE->get_renderer('mod_assign');
2592         return $this->output;
2593     }
2595     /**
2596      * Load the submission object for a particular user, optionally creating it if required.
2597      *
2598      * For team assignments there are 2 submissions - the student submission and the team submission
2599      * All files are associated with the team submission but the status of the students contribution is
2600      * recorded separately.
2601      *
2602      * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
2603      * @param bool $create optional - defaults to false. If set to true a new submission object
2604      *                     will be created in the database.
2605      * @param int $attemptnumber - -1 means the latest attempt
2606      * @return stdClass The submission
2607      */
2608     public function get_user_submission($userid, $create, $attemptnumber=-1) {
2609         global $DB, $USER;
2611         if (!$userid) {
2612             $userid = $USER->id;
2613         }
2614         // If the userid is not null then use userid.
2615         $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid, 'groupid'=>0);
2616         if ($attemptnumber >= 0) {
2617             $params['attemptnumber'] = $attemptnumber;
2618         }
2620         // Only return the row with the highest attemptnumber.
2621         $submission = null;
2622         $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
2623         if ($submissions) {
2624             $submission = reset($submissions);
2625         }
2627         if ($submission) {
2628             return $submission;
2629         }
2630         if ($create) {
2631             $submission = new stdClass();
2632             $submission->assignment   = $this->get_instance()->id;
2633             $submission->userid       = $userid;
2634             $submission->timecreated = time();
2635             $submission->timemodified = $submission->timecreated;
2636             $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
2637             if ($attemptnumber >= 0) {
2638                 $submission->attemptnumber = $attemptnumber;
2639             } else {
2640                 $submission->attemptnumber = 0;
2641             }
2642             $sid = $DB->insert_record('assign_submission', $submission);
2643             return $DB->get_record('assign_submission', array('id' => $sid));
2644         }
2645         return false;
2646     }
2648     /**
2649      * Load the submission object from it's id.
2650      *
2651      * @param int $submissionid The id of the submission we want
2652      * @return stdClass The submission
2653      */
2654     protected function get_submission($submissionid) {
2655         global $DB;
2657         $params = array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid);
2658         return $DB->get_record('assign_submission', $params, '*', MUST_EXIST);
2659     }
2661     /**
2662      * This will retrieve a user flags object from the db optionally creating it if required.
2663      * The user flags was split from the user_grades table in 2.5.
2664      *
2665      * @param int $userid The user we are getting the flags for.
2666      * @param bool $create If true the flags record will be created if it does not exist
2667      * @return stdClass The flags record
2668      */
2669     public function get_user_flags($userid, $create) {
2670         global $DB, $USER;
2672         // If the userid is not null then use userid.
2673         if (!$userid) {
2674             $userid = $USER->id;
2675         }
2677         $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
2679         $flags = $DB->get_record('assign_user_flags', $params);
2681         if ($flags) {
2682             return $flags;
2683         }
2684         if ($create) {
2685             $flags = new stdClass();
2686             $flags->assignment = $this->get_instance()->id;
2687             $flags->userid = $userid;
2688             $flags->locked = 0;
2689             $flags->extensionduedate = 0;
2690             $flags->workflowstate = '';
2691             $flags->allocatedmarker = 0;
2693             // The mailed flag can be one of 3 values: 0 is unsent, 1 is sent and 2 is do not send yet.
2694             // This is because students only want to be notified about certain types of update (grades and feedback).
2695             $flags->mailed = 2;
2697             $fid = $DB->insert_record('assign_user_flags', $flags);
2698             $flags->id = $fid;
2699             return $flags;
2700         }
2701         return false;
2702     }
2704     /**
2705      * This will retrieve a grade object from the db, optionally creating it if required.
2706      *
2707      * @param int $userid The user we are grading
2708      * @param bool $create If true the grade will be created if it does not exist
2709      * @param int $attemptnumber The attempt number to retrieve the grade for. -1 means the latest submission.
2710      * @return stdClass The grade record
2711      */
2712     public function get_user_grade($userid, $create, $attemptnumber=-1) {
2713         global $DB, $USER;
2715         // If the userid is not null then use userid.
2716         if (!$userid) {
2717             $userid = $USER->id;
2718         }
2720         $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
2721         if ($attemptnumber < 0) {
2722             // Make sure this grade matches the latest submission attempt.
2723             if ($this->get_instance()->teamsubmission) {
2724                 $submission = $this->get_group_submission($userid, 0, false);
2725             } else {
2726                 $submission = $this->get_user_submission($userid, false);
2727             }
2728             if ($submission) {
2729                 $attemptnumber = $submission->attemptnumber;
2730             }
2731         }
2733         if ($attemptnumber >= 0) {
2734             $params['attemptnumber'] = $attemptnumber;
2735         }
2737         $grades = $DB->get_records('assign_grades', $params, 'attemptnumber DESC', '*', 0, 1);
2739         if ($grades) {
2740             return reset($grades);
2741         }
2742         if ($create) {
2743             $grade = new stdClass();
2744             $grade->assignment   = $this->get_instance()->id;
2745             $grade->userid       = $userid;
2746             $grade->timecreated = time();
2747             $grade->timemodified = $grade->timecreated;
2748             $grade->grade = -1;
2749             $grade->grader = $USER->id;
2750             if ($attemptnumber >= 0) {
2751                 $grade->attemptnumber = $attemptnumber;
2752             }
2754             $gid = $DB->insert_record('assign_grades', $grade);
2755             $grade->id = $gid;
2756             return $grade;
2757         }
2758         return false;
2759     }
2761     /**
2762      * This will retrieve a grade object from the db.
2763      *
2764      * @param int $gradeid The id of the grade
2765      * @return stdClass The grade record
2766      */
2767     protected function get_grade($gradeid) {
2768         global $DB;
2770         $params = array('assignment'=>$this->get_instance()->id, 'id'=>$gradeid);
2771         return $DB->get_record('assign_grades', $params, '*', MUST_EXIST);
2772     }
2774     /**
2775      * Print the grading page for a single user submission.
2776      *
2777      * @param moodleform $mform
2778      * @return string
2779      */
2780     protected function view_single_grade_page($mform) {
2781         global $DB, $CFG;
2783         $o = '';
2784         $instance = $this->get_instance();
2786         require_once($CFG->dirroot . '/mod/assign/gradeform.php');
2788         // Need submit permission to submit an assignment.
2789         require_capability('mod/assign:grade', $this->context);
2791         $header = new assign_header($instance,
2792                                     $this->get_context(),
2793                                     false,
2794                                     $this->get_course_module()->id,
2795                                     get_string('grading', 'assign'));
2796         $o .= $this->get_renderer()->render($header);
2798         // If userid is passed - we are only grading a single student.
2799         $rownum = required_param('rownum', PARAM_INT);
2800         $useridlistid = optional_param('useridlistid', time(), PARAM_INT);
2801         $userid = optional_param('userid', 0, PARAM_INT);
2802         $attemptnumber = optional_param('attemptnumber', -1, PARAM_INT);
2804         $cache = cache::make_from_params(cache_store::MODE_SESSION, 'mod_assign', 'useridlist');
2805         if (!$userid) {
2806             if (!$useridlist = $cache->get($this->get_course_module()->id . '_' . $useridlistid)) {
2807                 $useridlist = $this->get_grading_userid_list();
2808             }
2809             $cache->set($this->get_course_module()->id . '_' . $useridlistid, $useridlist);
2810         } else {
2811             $rownum = 0;
2812             $useridlist = array($userid);
2813         }
2815         if ($rownum < 0 || $rownum > count($useridlist)) {
2816             throw new coding_exception('Row is out of bounds for the current grading table: ' . $rownum);
2817         }
2819         $last = false;
2820         $userid = $useridlist[$rownum];
2821         if ($rownum == count($useridlist) - 1) {
2822             $last = true;
2823         }
2824         $user = $DB->get_record('user', array('id' => $userid));
2825         if ($user) {
2826             $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2827             $usersummary = new assign_user_summary($user,
2828                                                    $this->get_course()->id,
2829                                                    $viewfullnames,
2830                                                    $this->is_blind_marking(),
2831                                                    $this->get_uniqueid_for_user($user->id),
2832                                                    get_extra_user_fields($this->get_context()),
2833                                                    !$this->is_active_user($userid));
2834             $o .= $this->get_renderer()->render($usersummary);
2835         }
2836         $submission = $this->get_user_submission($userid, false, $attemptnumber);
2837         $submissiongroup = null;
2838         $teamsubmission = null;
2839         $notsubmitted = array();
2840         if ($instance->teamsubmission) {
2841             $teamsubmission = $this->get_group_submission($userid, 0, false, $attemptnumber);
2842             $submissiongroup = $this->get_submission_group($userid);
2843             $groupid = 0;
2844             if ($submissiongroup) {
2845                 $groupid = $submissiongroup->id;
2846             }
2847             $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
2849         }
2851         // Get the requested grade.
2852         $grade = $this->get_user_grade($userid, false, $attemptnumber);
2853         $flags = $this->get_user_flags($userid, false);
2854         if ($this->can_view_submission($userid)) {
2855             $gradelocked = ($flags && $flags->locked) || $this->grading_disabled($userid);
2856             $extensionduedate = null;
2857             if ($flags) {
2858                 $extensionduedate = $flags->extensionduedate;
2859             }
2860             $showedit = $this->submissions_open($userid) && ($this->is_any_submission_plugin_enabled());
2861             $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2863             $submissionstatus = new assign_submission_status($instance->allowsubmissionsfromdate,
2864                                                              $instance->alwaysshowdescription,
2865                                                              $submission,
2866                                                              $instance->teamsubmission,
2867                                                              $teamsubmission,
2868                                                              $submissiongroup,
2869                                                              $notsubmitted,
2870                                                              $this->is_any_submission_plugin_enabled(),
2871                                                              $gradelocked,
2872                                                              $this->is_graded($userid),
2873                                                              $instance->duedate,
2874                                                              $instance->cutoffdate,
2875                                                              $this->get_submission_plugins(),
2876                                                              $this->get_return_action(),
2877                                                              $this->get_return_params(),
2878                                                              $this->get_course_module()->id,
2879                                                              $this->get_course()->id,
2880                                                              assign_submission_status::GRADER_VIEW,
2881                                                              $showedit,
2882                                                              false,
2883                                                              $viewfullnames,
2884                                                              $extensionduedate,
2885                                                              $this->get_context(),
2886                                                              $this->is_blind_marking(),
2887                                                              '',
2888                                                              $instance->attemptreopenmethod,
2889                                                              $instance->maxattempts);
2890             $o .= $this->get_renderer()->render($submissionstatus);
2891         }
2893         if ($grade) {
2894             $data = new stdClass();
2895             if ($grade->grade !== null && $grade->grade >= 0) {
2896                 $data->grade = format_float($grade->grade, 2);
2897             }
2898             if (!empty($flags->workflowstate)) {
2899                 $data->workflowstate = $flags->workflowstate;
2900             }
2901             if (!empty($flags->allocatedmarker)) {
2902                 $data->allocatedmarker = $flags->allocatedmarker;
2903             }
2904         } else {
2905             $data = new stdClass();
2906             $data->grade = '';
2907         }
2908         // Warning if required.
2909         $allsubmissions = $this->get_all_submissions($userid);
2911         if ($attemptnumber != -1) {
2912             $params = array('attemptnumber'=>$attemptnumber + 1,
2913                             'totalattempts'=>count($allsubmissions));
2914             $message = get_string('editingpreviousfeedbackwarning', 'assign', $params);
2915             $o .= $this->get_renderer()->notification($message);
2916         }
2918         // Now show the grading form.
2919         if (!$mform) {
2920             $pagination = array('rownum'=>$rownum,
2921                                 'useridlistid'=>$useridlistid,
2922                                 'last'=>$last,
2923                                 'userid'=>optional_param('userid', 0, PARAM_INT),
2924                                 'attemptnumber'=>$attemptnumber);
2925             $formparams = array($this, $data, $pagination);
2926             $mform = new mod_assign_grade_form(null,
2927                                                $formparams,
2928                                                'post',
2929                                                '',
2930                                                array('class'=>'gradeform'));
2931         }
2932         $o .= $this->get_renderer()->heading(get_string('grade'), 3);
2933         $o .= $this->get_renderer()->render(new assign_form('gradingform', $mform));
2935         if (count($allsubmissions) > 1 && $attemptnumber == -1) {
2936             $allgrades = $this->get_all_grades($userid);
2937             $history = new assign_attempt_history($allsubmissions,
2938                                                   $allgrades,
2939                                                   $this->get_submission_plugins(),
2940                                                   $this->get_feedback_plugins(),
2941                                                   $this->get_course_module()->id,
2942                                                   $this->get_return_action(),
2943                                                   $this->get_return_params(),
2944                                                   true,
2945                                                   $useridlistid,
2946                                                   $rownum);
2948             $o .= $this->get_renderer()->render($history);
2949         }
2951         \mod_assign\event\grading_form_viewed::create_from_user($this, $user)->trigger();
2953         $o .= $this->view_footer();
2954         return $o;
2955     }
2957     /**
2958      * Show a confirmation page to make sure they want to release student identities.
2959      *
2960      * @return string
2961      */
2962     protected function view_reveal_identities_confirm() {
2963         require_capability('mod/assign:revealidentities', $this->get_context());
2965         $o = '';
2966         $header = new assign_header($this->get_instance(),
2967                                     $this->get_context(),
2968                                     false,
2969                                     $this->get_course_module()->id);
2970         $o .= $this->get_renderer()->render($header);
2972         $urlparams = array('id'=>$this->get_course_module()->id,
2973                            'action'=>'revealidentitiesconfirm',
2974                            'sesskey'=>sesskey());
2975         $confirmurl = new moodle_url('/mod/assign/view.php', $urlparams);
2977         $urlparams = array('id'=>$this->get_course_module()->id,
2978                            'action'=>'grading');
2979         $cancelurl = new moodle_url('/mod/assign/view.php', $urlparams);
2981         $o .= $this->get_renderer()->confirm(get_string('revealidentitiesconfirm', 'assign'),
2982                                              $confirmurl,
2983                                              $cancelurl);
2984         $o .= $this->view_footer();
2986         \mod_assign\event\reveal_identities_confirmation_page_viewed::create_from_assign($this)->trigger();
2988         return $o;
2989     }
2991     /**
2992      * View a link to go back to the previous page. Uses url parameters returnaction and returnparams.
2993      *
2994      * @return string
2995      */
2996     protected function view_return_links() {
2997         $returnaction = optional_param('returnaction', '', PARAM_ALPHA);
2998         $returnparams = optional_param('returnparams', '', PARAM_TEXT);
3000         $params = array();
3001         $returnparams = str_replace('&amp;', '&', $returnparams);
3002         parse_str($returnparams, $params);
3003         $newparams = array('id' => $this->get_course_module()->id, 'action' => $returnaction);
3004         $params = array_merge($newparams, $params);
3006         $url = new moodle_url('/mod/assign/view.php', $params);
3007         return $this->get_renderer()->single_button($url, get_string('back'), 'get');
3008     }
3010     /**
3011      * View the grading table of all submissions for this assignment.
3012      *
3013      * @return string
3014      */
3015     protected function view_grading_table() {
3016         global $USER, $CFG;
3018         // Include grading options form.
3019         require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
3020         require_once($CFG->dirroot . '/mod/assign/quickgradingform.php');
3021         require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
3022         $o = '';
3023         $cmid = $this->get_course_module()->id;
3025         $links = array();
3026         if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
3027                 has_capability('moodle/grade:viewall', $this->get_course_context())) {
3028             $gradebookurl = '/grade/report/grader/index.php?id=' . $this->get_course()->id;
3029             $links[$gradebookurl] = get_string('viewgradebook', 'assign');
3030         }
3031         if ($this->is_any_submission_plugin_enabled() && $this->count_submissions()) {
3032             $downloadurl = '/mod/assign/view.php?id=' . $cmid . '&action=downloadall';
3033             $links[$downloadurl] = get_string('downloadall', 'assign');
3034         }
3035         if ($this->is_blind_marking() &&
3036                 has_capability('mod/assign:revealidentities', $this->get_context())) {
3037             $revealidentitiesurl = '/mod/assign/view.php?id=' . $cmid . '&action=revealidentities';
3038             $links[$revealidentitiesurl] = get_string('revealidentities', 'assign');
3039         }
3040         foreach ($this->get_feedback_plugins() as $plugin) {
3041             if ($plugin->is_enabled() && $plugin->is_visible()) {
3042                 foreach ($plugin->get_grading_actions() as $action => $description) {
3043                     $url = '/mod/assign/view.php' .
3044                            '?id=' .  $cmid .
3045                            '&plugin=' . $plugin->get_type() .
3046                            '&pluginsubtype=assignfeedback' .
3047                            '&action=viewpluginpage&pluginaction=' . $action;
3048                     $links[$url] = $description;
3049                 }
3050             }
3051         }
3053         // Sort links alphabetically based on the link description.
3054         core_collator::asort($links);
3056         $gradingactions = new url_select($links);
3057         $gradingactions->set_label(get_string('choosegradingaction', 'assign'));
3059         $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
3061         $perpage = get_user_preferences('assign_perpage', 10);
3062         $filter = get_user_preferences('assign_filter', '');
3063         $markerfilter = get_user_preferences('assign_markerfilter', '');
3064         $workflowfilter = get_user_preferences('assign_workflowfilter', '');
3065         $controller = $gradingmanager->get_active_controller();
3066         $showquickgrading = empty($controller) && $this->can_grade();
3067         $quickgrading = get_user_preferences('assign_quickgrading', false);
3068         $showonlyactiveenrolopt = has_capability('moodle/course:viewsuspendedusers', $this->context);
3070         $markingallocation = $this->get_instance()->markingallocation &&
3071             has_capability('mod/assign:manageallocations', $this->context);
3072         // Get markers to use in drop lists.
3073         $markingallocationoptions = array();
3074         if ($markingallocation) {
3075             $markers = get_users_by_capability($this->context, 'mod/assign:grade');
3076             $markingallocationoptions[''] = get_string('filternone', 'assign');
3077             $markingallocationoptions[ASSIGN_MARKER_FILTER_NO_MARKER] = get_string('markerfilternomarker', 'assign');
3078             foreach ($markers as $marker) {
3079                 $markingallocationoptions[$marker->id] = fullname($marker);
3080             }
3081         }
3083         $markingworkflow = $this->get_instance()->markingworkflow;
3084         // Get marking states to show in form.
3085         $markingworkflowoptions = array();
3086         if ($markingworkflow) {
3087             $notmarked = get_string('markingworkflowstatenotmarked', 'assign');
3088             $markingworkflowoptions[''] = get_string('filternone', 'assign');
3089             $markingworkflowoptions[ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED] = $notmarked;
3090             $markingworkflowoptions = array_merge($markingworkflowoptions, $this->get_marking_workflow_states_for_current_user());
3091         }
3093         // Print options for changing the filter and changing the number of results per page.
3094         $gradingoptionsformparams = array('cm'=>$cmid,
3095                                           'contextid'=>$this->context->id,
3096                                           'userid'=>$USER->id,
3097                                           'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
3098                                           'showquickgrading'=>$showquickgrading,
3099                                           'quickgrading'=>$quickgrading,
3100                                           'markingworkflowopt'=>$markingworkflowoptions,
3101                                           'markingallocationopt'=>$markingallocationoptions,
3102                                           'showonlyactiveenrolopt'=>$showonlyactiveenrolopt,
3103                                           'showonlyactiveenrol'=>$this->show_only_active_users());
3105         $classoptions = array('class'=>'gradingoptionsform');
3106         $gradingoptionsform = new mod_assign_grading_options_form(null,
3107                                                                   $gradingoptionsformparams,
3108                                                                   'post',
3109                                                                   '',
3110                                                                   $classoptions);
3112         $batchformparams = array('cm'=>$cmid,
3113                                  'submissiondrafts'=>$this->get_instance()->submissiondrafts,
3114                                  'duedate'=>$this->get_instance()->duedate,
3115                                  'attemptreopenmethod'=>$this->get_instance()->attemptreopenmethod,
3116                                  'feedbackplugins'=>$this->get_feedback_plugins(),
3117                                  'context'=>$this->get_context(),
3118                                  'markingworkflow'=>$markingworkflow,
3119                                  'markingallocation'=>$markingallocation);
3120         $classoptions = array('class'=>'gradingbatchoperationsform');
3122         $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
3123                                                                                    $batchformparams,
3124                                                                                    'post',
3125                                                                                    '',
3126                                                                                    $classoptions);
3128         $gradingoptionsdata = new stdClass();
3129         $gradingoptionsdata->perpage = $perpage;
3130         $gradingoptionsdata->filter = $filter;
3131         $gradingoptionsdata->markerfilter = $markerfilter;
3132         $gradingoptionsdata->workflowfilter = $workflowfilter;
3133         $gradingoptionsform->set_data($gradingoptionsdata);
3135         $actionformtext = $this->get_renderer()->render($gradingactions);
3136         $header = new assign_header($this->get_instance(),
3137                                     $this->get_context(),
3138                                     false,
3139                                     $this->get_course_module()->id,
3140                                     get_string('grading', 'assign'),
3141                                     $actionformtext);
3142         $o .= $this->get_renderer()->render($header);
3144         $currenturl = $CFG->wwwroot .
3145                       '/mod/assign/view.php?id=' .
3146                       $this->get_course_module()->id .
3147                       '&action=grading';
3149         $o .= groups_print_activity_menu($this->get_course_module(), $currenturl, true);
3151         // Plagiarism update status apearring in the grading book.
3152         if (!empty($CFG->enableplagiarism)) {
3153             require_once($CFG->libdir . '/plagiarismlib.php');
3154             $o .= plagiarism_update_status($this->get_course(), $this->get_course_module());
3155         }
3157         // Load and print the table of submissions.
3158         if ($showquickgrading && $quickgrading) {
3159             $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, true);
3160             $table = $this->get_renderer()->render($gradingtable);
3161             $quickformparams = array('cm'=>$this->get_course_module()->id,
3162                                      'gradingtable'=>$table,
3163                                      'sendstudentnotifications'=>$this->get_instance()->sendstudentnotifications);
3164             $quickgradingform = new mod_assign_quick_grading_form(null, $quickformparams);
3166             $o .= $this->get_renderer()->render(new assign_form('quickgradingform', $quickgradingform));
3167         } else {
3168             $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, false);
3169             $o .= $this->get_renderer()->render($gradingtable);
3170         }
3172         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
3173         $users = array_keys($this->list_participants($currentgroup, true));
3174         if (count($users) != 0 && $this->can_grade()) {
3175             // If no enrolled user in a course then don't display the batch operations feature.
3176             $assignform = new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform);
3177             $o .= $this->get_renderer()->render($assignform);
3178         }
3179         $assignform = new assign_form('gradingoptionsform',
3180                                       $gradingoptionsform,
3181                                       'M.mod_assign.init_grading_options');
3182         $o .= $this->get_renderer()->render($assignform);
3183         return $o;
3184     }
3186     /**
3187      * View entire grading page.
3188      *
3189      * @return string
3190      */
3191     protected function view_grading_page() {
3192         global $CFG;
3194         $o = '';
3195         // Need submit permission to submit an assignment.
3196         $this->require_view_grades();
3197         require_once($CFG->dirroot . '/mod/assign/gradeform.php');
3199         // Only load this if it is.
3201         $o .= $this->view_grading_table();
3203         $o .= $this->view_footer();
3205         \mod_assign\event\grading_table_viewed::create_from_assign($this)->trigger();
3207         return $o;
3208     }
3210     /**
3211      * Capture the output of the plagiarism plugins disclosures and return it as a string.
3212      *
3213      * @return string
3214      */
3215     protected function plagiarism_print_disclosure() {
3216         global $CFG;
3217         $o = '';
3219         if (!empty($CFG->enableplagiarism)) {
3220             require_once($CFG->libdir . '/plagiarismlib.php');
3222             $o .= plagiarism_print_disclosure($this->get_course_module()->id);
3223         }
3225         return $o;
3226     }
3228     /**
3229      * Message for students when assignment submissions have been closed.
3230      *
3231      * @param string $title The page title
3232      * @param array $notices The array of notices to show.
3233      * @return string
3234      */
3235     protected function view_notices($title, $notices) {
3236         global $CFG;
3238         $o = '';
3240         $header = new assign_header($this->get_instance(),
3241                                     $this->get_context(),
3242                                     $this->show_intro(),
3243                                     $this->get_course_module()->id,
3244                                     $title);
3245         $o .= $this->get_renderer()->render($header);
3247         foreach ($notices as $notice) {
3248             $o .= $this->get_renderer()->notification($notice);
3249         }
3251         $url = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id, 'action'=>'view'));
3252         $o .= $this->get_renderer()->continue_button($url);
3254         $o .= $this->view_footer();