MDL-37621 assign: Fix for DB error on update.
[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 context the context of the course module for this assign instance
81      *               (or just the course if we are creating a new one)
82      */
83     private $context;
85     /** @var stdClass the course this assign instance belongs to */
86     private $course;
88     /** @var stdClass the admin config for all assign instances  */
89     private $adminconfig;
91     /** @var assign_renderer the custom renderer for this module */
92     private $output;
94     /** @var stdClass the course module for this assign instance */
95     private $coursemodule;
97     /** @var array cache for things like the coursemodule name or the scale menu -
98      *             only lives for a single request.
99      */
100     private $cache;
102     /** @var array list of the installed submission plugins */
103     private $submissionplugins;
105     /** @var array list of the installed feedback plugins */
106     private $feedbackplugins;
108     /** @var string action to be used to return to this page
109      *              (without repeating any form submissions etc).
110      */
111     private $returnaction = 'view';
113     /** @var array params to be used to return to this page */
114     private $returnparams = array();
116     /** @var string modulename prevents excessive calls to get_string */
117     private static $modulename = null;
119     /** @var string modulenameplural prevents excessive calls to get_string */
120     private static $modulenameplural = null;
122     /** @var array of marking workflow states for the current user */
123     private $markingworkflowstates = null;
125     /**
126      * Constructor for the base assign class.
127      *
128      * @param mixed $coursemodulecontext context|null the course module context
129      *                                   (or the course context if the coursemodule has not been
130      *                                   created yet).
131      * @param mixed $coursemodule the current course module if it was already loaded,
132      *                            otherwise this class will load one from the context as required.
133      * @param mixed $course the current course  if it was already loaded,
134      *                      otherwise this class will load one from the context as required.
135      */
136     public function __construct($coursemodulecontext, $coursemodule, $course) {
137         global $PAGE;
139         $this->context = $coursemodulecontext;
140         $this->coursemodule = $coursemodule;
141         $this->course = $course;
143         // Temporary cache only lives for a single request - used to reduce db lookups.
144         $this->cache = array();
146         $this->submissionplugins = $this->load_plugins('assignsubmission');
147         $this->feedbackplugins = $this->load_plugins('assignfeedback');
148     }
150     /**
151      * Set the action and parameters that can be used to return to the current page.
152      *
153      * @param string $action The action for the current page
154      * @param array $params An array of name value pairs which form the parameters
155      *                      to return to the current page.
156      * @return void
157      */
158     public function register_return_link($action, $params) {
159         global $PAGE;
160         $params['action'] = $action;
161         $currenturl = $PAGE->url;
163         $currenturl->params($params);
164         $PAGE->set_url($currenturl);
165     }
167     /**
168      * Return an action that can be used to get back to the current page.
169      *
170      * @return string action
171      */
172     public function get_return_action() {
173         global $PAGE;
175         $params = $PAGE->url->params();
177         if (!empty($params['action'])) {
178             return $params['action'];
179         }
180         return '';
181     }
183     /**
184      * Based on the current assignment settings should we display the intro.
185      *
186      * @return bool showintro
187      */
188     protected function show_intro() {
189         if ($this->get_instance()->alwaysshowdescription ||
190                 time() > $this->get_instance()->allowsubmissionsfromdate) {
191             return true;
192         }
193         return false;
194     }
196     /**
197      * Return a list of parameters that can be used to get back to the current page.
198      *
199      * @return array params
200      */
201     public function get_return_params() {
202         global $PAGE;
204         $params = $PAGE->url->params();
205         unset($params['id']);
206         unset($params['action']);
207         return $params;
208     }
210     /**
211      * Set the submitted form data.
212      *
213      * @param stdClass $data The form data (instance)
214      */
215     public function set_instance(stdClass $data) {
216         $this->instance = $data;
217     }
219     /**
220      * Set the context.
221      *
222      * @param context $context The new context
223      */
224     public function set_context(context $context) {
225         $this->context = $context;
226     }
228     /**
229      * Set the course data.
230      *
231      * @param stdClass $course The course data
232      */
233     public function set_course(stdClass $course) {
234         $this->course = $course;
235     }
237     /**
238      * Get list of feedback plugins installed.
239      *
240      * @return array
241      */
242     public function get_feedback_plugins() {
243         return $this->feedbackplugins;
244     }
246     /**
247      * Get list of submission plugins installed.
248      *
249      * @return array
250      */
251     public function get_submission_plugins() {
252         return $this->submissionplugins;
253     }
255     /**
256      * Is blind marking enabled and reveal identities not set yet?
257      *
258      * @return bool
259      */
260     public function is_blind_marking() {
261         return $this->get_instance()->blindmarking && !$this->get_instance()->revealidentities;
262     }
264     /**
265      * Does an assignment have submission(s) or grade(s) already?
266      *
267      * @return bool
268      */
269     public function has_submissions_or_grades() {
270         $allgrades = $this->count_grades();
271         $allsubmissions = $this->count_submissions();
272         if (($allgrades == 0) && ($allsubmissions == 0)) {
273             return false;
274         }
275         return true;
276     }
278     /**
279      * Get a specific submission plugin by its type.
280      *
281      * @param string $subtype assignsubmission | assignfeedback
282      * @param string $type
283      * @return mixed assign_plugin|null
284      */
285     public function get_plugin_by_type($subtype, $type) {
286         $shortsubtype = substr($subtype, strlen('assign'));
287         $name = $shortsubtype . 'plugins';
288         if ($name != 'feedbackplugins' && $name != 'submissionplugins') {
289             return null;
290         }
291         $pluginlist = $this->$name;
292         foreach ($pluginlist as $plugin) {
293             if ($plugin->get_type() == $type) {
294                 return $plugin;
295             }
296         }
297         return null;
298     }
300     /**
301      * Get a feedback plugin by type.
302      *
303      * @param string $type - The type of plugin e.g comments
304      * @return mixed assign_feedback_plugin|null
305      */
306     public function get_feedback_plugin_by_type($type) {
307         return $this->get_plugin_by_type('assignfeedback', $type);
308     }
310     /**
311      * Get a submission plugin by type.
312      *
313      * @param string $type - The type of plugin e.g comments
314      * @return mixed assign_submission_plugin|null
315      */
316     public function get_submission_plugin_by_type($type) {
317         return $this->get_plugin_by_type('assignsubmission', $type);
318     }
320     /**
321      * Load the plugins from the sub folders under subtype.
322      *
323      * @param string $subtype - either submission or feedback
324      * @return array - The sorted list of plugins
325      */
326     protected function load_plugins($subtype) {
327         global $CFG;
328         $result = array();
330         $names = get_plugin_list($subtype);
332         foreach ($names as $name => $path) {
333             if (file_exists($path . '/locallib.php')) {
334                 require_once($path . '/locallib.php');
336                 $shortsubtype = substr($subtype, strlen('assign'));
337                 $pluginclass = 'assign_' . $shortsubtype . '_' . $name;
339                 $plugin = new $pluginclass($this, $name);
341                 if ($plugin instanceof assign_plugin) {
342                     $idx = $plugin->get_sort_order();
343                     while (array_key_exists($idx, $result)) {
344                         $idx +=1;
345                     }
346                     $result[$idx] = $plugin;
347                 }
348             }
349         }
350         ksort($result);
351         return $result;
352     }
354     /**
355      * Display the assignment, used by view.php
356      *
357      * The assignment is displayed differently depending on your role,
358      * the settings for the assignment and the status of the assignment.
359      *
360      * @param string $action The current action if any.
361      * @return string - The page output.
362      */
363     public function view($action='') {
365         $o = '';
366         $mform = null;
367         $notices = array();
368         $nextpageparams = array();
370         if (!empty($this->get_course_module()->id)) {
371             $nextpageparams['id'] = $this->get_course_module()->id;
372         }
374         // Handle form submissions first.
375         if ($action == 'savesubmission') {
376             $action = 'editsubmission';
377             if ($this->process_save_submission($mform, $notices)) {
378                 $action = 'redirect';
379                 $nextpageparams['action'] = 'view';
380             }
381         } else if ($action == 'editprevioussubmission') {
382             $action = 'editsubmission';
383             if ($this->process_copy_previous_attempt($notices)) {
384                 $action = 'redirect';
385                 $nextpageparams['action'] = 'editsubmission';
386             }
387         } else if ($action == 'lock') {
388             $this->process_lock();
389             $action = 'redirect';
390             $nextpageparams['action'] = 'grading';
391         } else if ($action == 'addattempt') {
392             $this->process_add_attempt(required_param('userid', PARAM_INT));
393             $action = 'redirect';
394             $nextpageparams['action'] = 'grading';
395         } else if ($action == 'reverttodraft') {
396             $this->process_revert_to_draft();
397             $action = 'redirect';
398             $nextpageparams['action'] = 'grading';
399         } else if ($action == 'unlock') {
400             $this->process_unlock();
401             $action = 'redirect';
402             $nextpageparams['action'] = 'grading';
403         } else if ($action == 'setbatchmarkingworkflowstate') {
404             $this->process_set_batch_marking_workflow_state();
405             $action = 'redirect';
406             $nextpageparams['action'] = 'grading';
407         } else if ($action == 'setbatchmarkingallocation') {
408             $this->process_set_batch_marking_allocation();
409             $action = 'redirect';
410             $nextpageparams['action'] = 'grading';
411         } else if ($action == 'confirmsubmit') {
412             $action = 'submit';
413             if ($this->process_submit_for_grading($mform)) {
414                 $action = 'redirect';
415                 $nextpageparams['action'] = 'view';
416             }
417         } else if ($action == 'gradingbatchoperation') {
418             $action = $this->process_grading_batch_operation($mform);
419             if ($action == 'grading') {
420                 $action = 'redirect';
421                 $nextpageparams['action'] = 'grading';
422             }
423         } else if ($action == 'submitgrade') {
424             if (optional_param('saveandshownext', null, PARAM_RAW)) {
425                 // Save and show next.
426                 $action = 'grade';
427                 if ($this->process_save_grade($mform)) {
428                     $action = 'redirect';
429                     $nextpageparams['action'] = 'grade';
430                     $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) + 1;
431                     $nextpageparams['useridlistid'] = optional_param('useridlistid', time(), PARAM_INT);
432                 }
433             } else if (optional_param('nosaveandprevious', null, PARAM_RAW)) {
434                 $action = 'redirect';
435                 $nextpageparams['action'] = 'grade';
436                 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) - 1;
437                 $nextpageparams['useridlistid'] = optional_param('useridlistid', time(), PARAM_INT);
438             } else if (optional_param('nosaveandnext', null, PARAM_RAW)) {
439                 $action = 'redirect';
440                 $nextpageparams['action'] = 'grade';
441                 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) + 1;
442                 $nextpageparams['useridlistid'] = optional_param('useridlistid', time(), PARAM_INT);
443             } else if (optional_param('savegrade', null, PARAM_RAW)) {
444                 // Save changes button.
445                 $action = 'grade';
446                 if ($this->process_save_grade($mform)) {
447                     $message = get_string('gradingchangessaved', 'assign');
448                     $action = 'savegradingresult';
449                 }
450             } else {
451                 // Cancel button.
452                 $action = 'redirect';
453                 $nextpageparams['action'] = 'grading';
454             }
455         } else if ($action == 'quickgrade') {
456             $message = $this->process_save_quick_grades();
457             $action = 'quickgradingresult';
458         } else if ($action == 'saveoptions') {
459             $this->process_save_grading_options();
460             $action = 'redirect';
461             $nextpageparams['action'] = 'grading';
462         } else if ($action == 'saveextension') {
463             $action = 'grantextension';
464             if ($this->process_save_extension($mform)) {
465                 $action = 'redirect';
466                 $nextpageparams['action'] = 'grading';
467             }
468         } else if ($action == 'revealidentitiesconfirm') {
469             $this->process_reveal_identities();
470             $action = 'redirect';
471             $nextpageparams['action'] = 'grading';
472         }
474         $returnparams = array('rownum'=>optional_param('rownum', 0, PARAM_INT),
475                               'useridlistid'=>optional_param('useridlistid', 0, PARAM_INT));
476         $this->register_return_link($action, $returnparams);
478         // Now show the right view page.
479         if ($action == 'redirect') {
480             $nextpageurl = new moodle_url('/mod/assign/view.php', $nextpageparams);
481             redirect($nextpageurl);
482             return;
483         } else if ($action == 'savegradingresult') {
484             $o .= $this->view_savegrading_result($message);
485         } else if ($action == 'quickgradingresult') {
486             $mform = null;
487             $o .= $this->view_quickgrading_result($message);
488         } else if ($action == 'grade') {
489             $o .= $this->view_single_grade_page($mform);
490         } else if ($action == 'viewpluginassignfeedback') {
491             $o .= $this->view_plugin_content('assignfeedback');
492         } else if ($action == 'viewpluginassignsubmission') {
493             $o .= $this->view_plugin_content('assignsubmission');
494         } else if ($action == 'editsubmission') {
495             $o .= $this->view_edit_submission_page($mform, $notices);
496         } else if ($action == 'grading') {
497             $o .= $this->view_grading_page();
498         } else if ($action == 'downloadall') {
499             $o .= $this->download_submissions();
500         } else if ($action == 'submit') {
501             $o .= $this->check_submit_for_grading($mform);
502         } else if ($action == 'grantextension') {
503             $o .= $this->view_grant_extension($mform);
504         } else if ($action == 'revealidentities') {
505             $o .= $this->view_reveal_identities_confirm($mform);
506         } else if ($action == 'plugingradingbatchoperation') {
507             $o .= $this->view_plugin_grading_batch_operation($mform);
508         } else if ($action == 'viewpluginpage') {
509              $o .= $this->view_plugin_page();
510         } else if ($action == 'viewcourseindex') {
511              $o .= $this->view_course_index();
512         } else if ($action == 'viewbatchsetmarkingworkflowstate') {
513              $o .= $this->view_batch_set_workflow_state($mform);
514         } else if ($action == 'viewbatchmarkingallocation') {
515             $o .= $this->view_batch_markingallocation($mform);
516         } else {
517             $o .= $this->view_submission_page();
518         }
520         return $o;
521     }
523     /**
524      * Add this instance to the database.
525      *
526      * @param stdClass $formdata The data submitted from the form
527      * @param bool $callplugins This is used to skip the plugin code
528      *             when upgrading an old assignment to a new one (the plugins get called manually)
529      * @return mixed false if an error occurs or the int id of the new instance
530      */
531     public function add_instance(stdClass $formdata, $callplugins) {
532         global $DB;
534         $err = '';
536         // Add the database record.
537         $update = new stdClass();
538         $update->name = $formdata->name;
539         $update->timemodified = time();
540         $update->timecreated = time();
541         $update->course = $formdata->course;
542         $update->courseid = $formdata->course;
543         $update->intro = $formdata->intro;
544         $update->introformat = $formdata->introformat;
545         $update->alwaysshowdescription = !empty($formdata->alwaysshowdescription);
546         $update->submissiondrafts = $formdata->submissiondrafts;
547         $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
548         $update->sendnotifications = $formdata->sendnotifications;
549         $update->sendlatenotifications = $formdata->sendlatenotifications;
550         $update->duedate = $formdata->duedate;
551         $update->cutoffdate = $formdata->cutoffdate;
552         $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
553         $update->grade = $formdata->grade;
554         $update->completionsubmit = !empty($formdata->completionsubmit);
555         $update->teamsubmission = $formdata->teamsubmission;
556         $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
557         if (isset($formdata->teamsubmissiongroupingid)) {
558             $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
559         }
560         $update->blindmarking = $formdata->blindmarking;
561         $update->attemptreopenmethod = ASSIGN_ATTEMPT_REOPEN_METHOD_NONE;
562         if (!empty($formdata->attemptreopenmethod)) {
563             $update->attemptreopenmethod = $formdata->attemptreopenmethod;
564         }
565         if (!empty($formdata->maxattempts)) {
566             $update->maxattempts = $formdata->maxattempts;
567         }
568         $update->markingworkflow = $formdata->markingworkflow;
569         $update->markingallocation = $formdata->markingallocation;
571         $returnid = $DB->insert_record('assign', $update);
572         $this->instance = $DB->get_record('assign', array('id'=>$returnid), '*', MUST_EXIST);
573         // Cache the course record.
574         $this->course = $DB->get_record('course', array('id'=>$formdata->course), '*', MUST_EXIST);
576         if ($callplugins) {
577             // Call save_settings hook for submission plugins.
578             foreach ($this->submissionplugins as $plugin) {
579                 if (!$this->update_plugin_instance($plugin, $formdata)) {
580                     print_error($plugin->get_error());
581                     return false;
582                 }
583             }
584             foreach ($this->feedbackplugins as $plugin) {
585                 if (!$this->update_plugin_instance($plugin, $formdata)) {
586                     print_error($plugin->get_error());
587                     return false;
588                 }
589             }
591             // In the case of upgrades the coursemodule has not been set,
592             // so we need to wait before calling these two.
593             $this->update_calendar($formdata->coursemodule);
594             $this->update_gradebook(false, $formdata->coursemodule);
596         }
598         $update = new stdClass();
599         $update->id = $this->get_instance()->id;
600         $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
601         $DB->update_record('assign', $update);
603         return $returnid;
604     }
606     /**
607      * Delete all grades from the gradebook for this assignment.
608      *
609      * @return bool
610      */
611     protected function delete_grades() {
612         global $CFG;
614         $result = grade_update('mod/assign',
615                                $this->get_course()->id,
616                                'mod',
617                                'assign',
618                                $this->get_instance()->id,
619                                0,
620                                null,
621                                array('deleted'=>1));
622         return $result == GRADE_UPDATE_OK;
623     }
625     /**
626      * Delete this instance from the database.
627      *
628      * @return bool false if an error occurs
629      */
630     public function delete_instance() {
631         global $DB;
632         $result = true;
634         foreach ($this->submissionplugins as $plugin) {
635             if (!$plugin->delete_instance()) {
636                 print_error($plugin->get_error());
637                 $result = false;
638             }
639         }
640         foreach ($this->feedbackplugins as $plugin) {
641             if (!$plugin->delete_instance()) {
642                 print_error($plugin->get_error());
643                 $result = false;
644             }
645         }
647         // Delete files associated with this assignment.
648         $fs = get_file_storage();
649         if (! $fs->delete_area_files($this->context->id) ) {
650             $result = false;
651         }
653         // Delete_records will throw an exception if it fails - so no need for error checking here.
654         $DB->delete_records('assign_submission', array('assignment'=>$this->get_instance()->id));
655         $DB->delete_records('assign_grades', array('assignment'=>$this->get_instance()->id));
656         $DB->delete_records('assign_plugin_config', array('assignment'=>$this->get_instance()->id));
658         // Delete items from the gradebook.
659         if (! $this->delete_grades()) {
660             $result = false;
661         }
663         // Delete the instance.
664         $DB->delete_records('assign', array('id'=>$this->get_instance()->id));
666         return $result;
667     }
669     /**
670      * Actual implementation of the reset course functionality, delete all the
671      * assignment submissions for course $data->courseid.
672      *
673      * @param $data the data submitted from the reset course.
674      * @return array status array
675      */
676     public function reset_userdata($data) {
677         global $CFG, $DB;
679         $componentstr = get_string('modulenameplural', 'assign');
680         $status = array();
682         $fs = get_file_storage();
683         if (!empty($data->reset_assign_submissions)) {
684             // Delete files associated with this assignment.
685             foreach ($this->submissionplugins as $plugin) {
686                 $fileareas = array();
687                 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
688                 $fileareas = $plugin->get_file_areas();
689                 foreach ($fileareas as $filearea) {
690                     $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
691                 }
693                 if (!$plugin->delete_instance()) {
694                     $status[] = array('component'=>$componentstr,
695                                       'item'=>get_string('deleteallsubmissions', 'assign'),
696                                       'error'=>$plugin->get_error());
697                 }
698             }
700             foreach ($this->feedbackplugins as $plugin) {
701                 $fileareas = array();
702                 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
703                 $fileareas = $plugin->get_file_areas();
704                 foreach ($fileareas as $filearea) {
705                     $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
706                 }
708                 if (!$plugin->delete_instance()) {
709                     $status[] = array('component'=>$componentstr,
710                                       'item'=>get_string('deleteallsubmissions', 'assign'),
711                                       'error'=>$plugin->get_error());
712                 }
713             }
715             $assignssql = 'SELECT a.id
716                              FROM {assign} a
717                            WHERE a.course=:course';
718             $params = array('course'=>$data->courseid);
720             $DB->delete_records_select('assign_submission', "assignment IN ($assignssql)", $params);
722             $status[] = array('component'=>$componentstr,
723                               'item'=>get_string('deleteallsubmissions', 'assign'),
724                               'error'=>false);
726             if (!empty($data->reset_gradebook_grades)) {
727                 $DB->delete_records_select('assign_grades', "assignment IN ($assignssql)", $params);
728                 // Remove all grades from gradebook.
729                 require_once($CFG->dirroot.'/mod/assign/lib.php');
730                 assign_reset_gradebook($data->courseid);
731             }
732         }
733         // Updating dates - shift may be negative too.
734         if ($data->timeshift) {
735             shift_course_mod_dates('assign',
736                                     array('duedate', 'allowsubmissionsfromdate', 'cutoffdate'),
737                                     $data->timeshift,
738                                     $data->courseid);
739             $status[] = array('component'=>$componentstr,
740                               'item'=>get_string('datechanged'),
741                               'error'=>false);
742         }
744         return $status;
745     }
747     /**
748      * Update the settings for a single plugin.
749      *
750      * @param assign_plugin $plugin The plugin to update
751      * @param stdClass $formdata The form data
752      * @return bool false if an error occurs
753      */
754     protected function update_plugin_instance(assign_plugin $plugin, stdClass $formdata) {
755         if ($plugin->is_visible()) {
756             $enabledname = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
757             if (!empty($formdata->$enabledname)) {
758                 $plugin->enable();
759                 if (!$plugin->save_settings($formdata)) {
760                     print_error($plugin->get_error());
761                     return false;
762                 }
763             } else {
764                 $plugin->disable();
765             }
766         }
767         return true;
768     }
770     /**
771      * Update the gradebook information for this assignment.
772      *
773      * @param bool $reset If true, will reset all grades in the gradbook for this assignment
774      * @param int $coursemoduleid This is required because it might not exist in the database yet
775      * @return bool
776      */
777     public function update_gradebook($reset, $coursemoduleid) {
778         global $CFG;
780         require_once($CFG->dirroot.'/mod/assign/lib.php');
781         $assign = clone $this->get_instance();
782         $assign->cmidnumber = $coursemoduleid;
783         $param = null;
784         if ($reset) {
785             $param = 'reset';
786         }
788         return assign_grade_item_update($assign, $param);
789     }
791     /**
792      * Load and cache the admin config for this module.
793      *
794      * @return stdClass the plugin config
795      */
796     public function get_admin_config() {
797         if ($this->adminconfig) {
798             return $this->adminconfig;
799         }
800         $this->adminconfig = get_config('assign');
801         return $this->adminconfig;
802     }
804     /**
805      * Update the calendar entries for this assignment.
806      *
807      * @param int $coursemoduleid - Required to pass this in because it might
808      *                              not exist in the database yet.
809      * @return bool
810      */
811     public function update_calendar($coursemoduleid) {
812         global $DB, $CFG;
813         require_once($CFG->dirroot.'/calendar/lib.php');
815         // Special case for add_instance as the coursemodule has not been set yet.
816         $instance = $this->get_instance();
818         if ($instance->duedate) {
819             $event = new stdClass();
821             $params = array('modulename'=>'assign', 'instance'=>$instance->id);
822             $event->id = $DB->get_field('event',
823                                         'id',
824                                         $params);
826             if ($event->id) {
827                 $event->name        = $instance->name;
828                 $event->description = format_module_intro('assign', $instance, $coursemoduleid);
829                 $event->timestart   = $instance->duedate;
831                 $calendarevent = calendar_event::load($event->id);
832                 $calendarevent->update($event);
833             } else {
834                 $event = new stdClass();
835                 $event->name        = $instance->name;
836                 $event->description = format_module_intro('assign', $instance, $coursemoduleid);
837                 $event->courseid    = $instance->course;
838                 $event->groupid     = 0;
839                 $event->userid      = 0;
840                 $event->modulename  = 'assign';
841                 $event->instance    = $instance->id;
842                 $event->eventtype   = 'due';
843                 $event->timestart   = $instance->duedate;
844                 $event->timeduration = 0;
846                 calendar_event::create($event);
847             }
848         } else {
849             $DB->delete_records('event', array('modulename'=>'assign', 'instance'=>$instance->id));
850         }
851     }
854     /**
855      * Update this instance in the database.
856      *
857      * @param stdClass $formdata - the data submitted from the form
858      * @return bool false if an error occurs
859      */
860     public function update_instance($formdata) {
861         global $DB;
863         $update = new stdClass();
864         $update->id = $formdata->instance;
865         $update->name = $formdata->name;
866         $update->timemodified = time();
867         $update->course = $formdata->course;
868         $update->intro = $formdata->intro;
869         $update->introformat = $formdata->introformat;
870         $update->alwaysshowdescription = !empty($formdata->alwaysshowdescription);
871         $update->submissiondrafts = $formdata->submissiondrafts;
872         $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
873         $update->sendnotifications = $formdata->sendnotifications;
874         $update->sendlatenotifications = $formdata->sendlatenotifications;
875         $update->duedate = $formdata->duedate;
876         $update->cutoffdate = $formdata->cutoffdate;
877         $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
878         $update->grade = $formdata->grade;
879         if (!empty($formdata->completionunlocked)) {
880             $update->completionsubmit = !empty($formdata->completionsubmit);
881         }
882         $update->teamsubmission = $formdata->teamsubmission;
883         $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
884         if (isset($formdata->teamsubmissiongroupingid)) {
885             $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
886         }
887         $update->blindmarking = $formdata->blindmarking;
888         $update->attemptreopenmethod = ASSIGN_ATTEMPT_REOPEN_METHOD_NONE;
889         if (!empty($formdata->attemptreopenmethod)) {
890             $update->attemptreopenmethod = $formdata->attemptreopenmethod;
891         }
892         if (!empty($formdata->maxattempts)) {
893             $update->maxattempts = $formdata->maxattempts;
894         }
895         $update->markingworkflow = $formdata->markingworkflow;
896         $update->markingallocation = $formdata->markingallocation;
898         $result = $DB->update_record('assign', $update);
899         $this->instance = $DB->get_record('assign', array('id'=>$update->id), '*', MUST_EXIST);
901         // Load the assignment so the plugins have access to it.
903         // Call save_settings hook for submission plugins.
904         foreach ($this->submissionplugins as $plugin) {
905             if (!$this->update_plugin_instance($plugin, $formdata)) {
906                 print_error($plugin->get_error());
907                 return false;
908             }
909         }
910         foreach ($this->feedbackplugins as $plugin) {
911             if (!$this->update_plugin_instance($plugin, $formdata)) {
912                 print_error($plugin->get_error());
913                 return false;
914             }
915         }
917         $this->update_calendar($this->get_course_module()->id);
918         $this->update_gradebook(false, $this->get_course_module()->id);
920         $update = new stdClass();
921         $update->id = $this->get_instance()->id;
922         $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
923         $DB->update_record('assign', $update);
925         return $result;
926     }
928     /**
929      * Add elements in grading plugin form.
930      *
931      * @param mixed $grade stdClass|null
932      * @param MoodleQuickForm $mform
933      * @param stdClass $data
934      * @param int $userid - The userid we are grading
935      * @return void
936      */
937     protected function add_plugin_grade_elements($grade, MoodleQuickForm $mform, stdClass $data, $userid) {
938         foreach ($this->feedbackplugins as $plugin) {
939             if ($plugin->is_enabled() && $plugin->is_visible()) {
940                 $mform->addElement('header', 'header_' . $plugin->get_type(), $plugin->get_name());
941                 $mform->setExpanded('header_' . $plugin->get_type());
942                 if (!$plugin->get_form_elements_for_user($grade, $mform, $data, $userid)) {
943                     $mform->removeElement('header_' . $plugin->get_type());
944                 }
945             }
946         }
947     }
951     /**
952      * Add one plugins settings to edit plugin form.
953      *
954      * @param assign_plugin $plugin The plugin to add the settings from
955      * @param MoodleQuickForm $mform The form to add the configuration settings to.
956      *                               This form is modified directly (not returned).
957      * @param array $pluginsenabled A list of form elements to be added to a group.
958      *                              The new element is added to this array by this function.
959      * @return void
960      */
961     protected function add_plugin_settings(assign_plugin $plugin, MoodleQuickForm $mform, & $pluginsenabled) {
962         global $CFG;
963         if ($plugin->is_visible()) {
965             $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
966             $label = $plugin->get_name();
967             $label .= ' ' . $this->get_renderer()->help_icon('enabled', $plugin->get_subtype() . '_' . $plugin->get_type());
968             $pluginsenabled[] = $mform->createElement('checkbox', $name, '', $label);
970             $default = get_config($plugin->get_subtype() . '_' . $plugin->get_type(), 'default');
971             if ($plugin->get_config('enabled') !== false) {
972                 $default = $plugin->is_enabled();
973             }
974             $mform->setDefault($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $default);
976             $plugin->get_settings($mform);
978         }
979     }
981     /**
982      * Add settings to edit plugin form.
983      *
984      * @param MoodleQuickForm $mform The form to add the configuration settings to.
985      *                               This form is modified directly (not returned).
986      * @return void
987      */
988     public function add_all_plugin_settings(MoodleQuickForm $mform) {
989         $mform->addElement('header', 'submissiontypes', get_string('submissiontypes', 'assign'));
991         $submissionpluginsenabled = array();
992         $group = $mform->addGroup(array(), 'submissionplugins', get_string('submissiontypes', 'assign'), array(' '), false);
993         foreach ($this->submissionplugins as $plugin) {
994             $this->add_plugin_settings($plugin, $mform, $submissionpluginsenabled);
995         }
996         $group->setElements($submissionpluginsenabled);
998         $mform->addElement('header', 'feedbacktypes', get_string('feedbacktypes', 'assign'));
999         $feedbackpluginsenabled = array();
1000         $group = $mform->addGroup(array(), 'feedbackplugins', get_string('feedbacktypes', 'assign'), array(' '), false);
1001         foreach ($this->feedbackplugins as $plugin) {
1002             $this->add_plugin_settings($plugin, $mform, $feedbackpluginsenabled);
1003         }
1004         $group->setElements($feedbackpluginsenabled);
1005         $mform->setExpanded('submissiontypes');
1006     }
1008     /**
1009      * Allow each plugin an opportunity to update the defaultvalues
1010      * passed in to the settings form (needed to set up draft areas for
1011      * editor and filemanager elements)
1012      *
1013      * @param array $defaultvalues
1014      */
1015     public function plugin_data_preprocessing(&$defaultvalues) {
1016         foreach ($this->submissionplugins as $plugin) {
1017             if ($plugin->is_visible()) {
1018                 $plugin->data_preprocessing($defaultvalues);
1019             }
1020         }
1021         foreach ($this->feedbackplugins as $plugin) {
1022             if ($plugin->is_visible()) {
1023                 $plugin->data_preprocessing($defaultvalues);
1024             }
1025         }
1026     }
1028     /**
1029      * Get the name of the current module.
1030      *
1031      * @return string the module name (Assignment)
1032      */
1033     protected function get_module_name() {
1034         if (isset(self::$modulename)) {
1035             return self::$modulename;
1036         }
1037         self::$modulename = get_string('modulename', 'assign');
1038         return self::$modulename;
1039     }
1041     /**
1042      * Get the plural name of the current module.
1043      *
1044      * @return string the module name plural (Assignments)
1045      */
1046     protected function get_module_name_plural() {
1047         if (isset(self::$modulenameplural)) {
1048             return self::$modulenameplural;
1049         }
1050         self::$modulenameplural = get_string('modulenameplural', 'assign');
1051         return self::$modulenameplural;
1052     }
1054     /**
1055      * Has this assignment been constructed from an instance?
1056      *
1057      * @return bool
1058      */
1059     public function has_instance() {
1060         return $this->instance || $this->get_course_module();
1061     }
1063     /**
1064      * Get the settings for the current instance of this assignment
1065      *
1066      * @return stdClass The settings
1067      */
1068     public function get_instance() {
1069         global $DB;
1070         if ($this->instance) {
1071             return $this->instance;
1072         }
1073         if ($this->get_course_module()) {
1074             $params = array('id' => $this->get_course_module()->instance);
1075             $this->instance = $DB->get_record('assign', $params, '*', MUST_EXIST);
1076         }
1077         if (!$this->instance) {
1078             throw new coding_exception('Improper use of the assignment class. ' .
1079                                        'Cannot load the assignment record.');
1080         }
1081         return $this->instance;
1082     }
1084     /**
1085      * Get the context of the current course.
1086      *
1087      * @return mixed context|null The course context
1088      */
1089     public function get_course_context() {
1090         if (!$this->context && !$this->course) {
1091             throw new coding_exception('Improper use of the assignment class. ' .
1092                                        'Cannot load the course context.');
1093         }
1094         if ($this->context) {
1095             return $this->context->get_course_context();
1096         } else {
1097             return context_course::instance($this->course->id);
1098         }
1099     }
1102     /**
1103      * Get the current course module.
1104      *
1105      * @return mixed stdClass|null The course module
1106      */
1107     public function get_course_module() {
1108         if ($this->coursemodule) {
1109             return $this->coursemodule;
1110         }
1111         if (!$this->context) {
1112             return null;
1113         }
1115         if ($this->context->contextlevel == CONTEXT_MODULE) {
1116             $this->coursemodule = get_coursemodule_from_id('assign',
1117                                                            $this->context->instanceid,
1118                                                            0,
1119                                                            false,
1120                                                            MUST_EXIST);
1121             return $this->coursemodule;
1122         }
1123         return null;
1124     }
1126     /**
1127      * Get context module.
1128      *
1129      * @return context
1130      */
1131     public function get_context() {
1132         return $this->context;
1133     }
1135     /**
1136      * Get the current course.
1137      *
1138      * @return mixed stdClass|null The course
1139      */
1140     public function get_course() {
1141         global $DB;
1143         if ($this->course) {
1144             return $this->course;
1145         }
1147         if (!$this->context) {
1148             return null;
1149         }
1150         $params = array('id' => $this->get_course_context()->instanceid);
1151         $this->course = $DB->get_record('course', $params, '*', MUST_EXIST);
1153         return $this->course;
1154     }
1156     /**
1157      * Return a grade in user-friendly form, whether it's a scale or not.
1158      *
1159      * @param mixed $grade int|null
1160      * @param boolean $editing Are we allowing changes to this grade?
1161      * @param int $userid The user id the grade belongs to
1162      * @param int $modified Timestamp from when the grade was last modified
1163      * @return string User-friendly representation of grade
1164      */
1165     public function display_grade($grade, $editing, $userid=0, $modified=0) {
1166         global $DB;
1168         static $scalegrades = array();
1170         $o = '';
1172         if ($this->get_instance()->grade >= 0) {
1173             // Normal number.
1174             if ($editing && $this->get_instance()->grade > 0) {
1175                 if ($grade < 0) {
1176                     $displaygrade = '';
1177                 } else {
1178                     $displaygrade = format_float($grade);
1179                 }
1180                 $o .= '<label class="accesshide" for="quickgrade_' . $userid . '">' .
1181                        get_string('usergrade', 'assign') .
1182                        '</label>';
1183                 $o .= '<input type="text"
1184                               id="quickgrade_' . $userid . '"
1185                               name="quickgrade_' . $userid . '"
1186                               value="' .  $displaygrade . '"
1187                               size="6"
1188                               maxlength="10"
1189                               class="quickgrade"/>';
1190                 $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade, 2);
1191                 $o .= '<input type="hidden"
1192                               name="grademodified_' . $userid . '"
1193                               value="' . $modified . '"/>';
1194                 return $o;
1195             } else {
1196                 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
1197                 if ($grade == -1 || $grade === null) {
1198                     $o .= '-';
1199                     return $o;
1200                 } else {
1201                     $o .= format_float($grade, 2) .
1202                           '&nbsp;/&nbsp;' .
1203                           format_float($this->get_instance()->grade, 2);
1204                     return $o;
1205                 }
1206             }
1208         } else {
1209             // Scale.
1210             if (empty($this->cache['scale'])) {
1211                 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
1212                     $this->cache['scale'] = make_menu_from_list($scale->scale);
1213                 } else {
1214                     $o .= '-';
1215                     return $o;
1216                 }
1217             }
1218             if ($editing) {
1219                 $o .= '<label class="accesshide"
1220                               for="quickgrade_' . $userid . '">' .
1221                       get_string('usergrade', 'assign') .
1222                       '</label>';
1223                 $o .= '<select name="quickgrade_' . $userid . '" class="quickgrade">';
1224                 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
1225                 foreach ($this->cache['scale'] as $optionid => $option) {
1226                     $selected = '';
1227                     if ($grade == $optionid) {
1228                         $selected = 'selected="selected"';
1229                     }
1230                     $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
1231                 }
1232                 $o .= '</select>';
1233                 $o .= '<input type="hidden" ' .
1234                              'name="grademodified_' . $userid . '" ' .
1235                              'value="' . $modified . '"/>';
1236                 return $o;
1237             } else {
1238                 $scaleid = (int)$grade;
1239                 if (isset($this->cache['scale'][$scaleid])) {
1240                     $o .= $this->cache['scale'][$scaleid];
1241                     return $o;
1242                 }
1243                 $o .= '-';
1244                 return $o;
1245             }
1246         }
1247     }
1249     /**
1250      * Load a list of users enrolled in the current course with the specified permission and group.
1251      * 0 for no group.
1252      *
1253      * @param int $currentgroup
1254      * @param bool $idsonly
1255      * @return array List of user records
1256      */
1257     public function list_participants($currentgroup, $idsonly) {
1258         if ($idsonly) {
1259             return get_enrolled_users($this->context, 'mod/assign:submit', $currentgroup, 'u.id');
1260         } else {
1261             return get_enrolled_users($this->context, 'mod/assign:submit', $currentgroup);
1262         }
1263     }
1265     /**
1266      * Load a count of valid teams for this assignment.
1267      *
1268      * @return int number of valid teams
1269      */
1270     public function count_teams() {
1272         $groups = groups_get_all_groups($this->get_course()->id,
1273                                         0,
1274                                         $this->get_instance()->teamsubmissiongroupingid,
1275                                         'g.id');
1276         $count = count($groups);
1278         // See if there are any users in the default group.
1279         $defaultusers = $this->get_submission_group_members(0, true);
1280         if (count($defaultusers) > 0) {
1281             $count += 1;
1282         }
1283         return $count;
1284     }
1286     /**
1287      * Load a count of users enrolled in the current course with the specified permission and group.
1288      * 0 for no group.
1289      *
1290      * @param int $currentgroup
1291      * @return int number of matching users
1292      */
1293     public function count_participants($currentgroup) {
1294         return count_enrolled_users($this->context, 'mod/assign:submit', $currentgroup);
1295     }
1297     /**
1298      * Load a count of users submissions in the current module that require grading
1299      * This means the submission modification time is more recent than the
1300      * grading modification time and the status is SUBMITTED.
1301      *
1302      * @return int number of matching submissions
1303      */
1304     public function count_submissions_need_grading() {
1305         global $DB;
1307         if ($this->get_instance()->teamsubmission) {
1308             // This does not make sense for group assignment because the submission is shared.
1309             return 0;
1310         }
1312         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1313         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1315         $submissionmaxattempt = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt
1316                                  FROM {assign_submission} mxs
1317                                  WHERE mxs.assignment = :assignid2 GROUP BY mxs.userid';
1318         $grademaxattempt = 'SELECT mxg.userid, MAX(mxg.attemptnumber) AS maxattempt
1319                             FROM {assign_grades} mxg
1320                             WHERE mxg.assignment = :assignid3 GROUP BY mxg.userid';
1322         $params['assignid'] = $this->get_instance()->id;
1323         $params['assignid2'] = $this->get_instance()->id;
1324         $params['assignid3'] = $this->get_instance()->id;
1325         $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1327         $sql = 'SELECT COUNT(s.userid)
1328                    FROM {assign_submission} s
1329                    LEFT JOIN ( ' . $submissionmaxattempt . ' ) smx ON s.userid = smx.userid
1330                    LEFT JOIN ( ' . $grademaxattempt . ' ) gmx ON s.userid = gmx.userid
1331                    LEFT JOIN {assign_grades} g ON
1332                         s.assignment = g.assignment AND
1333                         s.userid = g.userid AND
1334                         g.attemptnumber = gmx.maxattempt
1335                    JOIN(' . $esql . ') e ON e.id = s.userid
1336                    WHERE
1337                         s.attemptnumber = smx.maxattempt AND
1338                         s.assignment = :assignid AND
1339                         s.timemodified IS NOT NULL AND
1340                         s.status = :submitted AND
1341                         (s.timemodified > g.timemodified OR g.timemodified IS NULL)';
1343         return $DB->count_records_sql($sql, $params);
1344     }
1346     /**
1347      * Load a count of grades.
1348      *
1349      * @return int number of grades
1350      */
1351     public function count_grades() {
1352         global $DB;
1354         if (!$this->has_instance()) {
1355             return 0;
1356         }
1358         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1359         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1361         $params['assignid'] = $this->get_instance()->id;
1363         $sql = 'SELECT COUNT(g.userid)
1364                    FROM {assign_grades} g
1365                    JOIN(' . $esql . ') e ON e.id = g.userid
1366                    WHERE g.assignment = :assignid';
1368         return $DB->count_records_sql($sql, $params);
1369     }
1371     /**
1372      * Load a count of submissions.
1373      *
1374      * @return int number of submissions
1375      */
1376     public function count_submissions() {
1377         global $DB;
1379         if (!$this->has_instance()) {
1380             return 0;
1381         }
1383         $params = array();
1385         if ($this->get_instance()->teamsubmission) {
1386             // We cannot join on the enrolment tables for group submissions (no userid).
1387             $sql = 'SELECT COUNT(DISTINCT s.groupid)
1388                         FROM {assign_submission} s
1389                         WHERE
1390                             s.assignment = :assignid AND
1391                             s.timemodified IS NOT NULL AND
1392                             s.userid = :groupuserid';
1394             $params['assignid'] = $this->get_instance()->id;
1395             $params['groupuserid'] = 0;
1396         } else {
1397             $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1398             list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1400             $params['assignid'] = $this->get_instance()->id;
1402             $sql = 'SELECT COUNT(DISTINCT s.userid)
1403                        FROM {assign_submission} s
1404                        JOIN(' . $esql . ') e ON e.id = s.userid
1405                        WHERE
1406                             s.assignment = :assignid AND
1407                             s.timemodified IS NOT NULL';
1408         }
1410         return $DB->count_records_sql($sql, $params);
1411     }
1413     /**
1414      * Load a count of submissions with a specified status.
1415      *
1416      * @param string $status The submission status - should match one of the constants
1417      * @return int number of matching submissions
1418      */
1419     public function count_submissions_with_status($status) {
1420         global $DB;
1422         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1423         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1425         $params['assignid'] = $this->get_instance()->id;
1426         $params['assignid2'] = $this->get_instance()->id;
1427         $params['submissionstatus'] = $status;
1429         if ($this->get_instance()->teamsubmission) {
1430             $maxattemptsql = 'SELECT mxs.groupid, MAX(mxs.attemptnumber) AS maxattempt
1431                               FROM {assign_submission} mxs
1432                               WHERE mxs.assignment = :assignid2 GROUP BY mxs.groupid';
1434             $sql = 'SELECT COUNT(s.groupid)
1435                         FROM {assign_submission} s
1436                         JOIN(' . $maxattemptsql . ') smx ON s.groupid = smx.groupid
1437                         WHERE
1438                             s.attemptnumber = smx.maxattempt AND
1439                             s.assignment = :assignid AND
1440                             s.timemodified IS NOT NULL AND
1441                             s.userid = :groupuserid AND
1442                             s.status = :submissionstatus';
1443             $params['groupuserid'] = 0;
1444         } else {
1445             $maxattemptsql = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt
1446                               FROM {assign_submission} mxs
1447                               WHERE mxs.assignment = :assignid2 GROUP BY mxs.userid';
1449             $sql = 'SELECT COUNT(s.userid)
1450                         FROM {assign_submission} s
1451                         JOIN(' . $esql . ') e ON e.id = s.userid
1452                         JOIN(' . $maxattemptsql . ') smx ON s.userid = smx.userid
1453                         WHERE
1454                             s.attemptnumber = smx.maxattempt AND
1455                             s.assignment = :assignid AND
1456                             s.timemodified IS NOT NULL AND
1457                             s.status = :submissionstatus';
1458         }
1460         return $DB->count_records_sql($sql, $params);
1461     }
1463     /**
1464      * Utility function to get the userid for every row in the grading table
1465      * so the order can be frozen while we iterate it.
1466      *
1467      * @return array An array of userids
1468      */
1469     protected function get_grading_userid_list() {
1470         $filter = get_user_preferences('assign_filter', '');
1471         $table = new assign_grading_table($this, 0, $filter, 0, false);
1473         $useridlist = $table->get_column_data('userid');
1475         return $useridlist;
1476     }
1478     /**
1479      * Generate zip file from array of given files.
1480      *
1481      * @param array $filesforzipping - array of files to pass into archive_to_pathname.
1482      *                                 This array is indexed by the final file name and each
1483      *                                 element in the array is an instance of a stored_file object.
1484      * @return path of temp file - note this returned file does
1485      *         not have a .zip extension - it is a temp file.
1486      */
1487     protected function pack_files($filesforzipping) {
1488         global $CFG;
1489         // Create path for new zip file.
1490         $tempzip = tempnam($CFG->tempdir . '/', 'assignment_');
1491         // Zip files.
1492         $zipper = new zip_packer();
1493         if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
1494             return $tempzip;
1495         }
1496         return false;
1497     }
1499     /**
1500      * Finds all assignment notifications that have yet to be mailed out, and mails them.
1501      *
1502      * Cron function to be run periodically according to the moodle cron.
1503      *
1504      * @return bool
1505      */
1506     public static function cron() {
1507         global $DB;
1509         // Only ever send a max of one days worth of updates.
1510         $yesterday = time() - (24 * 3600);
1511         $timenow   = time();
1513         // Collect all submissions from the past 24 hours that require mailing.
1514         $sql = 'SELECT a.course, a.name, a.blindmarking, a.revealidentities,
1515                        g.*, g.id as gradeid, g.timemodified as lastmodified
1516                  FROM {assign} a
1517                  JOIN {assign_grades} g ON g.assignment = a.id
1518                  LEFT JOIN {assign_user_flags} uf ON uf.assignment = a.id AND uf.userid = g.userid
1519                 WHERE g.timemodified >= :yesterday AND
1520                       g.timemodified <= :today AND
1521                       uf.mailed = 0';
1523         $params = array('yesterday' => $yesterday, 'today' => $timenow);
1524         $submissions = $DB->get_records_sql($sql, $params);
1526         if (empty($submissions)) {
1527             return true;
1528         }
1530         mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
1532         // Preload courses we are going to need those.
1533         $courseids = array();
1534         foreach ($submissions as $submission) {
1535             $courseids[] = $submission->course;
1536         }
1538         // Filter out duplicates.
1539         $courseids = array_unique($courseids);
1540         $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1541         list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
1542         $sql = 'SELECT c.*, ' . $ctxselect .
1543                   ' FROM {course} c
1544              LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
1545                  WHERE c.id ' . $courseidsql;
1547         $params['contextlevel'] = CONTEXT_COURSE;
1548         $courses = $DB->get_records_sql($sql, $params);
1550         // Clean up... this could go on for a while.
1551         unset($courseids);
1552         unset($ctxselect);
1553         unset($courseidsql);
1554         unset($params);
1556         // Simple array we'll use for caching modules.
1557         $modcache = array();
1559         // Message students about new feedback.
1560         foreach ($submissions as $submission) {
1562             mtrace("Processing assignment submission $submission->id ...");
1564             // Do not cache user lookups - could be too many.
1565             if (!$user = $DB->get_record('user', array('id'=>$submission->userid))) {
1566                 mtrace('Could not find user ' . $submission->userid);
1567                 continue;
1568             }
1570             // Use a cache to prevent the same DB queries happening over and over.
1571             if (!array_key_exists($submission->course, $courses)) {
1572                 mtrace('Could not find course ' . $submission->course);
1573                 continue;
1574             }
1575             $course = $courses[$submission->course];
1576             if (isset($course->ctxid)) {
1577                 // Context has not yet been preloaded. Do so now.
1578                 context_helper::preload_from_record($course);
1579             }
1581             // Override the language and timezone of the "current" user, so that
1582             // mail is customised for the receiver.
1583             cron_setup_user($user, $course);
1585             // Context lookups are already cached.
1586             $coursecontext = context_course::instance($course->id);
1587             if (!is_enrolled($coursecontext, $user->id)) {
1588                 $courseshortname = format_string($course->shortname,
1589                                                  true,
1590                                                  array('context' => $coursecontext));
1591                 mtrace(fullname($user) . ' not an active participant in ' . $courseshortname);
1592                 continue;
1593             }
1595             if (!$grader = $DB->get_record('user', array('id'=>$submission->grader))) {
1596                 mtrace('Could not find grader ' . $submission->grader);
1597                 continue;
1598             }
1600             if (!array_key_exists($submission->assignment, $modcache)) {
1601                 $mod = get_coursemodule_from_instance('assign', $submission->assignment, $course->id);
1602                 if (empty($mod)) {
1603                     mtrace('Could not find course module for assignment id ' . $submission->assignment);
1604                     continue;
1605                 }
1606                 $modcache[$submission->assignment] = $mod;
1607             } else {
1608                 $mod = $modcache[$submission->assignment];
1609             }
1610             // Context lookups are already cached.
1611             $contextmodule = context_module::instance($mod->id);
1613             if (!$mod->visible) {
1614                 // Hold mail notification for hidden assignments until later.
1615                 continue;
1616             }
1618             // Need to send this to the student.
1619             $messagetype = 'feedbackavailable';
1620             $eventtype = 'assign_notification';
1621             $updatetime = $submission->lastmodified;
1622             $modulename = get_string('modulename', 'assign');
1624             $uniqueid = 0;
1625             if ($submission->blindmarking && !$submission->revealidentities) {
1626                 $uniqueid = self::get_uniqueid_for_user_static($submission->assignment, $user->id);
1627             }
1628             $showusers = $submission->blindmarking && !$submission->revealidentities;
1629             self::send_assignment_notification($grader,
1630                                                $user,
1631                                                $messagetype,
1632                                                $eventtype,
1633                                                $updatetime,
1634                                                $mod,
1635                                                $contextmodule,
1636                                                $course,
1637                                                $modulename,
1638                                                $submission->name,
1639                                                $showusers,
1640                                                $uniqueid);
1642             $flags = $DB->get_record('assign_user_flags', array('userid'=>$user->id, 'assignment'=>$submission->assignment));
1643             if ($flags) {
1644                 $flags->mailed = 1;
1645                 $DB->update_record('assign_user_flags', $flags);
1646             } else {
1647                 $flags = new stdClass();
1648                 $flags->userid = $user->id;
1649                 $flags->assignment = $submission->assignment;
1650                 $flags->mailed = 1;
1651                 $DB->insert_record('assign_user_flags', $flags);
1652             }
1654             mtrace('Done');
1655         }
1656         mtrace('Done processing ' . count($submissions) . ' assignment submissions');
1658         cron_setup_user();
1660         // Free up memory just to be sure.
1661         unset($courses);
1662         unset($modcache);
1664         return true;
1665     }
1667     /**
1668      * Mark in the database that this grade record should have an update notification sent by cron.
1669      *
1670      * @param stdClass $grade a grade record keyed on id
1671      * @return bool true for success
1672      */
1673     public function notify_grade_modified($grade) {
1674         global $DB;
1676         $flags = $this->get_user_flags($grade->userid, true);
1677         if ($flags->mailed != 1) {
1678             $flags->mailed = 0;
1679         }
1681         return $this->update_user_flags($flags);
1682     }
1684     /**
1685      * Update user flags for this user in this assignment.
1686      *
1687      * @param stdClass $flags a flags record keyed on id
1688      * @return bool true for success
1689      */
1690     public function update_user_flags($flags) {
1691         global $DB;
1692         if ($flags->userid <= 0 || $flags->assignment <= 0 || $flags->id <= 0) {
1693             return false;
1694         }
1696         $result = $DB->update_record('assign_user_flags', $flags);
1697         return $result;
1698     }
1700     /**
1701      * Update a grade in the grade table for the assignment and in the gradebook.
1702      *
1703      * @param stdClass $grade a grade record keyed on id
1704      * @return bool true for success
1705      */
1706     public function update_grade($grade) {
1707         global $DB;
1709         $grade->timemodified = time();
1711         if (!empty($grade->workflowstate)) {
1712             $validstates = $this->get_marking_workflow_states_for_current_user();
1713             if (!array_key_exists($grade->workflowstate, $validstates)) {
1714                 return false;
1715             }
1716         }
1718         if ($grade->grade && $grade->grade != -1) {
1719             if ($this->get_instance()->grade > 0) {
1720                 if (!is_numeric($grade->grade)) {
1721                     return false;
1722                 } else if ($grade->grade > $this->get_instance()->grade) {
1723                     return false;
1724                 } else if ($grade->grade < 0) {
1725                     return false;
1726                 }
1727             } else {
1728                 // This is a scale.
1729                 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
1730                     $scaleoptions = make_menu_from_list($scale->scale);
1731                     if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
1732                         return false;
1733                     }
1734                 }
1735             }
1736         }
1738         if (empty($grade->attemptnumber)) {
1739             // Set it to the default.
1740             $grade->attemptnumber = 0;
1741         }
1742         $result = $DB->update_record('assign_grades', $grade);
1744         // Only push to gradebook if the update is for the latest attempt.
1745         $submission = null;
1746         if ($this->get_instance()->teamsubmission) {
1747             $submission = $this->get_group_submission($grade->userid, 0, false);
1748         } else {
1749             $submission = $this->get_user_submission($grade->userid, false);
1750         }
1751         // Not the latest attempt.
1752         if ($submission && $submission->attemptnumber != $grade->attemptnumber) {
1753             return true;
1754         }
1756         if ($result) {
1757             $this->gradebook_item_update(null, $grade);
1758         }
1759         return $result;
1760     }
1762     /**
1763      * View the grant extension date page.
1764      *
1765      * Uses url parameters 'userid'
1766      * or from parameter 'selectedusers'
1767      *
1768      * @param moodleform $mform - Used for validation of the submitted data
1769      * @return string
1770      */
1771     protected function view_grant_extension($mform) {
1772         global $DB, $CFG;
1773         require_once($CFG->dirroot . '/mod/assign/extensionform.php');
1775         $o = '';
1776         $batchusers = optional_param('selectedusers', '', PARAM_SEQUENCE);
1777         $data = new stdClass();
1778         $data->extensionduedate = null;
1779         $userid = 0;
1780         if (!$batchusers) {
1781             $userid = required_param('userid', PARAM_INT);
1783             $grade = $this->get_user_grade($userid, false);
1785             $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
1787             if ($grade) {
1788                 $data->extensionduedate = $grade->extensionduedate;
1789             }
1790             $data->userid = $userid;
1791         } else {
1792             $data->batchusers = $batchusers;
1793         }
1794         $header = new assign_header($this->get_instance(),
1795                                     $this->get_context(),
1796                                     $this->show_intro(),
1797                                     $this->get_course_module()->id,
1798                                     get_string('grantextension', 'assign'));
1799         $o .= $this->get_renderer()->render($header);
1801         if (!$mform) {
1802             $formparams = array($this->get_course_module()->id,
1803                                 $userid,
1804                                 $batchusers,
1805                                 $this->get_instance(),
1806                                 $data);
1807             $mform = new mod_assign_extension_form(null, $formparams);
1808         }
1809         $o .= $this->get_renderer()->render(new assign_form('extensionform', $mform));
1810         $o .= $this->view_footer();
1811         return $o;
1812     }
1814     /**
1815      * Get a list of the users in the same group as this user.
1816      *
1817      * @param int $groupid The id of the group whose members we want or 0 for the default group
1818      * @param bool $onlyids Whether to retrieve only the user id's
1819      * @return array The users (possibly id's only)
1820      */
1821     public function get_submission_group_members($groupid, $onlyids) {
1822         $members = array();
1823         if ($groupid != 0) {
1824             if ($onlyids) {
1825                 $allusers = groups_get_members($groupid, 'u.id');
1826             } else {
1827                 $allusers = groups_get_members($groupid);
1828             }
1829             foreach ($allusers as $user) {
1830                 if ($this->get_submission_group($user->id)) {
1831                     $members[] = $user;
1832                 }
1833             }
1834         } else {
1835             $allusers = $this->list_participants(null, $onlyids);
1836             foreach ($allusers as $user) {
1837                 if ($this->get_submission_group($user->id) == null) {
1838                     $members[] = $user;
1839                 }
1840             }
1841         }
1842         return $members;
1843     }
1845     /**
1846      * Get a list of the users in the same group as this user that have not submitted the assignment.
1847      *
1848      * @param int $groupid The id of the group whose members we want or 0 for the default group
1849      * @param bool $onlyids Whether to retrieve only the user id's
1850      * @return array The users (possibly id's only)
1851      */
1852     public function get_submission_group_members_who_have_not_submitted($groupid, $onlyids) {
1853         $instance = $this->get_instance();
1854         if (!$instance->teamsubmission || !$instance->requireallteammemberssubmit) {
1855             return array();
1856         }
1857         $members = $this->get_submission_group_members($groupid, $onlyids);
1859         foreach ($members as $id => $member) {
1860             $submission = $this->get_user_submission($member->id, false);
1861             if ($submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
1862                 unset($members[$id]);
1863             } else {
1864                 if ($this->is_blind_marking()) {
1865                     $members[$id]->alias = get_string('hiddenuser', 'assign') .
1866                                            $this->get_uniqueid_for_user($id);
1867                 }
1868             }
1869         }
1870         return $members;
1871     }
1873     /**
1874      * Load the group submission object for a particular user, optionally creating it if required.
1875      *
1876      * @param int $userid The id of the user whose submission we want
1877      * @param int $groupid The id of the group for this user - may be 0 in which
1878      *                     case it is determined from the userid.
1879      * @param bool $create If set to true a new submission object will be created in the database
1880      * @param int $attemptnumber - -1 means the latest attempt
1881      * @return stdClass The submission
1882      */
1883     public function get_group_submission($userid, $groupid, $create, $attemptnumber=-1) {
1884         global $DB;
1886         if ($groupid == 0) {
1887             $group = $this->get_submission_group($userid);
1888             if ($group) {
1889                 $groupid = $group->id;
1890             }
1891         }
1893         // Now get the group submission.
1894         $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
1895         if ($attemptnumber >= 0) {
1896             $params['attemptnumber'] = $attemptnumber;
1897         }
1899         // Only return the row with the highest attemptnumber.
1900         $submission = null;
1901         $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
1902         if ($submissions) {
1903             $submission = reset($submissions);
1904         }
1906         if ($submission) {
1907             return $submission;
1908         }
1909         if ($create) {
1910             $submission = new stdClass();
1911             $submission->assignment = $this->get_instance()->id;
1912             $submission->userid = 0;
1913             $submission->groupid = $groupid;
1914             $submission->timecreated = time();
1915             $submission->timemodified = $submission->timecreated;
1916             if ($attemptnumber >= 0) {
1917                 $submission->attemptnumber = $attemptnumber;
1918             } else {
1919                 $submission->attemptnumber = 0;
1920             }
1922             $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
1923             $sid = $DB->insert_record('assign_submission', $submission);
1924             $submission->id = $sid;
1925             return $submission;
1926         }
1927         return false;
1928     }
1930     /**
1931      * View a summary listing of all assignments in the current course.
1932      *
1933      * @return string
1934      */
1935     private function view_course_index() {
1936         global $USER;
1938         $o = '';
1940         $course = $this->get_course();
1941         $strplural = get_string('modulenameplural', 'assign');
1943         if (!$cms = get_coursemodules_in_course('assign', $course->id, 'm.duedate')) {
1944             $o .= $this->get_renderer()->notification(get_string('thereareno', 'moodle', $strplural));
1945             $o .= $this->get_renderer()->continue_button(new moodle_url('/course/view.php', array('id' => $course->id)));
1946             return $o;
1947         }
1949         $strsectionname  = get_string('sectionname', 'format_'.$course->format);
1950         $usesections = course_format_uses_sections($course->format);
1951         $modinfo = get_fast_modinfo($course);
1953         if ($usesections) {
1954             $sections = $modinfo->get_section_info_all();
1955         }
1956         $courseindexsummary = new assign_course_index_summary($usesections, $strsectionname);
1958         $timenow = time();
1960         $currentsection = '';
1961         foreach ($modinfo->instances['assign'] as $cm) {
1962             if (!$cm->uservisible) {
1963                 continue;
1964             }
1966             $timedue = $cms[$cm->id]->duedate;
1968             $sectionname = '';
1969             if ($usesections && $cm->sectionnum) {
1970                 $sectionname = get_section_name($course, $sections[$cm->sectionnum]);
1971             }
1973             $submitted = '';
1974             $context = context_module::instance($cm->id);
1976             $assignment = new assign($context, $cm, $course);
1978             if (has_capability('mod/assign:grade', $context)) {
1979                 $submitted = $assignment->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED);
1981             } else if (has_capability('mod/assign:submit', $context)) {
1982                 $usersubmission = $assignment->get_user_submission($USER->id, false);
1984                 if (!empty($usersubmission->status)) {
1985                     $submitted = get_string('submissionstatus_' . $usersubmission->status, 'assign');
1986                 } else {
1987                     $submitted = get_string('submissionstatus_', 'assign');
1988                 }
1989             }
1990             $grading_info = grade_get_grades($course->id, 'mod', 'assign', $cm->instance, $USER->id);
1991             if (isset($grading_info->items[0]->grades[$USER->id]) &&
1992                     !$grading_info->items[0]->grades[$USER->id]->hidden ) {
1993                 $grade = $grading_info->items[0]->grades[$USER->id]->str_grade;
1994             } else {
1995                 $grade = '-';
1996             }
1998             $courseindexsummary->add_assign_info($cm->id, $cm->name, $sectionname, $timedue, $submitted, $grade);
2000         }
2002         $o .= $this->get_renderer()->render($courseindexsummary);
2003         $o .= $this->view_footer();
2005         return $o;
2006     }
2008     /**
2009      * View a page rendered by a plugin.
2010      *
2011      * Uses url parameters 'pluginaction', 'pluginsubtype', 'plugin', and 'id'.
2012      *
2013      * @return string
2014      */
2015     protected function view_plugin_page() {
2016         global $USER;
2018         $o = '';
2020         $pluginsubtype = required_param('pluginsubtype', PARAM_ALPHA);
2021         $plugintype = required_param('plugin', PARAM_TEXT);
2022         $pluginaction = required_param('pluginaction', PARAM_ALPHA);
2024         $plugin = $this->get_plugin_by_type($pluginsubtype, $plugintype);
2025         if (!$plugin) {
2026             print_error('invalidformdata', '');
2027             return;
2028         }
2030         $o .= $plugin->view_page($pluginaction);
2032         return $o;
2033     }
2036     /**
2037      * This is used for team assignments to get the group for the specified user.
2038      * If the user is a member of multiple or no groups this will return false
2039      *
2040      * @param int $userid The id of the user whose submission we want
2041      * @return mixed The group or false
2042      */
2043     public function get_submission_group($userid) {
2044         $grouping = $this->get_instance()->teamsubmissiongroupingid;
2045         $groups = groups_get_all_groups($this->get_course()->id, $userid, $grouping);
2046         if (count($groups) != 1) {
2047             return false;
2048         }
2049         return array_pop($groups);
2050     }
2053     /**
2054      * Display the submission that is used by a plugin.
2055      *
2056      * Uses url parameters 'sid', 'gid' and 'plugin'.
2057      *
2058      * @param string $pluginsubtype
2059      * @return string
2060      */
2061     protected function view_plugin_content($pluginsubtype) {
2062         global $USER;
2064         $o = '';
2066         $submissionid = optional_param('sid', 0, PARAM_INT);
2067         $gradeid = optional_param('gid', 0, PARAM_INT);
2068         $plugintype = required_param('plugin', PARAM_TEXT);
2069         $item = null;
2070         if ($pluginsubtype == 'assignsubmission') {
2071             $plugin = $this->get_submission_plugin_by_type($plugintype);
2072             if ($submissionid <= 0) {
2073                 throw new coding_exception('Submission id should not be 0');
2074             }
2075             $item = $this->get_submission($submissionid);
2077             // Check permissions.
2078             if ($item->userid != $USER->id) {
2079                 require_capability('mod/assign:grade', $this->context);
2080             }
2081             $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2082                                                               $this->get_context(),
2083                                                               $this->show_intro(),
2084                                                               $this->get_course_module()->id,
2085                                                               $plugin->get_name()));
2086             $o .= $this->get_renderer()->render(new assign_submission_plugin_submission($plugin,
2087                                                               $item,
2088                                                               assign_submission_plugin_submission::FULL,
2089                                                               $this->get_course_module()->id,
2090                                                               $this->get_return_action(),
2091                                                               $this->get_return_params()));
2093             $logmessage = get_string('viewsubmissionforuser', 'assign', $item->userid);
2094             $this->add_to_log('view submission', $logmessage);
2095         } else {
2096             $plugin = $this->get_feedback_plugin_by_type($plugintype);
2097             if ($gradeid <= 0) {
2098                 throw new coding_exception('Grade id should not be 0');
2099             }
2100             $item = $this->get_grade($gradeid);
2101             // Check permissions.
2102             if ($item->userid != $USER->id) {
2103                 require_capability('mod/assign:grade', $this->context);
2104             }
2105             $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2106                                                               $this->get_context(),
2107                                                               $this->show_intro(),
2108                                                               $this->get_course_module()->id,
2109                                                               $plugin->get_name()));
2110             $o .= $this->get_renderer()->render(new assign_feedback_plugin_feedback($plugin,
2111                                                               $item,
2112                                                               assign_feedback_plugin_feedback::FULL,
2113                                                               $this->get_course_module()->id,
2114                                                               $this->get_return_action(),
2115                                                               $this->get_return_params()));
2116             $logmessage = get_string('viewfeedbackforuser', 'assign', $item->userid);
2117             $this->add_to_log('view feedback', $logmessage);
2118         }
2120         $o .= $this->view_return_links();
2122         $o .= $this->view_footer();
2123         return $o;
2124     }
2126     /**
2127      * Rewrite plugin file urls so they resolve correctly in an exported zip.
2128      *
2129      * @param stdClass $user - The user record
2130      * @param assign_plugin $plugin - The assignment plugin
2131      */
2132     public function download_rewrite_pluginfile_urls($text, $user, $plugin) {
2133         $groupmode = groups_get_activity_groupmode($this->get_course_module());
2134         $groupname = '';
2135         if ($groupmode) {
2136             $groupid = groups_get_activity_group($this->get_course_module(), true);
2137             $groupname = groups_get_group_name($groupid).'-';
2138         }
2140         if ($this->is_blind_marking()) {
2141             $prefix = $groupname . get_string('participant', 'assign');
2142             $prefix = str_replace('_', ' ', $prefix);
2143             $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2144         } else {
2145             $prefix = $groupname . fullname($user);
2146             $prefix = str_replace('_', ' ', $prefix);
2147             $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2148         }
2150         $subtype = $plugin->get_subtype();
2151         $type = $plugin->get_type();
2152         $prefix = $prefix . $subtype . '_' . $type . '_';
2154         $result = str_replace('@@PLUGINFILE@@/', $prefix, $text);
2156         return $result;
2157     }
2159     /**
2160      * Render the content in editor that is often used by plugin.
2161      *
2162      * @param string $filearea
2163      * @param int  $submissionid
2164      * @param string $plugintype
2165      * @param string $editor
2166      * @param string $component
2167      * @return string
2168      */
2169     public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
2170         global $CFG;
2172         $result = '';
2174         $plugin = $this->get_submission_plugin_by_type($plugintype);
2176         $text = $plugin->get_editor_text($editor, $submissionid);
2177         $format = $plugin->get_editor_format($editor, $submissionid);
2179         $finaltext = file_rewrite_pluginfile_urls($text,
2180                                                   'pluginfile.php',
2181                                                   $this->get_context()->id,
2182                                                   $component,
2183                                                   $filearea,
2184                                                   $submissionid);
2185         $params = array('overflowdiv' => true, 'context' => $this->get_context());
2186         $result .= format_text($finaltext, $format, $params);
2188         if ($CFG->enableportfolios) {
2189             require_once($CFG->libdir . '/portfoliolib.php');
2191             $button = new portfolio_add_button();
2192             $portfolioparams = array('cmid' => $this->get_course_module()->id,
2193                                      'sid' => $submissionid,
2194                                      'plugin' => $plugintype,
2195                                      'editor' => $editor,
2196                                      'area'=>$filearea);
2197             $button->set_callback_options('assign_portfolio_caller', $portfolioparams, 'mod_assign');
2198             $fs = get_file_storage();
2200             if ($files = $fs->get_area_files($this->context->id,
2201                                              $component,
2202                                              $filearea,
2203                                              $submissionid,
2204                                              'timemodified',
2205                                              false)) {
2206                 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
2207             } else {
2208                 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
2209             }
2210             $result .= $button->to_html();
2211         }
2212         return $result;
2213     }
2215     /**
2216      * Display a continue page.
2217      *
2218      * @return string
2219      */
2220     protected function view_savegrading_result($message) {
2221         $o = '';
2222         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2223                                                       $this->get_context(),
2224                                                       $this->show_intro(),
2225                                                       $this->get_course_module()->id,
2226                                                       get_string('savegradingresult', 'assign')));
2227         $gradingresult = new assign_gradingmessage(get_string('savegradingresult', 'assign'),
2228                                                    $message,
2229                                                    $this->get_course_module()->id);
2230         $o .= $this->get_renderer()->render($gradingresult);
2231         $o .= $this->view_footer();
2232         return $o;
2233     }
2234     /**
2235      * Display a grading error.
2236      *
2237      * @param string $message - The description of the result
2238      * @return string
2239      */
2240     protected function view_quickgrading_result($message) {
2241         $o = '';
2242         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2243                                                       $this->get_context(),
2244                                                       $this->show_intro(),
2245                                                       $this->get_course_module()->id,
2246                                                       get_string('quickgradingresult', 'assign')));
2247         $gradingresult = new assign_gradingmessage(get_string('quickgradingresult', 'assign'),
2248                                                    $message,
2249                                                    $this->get_course_module()->id);
2250         $o .= $this->get_renderer()->render($gradingresult);
2251         $o .= $this->view_footer();
2252         return $o;
2253     }
2255     /**
2256      * Display the page footer.
2257      *
2258      * @return string
2259      */
2260     protected function view_footer() {
2261         return $this->get_renderer()->render_footer();
2262     }
2264     /**
2265      * Does this user have grade permission for this assignment?
2266      *
2267      * @return bool
2268      */
2269     protected function can_grade() {
2270         // Permissions check.
2271         if (!has_capability('mod/assign:grade', $this->context)) {
2272             return false;
2273         }
2275         return true;
2276     }
2278     /**
2279      * Download a zip file of all assignment submissions.
2280      *
2281      * @return string - If an error occurs, this will contain the error page.
2282      */
2283     protected function download_submissions() {
2284         global $CFG, $DB;
2286         // More efficient to load this here.
2287         require_once($CFG->libdir.'/filelib.php');
2289         require_capability('mod/assign:grade', $this->context);
2291         // Load all users with submit.
2292         $students = get_enrolled_users($this->context, "mod/assign:submit");
2294         // Build a list of files to zip.
2295         $filesforzipping = array();
2296         $fs = get_file_storage();
2298         $groupmode = groups_get_activity_groupmode($this->get_course_module());
2299         // All users.
2300         $groupid = 0;
2301         $groupname = '';
2302         if ($groupmode) {
2303             $groupid = groups_get_activity_group($this->get_course_module(), true);
2304             $groupname = groups_get_group_name($groupid).'-';
2305         }
2307         // Construct the zip file name.
2308         $filename = clean_filename($this->get_course()->shortname . '-' .
2309                                    $this->get_instance()->name . '-' .
2310                                    $groupname.$this->get_course_module()->id . '.zip');
2312         // Get all the files for each student.
2313         foreach ($students as $student) {
2314             $userid = $student->id;
2316             if ((groups_is_member($groupid, $userid) or !$groupmode or !$groupid)) {
2317                 // Get the plugins to add their own files to the zip.
2319                 $submissiongroup = false;
2320                 $groupname = '';
2321                 if ($this->get_instance()->teamsubmission) {
2322                     $submission = $this->get_group_submission($userid, 0, false);
2323                     $submissiongroup = $this->get_submission_group($userid);
2324                     if ($submissiongroup) {
2325                         $groupname = $submissiongroup->name . '-';
2326                     } else {
2327                         $groupname = get_string('defaultteam', 'assign') . '-';
2328                     }
2329                 } else {
2330                     $submission = $this->get_user_submission($userid, false);
2331                 }
2333                 if ($this->is_blind_marking()) {
2334                     $prefix = str_replace('_', ' ', $groupname . get_string('participant', 'assign'));
2335                     $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2336                 } else {
2337                     $prefix = str_replace('_', ' ', $groupname . fullname($student));
2338                     $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2339                 }
2341                 if ($submission) {
2342                     foreach ($this->submissionplugins as $plugin) {
2343                         if ($plugin->is_enabled() && $plugin->is_visible()) {
2344                             $pluginfiles = $plugin->get_files($submission, $student);
2345                             foreach ($pluginfiles as $zipfilename => $file) {
2346                                 $subtype = $plugin->get_subtype();
2347                                 $type = $plugin->get_type();
2348                                 $prefixedfilename = clean_filename($prefix .
2349                                                                    $subtype .
2350                                                                    '_' .
2351                                                                    $type .
2352                                                                    '_' .
2353                                                                    $zipfilename);
2354                                 $filesforzipping[$prefixedfilename] = $file;
2355                             }
2356                         }
2357                     }
2358                 }
2359             }
2360         }
2361         $result = '';
2362         if (count($filesforzipping) == 0) {
2363             $header = new assign_header($this->get_instance(),
2364                                         $this->get_context(),
2365                                         '',
2366                                         $this->get_course_module()->id,
2367                                         get_string('downloadall', 'assign'));
2368             $result .= $this->get_renderer()->render($header);
2369             $result .= $this->get_renderer()->notification(get_string('nosubmission', 'assign'));
2370             $url = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id,
2371                                                                     'action'=>'grading'));
2372             $result .= $this->get_renderer()->continue_button($url);
2373             $result .= $this->view_footer();
2374         } else if ($zipfile = $this->pack_files($filesforzipping)) {
2375             $this->add_to_log('download all submissions', get_string('downloadall', 'assign'));
2376             // Send file and delete after sending.
2377             send_temp_file($zipfile, $filename);
2378             // We will not get here - send_temp_file calls exit.
2379         }
2380         return $result;
2381     }
2383     /**
2384      * Util function to add a message to the log.
2385      *
2386      * @param string $action The current action
2387      * @param string $info A detailed description of the change. But no more than 255 characters.
2388      * @param string $url The url to the assign module instance.
2389      * @return void
2390      */
2391     public function add_to_log($action = '', $info = '', $url='') {
2392         global $USER;
2394         $fullurl = 'view.php?id=' . $this->get_course_module()->id;
2395         if ($url != '') {
2396             $fullurl .= '&' . $url;
2397         }
2399         add_to_log($this->get_course()->id,
2400                    'assign',
2401                    $action,
2402                    $fullurl,
2403                    $info,
2404                    $this->get_course_module()->id,
2405                    $USER->id);
2406     }
2408     /**
2409      * Lazy load the page renderer and expose the renderer to plugins.
2410      *
2411      * @return assign_renderer
2412      */
2413     public function get_renderer() {
2414         global $PAGE;
2415         if ($this->output) {
2416             return $this->output;
2417         }
2418         $this->output = $PAGE->get_renderer('mod_assign');
2419         return $this->output;
2420     }
2422     /**
2423      * Load the submission object for a particular user, optionally creating it if required.
2424      *
2425      * For team assignments there are 2 submissions - the student submission and the team submission
2426      * All files are associated with the team submission but the status of the students contribution is
2427      * recorded separately.
2428      *
2429      * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
2430      * @param bool $create optional - defaults to false. If set to true a new submission object
2431      *                     will be created in the database.
2432      * @param int $attemptnumber - -1 means the latest attempt
2433      * @return stdClass The submission
2434      */
2435     public function get_user_submission($userid, $create, $attemptnumber=-1) {
2436         global $DB, $USER;
2438         if (!$userid) {
2439             $userid = $USER->id;
2440         }
2441         // If the userid is not null then use userid.
2442         $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid, 'groupid'=>0);
2443         if ($attemptnumber >= 0) {
2444             $params['attemptnumber'] = $attemptnumber;
2445         }
2447         // Only return the row with the highest attemptnumber.
2448         $submission = null;
2449         $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
2450         if ($submissions) {
2451             $submission = reset($submissions);
2452         }
2454         if ($submission) {
2455             return $submission;
2456         }
2457         if ($create) {
2458             $submission = new stdClass();
2459             $submission->assignment   = $this->get_instance()->id;
2460             $submission->userid       = $userid;
2461             $submission->timecreated = time();
2462             $submission->timemodified = $submission->timecreated;
2463             $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
2464             if ($attemptnumber >= 0) {
2465                 $submission->attemptnumber = $attemptnumber;
2466             } else {
2467                 $submission->attemptnumber = 0;
2468             }
2469             $sid = $DB->insert_record('assign_submission', $submission);
2470             $submission->id = $sid;
2471             return $submission;
2472         }
2473         return false;
2474     }
2476     /**
2477      * Load the submission object from it's id.
2478      *
2479      * @param int $submissionid The id of the submission we want
2480      * @return stdClass The submission
2481      */
2482     protected function get_submission($submissionid) {
2483         global $DB;
2485         $params = array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid);
2486         return $DB->get_record('assign_submission', $params, '*', MUST_EXIST);
2487     }
2489     /**
2490      * This will retrieve a user flags object from the db optionally creating it if required.
2491      * The user flags was split from the user_grades table in 2.5.
2492      *
2493      * @param int $userid The user we are getting the flags for.
2494      * @param bool $create If true the flags record will be created if it does not exist
2495      * @return stdClass The flags record
2496      */
2497     public function get_user_flags($userid, $create) {
2498         global $DB, $USER;
2500         // If the userid is not null then use userid.
2501         if (!$userid) {
2502             $userid = $USER->id;
2503         }
2505         $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
2507         $flags = $DB->get_record('assign_user_flags', $params);
2509         if ($flags) {
2510             return $flags;
2511         }
2512         if ($create) {
2513             $flags = new stdClass();
2514             $flags->assignment = $this->get_instance()->id;
2515             $flags->userid = $userid;
2516             $flags->locked = 0;
2517             $flags->extensionduedate = 0;
2518             $flags->workflowstate = '';
2519             $flags->allocatedmarker = 0;
2521             // The mailed flag can be one of 3 values: 0 is unsent, 1 is sent and 2 is do not send yet.
2522             // This is because students only want to be notified about certain types of update (grades and feedback).
2523             $flags->mailed = 2;
2525             $fid = $DB->insert_record('assign_user_flags', $flags);
2526             $flags->id = $fid;
2527             return $flags;
2528         }
2529         return false;
2530     }
2532     /**
2533      * This will retrieve a grade object from the db, optionally creating it if required.
2534      *
2535      * @param int $userid The user we are grading
2536      * @param bool $create If true the grade will be created if it does not exist
2537      * @param int $attemptnumber The attempt number to retrieve the grade for. -1 means the latest submission.
2538      * @return stdClass The grade record
2539      */
2540     public function get_user_grade($userid, $create, $attemptnumber=-1) {
2541         global $DB, $USER;
2543         // If the userid is not null then use userid.
2544         if (!$userid) {
2545             $userid = $USER->id;
2546         }
2548         $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
2549         if ($attemptnumber < 0) {
2550             // Make sure this grade matches the latest submission attempt.
2551             if ($this->get_instance()->teamsubmission) {
2552                 $submission = $this->get_group_submission($userid, 0, false);
2553             } else {
2554                 $submission = $this->get_user_submission($userid, false);
2555             }
2556             if ($submission) {
2557                 $attemptnumber = $submission->attemptnumber;
2558             }
2559         }
2561         if ($attemptnumber >= 0) {
2562             $params['attemptnumber'] = $attemptnumber;
2563         }
2565         $grades = $DB->get_records('assign_grades', $params, 'attemptnumber DESC', '*', 0, 1);
2567         if ($grades) {
2568             return reset($grades);
2569         }
2570         if ($create) {
2571             $grade = new stdClass();
2572             $grade->assignment   = $this->get_instance()->id;
2573             $grade->userid       = $userid;
2574             $grade->timecreated = time();
2575             $grade->timemodified = $grade->timecreated;
2576             $grade->grade = -1;
2577             $grade->grader = $USER->id;
2578             if ($attemptnumber >= 0) {
2579                 $grade->attemptnumber = $attemptnumber;
2580             }
2582             $gid = $DB->insert_record('assign_grades', $grade);
2583             $grade->id = $gid;
2584             return $grade;
2585         }
2586         return false;
2587     }
2589     /**
2590      * This will retrieve a grade object from the db.
2591      *
2592      * @param int $gradeid The id of the grade
2593      * @return stdClass The grade record
2594      */
2595     protected function get_grade($gradeid) {
2596         global $DB;
2598         $params = array('assignment'=>$this->get_instance()->id, 'id'=>$gradeid);
2599         return $DB->get_record('assign_grades', $params, '*', MUST_EXIST);
2600     }
2602     /**
2603      * Print the grading page for a single user submission.
2604      *
2605      * @param moodleform $mform
2606      * @return string
2607      */
2608     protected function view_single_grade_page($mform) {
2609         global $DB, $CFG;
2611         $o = '';
2612         $instance = $this->get_instance();
2614         require_once($CFG->dirroot . '/mod/assign/gradeform.php');
2616         // Need submit permission to submit an assignment.
2617         require_capability('mod/assign:grade', $this->context);
2619         $header = new assign_header($instance,
2620                                     $this->get_context(),
2621                                     false,
2622                                     $this->get_course_module()->id,
2623                                     get_string('grading', 'assign'));
2624         $o .= $this->get_renderer()->render($header);
2626         // If userid is passed - we are only grading a single student.
2627         $rownum = required_param('rownum', PARAM_INT);
2628         $useridlistid = optional_param('useridlistid', time(), PARAM_INT);
2629         $userid = optional_param('userid', 0, PARAM_INT);
2630         $attemptnumber = optional_param('attemptnumber', -1, PARAM_INT);
2632         $cache = cache::make_from_params(cache_store::MODE_SESSION, 'mod_assign', 'useridlist');
2633         if (!$userid) {
2634             if (!$useridlist = $cache->get($this->get_course_module()->id . '_' . $useridlistid)) {
2635                 $useridlist = $this->get_grading_userid_list();
2636             }
2637             $cache->set($this->get_course_module()->id . '_' . $useridlistid, $useridlist);
2638         } else {
2639             $rownum = 0;
2640             $useridlist = array($userid);
2641         }
2643         if ($rownum < 0 || $rownum > count($useridlist)) {
2644             throw new coding_exception('Row is out of bounds for the current grading table: ' . $rownum);
2645         }
2647         $last = false;
2648         $userid = $useridlist[$rownum];
2649         if ($rownum == count($useridlist) - 1) {
2650             $last = true;
2651         }
2652         $user = $DB->get_record('user', array('id' => $userid));
2653         if ($user) {
2654             $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2655             $usersummary = new assign_user_summary($user,
2656                                                    $this->get_course()->id,
2657                                                    $viewfullnames,
2658                                                    $this->is_blind_marking(),
2659                                                    $this->get_uniqueid_for_user($user->id),
2660                                                    get_extra_user_fields($this->get_context()));
2661             $o .= $this->get_renderer()->render($usersummary);
2662         }
2663         $submission = $this->get_user_submission($userid, false, $attemptnumber);
2664         $submissiongroup = null;
2665         $submissiongroupmemberswhohavenotsubmitted = array();
2666         $teamsubmission = null;
2667         $notsubmitted = array();
2668         if ($instance->teamsubmission) {
2669             $teamsubmission = $this->get_group_submission($userid, 0, false, $attemptnumber);
2670             $submissiongroup = $this->get_submission_group($userid);
2671             $groupid = 0;
2672             if ($submissiongroup) {
2673                 $groupid = $submissiongroup->id;
2674             }
2675             $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
2677         }
2679         // Get the requested grade.
2680         $grade = $this->get_user_grade($userid, false, $attemptnumber);
2681         $flags = $this->get_user_flags($userid, false);
2682         if ($this->can_view_submission($userid)) {
2683             $gradelocked = ($flags && $flags->locked) || $this->grading_disabled($userid);
2684             $extensionduedate = null;
2685             if ($flags) {
2686                 $extensionduedate = $flags->extensionduedate;
2687             }
2688             $showedit = $this->submissions_open($userid) && ($this->is_any_submission_plugin_enabled());
2690             if ($teamsubmission) {
2691                 $showsubmit = $showedit &&
2692                               $teamsubmission &&
2693                               ($teamsubmission->status == ASSIGN_SUBMISSION_STATUS_DRAFT);
2694             } else {
2695                 $showsubmit = $showedit &&
2696                               $submission &&
2697                               ($submission->status == ASSIGN_SUBMISSION_STATUS_DRAFT);
2698             }
2699             if (!$this->get_instance()->submissiondrafts) {
2700                 $showsubmit = false;
2701             }
2702             $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2704             $submissionstatus = new assign_submission_status($instance->allowsubmissionsfromdate,
2705                                                              $instance->alwaysshowdescription,
2706                                                              $submission,
2707                                                              $instance->teamsubmission,
2708                                                              $teamsubmission,
2709                                                              $submissiongroup,
2710                                                              $notsubmitted,
2711                                                              $this->is_any_submission_plugin_enabled(),
2712                                                              $gradelocked,
2713                                                              $this->is_graded($userid),
2714                                                              $instance->duedate,
2715                                                              $instance->cutoffdate,
2716                                                              $this->get_submission_plugins(),
2717                                                              $this->get_return_action(),
2718                                                              $this->get_return_params(),
2719                                                              $this->get_course_module()->id,
2720                                                              $this->get_course()->id,
2721                                                              assign_submission_status::GRADER_VIEW,
2722                                                              $showedit,
2723                                                              $showsubmit,
2724                                                              $viewfullnames,
2725                                                              $extensionduedate,
2726                                                              $this->get_context(),
2727                                                              $this->is_blind_marking(),
2728                                                              '',
2729                                                              $instance->attemptreopenmethod,
2730                                                              $instance->maxattempts);
2731             $o .= $this->get_renderer()->render($submissionstatus);
2732         }
2734         if ($grade) {
2735             $data = new stdClass();
2736             if ($grade->grade !== null && $grade->grade >= 0) {
2737                 $data->grade = format_float($grade->grade, 2);
2738             }
2739             if (!empty($flags->workflowstate)) {
2740                 $data->workflowstate = $flags->workflowstate;
2741             }
2742             if (!empty($flags->allocatedmarker)) {
2743                 $data->allocatedmarker = $flags->allocatedmarker;
2744             }
2745         } else {
2746             $data = new stdClass();
2747             $data->grade = '';
2748         }
2749         // Warning if required.
2750         $allsubmissions = $this->get_all_submissions($userid);
2752         if ($attemptnumber != -1) {
2753             $params = array('attemptnumber'=>$attemptnumber + 1,
2754                             'totalattempts'=>count($allsubmissions));
2755             $message = get_string('editingpreviousfeedbackwarning', 'assign', $params);
2756             $o .= $this->get_renderer()->notification($message);
2757         }
2759         // Now show the grading form.
2760         if (!$mform) {
2761             $pagination = array('rownum'=>$rownum,
2762                                 'useridlistid'=>$useridlistid,
2763                                 'last'=>$last,
2764                                 'userid'=>optional_param('userid', 0, PARAM_INT),
2765                                 'attemptnumber'=>$attemptnumber);
2766             $formparams = array($this, $data, $pagination);
2767             $mform = new mod_assign_grade_form(null,
2768                                                $formparams,
2769                                                'post',
2770                                                '',
2771                                                array('class'=>'gradeform'));
2772         }
2773         $o .= $this->get_renderer()->heading(get_string('grade'), 3);
2774         $o .= $this->get_renderer()->render(new assign_form('gradingform', $mform));
2776         if (count($allsubmissions) > 1 && $attemptnumber == -1) {
2777             $allgrades = $this->get_all_grades($userid);
2778             $history = new assign_attempt_history($allsubmissions,
2779                                                   $allgrades,
2780                                                   $this->get_submission_plugins(),
2781                                                   $this->get_feedback_plugins(),
2782                                                   $this->get_course_module()->id,
2783                                                   $this->get_return_action(),
2784                                                   $this->get_return_params(),
2785                                                   true);
2787             $o .= $this->get_renderer()->render($history);
2788         }
2790         $msg = get_string('viewgradingformforstudent',
2791                           'assign',
2792                           array('id'=>$user->id, 'fullname'=>fullname($user)));
2793         $this->add_to_log('view grading form', $msg);
2795         $o .= $this->view_footer();
2796         return $o;
2797     }
2799     /**
2800      * Show a confirmation page to make sure they want to release student identities.
2801      *
2802      * @return string
2803      */
2804     protected function view_reveal_identities_confirm() {
2805         global $CFG, $USER;
2807         require_capability('mod/assign:revealidentities', $this->get_context());
2809         $o = '';
2810         $header = new assign_header($this->get_instance(),
2811                                     $this->get_context(),
2812                                     false,
2813                                     $this->get_course_module()->id);
2814         $o .= $this->get_renderer()->render($header);
2816         $urlparams = array('id'=>$this->get_course_module()->id,
2817                            'action'=>'revealidentitiesconfirm',
2818                            'sesskey'=>sesskey());
2819         $confirmurl = new moodle_url('/mod/assign/view.php', $urlparams);
2821         $urlparams = array('id'=>$this->get_course_module()->id,
2822                            'action'=>'grading');
2823         $cancelurl = new moodle_url('/mod/assign/view.php', $urlparams);
2825         $o .= $this->get_renderer()->confirm(get_string('revealidentitiesconfirm', 'assign'),
2826                                              $confirmurl,
2827                                              $cancelurl);
2828         $o .= $this->view_footer();
2829         $this->add_to_log('view', get_string('viewrevealidentitiesconfirm', 'assign'));
2830         return $o;
2831     }
2833     /**
2834      * View a link to go back to the previous page. Uses url parameters returnaction and returnparams.
2835      *
2836      * @return string
2837      */
2838     protected function view_return_links() {
2839         $returnaction = optional_param('returnaction', '', PARAM_ALPHA);
2840         $returnparams = optional_param('returnparams', '', PARAM_TEXT);
2842         $params = array();
2843         $returnparams = str_replace('&amp;', '&', $returnparams);
2844         parse_str($returnparams, $params);
2845         $newparams = array('id' => $this->get_course_module()->id, 'action' => $returnaction);
2846         $params = array_merge($newparams, $params);
2848         $url = new moodle_url('/mod/assign/view.php', $params);
2849         return $this->get_renderer()->single_button($url, get_string('back'), 'get');
2850     }
2852     /**
2853      * View the grading table of all submissions for this assignment.
2854      *
2855      * @return string
2856      */
2857     protected function view_grading_table() {
2858         global $USER, $CFG;
2860         // Include grading options form.
2861         require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
2862         require_once($CFG->dirroot . '/mod/assign/quickgradingform.php');
2863         require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
2864         $o = '';
2865         $cmid = $this->get_course_module()->id;
2867         $links = array();
2868         if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
2869                 has_capability('moodle/grade:viewall', $this->get_course_context())) {
2870             $gradebookurl = '/grade/report/grader/index.php?id=' . $this->get_course()->id;
2871             $links[$gradebookurl] = get_string('viewgradebook', 'assign');
2872         }
2873         if ($this->is_any_submission_plugin_enabled() && $this->count_submissions()) {
2874             $downloadurl = '/mod/assign/view.php?id=' . $cmid . '&action=downloadall';
2875             $links[$downloadurl] = get_string('downloadall', 'assign');
2876         }
2877         if ($this->is_blind_marking() &&
2878                 has_capability('mod/assign:revealidentities', $this->get_context())) {
2879             $revealidentitiesurl = '/mod/assign/view.php?id=' . $cmid . '&action=revealidentities';
2880             $links[$revealidentitiesurl] = get_string('revealidentities', 'assign');
2881         }
2882         foreach ($this->get_feedback_plugins() as $plugin) {
2883             if ($plugin->is_enabled() && $plugin->is_visible()) {
2884                 foreach ($plugin->get_grading_actions() as $action => $description) {
2885                     $url = '/mod/assign/view.php' .
2886                            '?id=' .  $cmid .
2887                            '&plugin=' . $plugin->get_type() .
2888                            '&pluginsubtype=assignfeedback' .
2889                            '&action=viewpluginpage&pluginaction=' . $action;
2890                     $links[$url] = $description;
2891                 }
2892             }
2893         }
2895         $gradingactions = new url_select($links);
2896         $gradingactions->set_label(get_string('choosegradingaction', 'assign'));
2898         $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2900         $perpage = get_user_preferences('assign_perpage', 10);
2901         $filter = get_user_preferences('assign_filter', '');
2902         $markerfilter = get_user_preferences('assign_markerfilter', '');
2903         $workflowfilter = get_user_preferences('assign_workflowfilter', '');
2904         $controller = $gradingmanager->get_active_controller();
2905         $showquickgrading = empty($controller);
2906         $quickgrading = get_user_preferences('assign_quickgrading', false);
2908         $markingallocation = $this->get_instance()->markingallocation &&
2909             has_capability('mod/assign:manageallocations', $this->context);
2910         // Get markers to use in drop lists.
2911         $markingallocationoptions = array();
2912         if ($markingallocation) {
2913             $markers = get_users_by_capability($this->context, 'mod/assign:grade');
2914             $markingallocationoptions[''] = get_string('filternone', 'assign');
2915             foreach ($markers as $marker) {
2916                 $markingallocationoptions[$marker->id] = fullname($marker);
2917             }
2918         }
2920         $markingworkflow = $this->get_instance()->markingworkflow;
2921         // Get marking states to show in form.
2922         $markingworkflowoptions = array();
2923         if ($markingworkflow) {
2924             $markingworkflowoptions[''] = get_string('filternone', 'assign');
2925             $markingworkflowoptions[ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED] = get_string('markingworkflowstatenotmarked', 'assign');
2926             $markingworkflowoptions = array_merge($markingworkflowoptions, $this->get_marking_workflow_states_for_current_user());
2927         }
2929         // Print options for changing the filter and changing the number of results per page.
2930         $gradingoptionsformparams = array('cm'=>$cmid,
2931                                           'contextid'=>$this->context->id,
2932                                           'userid'=>$USER->id,
2933                                           'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
2934                                           'showquickgrading'=>$showquickgrading,
2935                                           'quickgrading'=>$quickgrading,
2936                                           'markingworkflowopt'=>$markingworkflowoptions,
2937                                           'markingallocationopt'=>$markingallocationoptions);
2939         $classoptions = array('class'=>'gradingoptionsform');
2940         $gradingoptionsform = new mod_assign_grading_options_form(null,
2941                                                                   $gradingoptionsformparams,
2942                                                                   'post',
2943                                                                   '',
2944                                                                   $classoptions);
2946         $batchformparams = array('cm'=>$cmid,
2947                                  'submissiondrafts'=>$this->get_instance()->submissiondrafts,
2948                                  'duedate'=>$this->get_instance()->duedate,
2949                                  'attemptreopenmethod'=>$this->get_instance()->attemptreopenmethod,
2950                                  'feedbackplugins'=>$this->get_feedback_plugins(),
2951                                  'context'=>$this->get_context(),
2952                                  'markingworkflow'=>$markingworkflow,
2953                                  'markingallocation'=>$markingallocation);
2954         $classoptions = array('class'=>'gradingbatchoperationsform');
2956         $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
2957                                                                                    $batchformparams,
2958                                                                                    'post',
2959                                                                                    '',
2960                                                                                    $classoptions);
2962         $gradingoptionsdata = new stdClass();
2963         $gradingoptionsdata->perpage = $perpage;
2964         $gradingoptionsdata->filter = $filter;
2965         $gradingoptionsdata->markerfilter = $markerfilter;
2966         $gradingoptionsdata->workflowfilter = $workflowfilter;
2967         $gradingoptionsform->set_data($gradingoptionsdata);
2969         $actionformtext = $this->get_renderer()->render($gradingactions);
2970         $header = new assign_header($this->get_instance(),
2971                                     $this->get_context(),
2972                                     false,
2973                                     $this->get_course_module()->id,
2974                                     get_string('grading', 'assign'),
2975                                     $actionformtext);
2976         $o .= $this->get_renderer()->render($header);
2978         $currenturl = $CFG->wwwroot .
2979                       '/mod/assign/view.php?id=' .
2980                       $this->get_course_module()->id .
2981                       '&action=grading';
2983         $o .= groups_print_activity_menu($this->get_course_module(), $currenturl, true);
2985         // Plagiarism update status apearring in the grading book.
2986         if (!empty($CFG->enableplagiarism)) {
2987             require_once($CFG->libdir . '/plagiarismlib.php');
2988             $o .= plagiarism_update_status($this->get_course(), $this->get_course_module());
2989         }
2991         // Load and print the table of submissions.
2992         if ($showquickgrading && $quickgrading) {
2993             $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, true);
2994             $table = $this->get_renderer()->render($gradingtable);
2995             $quickformparams = array('cm'=>$this->get_course_module()->id, 'gradingtable'=>$table);
2996             $quickgradingform = new mod_assign_quick_grading_form(null, $quickformparams);
2998             $o .= $this->get_renderer()->render(new assign_form('quickgradingform', $quickgradingform));
2999         } else {
3000             $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, false);
3001             $o .= $this->get_renderer()->render($gradingtable);
3002         }
3004         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
3005         $users = array_keys($this->list_participants($currentgroup, true));
3006         if (count($users) != 0) {
3007             // If no enrolled user in a course then don't display the batch operations feature.
3008             $assignform = new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform);
3009             $o .= $this->get_renderer()->render($assignform);
3010         }
3011         $assignform = new assign_form('gradingoptionsform',
3012                                       $gradingoptionsform,
3013                                       'M.mod_assign.init_grading_options');
3014         $o .= $this->get_renderer()->render($assignform);
3015         return $o;
3016     }
3018     /**
3019      * View entire grading page.
3020      *
3021      * @return string
3022      */
3023     protected function view_grading_page() {
3024         global $CFG;
3026         $o = '';
3027         // Need submit permission to submit an assignment.
3028         require_capability('mod/assign:grade', $this->context);
3029         require_once($CFG->dirroot . '/mod/assign/gradeform.php');
3031         // Only load this if it is.
3033         $o .= $this->view_grading_table();
3035         $o .= $this->view_footer();
3037         $logmessage = get_string('viewsubmissiongradingtable', 'assign');
3038         $this->add_to_log('view submission grading table', $logmessage);
3039         return $o;
3040     }
3042     /**
3043      * Capture the output of the plagiarism plugins disclosures and return it as a string.
3044      *
3045      * @return void
3046      */
3047     protected function plagiarism_print_disclosure() {
3048         global $CFG;
3049         $o = '';
3051         if (!empty($CFG->enableplagiarism)) {
3052             require_once($CFG->libdir . '/plagiarismlib.php');
3054             $o .= plagiarism_print_disclosure($this->get_course_module()->id);
3055         }
3057         return $o;
3058     }
3060     /**
3061      * Message for students when assignment submissions have been closed.
3062      *
3063      * @return string
3064      */
3065     protected function view_student_error_message() {
3066         global $CFG;
3068         $o = '';
3069         // Need submit permission to submit an assignment.
3070         require_capability('mod/assign:submit', $this->context);
3072         $header = new assign_header($this->get_instance(),
3073                                     $this->get_context(),
3074                                     $this->show_intro(),
3075                                     $this->get_course_module()->id,
3076                                     get_string('editsubmission', 'assign'));
3077         $o .= $this->get_renderer()->render($header);
3079         $o .= $this->get_renderer()->notification(get_string('submissionsclosed', 'assign'));
3081         $o .= $this->view_footer();
3083         return $o;
3085     }
3087     /**
3088      * View edit submissions page.
3089      *
3090      * @param moodleform $mform
3091      * @param array $notices A list of notices to display at the top of the
3092      *                       edit submission form (e.g. from plugins).
3093      * @return string The page output.
3094      */
3095     protected function view_edit_submission_page($mform, $notices) {
3096         global $CFG;
3098         $o = '';
3099         require_once($CFG->dirroot . '/mod/assign/submission_form.php');
3100         // Need submit permission to submit an assignment.
3101         require_capability('mod/assign:submit', $this->context);
3103         if (!$this->submissions_open()) {
3104             return $this->view_student_error_message();
3105         }
3106         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
3107                                                       $this->get_context(),
3108                                                       $this->show_intro(),
3109                                                       $this->get_course_module()->id,
3110                                                       get_string('editsubmission', 'assign')));
3111         $o .= $this->plagiarism_print_disclosure();
3112         $data = new stdClass();
3114         if (!$mform) {
3115             $mform = new mod_assign_submission_form(null, array($this, $data));
3116         }
3118         foreach ($notices as $notice) {
3119             $o .= $this->get_renderer()->notification($notice);
3120         }
3122         $o .= $this->get_renderer()->render(new assign_form('editsubmissionform', $mform));
3124         $o .= $this->view_footer();
3125         $this->add_to_log('view submit assignment form', get_string('viewownsubmissionform', 'assign'));
3127         return $o;
3128     }
3130     /**
3131      * See if this assignment has a grade yet.
3132      *
3133      * @param int $userid
3134      * @return bool
3135      */
3136     protected function is_graded($userid) {
3137         $grade = $this->get_user_grade($userid, false);
3138         if ($grade) {
3139             return ($grade->grade !== null && $grade->grade >= 0);
3140         }
3141         return false;
3142     }
3144     /**
3145      * Perform an access check to see if the current $USER can view this group submission.
3146      *
3147      * @param int $groupid
3148      * @return bool
3149      */
3150     public function can_view_group_submission($groupid) {
3151         global $USER;
3153         if (!is_enrolled($this->get_course_context(), $USER->id)) {
3154             return false;
3155         }
3156         if (has_capability('mod/assign:grade', $this->context)) {
3157             return true;
3158         }
3159         $members = $this->get_submission_group_members($groupid, true);
3160         foreach ($members as $member) {
3161             if ($member->id == $USER->id) {
3162                 return true;
3163             }
3164         }
3165         return false;
3166     }
3168     /**
3169      * Perform an access check to see if the current $USER can view this users submission.
3170      *
3171      * @param int $userid
3172      * @return bool
3173      */
3174     public function can_view_submission($userid) {
3175         global $USER;
3177         if (is_siteadmin()) {
3178             return true;
3179         }
3180         if (!is_enrolled($this->get_course_context(), $userid)) {
3181             return false;
3182         }
3183         if ($userid == $USER->id && has_capability('mod/assign:submit', $this->context)) {
3184             return true;
3185         }
3186         if (has_capability('mod/assign:grade', $this->context)) {
3187             return true;
3188         }
3189         return false;
3190     }
3192     /**
3193      * Allows the plugin to show a batch grading operation page.
3194      *
3195      * @return none
3196      */
3197     protected function view_plugin_grading_batch_operation($mform) {
3198         require_capability('mod/assign:grade', $this->context);
3199         $prefix = 'plugingradingbatchoperation_';
3201         if ($data = $mform->get_data()) {
3202             $tail = substr($data->operation, strlen($prefix));
3203             list($plugintype, $action) = explode('_', $tail, 2);
3205             $plugin = $this->get_feedback_plugin_by_type($plugintype);
3206             if ($plugin) {
3207                 $users = $data->selectedusers;
3208                 $userlist = explode(',', $users);
3209                 echo $plugin->grading_batch_operation($action, $userlist);
3210                 return;
3211             }
3212         }
3213         print_error('invalidformdata', '');
3214     }
3216     /**
3217      * Ask the user to confirm they want to perform this batch operation
3218      *
3219      * @param moodleform $mform Set to a grading batch operations form
3220      * @return string - the page to view after processing these actions
3221      */
3222     protected function process_grading_batch_operation(& $mform) {
3223         global $CFG;
3224         require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
3225         require_sesskey();
3227         $markingallocation = $this->get_instance()->markingallocation &&
3228             has_capability('mod/assign:manageallocations', $this->context);
3230         $batchformparams = array('cm'=>$this->get_course_module()->id,
3231                                  'submissiondrafts'=>$this->get_instance()->submissiondrafts,
3232                                  'duedate'=>$this->get_instance()->duedate,
3233                                  'attemptreopenmethod'=>$this->get_instance()->attemptreopenmethod,
3234                                  'feedbackplugins'=>$this->get_feedback_plugins(),
3235                                  'context'=>$this->get_context(),
3236                                  'markingworkflow'=>$this->get_instance()->markingworkflow,
3237                                  'markingallocation'=>$markingallocation);
3238         $formclasses = array('class'=>'gradingbatchoperationsform');
3239         $mform = new mod_assign_grading_batch_operations_form(null,
3240                                                               $batchformparams,
3241                                                               'post',
3242                                                               '',
3243                                                               $formclasses);
3245         if ($data = $mform->get_data()) {
3246             // Get the list of users.
3247             $users = $data->selectedusers;
3248             $userlist = explode(',', $users);
3250             $prefix = 'plugingradingbatchoperation_';
3252             if ($data->operation == 'grantextension') {
3253                 // Reset the form so the grant extension page will create the extension form.
3254                 $mform = null;
3255                 return 'grantextension';
3256             } else if ($data->operation == 'setmarkingworkflowstate') {
3257                 return 'viewbatchsetmarkingworkflowstate';
3258             } else if ($data->operation == 'setmarkingallocation') {
3259                 return 'viewbatchmarkingallocation';
3260             } else if (strpos($data->operation, $prefix) === 0) {