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