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