eb8348ef54fafe99baf9947436f753eacacdc447
[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         $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
558         $update->blindmarking = $formdata->blindmarking;
559         $update->attemptreopenmethod = ASSIGN_ATTEMPT_REOPEN_METHOD_NONE;
560         if (!empty($formdata->attemptreopenmethod)) {
561             $update->attemptreopenmethod = $formdata->attemptreopenmethod;
562         }
563         if (!empty($formdata->maxattempts)) {
564             $update->maxattempts = $formdata->maxattempts;
565         }
566         $update->markingworkflow = $formdata->markingworkflow;
567         $update->markingallocation = $formdata->markingallocation;
569         $returnid = $DB->insert_record('assign', $update);
570         $this->instance = $DB->get_record('assign', array('id'=>$returnid), '*', MUST_EXIST);
571         // Cache the course record.
572         $this->course = $DB->get_record('course', array('id'=>$formdata->course), '*', MUST_EXIST);
574         if ($callplugins) {
575             // Call save_settings hook for submission plugins.
576             foreach ($this->submissionplugins as $plugin) {
577                 if (!$this->update_plugin_instance($plugin, $formdata)) {
578                     print_error($plugin->get_error());
579                     return false;
580                 }
581             }
582             foreach ($this->feedbackplugins as $plugin) {
583                 if (!$this->update_plugin_instance($plugin, $formdata)) {
584                     print_error($plugin->get_error());
585                     return false;
586                 }
587             }
589             // In the case of upgrades the coursemodule has not been set,
590             // so we need to wait before calling these two.
591             $this->update_calendar($formdata->coursemodule);
592             $this->update_gradebook(false, $formdata->coursemodule);
594         }
596         $update = new stdClass();
597         $update->id = $this->get_instance()->id;
598         $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
599         $DB->update_record('assign', $update);
601         return $returnid;
602     }
604     /**
605      * Delete all grades from the gradebook for this assignment.
606      *
607      * @return bool
608      */
609     protected function delete_grades() {
610         global $CFG;
612         $result = grade_update('mod/assign',
613                                $this->get_course()->id,
614                                'mod',
615                                'assign',
616                                $this->get_instance()->id,
617                                0,
618                                null,
619                                array('deleted'=>1));
620         return $result == GRADE_UPDATE_OK;
621     }
623     /**
624      * Delete this instance from the database.
625      *
626      * @return bool false if an error occurs
627      */
628     public function delete_instance() {
629         global $DB;
630         $result = true;
632         foreach ($this->submissionplugins as $plugin) {
633             if (!$plugin->delete_instance()) {
634                 print_error($plugin->get_error());
635                 $result = false;
636             }
637         }
638         foreach ($this->feedbackplugins as $plugin) {
639             if (!$plugin->delete_instance()) {
640                 print_error($plugin->get_error());
641                 $result = false;
642             }
643         }
645         // Delete files associated with this assignment.
646         $fs = get_file_storage();
647         if (! $fs->delete_area_files($this->context->id) ) {
648             $result = false;
649         }
651         // Delete_records will throw an exception if it fails - so no need for error checking here.
652         $DB->delete_records('assign_submission', array('assignment'=>$this->get_instance()->id));
653         $DB->delete_records('assign_grades', array('assignment'=>$this->get_instance()->id));
654         $DB->delete_records('assign_plugin_config', array('assignment'=>$this->get_instance()->id));
656         // Delete items from the gradebook.
657         if (! $this->delete_grades()) {
658             $result = false;
659         }
661         // Delete the instance.
662         $DB->delete_records('assign', array('id'=>$this->get_instance()->id));
664         return $result;
665     }
667     /**
668      * Actual implementation of the reset course functionality, delete all the
669      * assignment submissions for course $data->courseid.
670      *
671      * @param $data the data submitted from the reset course.
672      * @return array status array
673      */
674     public function reset_userdata($data) {
675         global $CFG, $DB;
677         $componentstr = get_string('modulenameplural', 'assign');
678         $status = array();
680         $fs = get_file_storage();
681         if (!empty($data->reset_assign_submissions)) {
682             // Delete files associated with this assignment.
683             foreach ($this->submissionplugins as $plugin) {
684                 $fileareas = array();
685                 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
686                 $fileareas = $plugin->get_file_areas();
687                 foreach ($fileareas as $filearea) {
688                     $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
689                 }
691                 if (!$plugin->delete_instance()) {
692                     $status[] = array('component'=>$componentstr,
693                                       'item'=>get_string('deleteallsubmissions', 'assign'),
694                                       'error'=>$plugin->get_error());
695                 }
696             }
698             foreach ($this->feedbackplugins as $plugin) {
699                 $fileareas = array();
700                 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
701                 $fileareas = $plugin->get_file_areas();
702                 foreach ($fileareas as $filearea) {
703                     $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
704                 }
706                 if (!$plugin->delete_instance()) {
707                     $status[] = array('component'=>$componentstr,
708                                       'item'=>get_string('deleteallsubmissions', 'assign'),
709                                       'error'=>$plugin->get_error());
710                 }
711             }
713             $assignssql = 'SELECT a.id
714                              FROM {assign} a
715                            WHERE a.course=:course';
716             $params = array('course'=>$data->courseid);
718             $DB->delete_records_select('assign_submission', "assignment IN ($assignssql)", $params);
720             $status[] = array('component'=>$componentstr,
721                               'item'=>get_string('deleteallsubmissions', 'assign'),
722                               'error'=>false);
724             if (!empty($data->reset_gradebook_grades)) {
725                 $DB->delete_records_select('assign_grades', "assignment IN ($assignssql)", $params);
726                 // Remove all grades from gradebook.
727                 require_once($CFG->dirroot.'/mod/assign/lib.php');
728                 assign_reset_gradebook($data->courseid);
729             }
730         }
731         // Updating dates - shift may be negative too.
732         if ($data->timeshift) {
733             shift_course_mod_dates('assign',
734                                     array('duedate', 'allowsubmissionsfromdate', 'cutoffdate'),
735                                     $data->timeshift,
736                                     $data->courseid);
737             $status[] = array('component'=>$componentstr,
738                               'item'=>get_string('datechanged'),
739                               'error'=>false);
740         }
742         return $status;
743     }
745     /**
746      * Update the settings for a single plugin.
747      *
748      * @param assign_plugin $plugin The plugin to update
749      * @param stdClass $formdata The form data
750      * @return bool false if an error occurs
751      */
752     protected function update_plugin_instance(assign_plugin $plugin, stdClass $formdata) {
753         if ($plugin->is_visible()) {
754             $enabledname = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
755             if (!empty($formdata->$enabledname)) {
756                 $plugin->enable();
757                 if (!$plugin->save_settings($formdata)) {
758                     print_error($plugin->get_error());
759                     return false;
760                 }
761             } else {
762                 $plugin->disable();
763             }
764         }
765         return true;
766     }
768     /**
769      * Update the gradebook information for this assignment.
770      *
771      * @param bool $reset If true, will reset all grades in the gradbook for this assignment
772      * @param int $coursemoduleid This is required because it might not exist in the database yet
773      * @return bool
774      */
775     public function update_gradebook($reset, $coursemoduleid) {
776         global $CFG;
778         require_once($CFG->dirroot.'/mod/assign/lib.php');
779         $assign = clone $this->get_instance();
780         $assign->cmidnumber = $coursemoduleid;
781         $param = null;
782         if ($reset) {
783             $param = 'reset';
784         }
786         return assign_grade_item_update($assign, $param);
787     }
789     /**
790      * Load and cache the admin config for this module.
791      *
792      * @return stdClass the plugin config
793      */
794     public function get_admin_config() {
795         if ($this->adminconfig) {
796             return $this->adminconfig;
797         }
798         $this->adminconfig = get_config('assign');
799         return $this->adminconfig;
800     }
802     /**
803      * Update the calendar entries for this assignment.
804      *
805      * @param int $coursemoduleid - Required to pass this in because it might
806      *                              not exist in the database yet.
807      * @return bool
808      */
809     public function update_calendar($coursemoduleid) {
810         global $DB, $CFG;
811         require_once($CFG->dirroot.'/calendar/lib.php');
813         // Special case for add_instance as the coursemodule has not been set yet.
814         $instance = $this->get_instance();
816         if ($instance->duedate) {
817             $event = new stdClass();
819             $params = array('modulename'=>'assign', 'instance'=>$instance->id);
820             $event->id = $DB->get_field('event',
821                                         'id',
822                                         $params);
824             if ($event->id) {
825                 $event->name        = $instance->name;
826                 $event->description = format_module_intro('assign', $instance, $coursemoduleid);
827                 $event->timestart   = $instance->duedate;
829                 $calendarevent = calendar_event::load($event->id);
830                 $calendarevent->update($event);
831             } else {
832                 $event = new stdClass();
833                 $event->name        = $instance->name;
834                 $event->description = format_module_intro('assign', $instance, $coursemoduleid);
835                 $event->courseid    = $instance->course;
836                 $event->groupid     = 0;
837                 $event->userid      = 0;
838                 $event->modulename  = 'assign';
839                 $event->instance    = $instance->id;
840                 $event->eventtype   = 'due';
841                 $event->timestart   = $instance->duedate;
842                 $event->timeduration = 0;
844                 calendar_event::create($event);
845             }
846         } else {
847             $DB->delete_records('event', array('modulename'=>'assign', 'instance'=>$instance->id));
848         }
849     }
852     /**
853      * Update this instance in the database.
854      *
855      * @param stdClass $formdata - the data submitted from the form
856      * @return bool false if an error occurs
857      */
858     public function update_instance($formdata) {
859         global $DB;
861         $update = new stdClass();
862         $update->id = $formdata->instance;
863         $update->name = $formdata->name;
864         $update->timemodified = time();
865         $update->course = $formdata->course;
866         $update->intro = $formdata->intro;
867         $update->introformat = $formdata->introformat;
868         $update->alwaysshowdescription = !empty($formdata->alwaysshowdescription);
869         $update->submissiondrafts = $formdata->submissiondrafts;
870         $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
871         $update->sendnotifications = $formdata->sendnotifications;
872         $update->sendlatenotifications = $formdata->sendlatenotifications;
873         $update->duedate = $formdata->duedate;
874         $update->cutoffdate = $formdata->cutoffdate;
875         $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
876         $update->grade = $formdata->grade;
877         if (!empty($formdata->completionunlocked)) {
878             $update->completionsubmit = !empty($formdata->completionsubmit);
879         }
880         $update->teamsubmission = $formdata->teamsubmission;
881         $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
882         $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
883         $update->blindmarking = $formdata->blindmarking;
884         $update->attemptreopenmethod = ASSIGN_ATTEMPT_REOPEN_METHOD_NONE;
885         if (!empty($formdata->attemptreopenmethod)) {
886             $update->attemptreopenmethod = $formdata->attemptreopenmethod;
887         }
888         if (!empty($formdata->maxattempts)) {
889             $update->maxattempts = $formdata->maxattempts;
890         }
891         $update->markingworkflow = $formdata->markingworkflow;
892         $update->markingallocation = $formdata->markingallocation;
894         $result = $DB->update_record('assign', $update);
895         $this->instance = $DB->get_record('assign', array('id'=>$update->id), '*', MUST_EXIST);
897         // Load the assignment so the plugins have access to it.
899         // Call save_settings hook for submission plugins.
900         foreach ($this->submissionplugins as $plugin) {
901             if (!$this->update_plugin_instance($plugin, $formdata)) {
902                 print_error($plugin->get_error());
903                 return false;
904             }
905         }
906         foreach ($this->feedbackplugins as $plugin) {
907             if (!$this->update_plugin_instance($plugin, $formdata)) {
908                 print_error($plugin->get_error());
909                 return false;
910             }
911         }
913         $this->update_calendar($this->get_course_module()->id);
914         $this->update_gradebook(false, $this->get_course_module()->id);
916         $update = new stdClass();
917         $update->id = $this->get_instance()->id;
918         $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
919         $DB->update_record('assign', $update);
921         return $result;
922     }
924     /**
925      * Add elements in grading plugin form.
926      *
927      * @param mixed $grade stdClass|null
928      * @param MoodleQuickForm $mform
929      * @param stdClass $data
930      * @param int $userid - The userid we are grading
931      * @return void
932      */
933     protected function add_plugin_grade_elements($grade, MoodleQuickForm $mform, stdClass $data, $userid) {
934         foreach ($this->feedbackplugins as $plugin) {
935             if ($plugin->is_enabled() && $plugin->is_visible()) {
936                 $mform->addElement('header', 'header_' . $plugin->get_type(), $plugin->get_name());
937                 $mform->setExpanded('header_' . $plugin->get_type());
938                 if (!$plugin->get_form_elements_for_user($grade, $mform, $data, $userid)) {
939                     $mform->removeElement('header_' . $plugin->get_type());
940                 }
941             }
942         }
943     }
947     /**
948      * Add one plugins settings to edit plugin form.
949      *
950      * @param assign_plugin $plugin The plugin to add the settings from
951      * @param MoodleQuickForm $mform The form to add the configuration settings to.
952      *                               This form is modified directly (not returned).
953      * @param array $pluginsenabled A list of form elements to be added to a group.
954      *                              The new element is added to this array by this function.
955      * @return void
956      */
957     protected function add_plugin_settings(assign_plugin $plugin, MoodleQuickForm $mform, & $pluginsenabled) {
958         global $CFG;
959         if ($plugin->is_visible()) {
961             $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
962             $label = $plugin->get_name();
963             $label .= ' ' . $this->get_renderer()->help_icon('enabled', $plugin->get_subtype() . '_' . $plugin->get_type());
964             $pluginsenabled[] = $mform->createElement('checkbox', $name, '', $label);
966             $default = get_config($plugin->get_subtype() . '_' . $plugin->get_type(), 'default');
967             if ($plugin->get_config('enabled') !== false) {
968                 $default = $plugin->is_enabled();
969             }
970             $mform->setDefault($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $default);
972             $plugin->get_settings($mform);
974         }
975     }
977     /**
978      * Add settings to edit plugin form.
979      *
980      * @param MoodleQuickForm $mform The form to add the configuration settings to.
981      *                               This form is modified directly (not returned).
982      * @return void
983      */
984     public function add_all_plugin_settings(MoodleQuickForm $mform) {
985         $mform->addElement('header', 'submissiontypes', get_string('submissiontypes', 'assign'));
987         $submissionpluginsenabled = array();
988         $group = $mform->addGroup(array(), 'submissionplugins', get_string('submissiontypes', 'assign'), array(' '), false);
989         foreach ($this->submissionplugins as $plugin) {
990             $this->add_plugin_settings($plugin, $mform, $submissionpluginsenabled);
991         }
992         $group->setElements($submissionpluginsenabled);
994         $mform->addElement('header', 'feedbacktypes', get_string('feedbacktypes', 'assign'));
995         $feedbackpluginsenabled = array();
996         $group = $mform->addGroup(array(), 'feedbackplugins', get_string('feedbacktypes', 'assign'), array(' '), false);
997         foreach ($this->feedbackplugins as $plugin) {
998             $this->add_plugin_settings($plugin, $mform, $feedbackpluginsenabled);
999         }
1000         $group->setElements($feedbackpluginsenabled);
1001         $mform->setExpanded('submissiontypes');
1002     }
1004     /**
1005      * Allow each plugin an opportunity to update the defaultvalues
1006      * passed in to the settings form (needed to set up draft areas for
1007      * editor and filemanager elements)
1008      *
1009      * @param array $defaultvalues
1010      */
1011     public function plugin_data_preprocessing(&$defaultvalues) {
1012         foreach ($this->submissionplugins as $plugin) {
1013             if ($plugin->is_visible()) {
1014                 $plugin->data_preprocessing($defaultvalues);
1015             }
1016         }
1017         foreach ($this->feedbackplugins as $plugin) {
1018             if ($plugin->is_visible()) {
1019                 $plugin->data_preprocessing($defaultvalues);
1020             }
1021         }
1022     }
1024     /**
1025      * Get the name of the current module.
1026      *
1027      * @return string the module name (Assignment)
1028      */
1029     protected function get_module_name() {
1030         if (isset(self::$modulename)) {
1031             return self::$modulename;
1032         }
1033         self::$modulename = get_string('modulename', 'assign');
1034         return self::$modulename;
1035     }
1037     /**
1038      * Get the plural name of the current module.
1039      *
1040      * @return string the module name plural (Assignments)
1041      */
1042     protected function get_module_name_plural() {
1043         if (isset(self::$modulenameplural)) {
1044             return self::$modulenameplural;
1045         }
1046         self::$modulenameplural = get_string('modulenameplural', 'assign');
1047         return self::$modulenameplural;
1048     }
1050     /**
1051      * Has this assignment been constructed from an instance?
1052      *
1053      * @return bool
1054      */
1055     public function has_instance() {
1056         return $this->instance || $this->get_course_module();
1057     }
1059     /**
1060      * Get the settings for the current instance of this assignment
1061      *
1062      * @return stdClass The settings
1063      */
1064     public function get_instance() {
1065         global $DB;
1066         if ($this->instance) {
1067             return $this->instance;
1068         }
1069         if ($this->get_course_module()) {
1070             $params = array('id' => $this->get_course_module()->instance);
1071             $this->instance = $DB->get_record('assign', $params, '*', MUST_EXIST);
1072         }
1073         if (!$this->instance) {
1074             throw new coding_exception('Improper use of the assignment class. ' .
1075                                        'Cannot load the assignment record.');
1076         }
1077         return $this->instance;
1078     }
1080     /**
1081      * Get the context of the current course.
1082      *
1083      * @return mixed context|null The course context
1084      */
1085     public function get_course_context() {
1086         if (!$this->context && !$this->course) {
1087             throw new coding_exception('Improper use of the assignment class. ' .
1088                                        'Cannot load the course context.');
1089         }
1090         if ($this->context) {
1091             return $this->context->get_course_context();
1092         } else {
1093             return context_course::instance($this->course->id);
1094         }
1095     }
1098     /**
1099      * Get the current course module.
1100      *
1101      * @return mixed stdClass|null The course module
1102      */
1103     public function get_course_module() {
1104         if ($this->coursemodule) {
1105             return $this->coursemodule;
1106         }
1107         if (!$this->context) {
1108             return null;
1109         }
1111         if ($this->context->contextlevel == CONTEXT_MODULE) {
1112             $this->coursemodule = get_coursemodule_from_id('assign',
1113                                                            $this->context->instanceid,
1114                                                            0,
1115                                                            false,
1116                                                            MUST_EXIST);
1117             return $this->coursemodule;
1118         }
1119         return null;
1120     }
1122     /**
1123      * Get context module.
1124      *
1125      * @return context
1126      */
1127     public function get_context() {
1128         return $this->context;
1129     }
1131     /**
1132      * Get the current course.
1133      *
1134      * @return mixed stdClass|null The course
1135      */
1136     public function get_course() {
1137         global $DB;
1139         if ($this->course) {
1140             return $this->course;
1141         }
1143         if (!$this->context) {
1144             return null;
1145         }
1146         $params = array('id' => $this->get_course_context()->instanceid);
1147         $this->course = $DB->get_record('course', $params, '*', MUST_EXIST);
1149         return $this->course;
1150     }
1152     /**
1153      * Return a grade in user-friendly form, whether it's a scale or not.
1154      *
1155      * @param mixed $grade int|null
1156      * @param boolean $editing Are we allowing changes to this grade?
1157      * @param int $userid The user id the grade belongs to
1158      * @param int $modified Timestamp from when the grade was last modified
1159      * @return string User-friendly representation of grade
1160      */
1161     public function display_grade($grade, $editing, $userid=0, $modified=0) {
1162         global $DB;
1164         static $scalegrades = array();
1166         $o = '';
1168         if ($this->get_instance()->grade >= 0) {
1169             // Normal number.
1170             if ($editing && $this->get_instance()->grade > 0) {
1171                 if ($grade < 0) {
1172                     $displaygrade = '';
1173                 } else {
1174                     $displaygrade = format_float($grade);
1175                 }
1176                 $o .= '<label class="accesshide" for="quickgrade_' . $userid . '">' .
1177                        get_string('usergrade', 'assign') .
1178                        '</label>';
1179                 $o .= '<input type="text"
1180                               id="quickgrade_' . $userid . '"
1181                               name="quickgrade_' . $userid . '"
1182                               value="' .  $displaygrade . '"
1183                               size="6"
1184                               maxlength="10"
1185                               class="quickgrade"/>';
1186                 $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade, 2);
1187                 $o .= '<input type="hidden"
1188                               name="grademodified_' . $userid . '"
1189                               value="' . $modified . '"/>';
1190                 return $o;
1191             } else {
1192                 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
1193                 if ($grade == -1 || $grade === null) {
1194                     $o .= '-';
1195                     return $o;
1196                 } else {
1197                     $o .= format_float($grade, 2) .
1198                           '&nbsp;/&nbsp;' .
1199                           format_float($this->get_instance()->grade, 2);
1200                     return $o;
1201                 }
1202             }
1204         } else {
1205             // Scale.
1206             if (empty($this->cache['scale'])) {
1207                 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
1208                     $this->cache['scale'] = make_menu_from_list($scale->scale);
1209                 } else {
1210                     $o .= '-';
1211                     return $o;
1212                 }
1213             }
1214             if ($editing) {
1215                 $o .= '<label class="accesshide"
1216                               for="quickgrade_' . $userid . '">' .
1217                       get_string('usergrade', 'assign') .
1218                       '</label>';
1219                 $o .= '<select name="quickgrade_' . $userid . '" class="quickgrade">';
1220                 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
1221                 foreach ($this->cache['scale'] as $optionid => $option) {
1222                     $selected = '';
1223                     if ($grade == $optionid) {
1224                         $selected = 'selected="selected"';
1225                     }
1226                     $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
1227                 }
1228                 $o .= '</select>';
1229                 $o .= '<input type="hidden" ' .
1230                              'name="grademodified_' . $userid . '" ' .
1231                              'value="' . $modified . '"/>';
1232                 return $o;
1233             } else {
1234                 $scaleid = (int)$grade;
1235                 if (isset($this->cache['scale'][$scaleid])) {
1236                     $o .= $this->cache['scale'][$scaleid];
1237                     return $o;
1238                 }
1239                 $o .= '-';
1240                 return $o;
1241             }
1242         }
1243     }
1245     /**
1246      * Load a list of users enrolled in the current course with the specified permission and group.
1247      * 0 for no group.
1248      *
1249      * @param int $currentgroup
1250      * @param bool $idsonly
1251      * @return array List of user records
1252      */
1253     public function list_participants($currentgroup, $idsonly) {
1254         if ($idsonly) {
1255             return get_enrolled_users($this->context, 'mod/assign:submit', $currentgroup, 'u.id');
1256         } else {
1257             return get_enrolled_users($this->context, 'mod/assign:submit', $currentgroup);
1258         }
1259     }
1261     /**
1262      * Load a count of valid teams for this assignment.
1263      *
1264      * @return int number of valid teams
1265      */
1266     public function count_teams() {
1268         $groups = groups_get_all_groups($this->get_course()->id,
1269                                         0,
1270                                         $this->get_instance()->teamsubmissiongroupingid,
1271                                         'g.id');
1272         $count = count($groups);
1274         // See if there are any users in the default group.
1275         $defaultusers = $this->get_submission_group_members(0, true);
1276         if (count($defaultusers) > 0) {
1277             $count += 1;
1278         }
1279         return $count;
1280     }
1282     /**
1283      * Load a count of users enrolled in the current course with the specified permission and group.
1284      * 0 for no group.
1285      *
1286      * @param int $currentgroup
1287      * @return int number of matching users
1288      */
1289     public function count_participants($currentgroup) {
1290         return count_enrolled_users($this->context, 'mod/assign:submit', $currentgroup);
1291     }
1293     /**
1294      * Load a count of users submissions in the current module that require grading
1295      * This means the submission modification time is more recent than the
1296      * grading modification time and the status is SUBMITTED.
1297      *
1298      * @return int number of matching submissions
1299      */
1300     public function count_submissions_need_grading() {
1301         global $DB;
1303         if ($this->get_instance()->teamsubmission) {
1304             // This does not make sense for group assignment because the submission is shared.
1305             return 0;
1306         }
1308         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1309         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1311         $submissionmaxattempt = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt
1312                                  FROM {assign_submission} mxs
1313                                  WHERE mxs.assignment = :assignid2 GROUP BY mxs.userid';
1314         $grademaxattempt = 'SELECT mxg.userid, MAX(mxg.attemptnumber) AS maxattempt
1315                             FROM {assign_grades} mxg
1316                             WHERE mxg.assignment = :assignid3 GROUP BY mxg.userid';
1318         $params['assignid'] = $this->get_instance()->id;
1319         $params['assignid2'] = $this->get_instance()->id;
1320         $params['assignid3'] = $this->get_instance()->id;
1321         $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1323         $sql = 'SELECT COUNT(s.userid)
1324                    FROM {assign_submission} s
1325                    LEFT JOIN ( ' . $submissionmaxattempt . ' ) smx ON s.userid = smx.userid
1326                    LEFT JOIN ( ' . $grademaxattempt . ' ) gmx ON s.userid = gmx.userid
1327                    LEFT JOIN {assign_grades} g ON
1328                         s.assignment = g.assignment AND
1329                         s.userid = g.userid AND
1330                         g.attemptnumber = gmx.maxattempt
1331                    JOIN(' . $esql . ') e ON e.id = s.userid
1332                    WHERE
1333                         s.attemptnumber = smx.maxattempt AND
1334                         s.assignment = :assignid AND
1335                         s.timemodified IS NOT NULL AND
1336                         s.status = :submitted AND
1337                         (s.timemodified > g.timemodified OR g.timemodified IS NULL)';
1339         return $DB->count_records_sql($sql, $params);
1340     }
1342     /**
1343      * Load a count of grades.
1344      *
1345      * @return int number of grades
1346      */
1347     public function count_grades() {
1348         global $DB;
1350         if (!$this->has_instance()) {
1351             return 0;
1352         }
1354         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1355         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1357         $params['assignid'] = $this->get_instance()->id;
1359         $sql = 'SELECT COUNT(g.userid)
1360                    FROM {assign_grades} g
1361                    JOIN(' . $esql . ') e ON e.id = g.userid
1362                    WHERE g.assignment = :assignid';
1364         return $DB->count_records_sql($sql, $params);
1365     }
1367     /**
1368      * Load a count of submissions.
1369      *
1370      * @return int number of submissions
1371      */
1372     public function count_submissions() {
1373         global $DB;
1375         if (!$this->has_instance()) {
1376             return 0;
1377         }
1379         $params = array();
1381         if ($this->get_instance()->teamsubmission) {
1382             // We cannot join on the enrolment tables for group submissions (no userid).
1383             $sql = 'SELECT COUNT(DISTINCT s.groupid)
1384                         FROM {assign_submission} s
1385                         WHERE
1386                             s.assignment = :assignid AND
1387                             s.timemodified IS NOT NULL AND
1388                             s.userid = :groupuserid';
1390             $params['assignid'] = $this->get_instance()->id;
1391             $params['groupuserid'] = 0;
1392         } else {
1393             $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1394             list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1396             $params['assignid'] = $this->get_instance()->id;
1398             $sql = 'SELECT COUNT(DISTINCT s.userid)
1399                        FROM {assign_submission} s
1400                        JOIN(' . $esql . ') e ON e.id = s.userid
1401                        WHERE
1402                             s.assignment = :assignid AND
1403                             s.timemodified IS NOT NULL';
1404         }
1406         return $DB->count_records_sql($sql, $params);
1407     }
1409     /**
1410      * Load a count of submissions with a specified status.
1411      *
1412      * @param string $status The submission status - should match one of the constants
1413      * @return int number of matching submissions
1414      */
1415     public function count_submissions_with_status($status) {
1416         global $DB;
1418         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1419         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1421         $params['assignid'] = $this->get_instance()->id;
1422         $params['assignid2'] = $this->get_instance()->id;
1423         $params['submissionstatus'] = $status;
1425         if ($this->get_instance()->teamsubmission) {
1426             $maxattemptsql = 'SELECT mxs.groupid, MAX(mxs.attemptnumber) AS maxattempt
1427                               FROM {assign_submission} mxs
1428                               WHERE mxs.assignment = :assignid2 GROUP BY mxs.groupid';
1430             $sql = 'SELECT COUNT(s.groupid)
1431                         FROM {assign_submission} s
1432                         JOIN(' . $maxattemptsql . ') smx ON s.groupid = smx.groupid
1433                         WHERE
1434                             s.attemptnumber = smx.maxattempt AND
1435                             s.assignment = :assignid AND
1436                             s.timemodified IS NOT NULL AND
1437                             s.userid = :groupuserid AND
1438                             s.status = :submissionstatus';
1439             $params['groupuserid'] = 0;
1440         } else {
1441             $maxattemptsql = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt
1442                               FROM {assign_submission} mxs
1443                               WHERE mxs.assignment = :assignid2 GROUP BY mxs.userid';
1445             $sql = 'SELECT COUNT(s.userid)
1446                         FROM {assign_submission} s
1447                         JOIN(' . $esql . ') e ON e.id = s.userid
1448                         JOIN(' . $maxattemptsql . ') smx ON s.userid = smx.userid
1449                         WHERE
1450                             s.attemptnumber = smx.maxattempt AND
1451                             s.assignment = :assignid AND
1452                             s.timemodified IS NOT NULL AND
1453                             s.status = :submissionstatus';
1454         }
1456         return $DB->count_records_sql($sql, $params);
1457     }
1459     /**
1460      * Utility function to get the userid for every row in the grading table
1461      * so the order can be frozen while we iterate it.
1462      *
1463      * @return array An array of userids
1464      */
1465     protected function get_grading_userid_list() {
1466         $filter = get_user_preferences('assign_filter', '');
1467         $table = new assign_grading_table($this, 0, $filter, 0, false);
1469         $useridlist = $table->get_column_data('userid');
1471         return $useridlist;
1472     }
1474     /**
1475      * Generate zip file from array of given files.
1476      *
1477      * @param array $filesforzipping - array of files to pass into archive_to_pathname.
1478      *                                 This array is indexed by the final file name and each
1479      *                                 element in the array is an instance of a stored_file object.
1480      * @return path of temp file - note this returned file does
1481      *         not have a .zip extension - it is a temp file.
1482      */
1483     protected function pack_files($filesforzipping) {
1484         global $CFG;
1485         // Create path for new zip file.
1486         $tempzip = tempnam($CFG->tempdir . '/', 'assignment_');
1487         // Zip files.
1488         $zipper = new zip_packer();
1489         if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
1490             return $tempzip;
1491         }
1492         return false;
1493     }
1495     /**
1496      * Finds all assignment notifications that have yet to be mailed out, and mails them.
1497      *
1498      * Cron function to be run periodically according to the moodle cron.
1499      *
1500      * @return bool
1501      */
1502     public static function cron() {
1503         global $DB;
1505         // Only ever send a max of one days worth of updates.
1506         $yesterday = time() - (24 * 3600);
1507         $timenow   = time();
1509         // Collect all submissions from the past 24 hours that require mailing.
1510         $sql = 'SELECT a.course, a.name, a.blindmarking, a.revealidentities,
1511                        g.*, g.id as gradeid, g.timemodified as lastmodified
1512                  FROM {assign} a
1513                  JOIN {assign_grades} g ON g.assignment = a.id
1514                  LEFT JOIN {assign_user_flags} uf ON uf.assignment = a.id AND uf.userid = g.userid
1515                 WHERE g.timemodified >= :yesterday AND
1516                       g.timemodified <= :today AND
1517                       uf.mailed = 0';
1519         $params = array('yesterday' => $yesterday, 'today' => $timenow);
1520         $submissions = $DB->get_records_sql($sql, $params);
1522         if (empty($submissions)) {
1523             return true;
1524         }
1526         mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
1528         // Preload courses we are going to need those.
1529         $courseids = array();
1530         foreach ($submissions as $submission) {
1531             $courseids[] = $submission->course;
1532         }
1534         // Filter out duplicates.
1535         $courseids = array_unique($courseids);
1536         $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1537         list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
1538         $sql = 'SELECT c.*, ' . $ctxselect .
1539                   ' FROM {course} c
1540              LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
1541                  WHERE c.id ' . $courseidsql;
1543         $params['contextlevel'] = CONTEXT_COURSE;
1544         $courses = $DB->get_records_sql($sql, $params);
1546         // Clean up... this could go on for a while.
1547         unset($courseids);
1548         unset($ctxselect);
1549         unset($courseidsql);
1550         unset($params);
1552         // Simple array we'll use for caching modules.
1553         $modcache = array();
1555         // Message students about new feedback.
1556         foreach ($submissions as $submission) {
1558             mtrace("Processing assignment submission $submission->id ...");
1560             // Do not cache user lookups - could be too many.
1561             if (!$user = $DB->get_record('user', array('id'=>$submission->userid))) {
1562                 mtrace('Could not find user ' . $submission->userid);
1563                 continue;
1564             }
1566             // Use a cache to prevent the same DB queries happening over and over.
1567             if (!array_key_exists($submission->course, $courses)) {
1568                 mtrace('Could not find course ' . $submission->course);
1569                 continue;
1570             }
1571             $course = $courses[$submission->course];
1572             if (isset($course->ctxid)) {
1573                 // Context has not yet been preloaded. Do so now.
1574                 context_helper::preload_from_record($course);
1575             }
1577             // Override the language and timezone of the "current" user, so that
1578             // mail is customised for the receiver.
1579             cron_setup_user($user, $course);
1581             // Context lookups are already cached.
1582             $coursecontext = context_course::instance($course->id);
1583             if (!is_enrolled($coursecontext, $user->id)) {
1584                 $courseshortname = format_string($course->shortname,
1585                                                  true,
1586                                                  array('context' => $coursecontext));
1587                 mtrace(fullname($user) . ' not an active participant in ' . $courseshortname);
1588                 continue;
1589             }
1591             if (!$grader = $DB->get_record('user', array('id'=>$submission->grader))) {
1592                 mtrace('Could not find grader ' . $submission->grader);
1593                 continue;
1594             }
1596             if (!array_key_exists($submission->assignment, $modcache)) {
1597                 $mod = get_coursemodule_from_instance('assign', $submission->assignment, $course->id);
1598                 if (empty($mod)) {
1599                     mtrace('Could not find course module for assignment id ' . $submission->assignment);
1600                     continue;
1601                 }
1602                 $modcache[$submission->assignment] = $mod;
1603             } else {
1604                 $mod = $modcache[$submission->assignment];
1605             }
1606             // Context lookups are already cached.
1607             $contextmodule = context_module::instance($mod->id);
1609             if (!$mod->visible) {
1610                 // Hold mail notification for hidden assignments until later.
1611                 continue;
1612             }
1614             // Need to send this to the student.
1615             $messagetype = 'feedbackavailable';
1616             $eventtype = 'assign_notification';
1617             $updatetime = $submission->lastmodified;
1618             $modulename = get_string('modulename', 'assign');
1620             $uniqueid = 0;
1621             if ($submission->blindmarking && !$submission->revealidentities) {
1622                 $uniqueid = self::get_uniqueid_for_user_static($submission->assignment, $user->id);
1623             }
1624             $showusers = $submission->blindmarking && !$submission->revealidentities;
1625             self::send_assignment_notification($grader,
1626                                                $user,
1627                                                $messagetype,
1628                                                $eventtype,
1629                                                $updatetime,
1630                                                $mod,
1631                                                $contextmodule,
1632                                                $course,
1633                                                $modulename,
1634                                                $submission->name,
1635                                                $showusers,
1636                                                $uniqueid);
1638             $flags = $DB->get_record('assign_user_flags', array('userid'=>$user->id, 'assignment'=>$submission->assignment));
1639             if ($flags) {
1640                 $flags->mailed = 1;
1641                 $DB->update_record('assign_user_flags', $flags);
1642             } else {
1643                 $flags = new stdClass();
1644                 $flags->userid = $user->id;
1645                 $flags->assignment = $submission->assignment;
1646                 $flags->mailed = 1;
1647                 $DB->insert_record('assign_user_flags', $flags);
1648             }
1650             mtrace('Done');
1651         }
1652         mtrace('Done processing ' . count($submissions) . ' assignment submissions');
1654         cron_setup_user();
1656         // Free up memory just to be sure.
1657         unset($courses);
1658         unset($modcache);
1660         return true;
1661     }
1663     /**
1664      * Mark in the database that this grade record should have an update notification sent by cron.
1665      *
1666      * @param stdClass $grade a grade record keyed on id
1667      * @return bool true for success
1668      */
1669     public function notify_grade_modified($grade) {
1670         global $DB;
1672         $flags = $this->get_user_flags($grade->userid, true);
1673         if ($flags->mailed != 1) {
1674             $flags->mailed = 0;
1675         }
1677         return $this->update_user_flags($flags);
1678     }
1680     /**
1681      * Update user flags for this user in this assignment.
1682      *
1683      * @param stdClass $flags a flags record keyed on id
1684      * @return bool true for success
1685      */
1686     public function update_user_flags($flags) {
1687         global $DB;
1688         if ($flags->userid <= 0 || $flags->assignment <= 0 || $flags->id <= 0) {
1689             return false;
1690         }
1692         $result = $DB->update_record('assign_user_flags', $flags);
1693         return $result;
1694     }
1696     /**
1697      * Update a grade in the grade table for the assignment and in the gradebook.
1698      *
1699      * @param stdClass $grade a grade record keyed on id
1700      * @return bool true for success
1701      */
1702     public function update_grade($grade) {
1703         global $DB;
1705         $grade->timemodified = time();
1707         if (!empty($grade->workflowstate)) {
1708             $validstates = $this->get_marking_workflow_states_for_current_user();
1709             if (!array_key_exists($grade->workflowstate, $validstates)) {
1710                 return false;
1711             }
1712         }
1714         if ($grade->grade && $grade->grade != -1) {
1715             if ($this->get_instance()->grade > 0) {
1716                 if (!is_numeric($grade->grade)) {
1717                     return false;
1718                 } else if ($grade->grade > $this->get_instance()->grade) {
1719                     return false;
1720                 } else if ($grade->grade < 0) {
1721                     return false;
1722                 }
1723             } else {
1724                 // This is a scale.
1725                 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
1726                     $scaleoptions = make_menu_from_list($scale->scale);
1727                     if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
1728                         return false;
1729                     }
1730                 }
1731             }
1732         }
1734         if (empty($grade->attemptnumber)) {
1735             // Set it to the default.
1736             $grade->attemptnumber = 0;
1737         }
1738         $result = $DB->update_record('assign_grades', $grade);
1740         // Only push to gradebook if the update is for the latest attempt.
1741         $submission = null;
1742         if ($this->get_instance()->teamsubmission) {
1743             $submission = $this->get_group_submission($grade->userid, 0, false);
1744         } else {
1745             $submission = $this->get_user_submission($grade->userid, false);
1746         }
1747         // Not the latest attempt.
1748         if ($submission && $submission->attemptnumber != $grade->attemptnumber) {
1749             return true;
1750         }
1752         if ($result) {
1753             $this->gradebook_item_update(null, $grade);
1754         }
1755         return $result;
1756     }
1758     /**
1759      * View the grant extension date page.
1760      *
1761      * Uses url parameters 'userid'
1762      * or from parameter 'selectedusers'
1763      *
1764      * @param moodleform $mform - Used for validation of the submitted data
1765      * @return string
1766      */
1767     protected function view_grant_extension($mform) {
1768         global $DB, $CFG;
1769         require_once($CFG->dirroot . '/mod/assign/extensionform.php');
1771         $o = '';
1772         $batchusers = optional_param('selectedusers', '', PARAM_SEQUENCE);
1773         $data = new stdClass();
1774         $data->extensionduedate = null;
1775         $userid = 0;
1776         if (!$batchusers) {
1777             $userid = required_param('userid', PARAM_INT);
1779             $grade = $this->get_user_grade($userid, false);
1781             $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
1783             if ($grade) {
1784                 $data->extensionduedate = $grade->extensionduedate;
1785             }
1786             $data->userid = $userid;
1787         } else {
1788             $data->batchusers = $batchusers;
1789         }
1790         $header = new assign_header($this->get_instance(),
1791                                     $this->get_context(),
1792                                     $this->show_intro(),
1793                                     $this->get_course_module()->id,
1794                                     get_string('grantextension', 'assign'));
1795         $o .= $this->get_renderer()->render($header);
1797         if (!$mform) {
1798             $formparams = array($this->get_course_module()->id,
1799                                 $userid,
1800                                 $batchusers,
1801                                 $this->get_instance(),
1802                                 $data);
1803             $mform = new mod_assign_extension_form(null, $formparams);
1804         }
1805         $o .= $this->get_renderer()->render(new assign_form('extensionform', $mform));
1806         $o .= $this->view_footer();
1807         return $o;
1808     }
1810     /**
1811      * Get a list of the users in the same group as this user.
1812      *
1813      * @param int $groupid The id of the group whose members we want or 0 for the default group
1814      * @param bool $onlyids Whether to retrieve only the user id's
1815      * @return array The users (possibly id's only)
1816      */
1817     public function get_submission_group_members($groupid, $onlyids) {
1818         $members = array();
1819         if ($groupid != 0) {
1820             if ($onlyids) {
1821                 $allusers = groups_get_members($groupid, 'u.id');
1822             } else {
1823                 $allusers = groups_get_members($groupid);
1824             }
1825             foreach ($allusers as $user) {
1826                 if ($this->get_submission_group($user->id)) {
1827                     $members[] = $user;
1828                 }
1829             }
1830         } else {
1831             $allusers = $this->list_participants(null, $onlyids);
1832             foreach ($allusers as $user) {
1833                 if ($this->get_submission_group($user->id) == null) {
1834                     $members[] = $user;
1835                 }
1836             }
1837         }
1838         return $members;
1839     }
1841     /**
1842      * Get a list of the users in the same group as this user that have not submitted the assignment.
1843      *
1844      * @param int $groupid The id of the group whose members we want or 0 for the default group
1845      * @param bool $onlyids Whether to retrieve only the user id's
1846      * @return array The users (possibly id's only)
1847      */
1848     public function get_submission_group_members_who_have_not_submitted($groupid, $onlyids) {
1849         $instance = $this->get_instance();
1850         if (!$instance->teamsubmission || !$instance->requireallteammemberssubmit) {
1851             return array();
1852         }
1853         $members = $this->get_submission_group_members($groupid, $onlyids);
1855         foreach ($members as $id => $member) {
1856             $submission = $this->get_user_submission($member->id, false);
1857             if ($submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
1858                 unset($members[$id]);
1859             } else {
1860                 if ($this->is_blind_marking()) {
1861                     $members[$id]->alias = get_string('hiddenuser', 'assign') .
1862                                            $this->get_uniqueid_for_user($id);
1863                 }
1864             }
1865         }
1866         return $members;
1867     }
1869     /**
1870      * Load the group submission object for a particular user, optionally creating it if required.
1871      *
1872      * @param int $userid The id of the user whose submission we want
1873      * @param int $groupid The id of the group for this user - may be 0 in which
1874      *                     case it is determined from the userid.
1875      * @param bool $create If set to true a new submission object will be created in the database
1876      * @param int $attemptnumber - -1 means the latest attempt
1877      * @return stdClass The submission
1878      */
1879     public function get_group_submission($userid, $groupid, $create, $attemptnumber=-1) {
1880         global $DB;
1882         if ($groupid == 0) {
1883             $group = $this->get_submission_group($userid);
1884             if ($group) {
1885                 $groupid = $group->id;
1886             }
1887         }
1889         // Now get the group submission.
1890         $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
1891         if ($attemptnumber >= 0) {
1892             $params['attemptnumber'] = $attemptnumber;
1893         }
1895         // Only return the row with the highest attemptnumber.
1896         $submission = null;
1897         $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
1898         if ($submissions) {
1899             $submission = reset($submissions);
1900         }
1902         if ($submission) {
1903             return $submission;
1904         }
1905         if ($create) {
1906             $submission = new stdClass();
1907             $submission->assignment = $this->get_instance()->id;
1908             $submission->userid = 0;
1909             $submission->groupid = $groupid;
1910             $submission->timecreated = time();
1911             $submission->timemodified = $submission->timecreated;
1912             if ($attemptnumber >= 0) {
1913                 $submission->attemptnumber = $attemptnumber;
1914             } else {
1915                 $submission->attemptnumber = 0;
1916             }
1918             $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
1919             $sid = $DB->insert_record('assign_submission', $submission);
1920             $submission->id = $sid;
1921             return $submission;
1922         }
1923         return false;
1924     }
1926     /**
1927      * View a summary listing of all assignments in the current course.
1928      *
1929      * @return string
1930      */
1931     private function view_course_index() {
1932         global $USER;
1934         $o = '';
1936         $course = $this->get_course();
1937         $strplural = get_string('modulenameplural', 'assign');
1939         if (!$cms = get_coursemodules_in_course('assign', $course->id, 'm.duedate')) {
1940             $o .= $this->get_renderer()->notification(get_string('thereareno', 'moodle', $strplural));
1941             $o .= $this->get_renderer()->continue_button(new moodle_url('/course/view.php', array('id' => $course->id)));
1942             return $o;
1943         }
1945         $strsectionname  = get_string('sectionname', 'format_'.$course->format);
1946         $usesections = course_format_uses_sections($course->format);
1947         $modinfo = get_fast_modinfo($course);
1949         if ($usesections) {
1950             $sections = $modinfo->get_section_info_all();
1951         }
1952         $courseindexsummary = new assign_course_index_summary($usesections, $strsectionname);
1954         $timenow = time();
1956         $currentsection = '';
1957         foreach ($modinfo->instances['assign'] as $cm) {
1958             if (!$cm->uservisible) {
1959                 continue;
1960             }
1962             $timedue = $cms[$cm->id]->duedate;
1964             $sectionname = '';
1965             if ($usesections && $cm->sectionnum) {
1966                 $sectionname = get_section_name($course, $sections[$cm->sectionnum]);
1967             }
1969             $submitted = '';
1970             $context = context_module::instance($cm->id);
1972             $assignment = new assign($context, $cm, $course);
1974             if (has_capability('mod/assign:grade', $context)) {
1975                 $submitted = $assignment->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED);
1977             } else if (has_capability('mod/assign:submit', $context)) {
1978                 $usersubmission = $assignment->get_user_submission($USER->id, false);
1980                 if (!empty($usersubmission->status)) {
1981                     $submitted = get_string('submissionstatus_' . $usersubmission->status, 'assign');
1982                 } else {
1983                     $submitted = get_string('submissionstatus_', 'assign');
1984                 }
1985             }
1986             $grading_info = grade_get_grades($course->id, 'mod', 'assign', $cm->instance, $USER->id);
1987             if (isset($grading_info->items[0]->grades[$USER->id]) &&
1988                     !$grading_info->items[0]->grades[$USER->id]->hidden ) {
1989                 $grade = $grading_info->items[0]->grades[$USER->id]->str_grade;
1990             } else {
1991                 $grade = '-';
1992             }
1994             $courseindexsummary->add_assign_info($cm->id, $cm->name, $sectionname, $timedue, $submitted, $grade);
1996         }
1998         $o .= $this->get_renderer()->render($courseindexsummary);
1999         $o .= $this->view_footer();
2001         return $o;
2002     }
2004     /**
2005      * View a page rendered by a plugin.
2006      *
2007      * Uses url parameters 'pluginaction', 'pluginsubtype', 'plugin', and 'id'.
2008      *
2009      * @return string
2010      */
2011     protected function view_plugin_page() {
2012         global $USER;
2014         $o = '';
2016         $pluginsubtype = required_param('pluginsubtype', PARAM_ALPHA);
2017         $plugintype = required_param('plugin', PARAM_TEXT);
2018         $pluginaction = required_param('pluginaction', PARAM_ALPHA);
2020         $plugin = $this->get_plugin_by_type($pluginsubtype, $plugintype);
2021         if (!$plugin) {
2022             print_error('invalidformdata', '');
2023             return;
2024         }
2026         $o .= $plugin->view_page($pluginaction);
2028         return $o;
2029     }
2032     /**
2033      * This is used for team assignments to get the group for the specified user.
2034      * If the user is a member of multiple or no groups this will return false
2035      *
2036      * @param int $userid The id of the user whose submission we want
2037      * @return mixed The group or false
2038      */
2039     public function get_submission_group($userid) {
2040         $grouping = $this->get_instance()->teamsubmissiongroupingid;
2041         $groups = groups_get_all_groups($this->get_course()->id, $userid, $grouping);
2042         if (count($groups) != 1) {
2043             return false;
2044         }
2045         return array_pop($groups);
2046     }
2049     /**
2050      * Display the submission that is used by a plugin.
2051      *
2052      * Uses url parameters 'sid', 'gid' and 'plugin'.
2053      *
2054      * @param string $pluginsubtype
2055      * @return string
2056      */
2057     protected function view_plugin_content($pluginsubtype) {
2058         global $USER;
2060         $o = '';
2062         $submissionid = optional_param('sid', 0, PARAM_INT);
2063         $gradeid = optional_param('gid', 0, PARAM_INT);
2064         $plugintype = required_param('plugin', PARAM_TEXT);
2065         $item = null;
2066         if ($pluginsubtype == 'assignsubmission') {
2067             $plugin = $this->get_submission_plugin_by_type($plugintype);
2068             if ($submissionid <= 0) {
2069                 throw new coding_exception('Submission id should not be 0');
2070             }
2071             $item = $this->get_submission($submissionid);
2073             // Check permissions.
2074             if ($item->userid != $USER->id) {
2075                 require_capability('mod/assign:grade', $this->context);
2076             }
2077             $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2078                                                               $this->get_context(),
2079                                                               $this->show_intro(),
2080                                                               $this->get_course_module()->id,
2081                                                               $plugin->get_name()));
2082             $o .= $this->get_renderer()->render(new assign_submission_plugin_submission($plugin,
2083                                                               $item,
2084                                                               assign_submission_plugin_submission::FULL,
2085                                                               $this->get_course_module()->id,
2086                                                               $this->get_return_action(),
2087                                                               $this->get_return_params()));
2089             $logmessage = get_string('viewsubmissionforuser', 'assign', $item->userid);
2090             $this->add_to_log('view submission', $logmessage);
2091         } else {
2092             $plugin = $this->get_feedback_plugin_by_type($plugintype);
2093             if ($gradeid <= 0) {
2094                 throw new coding_exception('Grade id should not be 0');
2095             }
2096             $item = $this->get_grade($gradeid);
2097             // Check permissions.
2098             if ($item->userid != $USER->id) {
2099                 require_capability('mod/assign:grade', $this->context);
2100             }
2101             $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2102                                                               $this->get_context(),
2103                                                               $this->show_intro(),
2104                                                               $this->get_course_module()->id,
2105                                                               $plugin->get_name()));
2106             $o .= $this->get_renderer()->render(new assign_feedback_plugin_feedback($plugin,
2107                                                               $item,
2108                                                               assign_feedback_plugin_feedback::FULL,
2109                                                               $this->get_course_module()->id,
2110                                                               $this->get_return_action(),
2111                                                               $this->get_return_params()));
2112             $logmessage = get_string('viewfeedbackforuser', 'assign', $item->userid);
2113             $this->add_to_log('view feedback', $logmessage);
2114         }
2116         $o .= $this->view_return_links();
2118         $o .= $this->view_footer();
2119         return $o;
2120     }
2122     /**
2123      * Rewrite plugin file urls so they resolve correctly in an exported zip.
2124      *
2125      * @param stdClass $user - The user record
2126      * @param assign_plugin $plugin - The assignment plugin
2127      */
2128     public function download_rewrite_pluginfile_urls($text, $user, $plugin) {
2129         $groupmode = groups_get_activity_groupmode($this->get_course_module());
2130         $groupname = '';
2131         if ($groupmode) {
2132             $groupid = groups_get_activity_group($this->get_course_module(), true);
2133             $groupname = groups_get_group_name($groupid).'-';
2134         }
2136         if ($this->is_blind_marking()) {
2137             $prefix = $groupname . get_string('participant', 'assign');
2138             $prefix = str_replace('_', ' ', $prefix);
2139             $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2140         } else {
2141             $prefix = $groupname . fullname($user);
2142             $prefix = str_replace('_', ' ', $prefix);
2143             $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2144         }
2146         $subtype = $plugin->get_subtype();
2147         $type = $plugin->get_type();
2148         $prefix = $prefix . $subtype . '_' . $type . '_';
2150         $result = str_replace('@@PLUGINFILE@@/', $prefix, $text);
2152         return $result;
2153     }
2155     /**
2156      * Render the content in editor that is often used by plugin.
2157      *
2158      * @param string $filearea
2159      * @param int  $submissionid
2160      * @param string $plugintype
2161      * @param string $editor
2162      * @param string $component
2163      * @return string
2164      */
2165     public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
2166         global $CFG;
2168         $result = '';
2170         $plugin = $this->get_submission_plugin_by_type($plugintype);
2172         $text = $plugin->get_editor_text($editor, $submissionid);
2173         $format = $plugin->get_editor_format($editor, $submissionid);
2175         $finaltext = file_rewrite_pluginfile_urls($text,
2176                                                   'pluginfile.php',
2177                                                   $this->get_context()->id,
2178                                                   $component,
2179                                                   $filearea,
2180                                                   $submissionid);
2181         $params = array('overflowdiv' => true, 'context' => $this->get_context());
2182         $result .= format_text($finaltext, $format, $params);
2184         if ($CFG->enableportfolios) {
2185             require_once($CFG->libdir . '/portfoliolib.php');
2187             $button = new portfolio_add_button();
2188             $portfolioparams = array('cmid' => $this->get_course_module()->id,
2189                                      'sid' => $submissionid,
2190                                      'plugin' => $plugintype,
2191                                      'editor' => $editor,
2192                                      'area'=>$filearea);
2193             $button->set_callback_options('assign_portfolio_caller', $portfolioparams, 'mod_assign');
2194             $fs = get_file_storage();
2196             if ($files = $fs->get_area_files($this->context->id,
2197                                              $component,
2198                                              $filearea,
2199                                              $submissionid,
2200                                              'timemodified',
2201                                              false)) {
2202                 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
2203             } else {
2204                 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
2205             }
2206             $result .= $button->to_html();
2207         }
2208         return $result;
2209     }
2211     /**
2212      * Display a continue page.
2213      *
2214      * @return string
2215      */
2216     protected function view_savegrading_result($message) {
2217         $o = '';
2218         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2219                                                       $this->get_context(),
2220                                                       $this->show_intro(),
2221                                                       $this->get_course_module()->id,
2222                                                       get_string('savegradingresult', 'assign')));
2223         $gradingresult = new assign_gradingmessage(get_string('savegradingresult', 'assign'),
2224                                                    $message,
2225                                                    $this->get_course_module()->id);
2226         $o .= $this->get_renderer()->render($gradingresult);
2227         $o .= $this->view_footer();
2228         return $o;
2229     }
2230     /**
2231      * Display a grading error.
2232      *
2233      * @param string $message - The description of the result
2234      * @return string
2235      */
2236     protected function view_quickgrading_result($message) {
2237         $o = '';
2238         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2239                                                       $this->get_context(),
2240                                                       $this->show_intro(),
2241                                                       $this->get_course_module()->id,
2242                                                       get_string('quickgradingresult', 'assign')));
2243         $gradingresult = new assign_gradingmessage(get_string('quickgradingresult', 'assign'),
2244                                                    $message,
2245                                                    $this->get_course_module()->id);
2246         $o .= $this->get_renderer()->render($gradingresult);
2247         $o .= $this->view_footer();
2248         return $o;
2249     }
2251     /**
2252      * Display the page footer.
2253      *
2254      * @return string
2255      */
2256     protected function view_footer() {
2257         return $this->get_renderer()->render_footer();
2258     }
2260     /**
2261      * Does this user have grade permission for this assignment?
2262      *
2263      * @return bool
2264      */
2265     protected function can_grade() {
2266         // Permissions check.
2267         if (!has_capability('mod/assign:grade', $this->context)) {
2268             return false;
2269         }
2271         return true;
2272     }
2274     /**
2275      * Download a zip file of all assignment submissions.
2276      *
2277      * @return string - If an error occurs, this will contain the error page.
2278      */
2279     protected function download_submissions() {
2280         global $CFG, $DB;
2282         // More efficient to load this here.
2283         require_once($CFG->libdir.'/filelib.php');
2285         require_capability('mod/assign:grade', $this->context);
2287         // Load all users with submit.
2288         $students = get_enrolled_users($this->context, "mod/assign:submit");
2290         // Build a list of files to zip.
2291         $filesforzipping = array();
2292         $fs = get_file_storage();
2294         $groupmode = groups_get_activity_groupmode($this->get_course_module());
2295         // All users.
2296         $groupid = 0;
2297         $groupname = '';
2298         if ($groupmode) {
2299             $groupid = groups_get_activity_group($this->get_course_module(), true);
2300             $groupname = groups_get_group_name($groupid).'-';
2301         }
2303         // Construct the zip file name.
2304         $filename = clean_filename($this->get_course()->shortname . '-' .
2305                                    $this->get_instance()->name . '-' .
2306                                    $groupname.$this->get_course_module()->id . '.zip');
2308         // Get all the files for each student.
2309         foreach ($students as $student) {
2310             $userid = $student->id;
2312             if ((groups_is_member($groupid, $userid) or !$groupmode or !$groupid)) {
2313                 // Get the plugins to add their own files to the zip.
2315                 $submissiongroup = false;
2316                 $groupname = '';
2317                 if ($this->get_instance()->teamsubmission) {
2318                     $submission = $this->get_group_submission($userid, 0, false);
2319                     $submissiongroup = $this->get_submission_group($userid);
2320                     if ($submissiongroup) {
2321                         $groupname = $submissiongroup->name . '-';
2322                     } else {
2323                         $groupname = get_string('defaultteam', 'assign') . '-';
2324                     }
2325                 } else {
2326                     $submission = $this->get_user_submission($userid, false);
2327                 }
2329                 if ($this->is_blind_marking()) {
2330                     $prefix = str_replace('_', ' ', $groupname . get_string('participant', 'assign'));
2331                     $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2332                 } else {
2333                     $prefix = str_replace('_', ' ', $groupname . fullname($student));
2334                     $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2335                 }
2337                 if ($submission) {
2338                     foreach ($this->submissionplugins as $plugin) {
2339                         if ($plugin->is_enabled() && $plugin->is_visible()) {
2340                             $pluginfiles = $plugin->get_files($submission, $student);
2341                             foreach ($pluginfiles as $zipfilename => $file) {
2342                                 $subtype = $plugin->get_subtype();
2343                                 $type = $plugin->get_type();
2344                                 $prefixedfilename = clean_filename($prefix .
2345                                                                    $subtype .
2346                                                                    '_' .
2347                                                                    $type .
2348                                                                    '_' .
2349                                                                    $zipfilename);
2350                                 $filesforzipping[$prefixedfilename] = $file;
2351                             }
2352                         }
2353                     }
2354                 }
2355             }
2356         }
2357         $result = '';
2358         if (count($filesforzipping) == 0) {
2359             $header = new assign_header($this->get_instance(),
2360                                         $this->get_context(),
2361                                         '',
2362                                         $this->get_course_module()->id,
2363                                         get_string('downloadall', 'assign'));
2364             $result .= $this->get_renderer()->render($header);
2365             $result .= $this->get_renderer()->notification(get_string('nosubmission', 'assign'));
2366             $url = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id,
2367                                                                     'action'=>'grading'));
2368             $result .= $this->get_renderer()->continue_button($url);
2369             $result .= $this->view_footer();
2370         } else if ($zipfile = $this->pack_files($filesforzipping)) {
2371             $this->add_to_log('download all submissions', get_string('downloadall', 'assign'));
2372             // Send file and delete after sending.
2373             send_temp_file($zipfile, $filename);
2374             // We will not get here - send_temp_file calls exit.
2375         }
2376         return $result;
2377     }
2379     /**
2380      * Util function to add a message to the log.
2381      *
2382      * @param string $action The current action
2383      * @param string $info A detailed description of the change. But no more than 255 characters.
2384      * @param string $url The url to the assign module instance.
2385      * @return void
2386      */
2387     public function add_to_log($action = '', $info = '', $url='') {
2388         global $USER;
2390         $fullurl = 'view.php?id=' . $this->get_course_module()->id;
2391         if ($url != '') {
2392             $fullurl .= '&' . $url;
2393         }
2395         add_to_log($this->get_course()->id,
2396                    'assign',
2397                    $action,
2398                    $fullurl,
2399                    $info,
2400                    $this->get_course_module()->id,
2401                    $USER->id);
2402     }
2404     /**
2405      * Lazy load the page renderer and expose the renderer to plugins.
2406      *
2407      * @return assign_renderer
2408      */
2409     public function get_renderer() {
2410         global $PAGE;
2411         if ($this->output) {
2412             return $this->output;
2413         }
2414         $this->output = $PAGE->get_renderer('mod_assign');
2415         return $this->output;
2416     }
2418     /**
2419      * Load the submission object for a particular user, optionally creating it if required.
2420      *
2421      * For team assignments there are 2 submissions - the student submission and the team submission
2422      * All files are associated with the team submission but the status of the students contribution is
2423      * recorded separately.
2424      *
2425      * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
2426      * @param bool $create optional - defaults to false. If set to true a new submission object
2427      *                     will be created in the database.
2428      * @param int $attemptnumber - -1 means the latest attempt
2429      * @return stdClass The submission
2430      */
2431     public function get_user_submission($userid, $create, $attemptnumber=-1) {
2432         global $DB, $USER;
2434         if (!$userid) {
2435             $userid = $USER->id;
2436         }
2437         // If the userid is not null then use userid.
2438         $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid, 'groupid'=>0);
2439         if ($attemptnumber >= 0) {
2440             $params['attemptnumber'] = $attemptnumber;
2441         }
2443         // Only return the row with the highest attemptnumber.
2444         $submission = null;
2445         $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
2446         if ($submissions) {
2447             $submission = reset($submissions);
2448         }
2450         if ($submission) {
2451             return $submission;
2452         }
2453         if ($create) {
2454             $submission = new stdClass();
2455             $submission->assignment   = $this->get_instance()->id;
2456             $submission->userid       = $userid;
2457             $submission->timecreated = time();
2458             $submission->timemodified = $submission->timecreated;
2459             $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
2460             if ($attemptnumber >= 0) {
2461                 $submission->attemptnumber = $attemptnumber;
2462             } else {
2463                 $submission->attemptnumber = 0;
2464             }
2465             $sid = $DB->insert_record('assign_submission', $submission);
2466             $submission->id = $sid;
2467             return $submission;
2468         }
2469         return false;
2470     }
2472     /**
2473      * Load the submission object from it's id.
2474      *
2475      * @param int $submissionid The id of the submission we want
2476      * @return stdClass The submission
2477      */
2478     protected function get_submission($submissionid) {
2479         global $DB;
2481         $params = array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid);
2482         return $DB->get_record('assign_submission', $params, '*', MUST_EXIST);
2483     }
2485     /**
2486      * This will retrieve a user flags object from the db optionally creating it if required.
2487      * The user flags was split from the user_grades table in 2.5.
2488      *
2489      * @param int $userid The user we are getting the flags for.
2490      * @param bool $create If true the flags record will be created if it does not exist
2491      * @return stdClass The flags record
2492      */
2493     public function get_user_flags($userid, $create) {
2494         global $DB, $USER;
2496         // If the userid is not null then use userid.
2497         if (!$userid) {
2498             $userid = $USER->id;
2499         }
2501         $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
2503         $flags = $DB->get_record('assign_user_flags', $params);
2505         if ($flags) {
2506             return $flags;
2507         }
2508         if ($create) {
2509             $flags = new stdClass();
2510             $flags->assignment = $this->get_instance()->id;
2511             $flags->userid = $userid;
2512             $flags->locked = 0;
2513             $flags->extensionduedate = 0;
2514             $flags->workflowstate = '';
2515             $flags->allocatedmarker = 0;
2517             // The mailed flag can be one of 3 values: 0 is unsent, 1 is sent and 2 is do not send yet.
2518             // This is because students only want to be notified about certain types of update (grades and feedback).
2519             $flags->mailed = 2;
2521             $fid = $DB->insert_record('assign_user_flags', $flags);
2522             $flags->id = $fid;
2523             return $flags;
2524         }
2525         return false;
2526     }
2528     /**
2529      * This will retrieve a grade object from the db, optionally creating it if required.
2530      *
2531      * @param int $userid The user we are grading
2532      * @param bool $create If true the grade will be created if it does not exist
2533      * @param int $attemptnumber The attempt number to retrieve the grade for. -1 means the latest submission.
2534      * @return stdClass The grade record
2535      */
2536     public function get_user_grade($userid, $create, $attemptnumber=-1) {
2537         global $DB, $USER;
2539         // If the userid is not null then use userid.
2540         if (!$userid) {
2541             $userid = $USER->id;
2542         }
2544         $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
2545         if ($attemptnumber < 0) {
2546             // Make sure this grade matches the latest submission attempt.
2547             if ($this->get_instance()->teamsubmission) {
2548                 $submission = $this->get_group_submission($userid, 0, false);
2549             } else {
2550                 $submission = $this->get_user_submission($userid, false);
2551             }
2552             if ($submission) {
2553                 $attemptnumber = $submission->attemptnumber;
2554             }
2555         }
2557         if ($attemptnumber >= 0) {
2558             $params['attemptnumber'] = $attemptnumber;
2559         }
2561         $grades = $DB->get_records('assign_grades', $params, 'attemptnumber DESC', '*', 0, 1);
2563         if ($grades) {
2564             return reset($grades);
2565         }
2566         if ($create) {
2567             $grade = new stdClass();
2568             $grade->assignment   = $this->get_instance()->id;
2569             $grade->userid       = $userid;
2570             $grade->timecreated = time();
2571             $grade->timemodified = $grade->timecreated;
2572             $grade->grade = -1;
2573             $grade->grader = $USER->id;
2574             if ($attemptnumber >= 0) {
2575                 $grade->attemptnumber = $attemptnumber;
2576             }
2578             $gid = $DB->insert_record('assign_grades', $grade);
2579             $grade->id = $gid;
2580             return $grade;
2581         }
2582         return false;
2583     }
2585     /**
2586      * This will retrieve a grade object from the db.
2587      *
2588      * @param int $gradeid The id of the grade
2589      * @return stdClass The grade record
2590      */
2591     protected function get_grade($gradeid) {
2592         global $DB;
2594         $params = array('assignment'=>$this->get_instance()->id, 'id'=>$gradeid);
2595         return $DB->get_record('assign_grades', $params, '*', MUST_EXIST);
2596     }
2598     /**
2599      * Print the grading page for a single user submission.
2600      *
2601      * @param moodleform $mform
2602      * @return string
2603      */
2604     protected function view_single_grade_page($mform) {
2605         global $DB, $CFG;
2607         $o = '';
2608         $instance = $this->get_instance();
2610         require_once($CFG->dirroot . '/mod/assign/gradeform.php');
2612         // Need submit permission to submit an assignment.
2613         require_capability('mod/assign:grade', $this->context);
2615         $header = new assign_header($instance,
2616                                     $this->get_context(),
2617                                     false,
2618                                     $this->get_course_module()->id,
2619                                     get_string('grading', 'assign'));
2620         $o .= $this->get_renderer()->render($header);
2622         // If userid is passed - we are only grading a single student.
2623         $rownum = required_param('rownum', PARAM_INT);
2624         $useridlistid = optional_param('useridlistid', time(), PARAM_INT);
2625         $userid = optional_param('userid', 0, PARAM_INT);
2626         $attemptnumber = optional_param('attemptnumber', -1, PARAM_INT);
2628         $cache = cache::make_from_params(cache_store::MODE_SESSION, 'mod_assign', 'useridlist');
2629         if (!$userid) {
2630             if (!$useridlist = $cache->get($this->get_course_module()->id . '_' . $useridlistid)) {
2631                 $useridlist = $this->get_grading_userid_list();
2632             }
2633             $cache->set($this->get_course_module()->id . '_' . $useridlistid, $useridlist);
2634         } else {
2635             $rownum = 0;
2636             $useridlist = array($userid);
2637         }
2639         if ($rownum < 0 || $rownum > count($useridlist)) {
2640             throw new coding_exception('Row is out of bounds for the current grading table: ' . $rownum);
2641         }
2643         $last = false;
2644         $userid = $useridlist[$rownum];
2645         if ($rownum == count($useridlist) - 1) {
2646             $last = true;
2647         }
2648         $user = $DB->get_record('user', array('id' => $userid));
2649         if ($user) {
2650             $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2651             $usersummary = new assign_user_summary($user,
2652                                                    $this->get_course()->id,
2653                                                    $viewfullnames,
2654                                                    $this->is_blind_marking(),
2655                                                    $this->get_uniqueid_for_user($user->id),
2656                                                    get_extra_user_fields($this->get_context()));
2657             $o .= $this->get_renderer()->render($usersummary);
2658         }
2659         $submission = $this->get_user_submission($userid, false, $attemptnumber);
2660         $submissiongroup = null;
2661         $submissiongroupmemberswhohavenotsubmitted = array();
2662         $teamsubmission = null;
2663         $notsubmitted = array();
2664         if ($instance->teamsubmission) {
2665             $teamsubmission = $this->get_group_submission($userid, 0, false, $attemptnumber);
2666             $submissiongroup = $this->get_submission_group($userid);
2667             $groupid = 0;
2668             if ($submissiongroup) {
2669                 $groupid = $submissiongroup->id;
2670             }
2671             $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
2673         }
2675         // Get the requested grade.
2676         $grade = $this->get_user_grade($userid, false, $attemptnumber);
2677         $flags = $this->get_user_flags($userid, false);
2678         if ($this->can_view_submission($userid)) {
2679             $gradelocked = ($flags && $flags->locked) || $this->grading_disabled($userid);
2680             $extensionduedate = null;
2681             if ($flags) {
2682                 $extensionduedate = $flags->extensionduedate;
2683             }
2684             $showedit = $this->submissions_open($userid) && ($this->is_any_submission_plugin_enabled());
2686             if ($teamsubmission) {
2687                 $showsubmit = $showedit &&
2688                               $teamsubmission &&
2689                               ($teamsubmission->status == ASSIGN_SUBMISSION_STATUS_DRAFT);
2690             } else {
2691                 $showsubmit = $showedit &&
2692                               $submission &&
2693                               ($submission->status == ASSIGN_SUBMISSION_STATUS_DRAFT);
2694             }
2695             if (!$this->get_instance()->submissiondrafts) {
2696                 $showsubmit = false;
2697             }
2698             $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2700             $submissionstatus = new assign_submission_status($instance->allowsubmissionsfromdate,
2701                                                              $instance->alwaysshowdescription,
2702                                                              $submission,
2703                                                              $instance->teamsubmission,
2704                                                              $teamsubmission,
2705                                                              $submissiongroup,
2706                                                              $notsubmitted,
2707                                                              $this->is_any_submission_plugin_enabled(),
2708                                                              $gradelocked,
2709                                                              $this->is_graded($userid),
2710                                                              $instance->duedate,
2711                                                              $instance->cutoffdate,
2712                                                              $this->get_submission_plugins(),
2713                                                              $this->get_return_action(),
2714                                                              $this->get_return_params(),
2715                                                              $this->get_course_module()->id,
2716                                                              $this->get_course()->id,
2717                                                              assign_submission_status::GRADER_VIEW,
2718                                                              $showedit,
2719                                                              $showsubmit,
2720                                                              $viewfullnames,
2721                                                              $extensionduedate,
2722                                                              $this->get_context(),
2723                                                              $this->is_blind_marking(),
2724                                                              '',
2725                                                              $instance->attemptreopenmethod,
2726                                                              $instance->maxattempts);
2727             $o .= $this->get_renderer()->render($submissionstatus);
2728         }
2730         if ($grade) {
2731             $data = new stdClass();
2732             if ($grade->grade !== null && $grade->grade >= 0) {
2733                 $data->grade = format_float($grade->grade, 2);
2734             }
2735             if (!empty($flags->workflowstate)) {
2736                 $data->workflowstate = $flags->workflowstate;
2737             }
2738             if (!empty($flags->allocatedmarker)) {
2739                 $data->allocatedmarker = $flags->allocatedmarker;
2740             }
2741         } else {
2742             $data = new stdClass();
2743             $data->grade = '';
2744         }
2745         // Warning if required.
2746         $allsubmissions = $this->get_all_submissions($userid);
2748         if ($attemptnumber != -1) {
2749             $params = array('attemptnumber'=>$attemptnumber + 1,
2750                             'totalattempts'=>count($allsubmissions));
2751             $message = get_string('editingpreviousfeedbackwarning', 'assign', $params);
2752             $o .= $this->get_renderer()->notification($message);
2753         }
2755         // Now show the grading form.
2756         if (!$mform) {
2757             $pagination = array('rownum'=>$rownum,
2758                                 'useridlistid'=>$useridlistid,
2759                                 'last'=>$last,
2760                                 'userid'=>optional_param('userid', 0, PARAM_INT),
2761                                 'attemptnumber'=>$attemptnumber);
2762             $formparams = array($this, $data, $pagination);
2763             $mform = new mod_assign_grade_form(null,
2764                                                $formparams,
2765                                                'post',
2766                                                '',
2767                                                array('class'=>'gradeform'));
2768         }
2769         $o .= $this->get_renderer()->heading(get_string('grade'), 3);
2770         $o .= $this->get_renderer()->render(new assign_form('gradingform', $mform));
2772         if (count($allsubmissions) > 1 && $attemptnumber == -1) {
2773             $allgrades = $this->get_all_grades($userid);
2774             $history = new assign_attempt_history($allsubmissions,
2775                                                   $allgrades,
2776                                                   $this->get_submission_plugins(),
2777                                                   $this->get_feedback_plugins(),
2778                                                   $this->get_course_module()->id,
2779                                                   $this->get_return_action(),
2780                                                   $this->get_return_params(),
2781                                                   true);
2783             $o .= $this->get_renderer()->render($history);
2784         }
2786         $msg = get_string('viewgradingformforstudent',
2787                           'assign',
2788                           array('id'=>$user->id, 'fullname'=>fullname($user)));
2789         $this->add_to_log('view grading form', $msg);
2791         $o .= $this->view_footer();
2792         return $o;
2793     }
2795     /**
2796      * Show a confirmation page to make sure they want to release student identities.
2797      *
2798      * @return string
2799      */
2800     protected function view_reveal_identities_confirm() {
2801         global $CFG, $USER;
2803         require_capability('mod/assign:revealidentities', $this->get_context());
2805         $o = '';
2806         $header = new assign_header($this->get_instance(),
2807                                     $this->get_context(),
2808                                     false,
2809                                     $this->get_course_module()->id);
2810         $o .= $this->get_renderer()->render($header);
2812         $urlparams = array('id'=>$this->get_course_module()->id,
2813                            'action'=>'revealidentitiesconfirm',
2814                            'sesskey'=>sesskey());
2815         $confirmurl = new moodle_url('/mod/assign/view.php', $urlparams);
2817         $urlparams = array('id'=>$this->get_course_module()->id,
2818                            'action'=>'grading');
2819         $cancelurl = new moodle_url('/mod/assign/view.php', $urlparams);
2821         $o .= $this->get_renderer()->confirm(get_string('revealidentitiesconfirm', 'assign'),
2822                                              $confirmurl,
2823                                              $cancelurl);
2824         $o .= $this->view_footer();
2825         $this->add_to_log('view', get_string('viewrevealidentitiesconfirm', 'assign'));
2826         return $o;
2827     }
2829     /**
2830      * View a link to go back to the previous page. Uses url parameters returnaction and returnparams.
2831      *
2832      * @return string
2833      */
2834     protected function view_return_links() {
2835         $returnaction = optional_param('returnaction', '', PARAM_ALPHA);
2836         $returnparams = optional_param('returnparams', '', PARAM_TEXT);
2838         $params = array();
2839         $returnparams = str_replace('&amp;', '&', $returnparams);
2840         parse_str($returnparams, $params);
2841         $newparams = array('id' => $this->get_course_module()->id, 'action' => $returnaction);
2842         $params = array_merge($newparams, $params);
2844         $url = new moodle_url('/mod/assign/view.php', $params);
2845         return $this->get_renderer()->single_button($url, get_string('back'), 'get');
2846     }
2848     /**
2849      * View the grading table of all submissions for this assignment.
2850      *
2851      * @return string
2852      */
2853     protected function view_grading_table() {
2854         global $USER, $CFG;
2856         // Include grading options form.
2857         require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
2858         require_once($CFG->dirroot . '/mod/assign/quickgradingform.php');
2859         require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
2860         $o = '';
2861         $cmid = $this->get_course_module()->id;
2863         $links = array();
2864         if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
2865                 has_capability('moodle/grade:viewall', $this->get_course_context())) {
2866             $gradebookurl = '/grade/report/grader/index.php?id=' . $this->get_course()->id;
2867             $links[$gradebookurl] = get_string('viewgradebook', 'assign');
2868         }
2869         if ($this->is_any_submission_plugin_enabled() && $this->count_submissions()) {
2870             $downloadurl = '/mod/assign/view.php?id=' . $cmid . '&action=downloadall';
2871             $links[$downloadurl] = get_string('downloadall', 'assign');
2872         }
2873         if ($this->is_blind_marking() &&
2874                 has_capability('mod/assign:revealidentities', $this->get_context())) {
2875             $revealidentitiesurl = '/mod/assign/view.php?id=' . $cmid . '&action=revealidentities';
2876             $links[$revealidentitiesurl] = get_string('revealidentities', 'assign');
2877         }
2878         foreach ($this->get_feedback_plugins() as $plugin) {
2879             if ($plugin->is_enabled() && $plugin->is_visible()) {
2880                 foreach ($plugin->get_grading_actions() as $action => $description) {
2881                     $url = '/mod/assign/view.php' .
2882                            '?id=' .  $cmid .
2883                            '&plugin=' . $plugin->get_type() .
2884                            '&pluginsubtype=assignfeedback' .
2885                            '&action=viewpluginpage&pluginaction=' . $action;
2886                     $links[$url] = $description;
2887                 }
2888             }
2889         }
2891         $gradingactions = new url_select($links);
2892         $gradingactions->set_label(get_string('choosegradingaction', 'assign'));
2894         $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2896         $perpage = get_user_preferences('assign_perpage', 10);
2897         $filter = get_user_preferences('assign_filter', '');
2898         $markerfilter = get_user_preferences('assign_markerfilter', '');
2899         $workflowfilter = get_user_preferences('assign_workflowfilter', '');
2900         $controller = $gradingmanager->get_active_controller();
2901         $showquickgrading = empty($controller);
2902         $quickgrading = get_user_preferences('assign_quickgrading', false);
2904         $markingallocation = $this->get_instance()->markingallocation &&
2905             has_capability('mod/assign:manageallocations', $this->context);
2906         // Get markers to use in drop lists.
2907         $markingallocationoptions = array();
2908         if ($markingallocation) {
2909             $markers = get_users_by_capability($this->context, 'mod/assign:grade');
2910             $markingallocationoptions[''] = get_string('filternone', 'assign');
2911             foreach ($markers as $marker) {
2912                 $markingallocationoptions[$marker->id] = fullname($marker);
2913             }
2914         }
2916         $markingworkflow = $this->get_instance()->markingworkflow;
2917         // Get marking states to show in form.
2918         $markingworkflowoptions = array();
2919         if ($markingworkflow) {
2920             $markingworkflowoptions[''] = get_string('filternone', 'assign');
2921             $markingworkflowoptions[ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED] = get_string('markingworkflowstatenotmarked', 'assign');
2922             $markingworkflowoptions = array_merge($markingworkflowoptions, $this->get_marking_workflow_states_for_current_user());
2923         }
2925         // Print options for changing the filter and changing the number of results per page.
2926         $gradingoptionsformparams = array('cm'=>$cmid,
2927                                           'contextid'=>$this->context->id,
2928                                           'userid'=>$USER->id,
2929                                           'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
2930                                           'showquickgrading'=>$showquickgrading,
2931                                           'quickgrading'=>$quickgrading,
2932                                           'markingworkflowopt'=>$markingworkflowoptions,
2933                                           'markingallocationopt'=>$markingallocationoptions);
2935         $classoptions = array('class'=>'gradingoptionsform');
2936         $gradingoptionsform = new mod_assign_grading_options_form(null,
2937                                                                   $gradingoptionsformparams,
2938                                                                   'post',
2939                                                                   '',
2940                                                                   $classoptions);
2942         $batchformparams = array('cm'=>$cmid,
2943                                  'submissiondrafts'=>$this->get_instance()->submissiondrafts,
2944                                  'duedate'=>$this->get_instance()->duedate,
2945                                  'attemptreopenmethod'=>$this->get_instance()->attemptreopenmethod,
2946                                  'feedbackplugins'=>$this->get_feedback_plugins(),
2947                                  'context'=>$this->get_context(),
2948                                  'markingworkflow'=>$markingworkflow,
2949                                  'markingallocation'=>$markingallocation);
2950         $classoptions = array('class'=>'gradingbatchoperationsform');
2952         $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
2953                                                                                    $batchformparams,
2954                                                                                    'post',
2955                                                                                    '',
2956                                                                                    $classoptions);
2958         $gradingoptionsdata = new stdClass();
2959         $gradingoptionsdata->perpage = $perpage;
2960         $gradingoptionsdata->filter = $filter;
2961         $gradingoptionsdata->markerfilter = $markerfilter;
2962         $gradingoptionsdata->workflowfilter = $workflowfilter;
2963         $gradingoptionsform->set_data($gradingoptionsdata);
2965         $actionformtext = $this->get_renderer()->render($gradingactions);
2966         $header = new assign_header($this->get_instance(),
2967                                     $this->get_context(),
2968                                     false,
2969                                     $this->get_course_module()->id,
2970                                     get_string('grading', 'assign'),
2971                                     $actionformtext);
2972         $o .= $this->get_renderer()->render($header);
2974         $currenturl = $CFG->wwwroot .
2975                       '/mod/assign/view.php?id=' .
2976                       $this->get_course_module()->id .
2977                       '&action=grading';
2979         $o .= groups_print_activity_menu($this->get_course_module(), $currenturl, true);
2981         // Plagiarism update status apearring in the grading book.
2982         if (!empty($CFG->enableplagiarism)) {
2983             require_once($CFG->libdir . '/plagiarismlib.php');
2984             $o .= plagiarism_update_status($this->get_course(), $this->get_course_module());
2985         }
2987         // Load and print the table of submissions.
2988         if ($showquickgrading && $quickgrading) {
2989             $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, true);
2990             $table = $this->get_renderer()->render($gradingtable);
2991             $quickformparams = array('cm'=>$this->get_course_module()->id, 'gradingtable'=>$table);
2992             $quickgradingform = new mod_assign_quick_grading_form(null, $quickformparams);
2994             $o .= $this->get_renderer()->render(new assign_form('quickgradingform', $quickgradingform));
2995         } else {
2996             $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, false);
2997             $o .= $this->get_renderer()->render($gradingtable);
2998         }
3000         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
3001         $users = array_keys($this->list_participants($currentgroup, true));
3002         if (count($users) != 0) {
3003             // If no enrolled user in a course then don't display the batch operations feature.
3004             $assignform = new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform);
3005             $o .= $this->get_renderer()->render($assignform);
3006         }
3007         $assignform = new assign_form('gradingoptionsform',
3008                                       $gradingoptionsform,
3009                                       'M.mod_assign.init_grading_options');
3010         $o .= $this->get_renderer()->render($assignform);
3011         return $o;
3012     }
3014     /**
3015      * View entire grading page.
3016      *
3017      * @return string
3018      */
3019     protected function view_grading_page() {
3020         global $CFG;
3022         $o = '';
3023         // Need submit permission to submit an assignment.
3024         require_capability('mod/assign:grade', $this->context);
3025         require_once($CFG->dirroot . '/mod/assign/gradeform.php');
3027         // Only load this if it is.
3029         $o .= $this->view_grading_table();
3031         $o .= $this->view_footer();
3033         $logmessage = get_string('viewsubmissiongradingtable', 'assign');
3034         $this->add_to_log('view submission grading table', $logmessage);
3035         return $o;
3036     }
3038     /**
3039      * Capture the output of the plagiarism plugins disclosures and return it as a string.
3040      *
3041      * @return void
3042      */
3043     protected function plagiarism_print_disclosure() {
3044         global $CFG;
3045         $o = '';
3047         if (!empty($CFG->enableplagiarism)) {
3048             require_once($CFG->libdir . '/plagiarismlib.php');
3050             $o .= plagiarism_print_disclosure($this->get_course_module()->id);
3051         }
3053         return $o;
3054     }
3056     /**
3057      * Message for students when assignment submissions have been closed.
3058      *
3059      * @return string
3060      */
3061     protected function view_student_error_message() {
3062         global $CFG;
3064         $o = '';
3065         // Need submit permission to submit an assignment.
3066         require_capability('mod/assign:submit', $this->context);
3068         $header = new assign_header($this->get_instance(),
3069                                     $this->get_context(),
3070                                     $this->show_intro(),
3071                                     $this->get_course_module()->id,
3072                                     get_string('editsubmission', 'assign'));
3073         $o .= $this->get_renderer()->render($header);
3075         $o .= $this->get_renderer()->notification(get_string('submissionsclosed', 'assign'));
3077         $o .= $this->view_footer();
3079         return $o;
3081     }
3083     /**
3084      * View edit submissions page.
3085      *
3086      * @param moodleform $mform
3087      * @param array $notices A list of notices to display at the top of the
3088      *                       edit submission form (e.g. from plugins).
3089      * @return string The page output.
3090      */
3091     protected function view_edit_submission_page($mform, $notices) {
3092         global $CFG;
3094         $o = '';
3095         require_once($CFG->dirroot . '/mod/assign/submission_form.php');
3096         // Need submit permission to submit an assignment.
3097         require_capability('mod/assign:submit', $this->context);
3099         if (!$this->submissions_open()) {
3100             return $this->view_student_error_message();
3101         }
3102         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
3103                                                       $this->get_context(),
3104                                                       $this->show_intro(),
3105                                                       $this->get_course_module()->id,
3106                                                       get_string('editsubmission', 'assign')));
3107         $o .= $this->plagiarism_print_disclosure();
3108         $data = new stdClass();
3110         if (!$mform) {
3111             $mform = new mod_assign_submission_form(null, array($this, $data));
3112         }
3114         foreach ($notices as $notice) {
3115             $o .= $this->get_renderer()->notification($notice);
3116         }
3118         $o .= $this->get_renderer()->render(new assign_form('editsubmissionform', $mform));
3120         $o .= $this->view_footer();
3121         $this->add_to_log('view submit assignment form', get_string('viewownsubmissionform', 'assign'));
3123         return $o;
3124     }
3126     /**
3127      * See if this assignment has a grade yet.
3128      *
3129      * @param int $userid
3130      * @return bool
3131      */
3132     protected function is_graded($userid) {
3133         $grade = $this->get_user_grade($userid, false);
3134         if ($grade) {
3135             return ($grade->grade !== null && $grade->grade >= 0);
3136         }
3137         return false;
3138     }
3140     /**
3141      * Perform an access check to see if the current $USER can view this group submission.
3142      *
3143      * @param int $groupid
3144      * @return bool
3145      */
3146     public function can_view_group_submission($groupid) {
3147         global $USER;
3149         if (!is_enrolled($this->get_course_context(), $USER->id)) {
3150             return false;
3151         }
3152         if (has_capability('mod/assign:grade', $this->context)) {
3153             return true;
3154         }
3155         $members = $this->get_submission_group_members($groupid, true);
3156         foreach ($members as $member) {
3157             if ($member->id == $USER->id) {
3158                 return true;
3159             }
3160         }
3161         return false;
3162     }
3164     /**
3165      * Perform an access check to see if the current $USER can view this users submission.
3166      *
3167      * @param int $userid
3168      * @return bool
3169      */
3170     public function can_view_submission($userid) {
3171         global $USER;
3173         if (is_siteadmin()) {
3174             return true;
3175         }
3176         if (!is_enrolled($this->get_course_context(), $userid)) {
3177             return false;
3178         }
3179         if ($userid == $USER->id && has_capability('mod/assign:submit', $this->context)) {
3180             return true;
3181         }
3182         if (has_capability('mod/assign:grade', $this->context)) {
3183             return true;
3184         }
3185         return false;
3186     }
3188     /**
3189      * Allows the plugin to show a batch grading operation page.
3190      *
3191      * @return none
3192      */
3193     protected function view_plugin_grading_batch_operation($mform) {
3194         require_capability('mod/assign:grade', $this->context);
3195         $prefix = 'plugingradingbatchoperation_';
3197         if ($data = $mform->get_data()) {
3198             $tail = substr($data->operation, strlen($prefix));
3199             list($plugintype, $action) = explode('_', $tail, 2);
3201             $plugin = $this->get_feedback_plugin_by_type($plugintype);
3202             if ($plugin) {
3203                 $users = $data->selectedusers;
3204                 $userlist = explode(',', $users);
3205                 echo $plugin->grading_batch_operation($action, $userlist);
3206                 return;
3207             }
3208         }
3209         print_error('invalidformdata', '');
3210     }
3212     /**
3213      * Ask the user to confirm they want to perform this batch operation
3214      *
3215      * @param moodleform $mform Set to a grading batch operations form
3216      * @return string - the page to view after processing these actions
3217      */
3218     protected function process_grading_batch_operation(& $mform) {
3219         global $CFG;
3220         require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
3221         require_sesskey();
3223         $markingallocation = $this->get_instance()->markingallocation &&
3224             has_capability('mod/assign:manageallocations', $this->context);
3226         $batchformparams = array('cm'=>$this->get_course_module()->id,
3227                                  'submissiondrafts'=>$this->get_instance()->submissiondrafts,
3228                                  'duedate'=>$this->get_instance()->duedate,
3229                                  'attemptreopenmethod'=>$this->get_instance()->attemptreopenmethod,
3230                                  'feedbackplugins'=>$this->get_feedback_plugins(),
3231                                  'context'=>$this->get_context(),
3232                                  'markingworkflow'=>$this->get_instance()->markingworkflow,
3233                                  'markingallocation'=>$markingallocation);
3234         $formclasses = array('class'=>'gradingbatchoperationsform');
3235         $mform = new mod_assign_grading_batch_operations_form(null,
3236                                                               $batchformparams,
3237                                                               'post',
3238                                                               '',
3239                                                               $formclasses);
3241         if ($data = $mform->get_data()) {
3242             // Get the list of users.
3243             $users = $data->selectedusers;
3244             $userlist = explode(',', $users);
3246             $prefix = 'plugingradingbatchoperation_';
3248             if ($data->operation == 'grantextension') {
3249                 // Reset the form so the grant extension page will create the extension form.
3250                 $mform = null;
3251                 return 'grantextension';
3252             } else if ($data->operation == 'setmarkingworkflowstate') {
3253                 return 'viewbatchsetmarkingworkflowstate';
3254             } else if ($data->operation == 'setmarkingallocation') {
3255                 return 'viewbatchmarkingallocation';
3256             } else if (strpos($data->operation, $prefix) === 0) {
3257                 $tail = substr($data->operation, strlen($prefix));
3258                 list($plugintype, $action) = explode('_', $tail, 2);
3260                 $plugin = $this->get_feedback_plugin_by_type($plugintype);
3261                 if ($plugin) {
3262                     return 'plugingradingbatchoperation';
3263                 }
3264             }
3266             foreach ($userlist as $userid) {
3267                 if ($data->operation == 'lock') {
3268                     $this->process_lock($userid);
3269                 } else if ($data->operation == 'unlock') {
3270                     $this->process_unlock($userid);
3271                 } else if ($data->operation == 'reverttodraft') {
3272                     $this->process_revert_to_draft($userid);
3273                 } else if ($data->operation == 'addattempt') {
3274                     if (!$this->get_instance()->teamsubmission) {
3275                         $this->process_add_attempt($userid);
3276                     }
3277                 }
3278             }
3279             if ($this->get_instance()->teamsubmission && $data->operation == 'addattempt') {
3280                 // This needs to be handled separately so that each team submission is only re-opened one time.
3281                 $this->process_add_attempt_group($userlist);
3282             }
3283         }
3285         return 'grading';
3286     }
3288     /**
3289      * Shows a form that allows the workflow state for selected submissions to be changed.
3290      *
3291      * @param moodleform $mform Set to a grading batch operations form
3292      * @return string - the page to view after processing these actions
3293      */
3294     private function view_batch_set_workflow_state($mform) {
3295         global $CFG, $DB;
3297         require_once($CFG->dirroot . '/mod/assign/batchsetmarkingworkflowstateform.php');
3299         $o = '';
3301         $submitteddata = $mform->get_data();
3302         $users = $submitteddata->selectedusers;
3303         $userlist = explode(',', $users);
3305         $formparams = array('cm'=>$this->get_course_module()->id,
3306                             'users'=>$userlist,
3307                             'context'=>$this->get_context());
3309         $usershtml = '';
3311         $usercount = 0;
3312         $extrauserfields = get_extra_user_fields($this->get_context());
3313         foreach ($userlist as $userid) {
3314             if ($usercount >= 5) {
3315                 $usershtml .= get_string('moreusers', 'assign', count($userlist) - 5);
3316                 break;
3317             }
3318             $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
3320             $usershtml .= $this->get_renderer()->render(new assign_user_summary($user,
3321                                                                 $this->get_course()->id,
3322                                                                 has_capability('moodle/site:viewfullnames',
3323                                                                 $this->get_course_context()),
3324                                                                 $this->is_blind_marking(),
3325                                                                 $this->get_uniqueid_for_user($user->id),
3326                                                                 $extrauserfields));
3327             $usercount += 1;
3328         }
3330         $formparams['usershtml'] = $usershtml;
3331         $formparams['markingworkflowstates'] = $this->get_marking_workflow_states_for_current_user();
3333         $mform = new mod_assign_batch_set_marking_workflow_state_form(null, $formparams);
3334         $o .= $this->get_renderer()->header();
3335         $o .= $this->get_renderer()->render(new assign_form('setworkflowstate', $mform));
3336         $o .= $this->view_footer();
3338         $this->add_to_log('view batch set marking workflow state', get_string('viewbatchsetmarkingworkflowstate', 'assign'));
3339         return $o;
3340     }
3342     /**
3343      * Shows a form that allows the allocated marker for selected submissions to be changed.
3344      *
3345      * @param moodleform $mform Set to a grading batch operations form
3346      * @return string - the page to view after processing these actions
3347      */
3348     private function view_batch_markingallocation($mform) {
3349         global $CFG, $DB;
3351         require_once($CFG->dirroot . '/mod/assign/batchsetallocatedmarkerform.php');
3353         $o = '';
3355         $submitteddata = $mform->get_data();
3356         $users = $submitteddata->selectedusers;
3357         $userlist = explode(',', $users);
3359         $formparams = array('cm'=>$this->get_course_module()->id,
3360             'users'=>$userlist,
3361             'context'=>$this->get_context());
3363         $usershtml = '';
3365         $usercount = 0;
3366         $extrauserfields = get_extra_user_fields($this->get_context());
3367         foreach ($userlist as $userid) {
3368             if ($usercount >= 5) {
3369                 $usershtml .= get_string('moreusers', 'assign', count($userlist) - 5);
3370                 break;
3371             }
3372             $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
3374             $usershtml .= $this->get_renderer()->render(new assign_user_summary($user,
3375                 $this->get_course()->id,
3376                 has_capability('moodle/site:viewfullnames',
3377                     $this->get_course_context()),
3378                 $this->is_blind_marking(),
3379                 $this->get_uniqueid_for_user($user->id),
3380                 $extrauserfields));
3381             $usercount += 1;
3382         }
3384         $formparams['usershtml'] = $usershtml;
3385         $markers = get_users_by_capability($this->get_context(), 'mod/assign:grade');
3386         $markerlist = array();
3387         foreach ($markers as $marker) {
3388             $markerlist[$marker->id] = fullname($marker);
3389         }
3391         $formparams['markers'] = $markerlist;
3393         $mform = new mod_assign_batch_set_allocatedmarker_form(null, $formparams);
3394         $o .= $this->get_renderer()->header();
3395         $o .= $this->get_renderer()->render(new assign_form('setworkflowstate', $mform));
3396         $o .= $this->view_footer();
3398         $this->add_to_log('view batch set marker allocation', get_string('viewbatchmarkingallocation', 'assign'));
3399         return $o;
3400     }
3402     /**
3403      * Ask the user to confirm they want to submit their work for grading.
3404      *
3405      * @param $mform moodleform - null unless form validation has failed
3406      * @return string
3407      */
3408     protected function check_submit_for_grading($mform) {
3409         global $USER, $CFG;
3411         require_once($CFG->dirroot . '/mod/assign/submissionconfirmform.php');
3413         // Check that all of the submission plugins are ready for this submission.
3414         $notifications = array();
3415         $submission = $this->get_user_submission($USER->id, false);
3416         $plugins = $this->get_submission_plugins();
3417         foreach ($plugins as $plugin) {
3418             if ($plugin->is_enabled() && $plugin->is_visible()) {
3419                 $check = $plugin->precheck_submission($submission);
3420                 if ($check !== true) {
3421                     $notifications[] = $check;
3422                 }
3423             }
3424         }
3426         $data = new stdClass();
3427         $adminconfig = $this->get_admin_config();
3428         $requiresubmissionstatement = $this->get_instance()->requiresubmissionstatement &&
3429                                        !empty($adminconfig->submissionstatement);
3431         $submissionstatement = '';
3432         if (!empty($adminconfig->submissionstatement)) {
3433             $submissionstatement = $adminconfig->submissionstatement;
3434         }
3436         if ($mform == null) {
3437             $mform = new mod_assign_confirm_submission_form(null, array($requiresubmissionstatement,
3438                                                                         $submissionstatement,
3439                                                                         $this->get_course_module()->id,
3440                                                                         $data));
3441         }
3442         $o = '';
3443         $o .= $this->get_renderer()->header();
3444         $submitforgradingpage = new assign_submit_for_grading_page($notifications,
3445                                                                    $this->get_course_module()->id,
3446                                                                    $mform);
3447         $o .= $this->get_renderer()->render($submitforgradingpage);
3448         $o .= $this->view_footer();
3450         $logmessage = get_string('viewownsubmissionform', 'assign');
3451         $this->add_to_log('view confirm submit assignment form', $logmessage);
3453         return $o;
3454     }
3456     /**
3457      * Print 2 tables of information with no action links -
3458      * the submission summary and the grading summary.
3459      *
3460      * @param stdClass $user the user to print the report for
3461      * @param bool $showlinks - Return plain text or links to the profile
3462      * @return string - the html summary
3463      */
3464     public function view_student_summary($user, $showlinks) {
3465         global $CFG, $DB, $PAGE;
3467         $instance = $this->get_instance();
3468         $grade = $this->get_user_grade($user->id, false);
3469         $flags = $this->get_user_flags($user->id, false);
3470         $submission = $this->get_user_submission($user->id, false);
3471         $o = '';
3473         $teamsubmission = null;
3474         $submissiongroup = null;
3475         $notsubmitted = array();
3476         if ($instance->teamsubmission) {
3477             $teamsubmission = $this->get_group_submission($user->id, 0, false);
3478             $submissiongroup = $this->get_submission_group($user->id);
3479             $groupid = 0;
3480             if ($submissiongroup) {
3481                 $groupid = $submissiongroup->id;
3482             }
3483             $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
3484         }
3486         if ($this->can_view_submission($user->id)) {
3487             $showedit = has_capability('mod/assign:submit', $this->context) &&
3488                         $this->submissions_open($user->id) &&
3489                         ($this->is_any_submission_plugin_enabled()) &&
3490                         $showlinks;
3492             $gradelocked = ($flags && $flags->locked) || $this->grading_disabled($user->id, false);
3494             // Grading criteria preview.
3495             $gradingmanager = get_grading_manager($this->context, 'mod_assign', 'submissions');
3496             $gradingcontrollerpreview = '';
3497             if ($gradingmethod = $gradingmanager->get_active_method()) {
3498                 $controller = $gradingmanager->get_controller($gradingmethod);
3499                 if ($controller->is_form_defined()) {
3500                     $gradingcontrollerpreview = $controller->render_preview($PAGE);
3501                 }
3502             }
3504             $showsubmit = ($submission || $teamsubmission) && $showlinks;
3505             if ($teamsubmission && ($teamsubmission->status != ASSIGN_SUBMISSION_STATUS_DRAFT)) {
3506                 $showsubmit = false;
3507             }
3508             if ($submission && ($submission->status != ASSIGN_SUBMISSION_STATUS_DRAFT)) {
3509                 $showsubmit = false;
3510             }
3511             if (!$this->get_instance()->submissiondrafts) {
3512                 $showsubmit = false;
3513             }
3514             $extensionduedate = null;
3515             if ($flags) {
3516                 $extensionduedate = $flags->extensionduedate;
3517             }
3518             $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
3520             $submissionstatus = new assign_submission_status($instance->allowsubmissionsfromdate,
3521                                                               $instance->alwaysshowdescription,
3522                                                               $submission,
3523                                                               $instance->teamsubmission,
3524                                                               $teamsubmission,
3525                                                               $submissiongroup,
3526                                                               $notsubmitted,
3527                                                               $this->is_any_submission_plugin_enabled(),
3528                                                               $gradelocked,
3529                                                               $this->is_graded($user->id),
3530                                                               $instance->duedate,
3531                                                               $instance->cutoffdate,
3532                                                               $this->get_submission_plugins(),
3533                                                               $this->get_return_action(),
3534                                                               $this->get_return_params(),
3535                                                               $this->get_course_module()->id,
3536                                                               $this->get_course()->id,
3537                                                               assign_submission_status::STUDENT_VIEW,
3538                                                               $showedit,
3539                                                               $showsubmit,
3540                                                               $viewfullnames,
3541                                                               $extensionduedate,
3542                                                               $this->get_context(),
3543                                                               $this->is_blind_marking(),
3544                                                               $gradingcontrollerpreview,
3545                                                               $instance->attemptreopenmethod,
3546                                                               $instance->maxattempts);
3547             $o .= $this->get_renderer()->render($submissionstatus);
3549             require_once($CFG->libdir.'/gradelib.php');
3550             require_once($CFG->dirroot.'/grade/grading/lib.php');
3552             $gradinginfo = grade_get_grades($this->get_course()->id,
3553                                         'mod',
3554                                         'assign',
3555                                         $instance->id,
3556                                         $user->id);
3558             $gradingitem = null;
3559             $gradebookgrade = null;
3560             if (isset($gradinginfo->items[0])) {
3561                 $gradingitem = $gradinginfo->items[0];
3562                 $gradebookgrade = $gradingitem->grades[$user->id];
3563             }
3565             // Check to see if all feedback plugins are empty.
3566             $emptyplugins = true;
3567             if ($grade) {
3568                 foreach ($this->get_feedback_plugins() as $plugin) {
3569                     if ($plugin->is_visible() && $plugin->is_enabled()) {
3570                         if (!$plugin->is_empty($grade)) {
3571                             $emptyplugins = false;
3572                         }
3573                     }
3574                 }
3575             }
3577             $gradereleased = true;
3578             if ($this->get_instance()->markingworkflow &&
3579                 (empty($grade) || $flags->workflowstate != ASSIGN_MARKING_WORKFLOW_STATE_RELEASED)) {
3580                 $gradereleased = false;
3581                 $emptyplugins = true; // Don't show feedback plugins until released either.
3582             }
3584             $cangrade = has_capability('mod/assign:grade', $this->get_context());
3585             // If there is feedback or a visible grade, show the summary.
3586             if ((!empty($gradebookgrade->grade) && ($cangrade || !$gradebookgrade->hidden) && $gradereleased) ||
3587                     !$emptyplugins) {
3589                 $gradefordisplay = null;
3590                 $gradeddate = null;
3591                 $grader = null;
3592                 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
3594                 // Only show the grade if it is not hidden in gradebook.
3595                 if (!empty($gradebookgrade->grade) && ($cangrade || !$gradebookgrade->hidden)) {
3596                     if ($controller = $gradingmanager->get_active_controller()) {
3597                         $controller->set_grade_range(make_grades_menu($this->get_instance()->grade));
3598                         $gradefordisplay = $controller->render_grade($PAGE,
3599                                                                      $grade->id,
3600                                                                      $gradingitem,
3601                                                                      $gradebookgrade->str_long_grade,
3602                                                                      $cangrade);
3603                     } else {
3604                         $gradefordisplay = $this->display_grade($gradebookgrade->grade, false);
3605                     }
3606                     $gradeddate = $gradebookgrade->dategraded;
3607                     if (isset($grade->grader)) {
3608                         $grader = $DB->get_record('user', array('id'=>$grade->grader));
3609                     }
3610                 }
3612                 $feedbackstatus = new assign_feedback_status($gradefordisplay,
3613                                                       $gradeddate,
3614                                                       $grader,
3615                                                       $this->get_feedback_plugins(),
3616                                                       $grade,
3617                                                       $this->get_course_module()->id,
3618                                                       $this->get_return_action(),
3619                                                       $this->get_return_params());
3621                 $o .= $this->get_renderer()->render($feedbackstatus);
3622             }
3624             $allsubmissions = $this->get_all_submissions($user->id);
3626             if (count($allsubmissions) > 1) {
3627                 $allgrades = $this->get_all_grades($user->id);
3628                 $history = new assign_attempt_history($allsubmissions,
3629                                                       $allgrades,
3630                                                       $this->get_submission_plugins(),
3631                                                       $this->get_feedback_plugins(),
3632                                                       $this->get_course_module()->id,
3633                                                       $this->get_return_action(),
3634                                                       $this->get_return_params(),
3635                                                       false);
3637                 $o .= $this->get_renderer()->render($history);
3638             }
3640         }
3641         return $o;
3642     }
3644     /**
3645      * Get the grades for all previous attempts.
3646      * For each grade - the grader is a full user record,
3647      * and gradefordisplay is added (rendered from grading manager).
3648      *
3649      * @param int $userid If not set, $USER->id will be used.
3650      * @return array $grades All grade records for this user.
3651      */
3652     protected function get_all_grades($userid) {
3653         global $DB, $USER, $PAGE;
3655         // If the userid is not null then use userid.
3656         if (!$userid) {
3657             $userid = $USER->id;
3658         }
3660         $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
3662         $grades = $DB->get_records('assign_grades', $params, 'attemptnumber ASC');
3664         $gradercache = array();
3665         $cangrade = has_capability('mod/assign:grade', $this->get_context());
3667         // Need gradingitem and gradingmanager.
3668         $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
3669         $controller = $gradingmanager->get_active_controller();
3671         $gradinginfo = grade_get_grades($this->get_course()->id,
3672                                         'mod',
3673                                         'assign',
3674                                         $this->get_instance()->id,
3675                                         $userid);
3677         $gradingitem = null;
3678         if (isset($gradinginfo->items[0])) {
3679             $gradingitem = $gradinginfo->items[0];
3680         }
3682         foreach ($grades as $grade) {
3683             // First lookup the grader info.
3684             if (isset($gradercache[$grade->grader])) {
3685                 $grade->grader = $gradercache[$grade->grader];
3686             } else {
3687                 // Not in cache - need to load the grader record.
3688                 $grade->grader = $DB->get_record('user', array('id'=>$grade->grader));
3689                 $gradercache[$grade->grader->id] = $grade->grader;
3690             }
3692             // Now get the gradefordisplay.
3693             if ($controller) {
3694                 $controller->set_grade_range(make_grades_menu($this->get_instance()->grade));
3695                 $grade->gradefordisplay = $controller->render_grade($PAGE,
3696                                                                      $grade->id,
3697                                                                      $gradingitem,
3698                                                                      $grade->grade,
3699                                                                      $cangrade);
3700             } else {
3701                 $grade->gradefordisplay = $this->display_grade($grade->grade, false);
3702             }
3704         }
3706         return $grades;
3707     }
3709     /**
3710      * Get the submissions for all previous attempts.
3711      *
3712      * @param int $userid If not set, $USER->id will be used.
3713      * @return array $submissions All submission records for this user (or group).
3714      */
3715     protected function get_all_submissions($userid) {
3716         global $DB, $USER;
3718         // If the userid is not null then use userid.
3719         if (!$userid) {
3720             $userid = $USER->id;
3721         }
3723         $params = array();
3725         if ($this->get_instance()->teamsubmission) {
3726             $groupid = 0;
3727             $group = $this->get_submission_group($userid);
3728             if ($group) {
3729                 $groupid = $group->id;
3730             }
3732            &n