e28ba439eed79c78336eeaa1bb489eac27c26d43
[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_DRAFT', 'draft');
31 define('ASSIGN_SUBMISSION_STATUS_SUBMITTED', 'submitted');
33 // Search filters for grading page.
34 define('ASSIGN_FILTER_SUBMITTED', 'submitted');
35 define('ASSIGN_FILTER_SINGLE_USER', 'singleuser');
36 define('ASSIGN_FILTER_REQUIRE_GRADING', 'require_grading');
38 require_once($CFG->libdir . '/accesslib.php');
39 require_once($CFG->libdir . '/formslib.php');
40 require_once($CFG->dirroot . '/repository/lib.php');
41 require_once($CFG->dirroot . '/mod/assign/mod_form.php');
42 require_once($CFG->libdir . '/gradelib.php');
43 require_once($CFG->dirroot . '/grade/grading/lib.php');
44 require_once($CFG->dirroot . '/mod/assign/feedbackplugin.php');
45 require_once($CFG->dirroot . '/mod/assign/submissionplugin.php');
46 require_once($CFG->dirroot . '/mod/assign/renderable.php');
47 require_once($CFG->dirroot . '/mod/assign/gradingtable.php');
48 require_once($CFG->libdir . '/eventslib.php');
49 require_once($CFG->libdir . '/portfolio/caller.php');
51 /**
52  * Standard base class for mod_assign (assignment types).
53  *
54  * @package   mod_assign
55  * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
56  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
57  */
58 class assign {
60     /** @var stdClass the assignment record that contains the global settings for this assign instance */
61     private $instance;
63     /** @var context the context of the course module for this assign instance
64      *               (or just the course if we are creating a new one)
65      */
66     private $context;
68     /** @var stdClass the course this assign instance belongs to */
69     private $course;
71     /** @var stdClass the admin config for all assign instances  */
72     private $adminconfig;
74     /** @var assign_renderer the custom renderer for this module */
75     private $output;
77     /** @var stdClass the course module for this assign instance */
78     private $coursemodule;
80     /** @var array cache for things like the coursemodule name or the scale menu -
81      *             only lives for a single request.
82      */
83     private $cache;
85     /** @var array list of the installed submission plugins */
86     private $submissionplugins;
88     /** @var array list of the installed feedback plugins */
89     private $feedbackplugins;
91     /** @var string action to be used to return to this page
92      *              (without repeating any form submissions etc).
93      */
94     private $returnaction = 'view';
96     /** @var array params to be used to return to this page */
97     private $returnparams = array();
99     /** @var string modulename prevents excessive calls to get_string */
100     private static $modulename = null;
102     /** @var string modulenameplural prevents excessive calls to get_string */
103     private static $modulenameplural = null;
105     /**
106      * Constructor for the base assign class.
107      *
108      * @param mixed $coursemodulecontext context|null the course module context
109      *                                   (or the course context if the coursemodule has not been
110      *                                   created yet).
111      * @param mixed $coursemodule the current course module if it was already loaded,
112      *                            otherwise this class will load one from the context as required.
113      * @param mixed $course the current course  if it was already loaded,
114      *                      otherwise this class will load one from the context as required.
115      */
116     public function __construct($coursemodulecontext, $coursemodule, $course) {
117         global $PAGE;
119         $this->context = $coursemodulecontext;
120         $this->coursemodule = $coursemodule;
121         $this->course = $course;
123         // Temporary cache only lives for a single request - used to reduce db lookups.
124         $this->cache = array();
126         $this->submissionplugins = $this->load_plugins('assignsubmission');
127         $this->feedbackplugins = $this->load_plugins('assignfeedback');
128     }
130     /**
131      * Set the action and parameters that can be used to return to the current page.
132      *
133      * @param string $action The action for the current page
134      * @param array $params An array of name value pairs which form the parameters
135      *                      to return to the current page.
136      * @return void
137      */
138     public function register_return_link($action, $params) {
139         $this->returnaction = $action;
140         $this->returnparams = $params;
141     }
143     /**
144      * Return an action that can be used to get back to the current page.
145      *
146      * @return string action
147      */
148     public function get_return_action() {
149         return $this->returnaction;
150     }
152     /**
153      * Based on the current assignment settings should we display the intro.
154      *
155      * @return bool showintro
156      */
157     protected function show_intro() {
158         if ($this->get_instance()->alwaysshowdescription ||
159                 time() > $this->get_instance()->allowsubmissionsfromdate) {
160             return true;
161         }
162         return false;
163     }
165     /**
166      * Return a list of parameters that can be used to get back to the current page.
167      *
168      * @return array params
169      */
170     public function get_return_params() {
171         return $this->returnparams;
172     }
174     /**
175      * Set the submitted form data.
176      *
177      * @param stdClass $data The form data (instance)
178      */
179     public function set_instance(stdClass $data) {
180         $this->instance = $data;
181     }
183     /**
184      * Set the context.
185      *
186      * @param context $context The new context
187      */
188     public function set_context(context $context) {
189         $this->context = $context;
190     }
192     /**
193      * Set the course data.
194      *
195      * @param stdClass $course The course data
196      */
197     public function set_course(stdClass $course) {
198         $this->course = $course;
199     }
201     /**
202      * Get list of feedback plugins installed.
203      *
204      * @return array
205      */
206     public function get_feedback_plugins() {
207         return $this->feedbackplugins;
208     }
210     /**
211      * Get list of submission plugins installed.
212      *
213      * @return array
214      */
215     public function get_submission_plugins() {
216         return $this->submissionplugins;
217     }
219     /**
220      * Is blind marking enabled and reveal identities not set yet?
221      *
222      * @return bool
223      */
224     public function is_blind_marking() {
225         return $this->get_instance()->blindmarking && !$this->get_instance()->revealidentities;
226     }
228     /**
229      * Does an assignment have submission(s) or grade(s) already?
230      *
231      * @return bool
232      */
233     public function has_submissions_or_grades() {
234         $allgrades = $this->count_grades();
235         $allsubmissions = $this->count_submissions();
236         if (($allgrades == 0) && ($allsubmissions == 0)) {
237             return false;
238         }
239         return true;
240     }
242     /**
243      * Get a specific submission plugin by its type.
244      *
245      * @param string $subtype assignsubmission | assignfeedback
246      * @param string $type
247      * @return mixed assign_plugin|null
248      */
249     public function get_plugin_by_type($subtype, $type) {
250         $shortsubtype = substr($subtype, strlen('assign'));
251         $name = $shortsubtype . 'plugins';
252         if ($name != 'feedbackplugins' && $name != 'submissionplugins') {
253             return null;
254         }
255         $pluginlist = $this->$name;
256         foreach ($pluginlist as $plugin) {
257             if ($plugin->get_type() == $type) {
258                 return $plugin;
259             }
260         }
261         return null;
262     }
264     /**
265      * Get a feedback plugin by type.
266      *
267      * @param string $type - The type of plugin e.g comments
268      * @return mixed assign_feedback_plugin|null
269      */
270     public function get_feedback_plugin_by_type($type) {
271         return $this->get_plugin_by_type('assignfeedback', $type);
272     }
274     /**
275      * Get a submission plugin by type.
276      *
277      * @param string $type - The type of plugin e.g comments
278      * @return mixed assign_submission_plugin|null
279      */
280     public function get_submission_plugin_by_type($type) {
281         return $this->get_plugin_by_type('assignsubmission', $type);
282     }
284     /**
285      * Load the plugins from the sub folders under subtype.
286      *
287      * @param string $subtype - either submission or feedback
288      * @return array - The sorted list of plugins
289      */
290     protected function load_plugins($subtype) {
291         global $CFG;
292         $result = array();
294         $names = get_plugin_list($subtype);
296         foreach ($names as $name => $path) {
297             if (file_exists($path . '/locallib.php')) {
298                 require_once($path . '/locallib.php');
300                 $shortsubtype = substr($subtype, strlen('assign'));
301                 $pluginclass = 'assign_' . $shortsubtype . '_' . $name;
303                 $plugin = new $pluginclass($this, $name);
305                 if ($plugin instanceof assign_plugin) {
306                     $idx = $plugin->get_sort_order();
307                     while (array_key_exists($idx, $result)) {
308                         $idx +=1;
309                     }
310                     $result[$idx] = $plugin;
311                 }
312             }
313         }
314         ksort($result);
315         return $result;
316     }
318     /**
319      * Display the assignment, used by view.php
320      *
321      * The assignment is displayed differently depending on your role,
322      * the settings for the assignment and the status of the assignment.
323      *
324      * @param string $action The current action if any.
325      * @return void
326      */
327     public function view($action='') {
329         $o = '';
330         $mform = null;
331         $notices = array();
333         // Handle form submissions first.
334         if ($action == 'savesubmission') {
335             $action = 'editsubmission';
336             if ($this->process_save_submission($mform, $notices)) {
337                 $action = 'view';
338             }
339         } else if ($action == 'lock') {
340             $this->process_lock();
341             $action = 'grading';
342         } else if ($action == 'reverttodraft') {
343             $this->process_revert_to_draft();
344             $action = 'grading';
345         } else if ($action == 'unlock') {
346             $this->process_unlock();
347             $action = 'grading';
348         } else if ($action == 'confirmsubmit') {
349             $action = 'submit';
350             if ($this->process_submit_for_grading($mform)) {
351                 $action = 'view';
352             }
353         } else if ($action == 'gradingbatchoperation') {
354             $action = $this->process_grading_batch_operation($mform);
355         } else if ($action == 'submitgrade') {
356             if (optional_param('saveandshownext', null, PARAM_RAW)) {
357                 // Save and show next.
358                 $action = 'grade';
359                 if ($this->process_save_grade($mform)) {
360                     $action = 'nextgrade';
361                 }
362             } else if (optional_param('nosaveandprevious', null, PARAM_RAW)) {
363                 $action = 'previousgrade';
364             } else if (optional_param('nosaveandnext', null, PARAM_RAW)) {
365                 // Show next button.
366                 $action = 'nextgrade';
367             } else if (optional_param('savegrade', null, PARAM_RAW)) {
368                 // Save changes button.
369                 $action = 'grade';
370                 if ($this->process_save_grade($mform)) {
371                     $action = 'grading';
372                 }
373             } else {
374                 // Cancel button.
375                 $action = 'grading';
376             }
377         } else if ($action == 'quickgrade') {
378             $message = $this->process_save_quick_grades();
379             $action = 'quickgradingresult';
380         } else if ($action == 'saveoptions') {
381             $this->process_save_grading_options();
382             $action = 'grading';
383         } else if ($action == 'saveextension') {
384             $action = 'grantextension';
385             if ($this->process_save_extension($mform)) {
386                 $action = 'grading';
387             }
388         } else if ($action == 'revealidentitiesconfirm') {
389             $this->process_reveal_identities();
390             $action = 'grading';
391         }
393         $returnparams = array('rownum'=>optional_param('rownum', 0, PARAM_INT));
394         $this->register_return_link($action, $returnparams);
396         // Now show the right view page.
397         if ($action == 'previousgrade') {
398             $mform = null;
399             $o .= $this->view_single_grade_page($mform, -1);
400         } else if ($action == 'quickgradingresult') {
401             $mform = null;
402             $o .= $this->view_quickgrading_result($message);
403         } else if ($action == 'nextgrade') {
404             $mform = null;
405             $o .= $this->view_single_grade_page($mform, 1);
406         } else if ($action == 'grade') {
407             $o .= $this->view_single_grade_page($mform);
408         } else if ($action == 'viewpluginassignfeedback') {
409             $o .= $this->view_plugin_content('assignfeedback');
410         } else if ($action == 'viewpluginassignsubmission') {
411             $o .= $this->view_plugin_content('assignsubmission');
412         } else if ($action == 'editsubmission') {
413             $o .= $this->view_edit_submission_page($mform, $notices);
414         } else if ($action == 'grading') {
415             $o .= $this->view_grading_page();
416         } else if ($action == 'downloadall') {
417             $o .= $this->download_submissions();
418         } else if ($action == 'submit') {
419             $o .= $this->check_submit_for_grading($mform);
420         } else if ($action == 'grantextension') {
421             $o .= $this->view_grant_extension($mform);
422         } else if ($action == 'revealidentities') {
423             $o .= $this->view_reveal_identities_confirm($mform);
424         } else if ($action == 'plugingradingbatchoperation') {
425             $o .= $this->view_plugin_grading_batch_operation($mform);
426         } else if ($action == 'viewpluginpage') {
427              $o .= $this->view_plugin_page();
428         } else if ($action == 'viewcourseindex') {
429              $o .= $this->view_course_index();
430         } else {
431             $o .= $this->view_submission_page();
432         }
434         return $o;
435     }
437     /**
438      * Add this instance to the database.
439      *
440      * @param stdClass $formdata The data submitted from the form
441      * @param bool $callplugins This is used to skip the plugin code
442      *             when upgrading an old assignment to a new one (the plugins get called manually)
443      * @return mixed false if an error occurs or the int id of the new instance
444      */
445     public function add_instance(stdClass $formdata, $callplugins) {
446         global $DB;
448         $err = '';
450         // Add the database record.
451         $update = new stdClass();
452         $update->name = $formdata->name;
453         $update->timemodified = time();
454         $update->timecreated = time();
455         $update->course = $formdata->course;
456         $update->courseid = $formdata->course;
457         $update->intro = $formdata->intro;
458         $update->introformat = $formdata->introformat;
459         $update->alwaysshowdescription = $formdata->alwaysshowdescription;
460         $update->submissiondrafts = $formdata->submissiondrafts;
461         $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
462         $update->sendnotifications = $formdata->sendnotifications;
463         $update->sendlatenotifications = $formdata->sendlatenotifications;
464         $update->duedate = $formdata->duedate;
465         $update->cutoffdate = $formdata->cutoffdate;
466         $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
467         $update->grade = $formdata->grade;
468         $update->completionsubmit = !empty($formdata->completionsubmit);
469         $update->teamsubmission = $formdata->teamsubmission;
470         $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
471         $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
472         $update->blindmarking = $formdata->blindmarking;
474         $returnid = $DB->insert_record('assign', $update);
475         $this->instance = $DB->get_record('assign', array('id'=>$returnid), '*', MUST_EXIST);
476         // Cache the course record.
477         $this->course = $DB->get_record('course', array('id'=>$formdata->course), '*', MUST_EXIST);
479         if ($callplugins) {
480             // Call save_settings hook for submission plugins.
481             foreach ($this->submissionplugins as $plugin) {
482                 if (!$this->update_plugin_instance($plugin, $formdata)) {
483                     print_error($plugin->get_error());
484                     return false;
485                 }
486             }
487             foreach ($this->feedbackplugins as $plugin) {
488                 if (!$this->update_plugin_instance($plugin, $formdata)) {
489                     print_error($plugin->get_error());
490                     return false;
491                 }
492             }
494             // In the case of upgrades the coursemodule has not been set,
495             // so we need to wait before calling these two.
496             $this->update_calendar($formdata->coursemodule);
497             $this->update_gradebook(false, $formdata->coursemodule);
499         }
501         $update = new stdClass();
502         $update->id = $this->get_instance()->id;
503         $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
504         $DB->update_record('assign', $update);
506         return $returnid;
507     }
509     /**
510      * Delete all grades from the gradebook for this assignment.
511      *
512      * @return bool
513      */
514     protected function delete_grades() {
515         global $CFG;
517         $result = grade_update('mod/assign',
518                                $this->get_course()->id,
519                                'mod',
520                                'assign',
521                                $this->get_instance()->id,
522                                0,
523                                null,
524                                array('deleted'=>1));
525         return $result == GRADE_UPDATE_OK;
526     }
528     /**
529      * Delete this instance from the database.
530      *
531      * @return bool false if an error occurs
532      */
533     public function delete_instance() {
534         global $DB;
535         $result = true;
537         foreach ($this->submissionplugins as $plugin) {
538             if (!$plugin->delete_instance()) {
539                 print_error($plugin->get_error());
540                 $result = false;
541             }
542         }
543         foreach ($this->feedbackplugins as $plugin) {
544             if (!$plugin->delete_instance()) {
545                 print_error($plugin->get_error());
546                 $result = false;
547             }
548         }
550         // Delete files associated with this assignment.
551         $fs = get_file_storage();
552         if (! $fs->delete_area_files($this->context->id) ) {
553             $result = false;
554         }
556         // Delete_records will throw an exception if it fails - so no need for error checking here.
557         $DB->delete_records('assign_submission', array('assignment'=>$this->get_instance()->id));
558         $DB->delete_records('assign_grades', array('assignment'=>$this->get_instance()->id));
559         $DB->delete_records('assign_plugin_config', array('assignment'=>$this->get_instance()->id));
561         // Delete items from the gradebook.
562         if (! $this->delete_grades()) {
563             $result = false;
564         }
566         // Delete the instance.
567         $DB->delete_records('assign', array('id'=>$this->get_instance()->id));
569         return $result;
570     }
572     /**
573      * Actual implementation of the reset course functionality, delete all the
574      * assignment submissions for course $data->courseid.
575      *
576      * @param $data the data submitted from the reset course.
577      * @return array status array
578      */
579     public function reset_userdata($data) {
580         global $CFG, $DB;
582         $componentstr = get_string('modulenameplural', 'assign');
583         $status = array();
585         $fs = get_file_storage();
586         if (!empty($data->reset_assign_submissions)) {
587             // Delete files associated with this assignment.
588             foreach ($this->submissionplugins as $plugin) {
589                 $fileareas = array();
590                 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
591                 $fileareas = $plugin->get_file_areas();
592                 foreach ($fileareas as $filearea) {
593                     $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
594                 }
596                 if (!$plugin->delete_instance()) {
597                     $status[] = array('component'=>$componentstr,
598                                       'item'=>get_string('deleteallsubmissions', 'assign'),
599                                       'error'=>$plugin->get_error());
600                 }
601             }
603             foreach ($this->feedbackplugins as $plugin) {
604                 $fileareas = array();
605                 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
606                 $fileareas = $plugin->get_file_areas();
607                 foreach ($fileareas as $filearea) {
608                     $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
609                 }
611                 if (!$plugin->delete_instance()) {
612                     $status[] = array('component'=>$componentstr,
613                                       'item'=>get_string('deleteallsubmissions', 'assign'),
614                                       'error'=>$plugin->get_error());
615                 }
616             }
618             $assignssql = 'SELECT a.id
619                              FROM {assign} a
620                            WHERE a.course=:course';
621             $params = array('course'=>$data->courseid);
623             $DB->delete_records_select('assign_submission', "assignment IN ($assignssql)", $params);
625             $status[] = array('component'=>$componentstr,
626                               'item'=>get_string('deleteallsubmissions', 'assign'),
627                               'error'=>false);
629             if (!empty($data->reset_gradebook_grades)) {
630                 $DB->delete_records_select('assign_grades', "assignment IN ($assignssql)", $params);
631                 // Remove all grades from gradebook.
632                 require_once($CFG->dirroot.'/mod/assign/lib.php');
633                 assign_reset_gradebook($data->courseid);
634             }
635         }
636         // Updating dates - shift may be negative too.
637         if ($data->timeshift) {
638             shift_course_mod_dates('assign',
639                                     array('duedate', 'allowsubmissionsfromdate', 'cutoffdate'),
640                                     $data->timeshift,
641                                     $data->courseid);
642             $status[] = array('component'=>$componentstr,
643                               'item'=>get_string('datechanged'),
644                               'error'=>false);
645         }
647         return $status;
648     }
650     /**
651      * Update the settings for a single plugin.
652      *
653      * @param assign_plugin $plugin The plugin to update
654      * @param stdClass $formdata The form data
655      * @return bool false if an error occurs
656      */
657     protected function update_plugin_instance(assign_plugin $plugin, stdClass $formdata) {
658         if ($plugin->is_visible()) {
659             $enabledname = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
660             if ($formdata->$enabledname) {
661                 $plugin->enable();
662                 if (!$plugin->save_settings($formdata)) {
663                     print_error($plugin->get_error());
664                     return false;
665                 }
666             } else {
667                 $plugin->disable();
668             }
669         }
670         return true;
671     }
673     /**
674      * Update the gradebook information for this assignment.
675      *
676      * @param bool $reset If true, will reset all grades in the gradbook for this assignment
677      * @param int $coursemoduleid This is required because it might not exist in the database yet
678      * @return bool
679      */
680     public function update_gradebook($reset, $coursemoduleid) {
681         global $CFG;
683         require_once($CFG->dirroot.'/mod/assign/lib.php');
684         $assign = clone $this->get_instance();
685         $assign->cmidnumber = $coursemoduleid;
686         $param = null;
687         if ($reset) {
688             $param = 'reset';
689         }
691         return assign_grade_item_update($assign, $param);
692     }
694     /**
695      * Load and cache the admin config for this module.
696      *
697      * @return stdClass the plugin config
698      */
699     public function get_admin_config() {
700         if ($this->adminconfig) {
701             return $this->adminconfig;
702         }
703         $this->adminconfig = get_config('assign');
704         return $this->adminconfig;
705     }
707     /**
708      * Update the calendar entries for this assignment.
709      *
710      * @param int $coursemoduleid - Required to pass this in because it might
711      *                              not exist in the database yet.
712      * @return bool
713      */
714     public function update_calendar($coursemoduleid) {
715         global $DB, $CFG;
716         require_once($CFG->dirroot.'/calendar/lib.php');
718         // Special case for add_instance as the coursemodule has not been set yet.
719         $instance = $this->get_instance();
721         if ($instance->duedate) {
722             $event = new stdClass();
724             $params = array('modulename'=>'assign', 'instance'=>$instance->id);
725             $event->id = $DB->get_field('event',
726                                         'id',
727                                         $params);
729             if ($event->id) {
730                 $event->name        = $instance->name;
731                 $event->description = format_module_intro('assign', $instance, $coursemoduleid);
732                 $event->timestart   = $instance->duedate;
734                 $calendarevent = calendar_event::load($event->id);
735                 $calendarevent->update($event);
736             } else {
737                 $event = new stdClass();
738                 $event->name        = $instance->name;
739                 $event->description = format_module_intro('assign', $instance, $coursemoduleid);
740                 $event->courseid    = $instance->course;
741                 $event->groupid     = 0;
742                 $event->userid      = 0;
743                 $event->modulename  = 'assign';
744                 $event->instance    = $instance->id;
745                 $event->eventtype   = 'due';
746                 $event->timestart   = $instance->duedate;
747                 $event->timeduration = 0;
749                 calendar_event::create($event);
750             }
751         } else {
752             $DB->delete_records('event', array('modulename'=>'assign', 'instance'=>$instance->id));
753         }
754     }
757     /**
758      * Update this instance in the database.
759      *
760      * @param stdClass $formdata - the data submitted from the form
761      * @return bool false if an error occurs
762      */
763     public function update_instance($formdata) {
764         global $DB;
766         $update = new stdClass();
767         $update->id = $formdata->instance;
768         $update->name = $formdata->name;
769         $update->timemodified = time();
770         $update->course = $formdata->course;
771         $update->intro = $formdata->intro;
772         $update->introformat = $formdata->introformat;
773         $update->alwaysshowdescription = $formdata->alwaysshowdescription;
774         $update->submissiondrafts = $formdata->submissiondrafts;
775         $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
776         $update->sendnotifications = $formdata->sendnotifications;
777         $update->sendlatenotifications = $formdata->sendlatenotifications;
778         $update->duedate = $formdata->duedate;
779         $update->cutoffdate = $formdata->cutoffdate;
780         $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
781         $update->grade = $formdata->grade;
782         $update->completionsubmit = !empty($formdata->completionsubmit);
783         $update->teamsubmission = $formdata->teamsubmission;
784         $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
785         $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
786         $update->blindmarking = $formdata->blindmarking;
788         $result = $DB->update_record('assign', $update);
789         $this->instance = $DB->get_record('assign', array('id'=>$update->id), '*', MUST_EXIST);
791         // Load the assignment so the plugins have access to it.
793         // Call save_settings hook for submission plugins.
794         foreach ($this->submissionplugins as $plugin) {
795             if (!$this->update_plugin_instance($plugin, $formdata)) {
796                 print_error($plugin->get_error());
797                 return false;
798             }
799         }
800         foreach ($this->feedbackplugins as $plugin) {
801             if (!$this->update_plugin_instance($plugin, $formdata)) {
802                 print_error($plugin->get_error());
803                 return false;
804             }
805         }
807         $this->update_calendar($this->get_course_module()->id);
808         $this->update_gradebook(false, $this->get_course_module()->id);
810         $update = new stdClass();
811         $update->id = $this->get_instance()->id;
812         $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
813         $DB->update_record('assign', $update);
815         return $result;
816     }
818     /**
819      * Add elements in grading plugin form.
820      *
821      * @param mixed $grade stdClass|null
822      * @param MoodleQuickForm $mform
823      * @param stdClass $data
824      * @param int $userid - The userid we are grading
825      * @return void
826      */
827     protected function add_plugin_grade_elements($grade, MoodleQuickForm $mform, stdClass $data, $userid) {
828         foreach ($this->feedbackplugins as $plugin) {
829             if ($plugin->is_enabled() && $plugin->is_visible()) {
830                 $mform->addElement('header', 'header_' . $plugin->get_type(), $plugin->get_name());
831                 if (!$plugin->get_form_elements_for_user($grade, $mform, $data, $userid)) {
832                     $mform->removeElement('header_' . $plugin->get_type());
833                 }
834             }
835         }
836     }
840     /**
841      * Add one plugins settings to edit plugin form.
842      *
843      * @param assign_plugin $plugin The plugin to add the settings from
844      * @param MoodleQuickForm $mform The form to add the configuration settings to.
845      *                               This form is modified directly (not returned).
846      * @return void
847      */
848     protected function add_plugin_settings(assign_plugin $plugin, MoodleQuickForm $mform) {
849         global $CFG;
850         if ($plugin->is_visible()) {
851             $mform->addElement('selectyesno',
852                                $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled',
853                                $plugin->get_name());
854             $mform->addHelpButton($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled',
855                                   'enabled',
856                                   $plugin->get_subtype() . '_' . $plugin->get_type());
858             $default = get_config($plugin->get_subtype() . '_' . $plugin->get_type(), 'default');
859             if ($plugin->get_config('enabled') !== false) {
860                 $default = $plugin->is_enabled();
861             }
862             $mform->setDefault($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $default);
864             $plugin->get_settings($mform);
866         }
867     }
869     /**
870      * Add settings to edit plugin form.
871      *
872      * @param MoodleQuickForm $mform The form to add the configuration settings to.
873      *                               This form is modified directly (not returned).
874      * @return void
875      */
876     public function add_all_plugin_settings(MoodleQuickForm $mform) {
877         $mform->addElement('header', 'general', get_string('submissionsettings', 'assign'));
879         foreach ($this->submissionplugins as $plugin) {
880             $this->add_plugin_settings($plugin, $mform);
882         }
883         $mform->addElement('header', 'general', get_string('feedbacksettings', 'assign'));
884         foreach ($this->feedbackplugins as $plugin) {
885             $this->add_plugin_settings($plugin, $mform);
886         }
887     }
889     /**
890      * Allow each plugin an opportunity to update the defaultvalues
891      * passed in to the settings form (needed to set up draft areas for
892      * editor and filemanager elements)
893      *
894      * @param array $defaultvalues
895      */
896     public function plugin_data_preprocessing(&$defaultvalues) {
897         foreach ($this->submissionplugins as $plugin) {
898             if ($plugin->is_visible()) {
899                 $plugin->data_preprocessing($defaultvalues);
900             }
901         }
902         foreach ($this->feedbackplugins as $plugin) {
903             if ($plugin->is_visible()) {
904                 $plugin->data_preprocessing($defaultvalues);
905             }
906         }
907     }
909     /**
910      * Get the name of the current module.
911      *
912      * @return string the module name (Assignment)
913      */
914     protected function get_module_name() {
915         if (isset(self::$modulename)) {
916             return self::$modulename;
917         }
918         self::$modulename = get_string('modulename', 'assign');
919         return self::$modulename;
920     }
922     /**
923      * Get the plural name of the current module.
924      *
925      * @return string the module name plural (Assignments)
926      */
927     protected function get_module_name_plural() {
928         if (isset(self::$modulenameplural)) {
929             return self::$modulenameplural;
930         }
931         self::$modulenameplural = get_string('modulenameplural', 'assign');
932         return self::$modulenameplural;
933     }
935     /**
936      * Has this assignment been constructed from an instance?
937      *
938      * @return bool
939      */
940     public function has_instance() {
941         return $this->instance || $this->get_course_module();
942     }
944     /**
945      * Get the settings for the current instance of this assignment
946      *
947      * @return stdClass The settings
948      */
949     public function get_instance() {
950         global $DB;
951         if ($this->instance) {
952             return $this->instance;
953         }
954         if ($this->get_course_module()) {
955             $params = array('id' => $this->get_course_module()->instance);
956             $this->instance = $DB->get_record('assign', $params, '*', MUST_EXIST);
957         }
958         if (!$this->instance) {
959             throw new coding_exception('Improper use of the assignment class. ' .
960                                        'Cannot load the assignment record.');
961         }
962         return $this->instance;
963     }
965     /**
966      * Get the context of the current course.
967      *
968      * @return mixed context|null The course context
969      */
970     public function get_course_context() {
971         if (!$this->context && !$this->course) {
972             throw new coding_exception('Improper use of the assignment class. ' .
973                                        'Cannot load the course context.');
974         }
975         if ($this->context) {
976             return $this->context->get_course_context();
977         } else {
978             return context_course::instance($this->course->id);
979         }
980     }
983     /**
984      * Get the current course module.
985      *
986      * @return mixed stdClass|null The course module
987      */
988     public function get_course_module() {
989         if ($this->coursemodule) {
990             return $this->coursemodule;
991         }
992         if (!$this->context) {
993             return null;
994         }
996         if ($this->context->contextlevel == CONTEXT_MODULE) {
997             $this->coursemodule = get_coursemodule_from_id('assign',
998                                                            $this->context->instanceid,
999                                                            0,
1000                                                            false,
1001                                                            MUST_EXIST);
1002             return $this->coursemodule;
1003         }
1004         return null;
1005     }
1007     /**
1008      * Get context module.
1009      *
1010      * @return context
1011      */
1012     public function get_context() {
1013         return $this->context;
1014     }
1016     /**
1017      * Get the current course.
1018      *
1019      * @return mixed stdClass|null The course
1020      */
1021     public function get_course() {
1022         global $DB;
1024         if ($this->course) {
1025             return $this->course;
1026         }
1028         if (!$this->context) {
1029             return null;
1030         }
1031         $params = array('id' => $this->get_course_context()->instanceid);
1032         $this->course = $DB->get_record('course', $params, '*', MUST_EXIST);
1034         return $this->course;
1035     }
1037     /**
1038      * Return a grade in user-friendly form, whether it's a scale or not.
1039      *
1040      * @param mixed $grade int|null
1041      * @param boolean $editing Are we allowing changes to this grade?
1042      * @param int $userid The user id the grade belongs to
1043      * @param int $modified Timestamp from when the grade was last modified
1044      * @return string User-friendly representation of grade
1045      */
1046     public function display_grade($grade, $editing, $userid=0, $modified=0) {
1047         global $DB;
1049         static $scalegrades = array();
1051         $o = '';
1053         if ($this->get_instance()->grade >= 0) {
1054             // Normal number.
1055             if ($editing && $this->get_instance()->grade > 0) {
1056                 if ($grade < 0) {
1057                     $displaygrade = '';
1058                 } else {
1059                     $displaygrade = format_float($grade);
1060                 }
1061                 $o .= '<label class="accesshide" for="quickgrade_' . $userid . '">' .
1062                        get_string('usergrade', 'assign') .
1063                        '</label>';
1064                 $o .= '<input type="text"
1065                               id="quickgrade_' . $userid . '"
1066                               name="quickgrade_' . $userid . '"
1067                               value="' .  $displaygrade . '"
1068                               size="6"
1069                               maxlength="10"
1070                               class="quickgrade"/>';
1071                 $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade, 2);
1072                 $o .= '<input type="hidden"
1073                               name="grademodified_' . $userid . '"
1074                               value="' . $modified . '"/>';
1075                 return $o;
1076             } else {
1077                 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
1078                 if ($grade == -1 || $grade === null) {
1079                     $o .= '-';
1080                     return $o;
1081                 } else {
1082                     $o .= format_float($grade, 2) .
1083                           '&nbsp;/&nbsp;' .
1084                           format_float($this->get_instance()->grade, 2);
1085                     return $o;
1086                 }
1087             }
1089         } else {
1090             // Scale.
1091             if (empty($this->cache['scale'])) {
1092                 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
1093                     $this->cache['scale'] = make_menu_from_list($scale->scale);
1094                 } else {
1095                     $o .= '-';
1096                     return $o;
1097                 }
1098             }
1099             if ($editing) {
1100                 $o .= '<label class="accesshide"
1101                               for="quickgrade_' . $userid . '">' .
1102                       get_string('usergrade', 'assign') .
1103                       '</label>';
1104                 $o .= '<select name="quickgrade_' . $userid . '" class="quickgrade">';
1105                 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
1106                 foreach ($this->cache['scale'] as $optionid => $option) {
1107                     $selected = '';
1108                     if ($grade == $optionid) {
1109                         $selected = 'selected="selected"';
1110                     }
1111                     $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
1112                 }
1113                 $o .= '</select>';
1114                 $o .= '<input type="hidden" ' .
1115                              'name="grademodified_' . $userid . '" ' .
1116                              'value="' . $modified . '"/>';
1117                 return $o;
1118             } else {
1119                 $scaleid = (int)$grade;
1120                 if (isset($this->cache['scale'][$scaleid])) {
1121                     $o .= $this->cache['scale'][$scaleid];
1122                     return $o;
1123                 }
1124                 $o .= '-';
1125                 return $o;
1126             }
1127         }
1128     }
1130     /**
1131      * Load a list of users enrolled in the current course with the specified permission and group.
1132      * 0 for no group.
1133      *
1134      * @param int $currentgroup
1135      * @param bool $idsonly
1136      * @return array List of user records
1137      */
1138     public function list_participants($currentgroup, $idsonly) {
1139         if ($idsonly) {
1140             return get_enrolled_users($this->context, 'mod/assign:submit', $currentgroup, 'u.id');
1141         } else {
1142             return get_enrolled_users($this->context, 'mod/assign:submit', $currentgroup);
1143         }
1144     }
1146     /**
1147      * Load a count of valid teams for this assignment.
1148      *
1149      * @return int number of valid teams
1150      */
1151     public function count_teams() {
1153         $groups = groups_get_all_groups($this->get_course()->id,
1154                                         0,
1155                                         $this->get_instance()->teamsubmissiongroupingid,
1156                                         'g.id');
1157         $count = count($groups);
1159         // See if there are any users in the default group.
1160         $defaultusers = $this->get_submission_group_members(0, true);
1161         if (count($defaultusers) > 0) {
1162             $count += 1;
1163         }
1164         return $count;
1165     }
1167     /**
1168      * Load a count of users enrolled in the current course with the specified permission and group.
1169      * 0 for no group.
1170      *
1171      * @param int $currentgroup
1172      * @return int number of matching users
1173      */
1174     public function count_participants($currentgroup) {
1175         return count_enrolled_users($this->context, 'mod/assign:submit', $currentgroup);
1176     }
1178     /**
1179      * Load a count of users submissions in the current module that require grading
1180      * This means the submission modification time is more recent than the
1181      * grading modification time and the status is SUBMITTED.
1182      *
1183      * @return int number of matching submissions
1184      */
1185     public function count_submissions_need_grading() {
1186         global $DB;
1188         if ($this->get_instance()->teamsubmission) {
1189             // This does not make sense for group assignment because the submission is shared.
1190             return 0;
1191         }
1193         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1194         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1196         $params['assignid'] = $this->get_instance()->id;
1197         $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1199         $sql = 'SELECT COUNT(s.userid)
1200                    FROM {assign_submission} s
1201                    LEFT JOIN {assign_grades} g ON
1202                         s.assignment = g.assignment AND
1203                         s.userid = g.userid
1204                    JOIN(' . $esql . ') e ON e.id = s.userid
1205                    WHERE
1206                         s.assignment = :assignid AND
1207                         s.timemodified IS NOT NULL AND
1208                         s.status = :submitted AND
1209                         (s.timemodified > g.timemodified OR g.timemodified IS NULL)';
1211         return $DB->count_records_sql($sql, $params);
1212     }
1214     /**
1215      * Load a count of grades.
1216      *
1217      * @return int number of grades
1218      */
1219     public function count_grades() {
1220         global $DB;
1222         if (!$this->has_instance()) {
1223             return 0;
1224         }
1226         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1227         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1229         $params['assignid'] = $this->get_instance()->id;
1231         $sql = 'SELECT COUNT(g.userid)
1232                    FROM {assign_grades} g
1233                    JOIN(' . $esql . ') e ON e.id = g.userid
1234                    WHERE g.assignment = :assignid';
1236         return $DB->count_records_sql($sql, $params);
1237     }
1239     /**
1240      * Load a count of submissions.
1241      *
1242      * @return int number of submissions
1243      */
1244     public function count_submissions() {
1245         global $DB;
1247         if (!$this->has_instance()) {
1248             return 0;
1249         }
1251         $params = array();
1253         if ($this->get_instance()->teamsubmission) {
1254             // We cannot join on the enrolment tables for group submissions (no userid).
1255             $sql = 'SELECT COUNT(s.groupid)
1256                         FROM {assign_submission} s
1257                         WHERE
1258                             s.assignment = :assignid AND
1259                             s.timemodified IS NOT NULL AND
1260                             s.userid = :groupuserid';
1262             $params['assignid'] = $this->get_instance()->id;
1263             $params['groupuserid'] = 0;
1264         } else {
1265             $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1266             list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1268             $params['assignid'] = $this->get_instance()->id;
1270             $sql = 'SELECT COUNT(s.userid)
1271                        FROM {assign_submission} s
1272                        JOIN(' . $esql . ') e ON e.id = s.userid
1273                        WHERE
1274                             s.assignment = :assignid AND
1275                             s.timemodified IS NOT NULL';
1276         }
1278         return $DB->count_records_sql($sql, $params);
1279     }
1281     /**
1282      * Load a count of submissions with a specified status.
1283      *
1284      * @param string $status The submission status - should match one of the constants
1285      * @return int number of matching submissions
1286      */
1287     public function count_submissions_with_status($status) {
1288         global $DB;
1290         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1291         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1293         $params['assignid'] = $this->get_instance()->id;
1294         $params['submissionstatus'] = $status;
1296         if ($this->get_instance()->teamsubmission) {
1297             $sql = 'SELECT COUNT(s.groupid)
1298                         FROM {assign_submission} s
1299                         WHERE
1300                             s.assignment = :assignid AND
1301                             s.timemodified IS NOT NULL AND
1302                             s.userid = :groupuserid AND
1303                             s.status = :submissionstatus';
1304             $params['groupuserid'] = 0;
1305         } else {
1306             $sql = 'SELECT COUNT(s.userid)
1307                         FROM {assign_submission} s
1308                         JOIN(' . $esql . ') e ON e.id = s.userid
1309                         WHERE
1310                             s.assignment = :assignid AND
1311                             s.timemodified IS NOT NULL AND
1312                             s.status = :submissionstatus';
1313         }
1315         return $DB->count_records_sql($sql, $params);
1316     }
1318     /**
1319      * Utility function to get the userid for every row in the grading table
1320      * so the order can be frozen while we iterate it.
1321      *
1322      * @return array An array of userids
1323      */
1324     protected function get_grading_userid_list() {
1325         $filter = get_user_preferences('assign_filter', '');
1326         $table = new assign_grading_table($this, 0, $filter, 0, false);
1328         $useridlist = $table->get_column_data('userid');
1330         return $useridlist;
1331     }
1333     /**
1334      * Generate zip file from array of given files.
1335      *
1336      * @param array $filesforzipping - array of files to pass into archive_to_pathname.
1337      *                                 This array is indexed by the final file name and each
1338      *                                 element in the array is an instance of a stored_file object.
1339      * @return path of temp file - note this returned file does
1340      *         not have a .zip extension - it is a temp file.
1341      */
1342     protected function pack_files($filesforzipping) {
1343         global $CFG;
1344         // Create path for new zip file.
1345         $tempzip = tempnam($CFG->tempdir . '/', 'assignment_');
1346         // Zip files.
1347         $zipper = new zip_packer();
1348         if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
1349             return $tempzip;
1350         }
1351         return false;
1352     }
1354     /**
1355      * Finds all assignment notifications that have yet to be mailed out, and mails them.
1356      *
1357      * Cron function to be run periodically according to the moodle cron.
1358      *
1359      * @return bool
1360      */
1361     public static function cron() {
1362         global $DB;
1364         // Only ever send a max of one days worth of updates.
1365         $yesterday = time() - (24 * 3600);
1366         $timenow   = time();
1368         // Collect all submissions from the past 24 hours that require mailing.
1369         $sql = 'SELECT s.*, a.course, a.name, a.blindmarking, a.revealidentities,
1370                        g.*, g.id as gradeid, g.timemodified as lastmodified
1371                  FROM {assign} a
1372                  JOIN {assign_grades} g ON g.assignment = a.id
1373             LEFT JOIN {assign_submission} s ON s.assignment = a.id AND s.userid = g.userid
1374                 WHERE g.timemodified >= :yesterday AND
1375                       g.timemodified <= :today AND
1376                       g.mailed = 0';
1378         $params = array('yesterday' => $yesterday, 'today' => $timenow);
1379         $submissions = $DB->get_records_sql($sql, $params);
1381         if (empty($submissions)) {
1382             return true;
1383         }
1385         mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
1387         // Preload courses we are going to need those.
1388         $courseids = array();
1389         foreach ($submissions as $submission) {
1390             $courseids[] = $submission->course;
1391         }
1393         // Filter out duplicates.
1394         $courseids = array_unique($courseids);
1395         $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1396         list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
1397         $sql = 'SELECT c.*, ' . $ctxselect .
1398                   ' FROM {course} c
1399              LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
1400                  WHERE c.id ' . $courseidsql;
1402         $params['contextlevel'] = CONTEXT_COURSE;
1403         $courses = $DB->get_records_sql($sql, $params);
1405         // Clean up... this could go on for a while.
1406         unset($courseids);
1407         unset($ctxselect);
1408         unset($courseidsql);
1409         unset($params);
1411         // Simple array we'll use for caching modules.
1412         $modcache = array();
1414         // Message students about new feedback.
1415         foreach ($submissions as $submission) {
1417             mtrace("Processing assignment submission $submission->id ...");
1419             // Do not cache user lookups - could be too many.
1420             if (!$user = $DB->get_record('user', array('id'=>$submission->userid))) {
1421                 mtrace('Could not find user ' . $submission->userid);
1422                 continue;
1423             }
1425             // Use a cache to prevent the same DB queries happening over and over.
1426             if (!array_key_exists($submission->course, $courses)) {
1427                 mtrace('Could not find course ' . $submission->course);
1428                 continue;
1429             }
1430             $course = $courses[$submission->course];
1431             if (isset($course->ctxid)) {
1432                 // Context has not yet been preloaded. Do so now.
1433                 context_helper::preload_from_record($course);
1434             }
1436             // Override the language and timezone of the "current" user, so that
1437             // mail is customised for the receiver.
1438             cron_setup_user($user, $course);
1440             // Context lookups are already cached.
1441             $coursecontext = context_course::instance($course->id);
1442             if (!is_enrolled($coursecontext, $user->id)) {
1443                 $courseshortname = format_string($course->shortname,
1444                                                  true,
1445                                                  array('context' => $coursecontext));
1446                 mtrace(fullname($user) . ' not an active participant in ' . $courseshortname);
1447                 continue;
1448             }
1450             if (!$grader = $DB->get_record('user', array('id'=>$submission->grader))) {
1451                 mtrace('Could not find grader ' . $submission->grader);
1452                 continue;
1453             }
1455             if (!array_key_exists($submission->assignment, $modcache)) {
1456                 $mod = get_coursemodule_from_instance('assign', $submission->assignment, $course->id);
1457                 if (empty($mod)) {
1458                     mtrace('Could not find course module for assignment id ' . $submission->assignment);
1459                     continue;
1460                 }
1461                 $modcache[$submission->assignment] = $mod;
1462             } else {
1463                 $mod = $modcache[$submission->assignment];
1464             }
1465             // Context lookups are already cached.
1466             $contextmodule = context_module::instance($mod->id);
1468             if (!$mod->visible) {
1469                 // Hold mail notification for hidden assignments until later.
1470                 continue;
1471             }
1473             // Need to send this to the student.
1474             $messagetype = 'feedbackavailable';
1475             $eventtype = 'assign_notification';
1476             $updatetime = $submission->lastmodified;
1477             $modulename = get_string('modulename', 'assign');
1479             $uniqueid = 0;
1480             if ($submission->blindmarking && !$submission->revealidentities) {
1481                 $uniqueid = self::get_uniqueid_for_user_static($submission->assignment, $user->id);
1482             }
1483             $showusers = $submission->blindmarking && !$submission->revealidentities;
1484             self::send_assignment_notification($grader,
1485                                                $user,
1486                                                $messagetype,
1487                                                $eventtype,
1488                                                $updatetime,
1489                                                $mod,
1490                                                $contextmodule,
1491                                                $course,
1492                                                $modulename,
1493                                                $submission->name,
1494                                                $showusers,
1495                                                $uniqueid);
1497             $grade = new stdClass();
1498             $grade->id = $submission->gradeid;
1499             $grade->mailed = 1;
1500             $DB->update_record('assign_grades', $grade);
1502             mtrace('Done');
1503         }
1504         mtrace('Done processing ' . count($submissions) . ' assignment submissions');
1506         cron_setup_user();
1508         // Free up memory just to be sure.
1509         unset($courses);
1510         unset($modcache);
1512         return true;
1513     }
1515     /**
1516      * Mark in the database that this grade record should have an update notification sent by cron.
1517      *
1518      * @param stdClass $grade a grade record keyed on id
1519      * @return bool true for success
1520      */
1521     public function notify_grade_modified($grade) {
1522         global $DB;
1524         $grade->timemodified = time();
1525         if ($grade->mailed != 1) {
1526             $grade->mailed = 0;
1527         }
1529         return $DB->update_record('assign_grades', $grade);
1530     }
1532     /**
1533      * Update a grade in the grade table for the assignment and in the gradebook.
1534      *
1535      * @param stdClass $grade a grade record keyed on id
1536      * @return bool true for success
1537      */
1538     public function update_grade($grade) {
1539         global $DB;
1541         $grade->timemodified = time();
1543         if ($grade->grade && $grade->grade != -1) {
1544             if ($this->get_instance()->grade > 0) {
1545                 if (!is_numeric($grade->grade)) {
1546                     return false;
1547                 } else if ($grade->grade > $this->get_instance()->grade) {
1548                     return false;
1549                 } else if ($grade->grade < 0) {
1550                     return false;
1551                 }
1552             } else {
1553                 // This is a scale.
1554                 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
1555                     $scaleoptions = make_menu_from_list($scale->scale);
1556                     if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
1557                         return false;
1558                     }
1559                 }
1560             }
1561         }
1563         $result = $DB->update_record('assign_grades', $grade);
1564         if ($result) {
1565             $this->gradebook_item_update(null, $grade);
1566         }
1567         return $result;
1568     }
1570     /**
1571      * View the grant extension date page.
1572      *
1573      * Uses url parameters 'userid'
1574      * or from parameter 'selectedusers'
1575      *
1576      * @param moodleform $mform - Used for validation of the submitted data
1577      * @return string
1578      */
1579     protected function view_grant_extension($mform) {
1580         global $DB, $CFG;
1581         require_once($CFG->dirroot . '/mod/assign/extensionform.php');
1583         $o = '';
1584         $batchusers = optional_param('selectedusers', '', PARAM_TEXT);
1585         $data = new stdClass();
1586         $data->extensionduedate = null;
1587         $userid = 0;
1588         if (!$batchusers) {
1589             $userid = required_param('userid', PARAM_INT);
1591             $grade = $this->get_user_grade($userid, false);
1593             $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
1595             if ($grade) {
1596                 $data->extensionduedate = $grade->extensionduedate;
1597             }
1598             $data->userid = $userid;
1599         } else {
1600             $data->batchusers = $batchusers;
1601         }
1602         $header = new assign_header($this->get_instance(),
1603                                     $this->get_context(),
1604                                     $this->show_intro(),
1605                                     $this->get_course_module()->id,
1606                                     get_string('grantextension', 'assign'));
1607         $o .= $this->get_renderer()->render($header);
1609         if (!$mform) {
1610             $formparams = array($this->get_course_module()->id,
1611                                 $userid,
1612                                 $batchusers,
1613                                 $this->get_instance(),
1614                                 $data);
1615             $mform = new mod_assign_extension_form(null, $formparams);
1616         }
1617         $o .= $this->get_renderer()->render(new assign_form('extensionform', $mform));
1618         $o .= $this->view_footer();
1619         return $o;
1620     }
1622     /**
1623      * Get a list of the users in the same group as this user.
1624      *
1625      * @param int $groupid The id of the group whose members we want or 0 for the default group
1626      * @param bool $onlyids Whether to retrieve only the user id's
1627      * @return array The users (possibly id's only)
1628      */
1629     public function get_submission_group_members($groupid, $onlyids) {
1630         $members = array();
1631         if ($groupid != 0) {
1632             if ($onlyids) {
1633                 $allusers = groups_get_members($groupid, 'u.id');
1634             } else {
1635                 $allusers = groups_get_members($groupid);
1636             }
1637             foreach ($allusers as $user) {
1638                 if ($this->get_submission_group($user->id)) {
1639                     $members[] = $user;
1640                 }
1641             }
1642         } else {
1643             $allusers = $this->list_participants(null, $onlyids);
1644             foreach ($allusers as $user) {
1645                 if ($this->get_submission_group($user->id) == null) {
1646                     $members[] = $user;
1647                 }
1648             }
1649         }
1650         return $members;
1651     }
1653     /**
1654      * Get a list of the users in the same group as this user that have not submitted the assignment.
1655      *
1656      * @param int $groupid The id of the group whose members we want or 0 for the default group
1657      * @param bool $onlyids Whether to retrieve only the user id's
1658      * @return array The users (possibly id's only)
1659      */
1660     public function get_submission_group_members_who_have_not_submitted($groupid, $onlyids) {
1661         $instance = $this->get_instance();
1662         if (!$instance->teamsubmission || !$instance->requireallteammemberssubmit) {
1663             return array();
1664         }
1665         $members = $this->get_submission_group_members($groupid, $onlyids);
1667         foreach ($members as $id => $member) {
1668             $submission = $this->get_user_submission($member->id, false);
1669             if ($submission && $submission->status != ASSIGN_SUBMISSION_STATUS_DRAFT) {
1670                 unset($members[$id]);
1671             } else {
1672                 if ($this->is_blind_marking()) {
1673                     $members[$id]->alias = get_string('hiddenuser', 'assign') .
1674                                            $this->get_uniqueid_for_user($id);
1675                 }
1676             }
1677         }
1678         return $members;
1679     }
1681     /**
1682      * Load the group submission object for a particular user, optionally creating it if required.
1683      *
1684      * @param int $userid The id of the user whose submission we want
1685      * @param int $groupid The id of the group for this user - may be 0 in which
1686      *                     case it is determined from the userid.
1687      * @param bool $create If set to true a new submission object will be created in the database
1688      * @return stdClass The submission
1689      */
1690     public function get_group_submission($userid, $groupid, $create) {
1691         global $DB;
1693         if ($groupid == 0) {
1694             $group = $this->get_submission_group($userid);
1695             if ($group) {
1696                 $groupid = $group->id;
1697             }
1698         }
1700         if ($create) {
1701             // Make sure there is a submission for this user.
1702             $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>0, 'userid'=>$userid);
1703             $submission = $DB->get_record('assign_submission', $params);
1705             if (!$submission) {
1706                 $submission = new stdClass();
1707                 $submission->assignment = $this->get_instance()->id;
1708                 $submission->userid = $userid;
1709                 $submission->groupid = 0;
1710                 $submission->timecreated = time();
1711                 $submission->timemodified = $submission->timecreated;
1713                 if ($this->get_instance()->submissiondrafts) {
1714                     $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
1715                 } else {
1716                     $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1717                 }
1718                 $DB->insert_record('assign_submission', $submission);
1719             }
1720         }
1721         // Now get the group submission.
1722         $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
1723         $submission = $DB->get_record('assign_submission', $params);
1725         if ($submission) {
1726             return $submission;
1727         }
1728         if ($create) {
1729             $submission = new stdClass();
1730             $submission->assignment = $this->get_instance()->id;
1731             $submission->userid = 0;
1732             $submission->groupid = $groupid;
1733             $submission->timecreated = time();
1734             $submission->timemodified = $submission->timecreated;
1736             if ($this->get_instance()->submissiondrafts) {
1737                 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
1738             } else {
1739                 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1740             }
1741             $sid = $DB->insert_record('assign_submission', $submission);
1742             $submission->id = $sid;
1743             return $submission;
1744         }
1745         return false;
1746     }
1748     /**
1749      * View a summary listing of all assignments in the current course.
1750      *
1751      * @return string
1752      */
1753     private function view_course_index() {
1754         global $USER;
1756         $o = '';
1758         $course = $this->get_course();
1759         $strplural = get_string('modulenameplural', 'assign');
1761         if (!$cms = get_coursemodules_in_course('assign', $course->id, 'm.duedate')) {
1762             $o .= $this->get_renderer()->notification(get_string('thereareno', 'moodle', $strplural));
1763             $o .= $this->get_renderer()->continue_button(new moodle_url('/course/view.php', array('id' => $course->id)));
1764             return $o;
1765         }
1767         $strsectionname  = get_string('sectionname', 'format_'.$course->format);
1768         $usesections = course_format_uses_sections($course->format);
1769         $modinfo = get_fast_modinfo($course);
1771         if ($usesections) {
1772             $sections = $modinfo->get_section_info_all();
1773         }
1774         $courseindexsummary = new assign_course_index_summary($usesections, $strsectionname);
1776         $timenow = time();
1778         $currentsection = '';
1779         foreach ($modinfo->instances['assign'] as $cm) {
1780             if (!$cm->uservisible) {
1781                 continue;
1782             }
1784             $timedue = $cms[$cm->id]->duedate;
1786             $sectionname = '';
1787             if ($usesections && $cm->sectionnum) {
1788                 $sectionname = get_section_name($course, $sections[$cm->sectionnum]);
1789             }
1791             $submitted = '';
1792             $context = context_module::instance($cm->id);
1794             $assignment = new assign($context, $cm, $course);
1796             if (has_capability('mod/assign:grade', $context)) {
1797                 $submitted = $assignment->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED);
1799             } else if (has_capability('mod/assign:submit', $context)) {
1800                 $usersubmission = $assignment->get_user_submission($USER->id, false);
1802                 if (!empty($usersubmission->status)) {
1803                     $submitted = get_string('submissionstatus_' . $usersubmission->status, 'assign');
1804                 } else {
1805                     $submitted = get_string('submissionstatus_', 'assign');
1806                 }
1807             }
1808             $grading_info = grade_get_grades($course->id, 'mod', 'assign', $cm->instance, $USER->id);
1809             if (isset($grading_info->items[0]->grades[$USER->id]) &&
1810                     !$grading_info->items[0]->grades[$USER->id]->hidden ) {
1811                 $grade = $grading_info->items[0]->grades[$USER->id]->str_grade;
1812             } else {
1813                 $grade = '-';
1814             }
1816             $courseindexsummary->add_assign_info($cm->id, $cm->name, $sectionname, $timedue, $submitted, $grade);
1818         }
1820         $o .= $this->get_renderer()->render($courseindexsummary);
1821         $o .= $this->view_footer();
1823         return $o;
1824     }
1826     /**
1827      * View a page rendered by a plugin.
1828      *
1829      * Uses url parameters 'pluginaction', 'pluginsubtype', 'plugin', and 'id'.
1830      *
1831      * @return string
1832      */
1833     protected function view_plugin_page() {
1834         global $USER;
1836         $o = '';
1838         $pluginsubtype = required_param('pluginsubtype', PARAM_ALPHA);
1839         $plugintype = required_param('plugin', PARAM_TEXT);
1840         $pluginaction = required_param('pluginaction', PARAM_ALPHA);
1842         $plugin = $this->get_plugin_by_type($pluginsubtype, $plugintype);
1843         if (!$plugin) {
1844             print_error('invalidformdata', '');
1845             return;
1846         }
1848         $o .= $plugin->view_page($pluginaction);
1850         return $o;
1851     }
1854     /**
1855      * This is used for team assignments to get the group for the specified user.
1856      * If the user is a member of multiple or no groups this will return false
1857      *
1858      * @param int $userid The id of the user whose submission we want
1859      * @return mixed The group or false
1860      */
1861     public function get_submission_group($userid) {
1862         $grouping = $this->get_instance()->teamsubmissiongroupingid;
1863         $groups = groups_get_all_groups($this->get_course()->id, $userid, $grouping);
1864         if (count($groups) != 1) {
1865             return false;
1866         }
1867         return array_pop($groups);
1868     }
1871     /**
1872      * Display the submission that is used by a plugin.
1873      *
1874      * Uses url parameters 'sid', 'gid' and 'plugin'.
1875      *
1876      * @param string $pluginsubtype
1877      * @return string
1878      */
1879     protected function view_plugin_content($pluginsubtype) {
1880         global $USER;
1882         $o = '';
1884         $submissionid = optional_param('sid', 0, PARAM_INT);
1885         $gradeid = optional_param('gid', 0, PARAM_INT);
1886         $plugintype = required_param('plugin', PARAM_TEXT);
1887         $item = null;
1888         if ($pluginsubtype == 'assignsubmission') {
1889             $plugin = $this->get_submission_plugin_by_type($plugintype);
1890             if ($submissionid <= 0) {
1891                 throw new coding_exception('Submission id should not be 0');
1892             }
1893             $item = $this->get_submission($submissionid);
1895             // Check permissions.
1896             if ($item->userid != $USER->id) {
1897                 require_capability('mod/assign:grade', $this->context);
1898             }
1899             $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
1900                                                               $this->get_context(),
1901                                                               $this->show_intro(),
1902                                                               $this->get_course_module()->id,
1903                                                               $plugin->get_name()));
1904             $o .= $this->get_renderer()->render(new assign_submission_plugin_submission($plugin,
1905                                                               $item,
1906                                                               assign_submission_plugin_submission::FULL,
1907                                                               $this->get_course_module()->id,
1908                                                               $this->get_return_action(),
1909                                                               $this->get_return_params()));
1911             $logmessage = get_string('viewsubmissionforuser', 'assign', $item->userid);
1912             $this->add_to_log('view submission', $logmessage);
1913         } else {
1914             $plugin = $this->get_feedback_plugin_by_type($plugintype);
1915             if ($gradeid <= 0) {
1916                 throw new coding_exception('Grade id should not be 0');
1917             }
1918             $item = $this->get_grade($gradeid);
1919             // Check permissions.
1920             if ($item->userid != $USER->id) {
1921                 require_capability('mod/assign:grade', $this->context);
1922             }
1923             $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
1924                                                               $this->get_context(),
1925                                                               $this->show_intro(),
1926                                                               $this->get_course_module()->id,
1927                                                               $plugin->get_name()));
1928             $o .= $this->get_renderer()->render(new assign_feedback_plugin_feedback($plugin,
1929                                                               $item,
1930                                                               assign_feedback_plugin_feedback::FULL,
1931                                                               $this->get_course_module()->id,
1932                                                               $this->get_return_action(),
1933                                                               $this->get_return_params()));
1934             $logmessage = get_string('viewfeedbackforuser', 'assign', $item->userid);
1935             $this->add_to_log('view feedback', $logmessage);
1936         }
1938         $o .= $this->view_return_links();
1940         $o .= $this->view_footer();
1941         return $o;
1942     }
1944     /**
1945      * Rewrite plugin file urls so they resolve correctly in an exported zip.
1946      *
1947      * @param stdClass $user - The user record
1948      * @param assign_plugin $plugin - The assignment plugin
1949      */
1950     public function download_rewrite_pluginfile_urls($text, $user, $plugin) {
1951         $groupmode = groups_get_activity_groupmode($this->get_course_module());
1952         $groupname = '';
1953         if ($groupmode) {
1954             $groupid = groups_get_activity_group($this->get_course_module(), true);
1955             $groupname = groups_get_group_name($groupid).'-';
1956         }
1958         if ($this->is_blind_marking()) {
1959             $prefix = $groupname . get_string('participant', 'assign');
1960             $prefix = str_replace('_', ' ', $prefix);
1961             $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
1962         } else {
1963             $prefix = $groupname . fullname($user);
1964             $prefix = str_replace('_', ' ', $prefix);
1965             $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
1966         }
1968         $subtype = $plugin->get_subtype();
1969         $type = $plugin->get_type();
1970         $prefix = $prefix . $subtype . '_' . $type . '_';
1972         $result = str_replace('@@PLUGINFILE@@/', $prefix, $text);
1974         return $result;
1975     }
1977     /**
1978      * Render the content in editor that is often used by plugin.
1979      *
1980      * @param string $filearea
1981      * @param int  $submissionid
1982      * @param string $plugintype
1983      * @param string $editor
1984      * @param string $component
1985      * @return string
1986      */
1987     public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
1988         global $CFG;
1990         $result = '';
1992         $plugin = $this->get_submission_plugin_by_type($plugintype);
1994         $text = $plugin->get_editor_text($editor, $submissionid);
1995         $format = $plugin->get_editor_format($editor, $submissionid);
1997         $finaltext = file_rewrite_pluginfile_urls($text,
1998                                                   'pluginfile.php',
1999                                                   $this->get_context()->id,
2000                                                   $component,
2001                                                   $filearea,
2002                                                   $submissionid);
2003         $params = array('overflowdiv' => true, 'context' => $this->get_context());
2004         $result .= format_text($finaltext, $format, $params);
2006         if ($CFG->enableportfolios) {
2007             require_once($CFG->libdir . '/portfoliolib.php');
2009             $button = new portfolio_add_button();
2010             $portfolioparams = array('cmid' => $this->get_course_module()->id,
2011                                      'sid' => $submissionid,
2012                                      'plugin' => $plugintype,
2013                                      'editor' => $editor,
2014                                      'area'=>$filearea);
2015             $button->set_callback_options('assign_portfolio_caller', $portfolioparams, 'mod_assign');
2016             $fs = get_file_storage();
2018             if ($files = $fs->get_area_files($this->context->id,
2019                                              $component,
2020                                              $filearea,
2021                                              $submissionid,
2022                                              'timemodified',
2023                                              false)) {
2024                 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
2025             } else {
2026                 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
2027             }
2028             $result .= $button->to_html();
2029         }
2030         return $result;
2031     }
2033     /**
2034      * Display a grading error.
2035      *
2036      * @param string $message - The description of the result
2037      * @return string
2038      */
2039     protected function view_quickgrading_result($message) {
2040         $o = '';
2041         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2042                                                       $this->get_context(),
2043                                                       $this->show_intro(),
2044                                                       $this->get_course_module()->id,
2045                                                       get_string('quickgradingresult', 'assign')));
2046         $gradingresult = new assign_quickgrading_result($message, $this->get_course_module()->id);
2047         $o .= $this->get_renderer()->render($gradingresult);
2048         $o .= $this->view_footer();
2049         return $o;
2050     }
2052     /**
2053      * Display the page footer.
2054      *
2055      * @return string
2056      */
2057     protected function view_footer() {
2058         return $this->get_renderer()->render_footer();
2059     }
2061     /**
2062      * Does this user have grade permission for this assignment?
2063      *
2064      * @return bool
2065      */
2066     protected function can_grade() {
2067         // Permissions check.
2068         if (!has_capability('mod/assign:grade', $this->context)) {
2069             return false;
2070         }
2072         return true;
2073     }
2075     /**
2076      * Download a zip file of all assignment submissions.
2077      *
2078      * @return void
2079      */
2080     protected function download_submissions() {
2081         global $CFG, $DB;
2083         // More efficient to load this here.
2084         require_once($CFG->libdir.'/filelib.php');
2086         // Load all users with submit.
2087         $students = get_enrolled_users($this->context, "mod/assign:submit");
2089         // Build a list of files to zip.
2090         $filesforzipping = array();
2091         $fs = get_file_storage();
2093         $groupmode = groups_get_activity_groupmode($this->get_course_module());
2094         // All users.
2095         $groupid = 0;
2096         $groupname = '';
2097         if ($groupmode) {
2098             $groupid = groups_get_activity_group($this->get_course_module(), true);
2099             $groupname = groups_get_group_name($groupid).'-';
2100         }
2102         // Construct the zip file name.
2103         $filename = clean_filename($this->get_course()->shortname . '-' .
2104                                    $this->get_instance()->name . '-' .
2105                                    $groupname.$this->get_course_module()->id . '.zip');
2107         // Get all the files for each student.
2108         foreach ($students as $student) {
2109             $userid = $student->id;
2111             if ((groups_is_member($groupid, $userid) or !$groupmode or !$groupid)) {
2112                 // Get the plugins to add their own files to the zip.
2114                 $submissiongroup = false;
2115                 $groupname = '';
2116                 if ($this->get_instance()->teamsubmission) {
2117                     $submission = $this->get_group_submission($userid, 0, false);
2118                     $submissiongroup = $this->get_submission_group($userid);
2119                     if ($submissiongroup) {
2120                         $groupname = $submissiongroup->name . '-';
2121                     } else {
2122                         $groupname = get_string('defaultteam', 'assign') . '-';
2123                     }
2124                 } else {
2125                     $submission = $this->get_user_submission($userid, false);
2126                 }
2128                 if ($this->is_blind_marking()) {
2129                     $prefix = str_replace('_', ' ', $groupname . get_string('participant', 'assign'));
2130                     $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2131                 } else {
2132                     $prefix = str_replace('_', ' ', $groupname . fullname($student));
2133                     $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2134                 }
2136                 if ($submission) {
2137                     foreach ($this->submissionplugins as $plugin) {
2138                         if ($plugin->is_enabled() && $plugin->is_visible()) {
2139                             $pluginfiles = $plugin->get_files($submission, $student);
2140                             foreach ($pluginfiles as $zipfilename => $file) {
2141                                 $subtype = $plugin->get_subtype();
2142                                 $type = $plugin->get_type();
2143                                 $prefixedfilename = clean_filename($prefix .
2144                                                                    $subtype .
2145                                                                    '_' .
2146                                                                    $type .
2147                                                                    '_' .
2148                                                                    $zipfilename);
2149                                 $filesforzipping[$prefixedfilename] = $file;
2150                             }
2151                         }
2152                     }
2153                 }
2154             }
2155         }
2156         $result = '';
2157         if (count($filesforzipping) == 0) {
2158             $header = new assign_header($this->get_instance(),
2159                                         $this->get_context(),
2160                                         '',
2161                                         $this->get_course_module()->id,
2162                                         get_string('downloadall', 'assign'));
2163             $result .= $this->get_renderer()->render($header);
2164             $result .= $this->get_renderer()->notification(get_string('nosubmission', 'assign'));
2165             $url = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id,
2166                                                                     'action'=>'grading'));
2167             $result .= $this->get_renderer()->continue_button($url);
2168             $result .= $this->view_footer();
2169         } else if ($zipfile = $this->pack_files($filesforzipping)) {
2170             $this->add_to_log('download all submissions', get_string('downloadall', 'assign'));
2171             // Send file and delete after sending.
2172             send_temp_file($zipfile, $filename);
2173             // We will not get here - send_temp_file calls exit.
2174         }
2175         return $result;
2176     }
2178     /**
2179      * Util function to add a message to the log.
2180      *
2181      * @param string $action The current action
2182      * @param string $info A detailed description of the change. But no more than 255 characters.
2183      * @param string $url The url to the assign module instance.
2184      * @return void
2185      */
2186     public function add_to_log($action = '', $info = '', $url='') {
2187         global $USER;
2189         $fullurl = 'view.php?id=' . $this->get_course_module()->id;
2190         if ($url != '') {
2191             $fullurl .= '&' . $url;
2192         }
2194         add_to_log($this->get_course()->id,
2195                    'assign',
2196                    $action,
2197                    $fullurl,
2198                    $info,
2199                    $this->get_course_module()->id,
2200                    $USER->id);
2201     }
2203     /**
2204      * Lazy load the page renderer and expose the renderer to plugins.
2205      *
2206      * @return assign_renderer
2207      */
2208     public function get_renderer() {
2209         global $PAGE;
2210         if ($this->output) {
2211             return $this->output;
2212         }
2213         $this->output = $PAGE->get_renderer('mod_assign');
2214         return $this->output;
2215     }
2217     /**
2218      * Load the submission object for a particular user, optionally creating it if required.
2219      *
2220      * For team assignments there are 2 submissions - the student submission and the team submission
2221      * All files are associated with the team submission but the status of the students contribution is
2222      * recorded separately.
2223      *
2224      * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
2225      * @param bool $create optional - defaults to false. If set to true a new submission object
2226      *                     will be created in the database.
2227      * @return stdClass The submission
2228      */
2229     public function get_user_submission($userid, $create) {
2230         global $DB, $USER;
2232         if (!$userid) {
2233             $userid = $USER->id;
2234         }
2235         // If the userid is not null then use userid.
2236         $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid, 'groupid'=>0);
2237         $submission = $DB->get_record('assign_submission', $params);
2239         if ($submission) {
2240             return $submission;
2241         }
2242         if ($create) {
2243             $submission = new stdClass();
2244             $submission->assignment   = $this->get_instance()->id;
2245             $submission->userid       = $userid;
2246             $submission->timecreated = time();
2247             $submission->timemodified = $submission->timecreated;
2248             $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
2249             $sid = $DB->insert_record('assign_submission', $submission);
2250             $submission->id = $sid;
2251             return $submission;
2252         }
2253         return false;
2254     }
2256     /**
2257      * Load the submission object from it's id.
2258      *
2259      * @param int $submissionid The id of the submission we want
2260      * @return stdClass The submission
2261      */
2262     protected function get_submission($submissionid) {
2263         global $DB;
2265         $params = array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid);
2266         return $DB->get_record('assign_submission', $params, '*', MUST_EXIST);
2267     }
2269     /**
2270      * This will retrieve a grade object from the db, optionally creating it if required.
2271      *
2272      * @param int $userid The user we are grading
2273      * @param bool $create If true the grade will be created if it does not exist
2274      * @return stdClass The grade record
2275      */
2276     public function get_user_grade($userid, $create) {
2277         global $DB, $USER;
2279         if (!$userid) {
2280             $userid = $USER->id;
2281         }
2283         // If the userid is not null then use userid.
2284         $grade = $DB->get_record('assign_grades', array('assignment'=>$this->get_instance()->id, 'userid'=>$userid));
2286         if ($grade) {
2287             return $grade;
2288         }
2289         if ($create) {
2290             $grade = new stdClass();
2291             $grade->assignment   = $this->get_instance()->id;
2292             $grade->userid       = $userid;
2293             $grade->timecreated = time();
2294             $grade->timemodified = $grade->timecreated;
2295             $grade->locked = 0;
2296             $grade->grade = -1;
2297             $grade->grader = $USER->id;
2298             $grade->extensionduedate = 0;
2300             // The mailed flag can be one of 3 values: 0 is unsent, 1 is sent and 2 is do not send yet.
2301             // This is because students only want to be notified about certain types of update (grades and feedback).
2302             $grade->mailed = 2;
2303             $gid = $DB->insert_record('assign_grades', $grade);
2304             $grade->id = $gid;
2305             return $grade;
2306         }
2307         return false;
2308     }
2310     /**
2311      * This will retrieve a grade object from the db.
2312      *
2313      * @param int $gradeid The id of the grade
2314      * @return stdClass The grade record
2315      */
2316     protected function get_grade($gradeid) {
2317         global $DB;
2319         $params = array('assignment'=>$this->get_instance()->id, 'id'=>$gradeid);
2320         return $DB->get_record('assign_grades', $params, '*', MUST_EXIST);
2321     }
2323     /**
2324      * Print the grading page for a single user submission.
2325      *
2326      * @param moodleform $mform
2327      * @param int $offset
2328      * @return string
2329      */
2330     protected function view_single_grade_page($mform, $offset=0) {
2331         global $DB, $CFG;
2333         $o = '';
2334         $instance = $this->get_instance();
2336         require_once($CFG->dirroot . '/mod/assign/gradeform.php');
2338         // Need submit permission to submit an assignment.
2339         require_capability('mod/assign:grade', $this->context);
2341         $header = new assign_header($instance,
2342                                     $this->get_context(),
2343                                     false,
2344                                     $this->get_course_module()->id,
2345                                     get_string('grading', 'assign'));
2346         $o .= $this->get_renderer()->render($header);
2348         $rownum = required_param('rownum', PARAM_INT) + $offset;
2349         $useridlist = optional_param('useridlist', '', PARAM_TEXT);
2350         if ($useridlist) {
2351             $useridlist = explode(',', $useridlist);
2352         } else {
2353             $useridlist = $this->get_grading_userid_list();
2354         }
2355         $last = false;
2356         $userid = $useridlist[$rownum];
2357         if ($rownum == count($useridlist) - 1) {
2358             $last = true;
2359         }
2360         if (!$userid) {
2361             throw new coding_exception('Row is out of bounds for the current grading table: ' . $rownum);
2362         }
2363         $user = $DB->get_record('user', array('id' => $userid));
2364         if ($user) {
2365             $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2366             $usersummary = new assign_user_summary($user,
2367                                                    $this->get_course()->id,
2368                                                    $viewfullnames,
2369                                                    $this->is_blind_marking(),
2370                                                    $this->get_uniqueid_for_user($user->id));
2371             $o .= $this->get_renderer()->render($usersummary);
2372         }
2373         $submission = $this->get_user_submission($userid, false);
2374         $submissiongroup = null;
2375         $submissiongroupmemberswhohavenotsubmitted = array();
2376         $teamsubmission = null;
2377         $notsubmitted = array();
2378         if ($instance->teamsubmission) {
2379             $teamsubmission = $this->get_group_submission($userid, 0, false);
2380             $submissiongroup = $this->get_submission_group($userid);
2381             $groupid = 0;
2382             if ($submissiongroup) {
2383                 $groupid = $submissiongroup->id;
2384             }
2385             $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
2387         }
2389         // Get the current grade.
2390         $grade = $this->get_user_grade($userid, false);
2391         if ($this->can_view_submission($userid)) {
2392             $gradelocked = ($grade && $grade->locked) || $this->grading_disabled($userid);
2393             $extensionduedate = null;
2394             if ($grade) {
2395                 $extensionduedate = $grade->extensionduedate;
2396             }
2397             $showedit = $this->submissions_open($userid) && ($this->is_any_submission_plugin_enabled());
2399             if ($teamsubmission) {
2400                 $showsubmit = $showedit &&
2401                               $teamsubmission &&
2402                               ($teamsubmission->status == ASSIGN_SUBMISSION_STATUS_DRAFT);
2403             } else {
2404                 $showsubmit = $showedit &&
2405                               $submission &&
2406                               ($submission->status == ASSIGN_SUBMISSION_STATUS_DRAFT);
2407             }
2408             if (!$this->get_instance()->submissiondrafts) {
2409                 $showsubmit = false;
2410             }
2411             $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2413             $submissionstatus = new assign_submission_status($instance->allowsubmissionsfromdate,
2414                                                              $instance->alwaysshowdescription,
2415                                                              $submission,
2416                                                              $instance->teamsubmission,
2417                                                              $teamsubmission,
2418                                                              $submissiongroup,
2419                                                              $notsubmitted,
2420                                                              $this->is_any_submission_plugin_enabled(),
2421                                                              $gradelocked,
2422                                                              $this->is_graded($userid),
2423                                                              $instance->duedate,
2424                                                              $instance->cutoffdate,
2425                                                              $this->get_submission_plugins(),
2426                                                              $this->get_return_action(),
2427                                                              $this->get_return_params(),
2428                                                              $this->get_course_module()->id,
2429                                                              $this->get_course()->id,
2430                                                              assign_submission_status::GRADER_VIEW,
2431                                                              $showedit,
2432                                                              $showsubmit,
2433                                                              $viewfullnames,
2434                                                              $extensionduedate,
2435                                                              $this->get_context(),
2436                                                              $this->is_blind_marking(),
2437                                                              '');
2438             $o .= $this->get_renderer()->render($submissionstatus);
2439         }
2440         if ($grade) {
2441             $data = new stdClass();
2442             if ($grade->grade !== null && $grade->grade >= 0) {
2443                 $data->grade = format_float($grade->grade, 2);
2444             }
2445         } else {
2446             $data = new stdClass();
2447             $data->grade = '';
2448         }
2450         // Now show the grading form.
2451         if (!$mform) {
2452             $pagination = array( 'rownum'=>$rownum, 'useridlist'=>$useridlist, 'last'=>$last);
2453             $formparams = array($this, $data, $pagination);
2454             $mform = new mod_assign_grade_form(null,
2455                                                $formparams,
2456                                                'post',
2457                                                '',
2458                                                array('class'=>'gradeform'));
2459         }
2460         $o .= $this->get_renderer()->render(new assign_form('gradingform', $mform));
2462         $msg = get_string('viewgradingformforstudent',
2463                           'assign',
2464                           array('id'=>$user->id, 'fullname'=>fullname($user)));
2465         $this->add_to_log('view grading form', $msg);
2467         $o .= $this->view_footer();
2468         return $o;
2469     }
2471     /**
2472      * Show a confirmation page to make sure they want to release student identities.
2473      *
2474      * @return string
2475      */
2476     protected function view_reveal_identities_confirm() {
2477         global $CFG, $USER;
2479         require_capability('mod/assign:revealidentities', $this->get_context());
2481         $o = '';
2482         $header = new assign_header($this->get_instance(),
2483                                     $this->get_context(),
2484                                     false,
2485                                     $this->get_course_module()->id);
2486         $o .= $this->get_renderer()->render($header);
2488         $urlparams = array('id'=>$this->get_course_module()->id,
2489                            'action'=>'revealidentitiesconfirm',
2490                            'sesskey'=>sesskey());
2491         $confirmurl = new moodle_url('/mod/assign/view.php', $urlparams);
2493         $urlparams = array('id'=>$this->get_course_module()->id,
2494                            'action'=>'grading');
2495         $cancelurl = new moodle_url('/mod/assign/view.php', $urlparams);
2497         $o .= $this->get_renderer()->confirm(get_string('revealidentitiesconfirm', 'assign'),
2498                                              $confirmurl,
2499                                              $cancelurl);
2500         $o .= $this->view_footer();
2501         $this->add_to_log('view', get_string('viewrevealidentitiesconfirm', 'assign'));
2502         return $o;
2503     }
2505     /**
2506      * View a link to go back to the previous page. Uses url parameters returnaction and returnparams.
2507      *
2508      * @return string
2509      */
2510     protected function view_return_links() {
2511         $returnaction = optional_param('returnaction', '', PARAM_ALPHA);
2512         $returnparams = optional_param('returnparams', '', PARAM_TEXT);
2514         $params = array();
2515         parse_str($returnparams, $params);
2516         $newparams = array('id' => $this->get_course_module()->id, 'action' => $returnaction);
2517         $params = array_merge($newparams, $params);
2519         $url = new moodle_url('/mod/assign/view.php', $params);
2520         return $this->get_renderer()->single_button($url, get_string('back'), 'get');
2521     }
2523     /**
2524      * View the grading table of all submissions for this assignment.
2525      *
2526      * @return string
2527      */
2528     protected function view_grading_table() {
2529         global $USER, $CFG;
2531         // Include grading options form.
2532         require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
2533         require_once($CFG->dirroot . '/mod/assign/quickgradingform.php');
2534         require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
2535         $o = '';
2536         $cmid = $this->get_course_module()->id;
2538         $links = array();
2539         if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
2540                 has_capability('moodle/grade:viewall', $this->get_course_context())) {
2541             $gradebookurl = '/grade/report/grader/index.php?id=' . $this->get_course()->id;
2542             $links[$gradebookurl] = get_string('viewgradebook', 'assign');
2543         }
2544         if ($this->is_any_submission_plugin_enabled() && $this->count_submissions()) {
2545             $downloadurl = '/mod/assign/view.php?id=' . $cmid . '&action=downloadall';
2546             $links[$downloadurl] = get_string('downloadall', 'assign');
2547         }
2548         if ($this->is_blind_marking() &&
2549                 has_capability('mod/assign:revealidentities', $this->get_context())) {
2550             $revealidentitiesurl = '/mod/assign/view.php?id=' . $cmid . '&action=revealidentities';
2551             $links[$revealidentitiesurl] = get_string('revealidentities', 'assign');
2552         }
2553         foreach ($this->get_feedback_plugins() as $plugin) {
2554             if ($plugin->is_enabled() && $plugin->is_visible()) {
2555                 foreach ($plugin->get_grading_actions() as $action => $description) {
2556                     $url = '/mod/assign/view.php' .
2557                            '?id=' .  $cmid .
2558                            '&plugin=' . $plugin->get_type() .
2559                            '&pluginsubtype=assignfeedback' .
2560                            '&action=viewpluginpage&pluginaction=' . $action;
2561                     $links[$url] = $description;
2562                 }
2563             }
2564         }
2566         $gradingactions = new url_select($links);
2567         $gradingactions->set_label(get_string('choosegradingaction', 'assign'));
2569         $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2571         $perpage = get_user_preferences('assign_perpage', 10);
2572         $filter = get_user_preferences('assign_filter', '');
2573         $controller = $gradingmanager->get_active_controller();
2574         $showquickgrading = empty($controller);
2575         if (optional_param('action', '', PARAM_ALPHA) == 'saveoptions') {
2576             $quickgrading = optional_param('quickgrading', false, PARAM_BOOL);
2577             set_user_preference('assign_quickgrading', $quickgrading);
2578         }
2579         $quickgrading = get_user_preferences('assign_quickgrading', false);
2581         // Print options for changing the filter and changing the number of results per page.
2582         $gradingoptionsformparams = array('cm'=>$cmid,
2583                                           'contextid'=>$this->context->id,
2584                                           'userid'=>$USER->id,
2585                                           'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
2586                                           'showquickgrading'=>$showquickgrading,
2587                                           'quickgrading'=>$quickgrading);
2589         $classoptions = array('class'=>'gradingoptionsform');
2590         $gradingoptionsform = new mod_assign_grading_options_form(null,
2591                                                                   $gradingoptionsformparams,
2592                                                                   'post',
2593                                                                   '',
2594                                                                   $classoptions);
2596         $batchformparams = array('cm'=>$cmid,
2597                                  'submissiondrafts'=>$this->get_instance()->submissiondrafts,
2598                                  'duedate'=>$this->get_instance()->duedate,
2599                                  'feedbackplugins'=>$this->get_feedback_plugins());
2600         $classoptions = array('class'=>'gradingbatchoperationsform');
2602         $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
2603                                                                                    $batchformparams,
2604                                                                                    'post',
2605                                                                                    '',
2606                                                                                    $classoptions);
2608         $gradingoptionsdata = new stdClass();
2609         $gradingoptionsdata->perpage = $perpage;
2610         $gradingoptionsdata->filter = $filter;
2611         $gradingoptionsform->set_data($gradingoptionsdata);
2613         $actionformtext = $this->get_renderer()->render($gradingactions);
2614         $header = new assign_header($this->get_instance(),
2615                                     $this->get_context(),
2616                                     false,
2617                                     $this->get_course_module()->id,
2618                                     get_string('grading', 'assign'),
2619                                     $actionformtext);
2620         $o .= $this->get_renderer()->render($header);
2622         $currenturl = $CFG->wwwroot .
2623                       '/mod/assign/view.php?id=' .
2624                       $this->get_course_module()->id .
2625                       '&action=grading';
2627         $o .= groups_print_activity_menu($this->get_course_module(), $currenturl, true);
2629         // Plagiarism update status apearring in the grading book.
2630         if (!empty($CFG->enableplagiarism)) {
2631             require_once($CFG->libdir . '/plagiarismlib.php');
2632             $o .= plagiarism_update_status($this->get_course(), $this->get_course_module());
2633         }
2635         // Load and print the table of submissions.
2636         if ($showquickgrading && $quickgrading) {
2637             $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, true);
2638             $table = $this->get_renderer()->render($gradingtable);
2639             $quickformparams = array('cm'=>$this->get_course_module()->id, 'gradingtable'=>$table);
2640             $quickgradingform = new mod_assign_quick_grading_form(null, $quickformparams);
2642             $o .= $this->get_renderer()->render(new assign_form('quickgradingform', $quickgradingform));
2643         } else {
2644             $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, false);
2645             $o .= $this->get_renderer()->render($gradingtable);
2646         }
2648         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
2649         $users = array_keys($this->list_participants($currentgroup, true));
2650         if (count($users) != 0) {
2651             // If no enrolled user in a course then don't display the batch operations feature.
2652             $assignform = new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform);
2653             $o .= $this->get_renderer()->render($assignform);
2654         }
2655         $assignform = new assign_form('gradingoptionsform',
2656                                       $gradingoptionsform,
2657                                       'M.mod_assign.init_grading_options');
2658         $o .= $this->get_renderer()->render($assignform);
2659         return $o;
2660     }
2662     /**
2663      * View entire grading page.
2664      *
2665      * @return string
2666      */
2667     protected function view_grading_page() {
2668         global $CFG;
2670         $o = '';
2671         // Need submit permission to submit an assignment.
2672         require_capability('mod/assign:grade', $this->context);
2673         require_once($CFG->dirroot . '/mod/assign/gradeform.php');
2675         // Only load this if it is.
2677         $o .= $this->view_grading_table();
2679         $o .= $this->view_footer();
2681         $logmessage = get_string('viewsubmissiongradingtable', 'assign');
2682         $this->add_to_log('view submission grading table', $logmessage);
2683         return $o;
2684     }
2686     /**
2687      * Capture the output of the plagiarism plugins disclosures and return it as a string.
2688      *
2689      * @return void
2690      */
2691     protected function plagiarism_print_disclosure() {
2692         global $CFG;
2693         $o = '';
2695         if (!empty($CFG->enableplagiarism)) {
2696             require_once($CFG->libdir . '/plagiarismlib.php');
2698             $o .= plagiarism_print_disclosure($this->get_course_module()->id);
2699         }
2701         return $o;
2702     }
2704     /**
2705      * Message for students when assignment submissions have been closed.
2706      *
2707      * @return string
2708      */
2709     protected function view_student_error_message() {
2710         global $CFG;
2712         $o = '';
2713         // Need submit permission to submit an assignment.
2714         require_capability('mod/assign:submit', $this->context);
2716         $header = new assign_header($this->get_instance(),
2717                                     $this->get_context(),
2718                                     $this->show_intro(),
2719                                     $this->get_course_module()->id,
2720                                     get_string('editsubmission', 'assign'));
2721         $o .= $this->get_renderer()->render($header);
2723         $o .= $this->get_renderer()->notification(get_string('submissionsclosed', 'assign'));
2725         $o .= $this->view_footer();
2727         return $o;
2729     }
2731     /**
2732      * View edit submissions page.
2733      *
2734      * @param moodleform $mform
2735      * @param array $notices A list of notices to display at the top of the
2736      *                       edit submission form (e.g. from plugins).
2737      * @return void
2738      */
2739     protected function view_edit_submission_page($mform, $notices) {
2740         global $CFG;
2742         $o = '';
2743         require_once($CFG->dirroot . '/mod/assign/submission_form.php');
2744         // Need submit permission to submit an assignment.
2745         require_capability('mod/assign:submit', $this->context);
2747         if (!$this->submissions_open()) {
2748             return $this->view_student_error_message();
2749         }
2750         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2751                                                       $this->get_context(),
2752                                                       $this->show_intro(),
2753                                                       $this->get_course_module()->id,
2754                                                       get_string('editsubmission', 'assign')));
2755         $o .= $this->plagiarism_print_disclosure();
2756         $data = new stdClass();
2758         if (!$mform) {
2759             $mform = new mod_assign_submission_form(null, array($this, $data));
2760         }
2762         foreach ($notices as $notice) {
2763             $o .= $this->get_renderer()->notification($notice);
2764         }
2766         $o .= $this->get_renderer()->render(new assign_form('editsubmissionform', $mform));
2768         $o .= $this->view_footer();
2769         $this->add_to_log('view submit assignment form', get_string('viewownsubmissionform', 'assign'));
2771         return $o;
2772     }
2774     /**
2775      * See if this assignment has a grade yet.
2776      *
2777      * @param int $userid
2778      * @return bool
2779      */
2780     protected function is_graded($userid) {
2781         $grade = $this->get_user_grade($userid, false);
2782         if ($grade) {
2783             return ($grade->grade !== null && $grade->grade >= 0);
2784         }
2785         return false;
2786     }
2788     /**
2789      * Perform an access check to see if the current $USER can view this group submission.
2790      *
2791      * @param int $groupid
2792      * @return bool
2793      */
2794     public function can_view_group_submission($groupid) {
2795         global $USER;
2797         if (!is_enrolled($this->get_course_context(), $USER->id)) {
2798             return false;
2799         }
2800         if (has_capability('mod/assign:grade', $this->context)) {
2801             return true;
2802         }
2803         $members = $this->get_submission_group_members($groupid, true);
2804         foreach ($members as $member) {
2805             if ($member->id == $USER->id) {
2806                 return true;
2807             }
2808         }
2809         return false;
2810     }
2812     /**
2813      * Perform an access check to see if the current $USER can view this users submission.
2814      *
2815      * @param int $userid
2816      * @return bool
2817      */
2818     public function can_view_submission($userid) {
2819         global $USER;
2821         if (!is_enrolled($this->get_course_context(), $userid)) {
2822             return false;
2823         }
2824         if ($userid == $USER->id && has_capability('mod/assign:submit', $this->context)) {
2825             return true;
2826         }
2827         if (has_capability('mod/assign:grade', $this->context)) {
2828             return true;
2829         }
2830         return false;
2831     }
2833     /**
2834      * Allows the plugin to show a batch grading operation page.
2835      *
2836      * @return none
2837      */
2838     protected function view_plugin_grading_batch_operation($mform) {
2839         require_capability('mod/assign:grade', $this->context);
2840         $prefix = 'plugingradingbatchoperation_';
2842         if ($data = $mform->get_data()) {
2843             $tail = substr($data->operation, strlen($prefix));
2844             list($plugintype, $action) = explode('_', $tail, 2);
2846             $plugin = $this->get_feedback_plugin_by_type($plugintype);
2847             if ($plugin) {
2848                 $users = $data->selectedusers;
2849                 $userlist = explode(',', $users);
2850                 echo $plugin->grading_batch_operation($action, $userlist);
2851                 return;
2852             }
2853         }
2854         print_error('invalidformdata', '');
2855     }
2857     /**
2858      * Ask the user to confirm they want to perform this batch operation
2859      *
2860      * @param moodleform $mform Set to a grading batch operations form
2861      * @return string - the page to view after processing these actions
2862      */
2863     protected function process_grading_batch_operation(& $mform) {
2864         global $CFG;
2865         require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
2866         require_sesskey();
2868         $batchformparams = array('cm'=>$this->get_course_module()->id,
2869                                  'submissiondrafts'=>$this->get_instance()->submissiondrafts,
2870                                  'duedate'=>$this->get_instance()->duedate,
2871                                  'feedbackplugins'=>$this->get_feedback_plugins());
2872         $formclasses = array('class'=>'gradingbatchoperationsform');
2873         $mform = new mod_assign_grading_batch_operations_form(null,
2874                                                               $batchformparams,
2875                                                               'post',
2876                                                               '',
2877                                                               $formclasses);
2879         if ($data = $mform->get_data()) {
2880             // Get the list of users.
2881             $users = $data->selectedusers;
2882             $userlist = explode(',', $users);
2884             $prefix = 'plugingradingbatchoperation_';
2886             if ($data->operation == 'grantextension') {
2887                 // Reset the form so the grant extension page will create the extension form.
2888                 $mform = null;
2889                 return 'grantextension';
2890             } else if (strpos($data->operation, $prefix) === 0) {
2891                 $tail = substr($data->operation, strlen($prefix));
2892                 list($plugintype, $action) = explode('_', $tail, 2);
2894                 $plugin = $this->get_feedback_plugin_by_type($plugintype);
2895                 if ($plugin) {
2896                     return 'plugingradingbatchoperation';
2897                 }
2898             }
2900             foreach ($userlist as $userid) {
2901                 if ($data->operation == 'lock') {
2902                     $this->process_lock($userid);
2903                 } else if ($data->operation == 'unlock') {
2904                     $this->process_unlock($userid);
2905                 } else if ($data->operation == 'reverttodraft') {
2906                     $this->process_revert_to_draft($userid);
2907                 }
2908             }
2909         }
2911         return 'grading';
2912     }
2914     /**
2915      * Ask the user to confirm they want to submit their work for grading.
2916      *
2917      * @param $mform moodleform - null unless form validation has failed
2918      * @return string
2919      */
2920     protected function check_submit_for_grading($mform) {
2921         global $USER, $CFG;
2923         require_once($CFG->dirroot . '/mod/assign/submissionconfirmform.php');
2925         // Check that all of the submission plugins are ready for this submission.
2926         $notifications = array();
2927         $submission = $this->get_user_submission($USER->id, false);
2928         $plugins = $this->get_submission_plugins();
2929         foreach ($plugins as $plugin) {
2930             if ($plugin->is_enabled() && $plugin->is_visible()) {
2931                 $check = $plugin->precheck_submission($submission);
2932                 if ($check !== true) {
2933                     $notifications[] = $check;
2934                 }
2935             }
2936         }
2938         $data = new stdClass();
2939         $adminconfig = $this->get_admin_config();
2940         $requiresubmissionstatement = (!empty($adminconfig->requiresubmissionstatement) ||
2941                                        $this->get_instance()->requiresubmissionstatement) &&
2942                                        !empty($adminconfig->submissionstatement);
2944         $submissionstatement = '';
2945         if (!empty($adminconfig->submissionstatement)) {
2946             $submissionstatement = $adminconfig->submissionstatement;
2947         }
2949         if ($mform == null) {
2950             $mform = new mod_assign_confirm_submission_form(null, array($requiresubmissionstatement,
2951                                                                         $submissionstatement,
2952                                                                         $this->get_course_module()->id,
2953                                                                         $data));
2954         }
2955         $o = '';
2956         $o .= $this->get_renderer()->header();
2957         $submitforgradingpage = new assign_submit_for_grading_page($notifications,
2958                                                                    $this->get_course_module()->id,
2959                                                                    $mform);
2960         $o .= $this->get_renderer()->render($submitforgradingpage);
2961         $o .= $this->view_footer();
2963         $logmessage = get_string('viewownsubmissionform', 'assign');
2964         $this->add_to_log('view confirm submit assignment form', $logmessage);
2966         return $o;
2967     }
2969     /**
2970      * Print 2 tables of information with no action links -
2971      * the submission summary and the grading summary.
2972      *
2973      * @param stdClass $user the user to print the report for
2974      * @param bool $showlinks - Return plain text or links to the profile
2975      * @return string - the html summary
2976      */
2977     public function view_student_summary($user, $showlinks) {
2978         global $CFG, $DB, $PAGE;
2980         $instance = $this->get_instance();
2981         $grade = $this->get_user_grade($user->id, false);
2982         $submission = $this->get_user_submission($user->id, false);
2983         $o = '';
2985         $teamsubmission = null;
2986         $submissiongroup = null;
2987         $notsubmitted = array();
2988         if ($instance->teamsubmission) {
2989             $teamsubmission = $this->get_group_submission($user->id, 0, false);
2990             $submissiongroup = $this->get_submission_group($user->id);
2991             $groupid = 0;
2992             if ($submissiongroup) {
2993                 $groupid = $submissiongroup->id;
2994             }
2995             $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
2996         }
2998         if ($this->can_view_submission($user->id)) {
2999             $showedit = has_capability('mod/assign:submit', $this->context) &&
3000                         $this->submissions_open($user->id) &&
3001                         ($this->is_any_submission_plugin_enabled()) &&
3002                         $showlinks;
3004             $gradelocked = ($grade && $grade->locked) || $this->grading_disabled($user->id);
3006             // Grading criteria preview.
3007             $gradingmanager = get_grading_manager($this->context, 'mod_assign', 'submissions');
3008             $gradingcontrollerpreview = '';
3009             if ($gradingmethod = $gradingmanager->get_active_method()) {
3010                 $controller = $gradingmanager->get_controller($gradingmethod);
3011                 if ($controller->is_form_defined()) {
3012                     $gradingcontrollerpreview = $controller->render_preview($PAGE);
3013                 }
3014             }
3016             $showsubmit = ($submission || $teamsubmission) && $showlinks;
3017             if ($teamsubmission && ($teamsubmission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED)) {
3018                 $showsubmit = false;
3019             }
3020             if ($submission && ($submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED)) {
3021                 $showsubmit = false;
3022             }
3023             if (!$this->get_instance()->submissiondrafts) {
3024                 $showsubmit = false;
3025             }
3026             $extensionduedate = null;
3027             if ($grade) {
3028                 $extensionduedate = $grade->extensionduedate;
3029             }
3030             $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
3032             $submissionstatus = new assign_submission_status($instance->allowsubmissionsfromdate,
3033                                                               $instance->alwaysshowdescription,
3034                                                               $submission,
3035                                                               $instance->teamsubmission,
3036                                                               $teamsubmission,
3037                                                               $submissiongroup,
3038                                                               $notsubmitted,
3039                                                               $this->is_any_submission_plugin_enabled(),
3040                                                               $gradelocked,
3041                                                               $this->is_graded($user->id),
3042                                                               $instance->duedate,
3043                                                               $instance->cutoffdate,
3044                                                               $this->get_submission_plugins(),
3045                                                               $this->get_return_action(),
3046                                                               $this->get_return_params(),
3047                                                               $this->get_course_module()->id,
3048                                                               $this->get_course()->id,
3049                                                               assign_submission_status::STUDENT_VIEW,
3050                                                               $showedit,
3051                                                               $showsubmit,
3052                                                               $viewfullnames,
3053                                                               $extensionduedate,
3054                                                               $this->get_context(),
3055                                                               $this->is_blind_marking(),
3056                                                               $gradingcontrollerpreview);
3057             $o .= $this->get_renderer()->render($submissionstatus);
3059             require_once($CFG->libdir.'/gradelib.php');
3060             require_once($CFG->dirroot.'/grade/grading/lib.php');
3062             $gradinginfo = grade_get_grades($this->get_course()->id,
3063                                         'mod',
3064                                         'assign',
3065                                         $instance->id,
3066                                         $user->id);
3068             $gradingitem = null;
3069             $gradebookgrade = null;
3070             if (isset($gradinginfo->items[0])) {
3071                 $gradingitem = $gradinginfo->items[0];
3072                 $gradebookgrade = $gradingitem->grades[$user->id];
3073             }
3075             // Check to see if all feedback plugins are empty.
3076             $emptyplugins = true;
3077             if ($grade) {
3078                 foreach ($this->get_feedback_plugins() as $plugin) {
3079                     if ($plugin->is_visible() && $plugin->is_enabled()) {
3080                         if (!$plugin->is_empty($grade)) {
3081                             $emptyplugins = false;
3082                         }
3083                     }
3084                 }
3085             }
3087             $cangrade = has_capability('mod/assign:grade', $this->get_context());
3088             // If there is feedback or a visible grade, show the summary.
3089             if ((!empty($gradebookgrade->grade) && ($cangrade || !$gradebookgrade->hidden)) ||
3090                     !$emptyplugins) {
3092                 $gradefordisplay = null;
3093                 $gradeddate = null;
3094                 $grader = null;
3095                 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
3097                 // Only show the grade if it is not hidden in gradebook.
3098                 if (!empty($gradebookgrade->grade) && ($cangrade || !$gradebookgrade->hidden)) {
3099                     if ($controller = $gradingmanager->get_active_controller()) {
3100                         $controller->set_grade_range(make_grades_menu($this->get_instance()->grade));
3101                         $gradefordisplay = $controller->render_grade($PAGE,
3102                                                                      $grade->id,
3103                                                                      $gradingitem,
3104                                                                      $gradebookgrade->str_long_grade,
3105                                                                      $cangrade);
3106                     } else {
3107                         $gradefordisplay = $this->display_grade($gradebookgrade->grade, false);
3108                     }
3109                     $gradeddate = $gradebookgrade->dategraded;
3110                     if (isset($grade->grader)) {
3111                         $grader = $DB->get_record('user', array('id'=>$grade->grader));
3112                     }
3113                 }
3116                 $feedbackstatus = new assign_feedback_status($gradefordisplay,
3117                                                       $gradeddate,
3118                                                       $grader,
3119                                                       $this->get_feedback_plugins(),
3120                                                       $grade,
3121                                                       $this->get_course_module()->id,
3122                                                       $this->get_return_action(),
3123                                                       $this->get_return_params());
3125                 $o .= $this->get_renderer()->render($feedbackstatus);
3126             }
3128         }
3129         return $o;
3130     }
3132     /**
3133      * View submissions page (contains details of current submission).
3134      *
3135      * @return string
3136      */
3137     protected function view_submission_page() {
3138         global $CFG, $DB, $USER, $PAGE;
3140         $instance = $this->get_instance();
3142         $o = '';
3143         $o .= $this->get_renderer()->render(new assign_header($instance,
3144                                                       $this->get_context(),
3145                                                       $this->show_intro(),
3146                                                       $this->get_course_module()->id));
3148         if ($this->can_grade()) {
3149             $draft = ASSIGN_SUBMISSION_STATUS_DRAFT;
3150             $submitted = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
3151             if ($instance->teamsubmission) {
3152                 $summary = new assign_grading_summary($this->count_teams(),
3153                                                       $instance->submissiondrafts,
3154                                                       $this->count_submissions_with_status($draft),
3155                                                       $this->is_any_submission_plugin_enabled(),
3156                                                       $this->count_submissions_with_status($submitted),
3157                                                       $instance->cutoffdate,
3158                                                       $instance->duedate,
3159                                                       $this->get_course_module()->id,
3160                                                       $this->count_submissions_need_grading(),
3161                                                       $instance->teamsubmission);
3162                 $o .= $this->get_renderer()->render($summary);
3163             } else {
3164                 $summary = new assign_grading_summary($this->count_participants(0),
3165                                                       $instance->submissiondrafts,
3166                                                       $this->count_submissions_with_status($draft),
3167                                                       $this->is_any_submission_plugin_enabled(),
3168                                                       $this->count_submissions_with_status($submitted),
3169                                                       $instance->cutoffdate,
3170                                                       $instance->duedate,
3171                                                       $this->get_course_module()->id,
3172                                                       $this->count_submissions_need_grading(),
3173                                                       $instance->teamsubmission);
3174                 $o .= $this->get_renderer()->render($summary);
3175             }
3176         }
3177         $grade = $this->get_user_grade($USER->id, false);
3178         $submission = $this->get_user_submission($USER->id, false);
3180         if ($this->can_view_submission($USER->id)) {
3181             $o .= $this->view_student_summary($USER, true);
3182         }
3184         $o .= $this->view_footer();
3185         $this->add_to_log('view', get_string('viewownsubmissionstatus', 'assign'));
3186         return $o;
3187     }
3189     /**
3190      * Convert the final raw grade(s) in the grading table for the gradebook.
3191      *
3192      * @param stdClass $grade
3193      * @return array
3194      */
3195     protected function convert_grade_for_gradebook(stdClass $grade) {
3196         $gradebookgrade = array();
3197         if ($grade->grade >= 0) {
3198             $gradebookgrade['rawgrade'] = $grade->grade;
3199         }
3200         $gradebookgrade['userid'] = $grade->userid;
3201         $gradebookgrade['usermodified'] = $grade->grader;
3202         $gradebookgrade['datesubmitted'] = null;
3203         $gradebookgrade['dategraded'] = $grade->timemodified;
3204         if (isset($grade->feedbackformat)) {
3205             $gradebookgrade['feedbackformat'] = $grade->feedbackformat;
3206         }
3207         if (isset($grade->feedbacktext)) {
3208             $gradebookgrade['feedback'] = $grade->feedbacktext;
3209         }
3211         return $gradebookgrade;
3212     }
3214     /**
3215      * Convert submission details for the gradebook.
3216      *
3217      * @param stdClass $submission
3218      * @return array
3219      */
3220     protected function convert_submission_for_gradebook(stdClass $submission) {
3221         $gradebookgrade = array();
3223         $gradebookgrade['userid'] = $submission->userid;
3224         $gradebookgrade['usermodified'] = $submission->userid;
3225         $gradebookgrade['datesubmitted'] = $submission->timemodified;
3227         return $gradebookgrade;
3228     }
3230     /**
3231      * Update grades in the gradebook.
3232      *
3233      * @param mixed $submission stdClass|null
3234      * @param mixed $grade stdClass|null
3235      * @return bool
3236      */
3237     protected function gradebook_item_update($submission=null, $grade=null) {
3239         // Do not push grade to gradebook if blind marking is active as
3240         // the gradebook would reveal the students.
3241         if ($this->is_blind_marking()) {
3242             return false;
3243         }
3244         if ($submission != null) {
3245             if ($submission->userid == 0) {
3246                 // This is a group submission update.
3247                 $team = groups_get_members($submission->groupid, 'u.id');
3249                 foreach ($team as $member) {
3250                     $submission->groupid = 0;
3251                     $submission->userid = $member->id;
3252                     $this->gradebook_item_update($submission, null);
3253                 }
3254                 return;
3255             }
3257             $gradebookgrade = $this->convert_submission_for_gradebook($submission);
3259         } else {
3260             $gradebookgrade = $this->convert_grade_for_gradebook($grade);
3261         }
3262         // Grading is disabled, return.
3263         if ($this->grading_disabled($gradebookgrade['userid'])) {
3264             return false;
3265         }
3266         $assign = clone $this->get_instance();
3267         $assign->cmidnumber = $this->get_course_module()->id;
3269         return assign_grade_item_update($assign, $gradebookgrade);
3270     }
3272     /**
3273      * Update team submission.
3274      *
3275      * @param stdClass $submission
3276      * @param int $userid
3277      * @param bool $updatetime
3278      * @return bool
3279      */
3280     protected function update_team_submission(stdClass $submission, $userid, $updatetime) {
3281         global $DB;
3283         if ($updatetime) {
3284             $submission->timemodified = time();
3285         }
3287         // First update the submission for the current user.
3288         $mysubmission = $this->get_user_submission($userid, true);
3289         $mysubmission->status = $submission->status;
3291         $this->update_submission($mysubmission, 0, $updatetime, false);
3293         // Now check the team settings to see if this assignment qualifies as submitted or draft.
3294         $team = $this->get_submission_group_members($submission->groupid, true);
3296         $allsubmitted = true;
3297         $anysubmitted = false;
3298         foreach ($team as $member) {
3299             $membersubmission = $this->get_user_submission($member->id, false);
3301             if (!$membersubmission || $membersubmission->status != ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
3302                 $allsubmitted = false;
3303                 if ($anysubmitted) {
3304                     break;
3305                 }
3306             } else {
3307                 $anysubmitted = true;
3308             }
3309         }
3310         if ($this->get_instance()->requireallteammemberssubmit) {
3311             if ($allsubmitted) {
3312                 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
3313             } else {
3314                 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
3315             }
3316             $result= $DB->update_record('assign_submission', $submission);
3317         } else {
3318             if ($anysubmitted) {
3319                 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
3320             } else {
3321                 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
3322             }
3323             $result= $DB->update_record('assign_submission', $submission);
3324         }
3326         $this->gradebook_item_update($submission);
3327         return $result;
3328     }
3331     /**
3332      * Update grades in the gradebook based on submission time.
3333      *
3334      * @param stdClass $submission
3335      * @param int $userid
3336      * @param bool $updatetime
3337      * @param bool $teamsubmission
3338      * @return bool
3339      */
3340     protected function update_submission(stdClass $submission, $userid, $updatetime, $teamsubmission) {
3341         global $DB;
3343         if ($teamsubmission) {
3344             return $this->update_team_submission($submission, $userid, $updatetime);
3345         }
3347         if ($updatetime) {
3348             $submission->timemodified = time();
3349         }
3350         $result= $DB->update_record('assign_submission', $submission);
3351         if ($result) {
3352             $this->gradebook_item_update($submission);
3353         }
3354         return $result;
3355     }
3357     /**
3358      * Is this assignment open for submissions?
3359      *
3360      * Check the due date,
3361      * prevent late submissions,
3362      * has this person already submitted,
3363      * is the assignment locked?
3364      *
3365      * @param int $userid - Optional userid so we can see if a different user can submit
3366      * @return bool
3367      */
3368     public function submissions_open($userid = 0) {
3369         global $USER;
3371         if (!$userid) {
3372             $userid = $USER->id;
3373         }
3375         $time = time();
3376         $dateopen = true;
3377         $finaldate = false;
3378         if ($this->get_instance()->cutoffdate) {
3379             $finaldate = $this->get_instance()->cutoffdate;
3380         }
3381         // User extensions.
3382         if ($finaldate) {
3383             $grade = $this->get_user_grade($userid, false);
3384             if ($grade && $grade->extensionduedate) {
3385                 // Extension can be before cut off date.
3386                 if ($grade->extensionduedate > $finaldate) {
3387                     $finaldate = $grade->extensionduedate;
3388                 }
3389             }
3390         }
3392         if ($finaldate) {
3393             $dateopen = ($this->get_instance()->allowsubmissionsfromdate <= $time && $time <= $finaldate);
3394         } else {
3395             $dateopen = ($this->get_instance()->allowsubmissionsfromdate <= $time);
3396         }
3398         if (!$dateopen) {
3399             return false;
3400         }
3402         // Now check if this user has already submitted etc.
3403         if (!is_enrolled($this->get_course_context(), $userid)) {
3404             return false;
3405         }
3406         $submission = false;
3407         if ($this->get_instance()->teamsubmission) {
3408             $submission = $this->get_group_submission($userid, 0, false);
3409         } else {
3410             $submission = $this->get_user_submission($userid, false);
3411         }
3412         if ($submission) {
3414             if ($this->get_instance()->submissiondrafts && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
3415                 // Drafts are tracked and the student has submitted the assignment.
3416                 return false;
3417             }
3418         }
3419         if ($grade = $this->get_user_grade($userid, false)) {
3420             if ($grade->locked) {
3421                 return false;
3422             }
3423         }
3425         if ($this->grading_disabled($userid)) {
3426             return false;
3427         }
3429         return true;
3430     }
3432     /**
3433      * Render the files in file area.
3434      *
3435      * @param string $component
3436      * @param string $area
3437      * @param int $submissionid
3438      * @return string
3439      */
3440     public function render_area_files($component, $area, $submissionid) {
3441         global $USER;
3443         $fs = get_file_storage();
3444         $browser = get_file_browser();
3445         $files = $fs->get_area_files($this->get_context()->id,
3446                                      $component,
3447                                      $area,
3448                                      $submissionid,
3449                                      'timemodified',
3450                                      false);
3451         return $this->get_renderer()->assign_files($this->context, $submissionid, $area, $component);
3453     }
3455     /**
3456      * Returns a list of teachers that should be grading given submission.
3457      *
3458      * @param int $userid The submission to grade
3459      * @return array
3460      */
3461     protected function get_graders($userid) {
3462         $potentialgraders = get_enrolled_users($this->context, 'mod/assign:grade');
3464         $graders = array();
3465         if (groups_get_activity_groupmode($this->get_course_module()) == SEPARATEGROUPS) {
3466             if ($groups = groups_get_all_groups($this->get_course()->id, $userid)) {
3467                 foreach ($groups as $group) {
3468                     foreach ($potentialgraders as $grader) {
3469                         if ($grader->id == $userid) {
3470                             // Do not send self.
3471                             continue;
3472                         }
3473                         if (groups_is_member($group->id, $grader->id)) {
3474                             $graders[$grader->id] = $grader;
3475                         }
3476                     }
3477                 }
3478             } else {
3479                 // User not in group, try to find graders without group.
3480                 foreach ($potentialgraders as $grader) {
3481                     if ($grader->id == $userid) {
3482                         // Do not send self.
3483                         continue;
3484                     }
3485                     if (!groups_has_membership($this->get_course_module(), $grader->id)) {
3486                         $graders[$grader->id] = $grader;
3487                     }
3488                 }
3489             }
3490         } else {
3491             foreach ($potentialgraders as $grader) {
3492                 if ($grader->id == $userid) {
3493                     // Do not send self.
3494                     continue;
3495                 }
3496                 // Must be enrolled.
3497                 if (is_enrolled($this->get_course_context(), $grader->id)) {
3498                     $graders[$grader->id] = $grader;
3499                 }
3500             }
3501         }
3502         return $graders;
3503     }
3505     /**
3506      * Format a notification for plain text.
3507      *
3508      * @param string $messagetype
3509      * @param stdClass $info
3510      * @param stdClass $course
3511      * @param stdClass $context
3512      * @param string $modulename
3513      * @param string $assignmentname
3514      */
3515     protected static function format_notification_message_text($messagetype,
3516                                                              $info,
3517                                                              $course,
3518                                                              $context,
3519                                                              $modulename,
3520                                                              $assignmentname) {
3521         $formatparams = array('context' => $context->get_course_context());
3522         $posttext  = format_string($course->shortname, true, $formatparams) .
3523                      ' -> ' .
3524                      $modulename .
3525                      ' -> ' .
3526                      format_string($assignmentname, true, $formatparams) . "\n";
3527         $posttext .= '---------------------------------------------------------------------' . "\n";
3528         $posttext .= get_string($messagetype . 'text', 'assign', $info)."\n";
3529         $posttext .= "\n---------------------------------------------------------------------\n";
3530         return $posttext;
3531     }
3533     /**
3534      * Format a notification for HTML.
3535      *
3536      * @param string $messagetype
3537      * @param stdClass $info
3538      * @param stdClass $course
3539      * @param stdClass $context
3540      * @param string $modulename
3541      * @param stdClass $coursemodule
3542      * @param string $assignmentname
3543      * @param stdClass $info
3544      */
3545     protected static function format_notification_message_html($messagetype,
3546                                                              $info,
3547                                                              $course,
3548                                                              $context,
3549                                                              $modulename,
3550                                                              $coursemodule,
3551                                                              $assignmentname) {
3552         global $CFG;
3553         $formatparams = array('context' => $context->get_course_context());
3554         $posthtml  = '<p><font face="sans-serif">' .
3555                      '<a href="' . $CFG->wwwroot . '/course/view.php?id=' . $course->id . '">' .
3556                      format_string($course->shortname, true, $formatparams) .
3557                      '</a> ->' .
3558                      '<a href="' . $CFG->wwwroot . '/mod/assign/index.php?id=' . $course->id . '">' .
3559                      $modulename .
3560                      '</a> ->' .
3561                      '<a href="' . $CFG->wwwroot . '/mod/assign/view.php?id=' . $coursemodule->id . '">' .
3562                      format_string($assignmentname, true, $formatparams) .
3563                      '</a></font></p>';
3564         $posthtml .= '<hr /><font face="sans-serif">';
3565         $posthtml .= '<p>' . get_string($messagetype . 'html', 'assign', $info) . '</p>';
3566         $posthtml .= '</font><hr />';
3567         return $posthtml;
3568     }
3570     /**
3571      * Message someone about something (static so it can be called from cron).
3572      *
3573      * @param stdClass $userfrom
3574      * @param stdClass $userto
3575      * @param string $messagetype
3576      * @param string $eventtype
3577      * @param int $updatetime
3578      * @param stdClass $coursemodule
3579      * @param stdClass $context
3580      * @param stdClass $course
3581      * @param string $modulename
3582      * @param string $assignmentname
3583      * @return void
3584      */
3585     public static function send_assignment_notification($userfrom,
3586                                                         $userto,
3587                                                         $messagetype,
3588                                                         $eventtype,
3589                                                         $updatetime,
3590                                                         $coursemodule,
3591                                                         $context,
3592                                                         $course,
3593                                                         $modulename,
3594                                                         $assignmentname,
3595                                                         $blindmarking,
3596                                                         $uniqueidforuser) {
3597         global $CFG;
3599         $info = new stdClass();
3600         if ($blindmarking) {
3601             $info->username = get_string('participant', 'assign') . ' ' . $uniqueidforuser;
3602         } else {
3603             $info->username = fullname($userfrom, true);
3604         }
3605         $info->assignment = format_string($assignmentname, true, array('context'=>$context));
3606         $info->url = $CFG->wwwroot.'/mod/assign/view.php?id='.$coursemodule->id;
3607         $info->timeupdated = userdate($updatetime, get_string('strftimerecentfull'));
3609         $postsubject = get_string($messagetype . 'small', 'assign', $info);
3610         $posttext = self::format_notification_message_text($messagetype,
3611                                                            $info,
3612                                                            $course,
3613                                                            $context,
3614                                                            $modulename,
3615                                                            $assignmentname);
3616         $posthtml = '';
3617         if ($userto->mailformat == 1) {
3618             $posthtml = self::format_notification_message_html($messagetype,
3619                                                                $info,
3620                                                                $course,
3621                                                                $context,
3622                                                                $modulename,
3623                                                                $coursemodule,
3624                                                                $assignmentname);
3625         }
3627         $eventdata = new stdClass();
3628         $eventdata->modulename       = 'assign';
3629         $eventdata->userfrom         = $userfrom;
3630         $eventdata->userto           = $userto;
3631         $eventdata->subject          = $postsubject;
3632         $eventdata->fullmessage      = $posttext;
3633         $eventdata->fullmessageformat = FORMAT_PLAIN;
3634         $eventdata->fullmessagehtml  = $posthtml;
3635         $eventdata->smallmessage     = $postsubject;
3637         $eventdata->name            = $eventtype;
3638         $eventdata->component       = 'mod_assign';
3639         $eventdata->notification    = 1;
3640         $eventdata->contexturl      = $info->url;
3641         $eventdata->contexturlname  = $info->assignment;
3643         message_send($eventdata);
3644     }
3646     /**
3647      * Message someone about something.
3648      *
3649      * @param stdClass $userfrom
3650      * @param stdClass $userto
3651      * @param string $messagetype
3652      * @param string $eventtype
3653      * @param int $updatetime
3654      * @return void
3655      */
3656     public function send_notification($userfrom,
3657                                       $userto,
3658                                       $messagetype,
3659                                       $eventtype,
3660                                       $updatetime) {
3661         self::send_assignment_notification($userfrom,
3662                                            $userto,
3663                                            $messagetype,
3664                                            $eventtype,
3665                                            $updatetime,
3666                                            $this->get_course_module(),
3667                                            $this->get_context(),
3668                                            $this->get_course(),
3669                                            $this->get_module_name(),
3670                                            $this->get_instance()->name,
3671                                            $this->is_blind_marking(),
3672                                            $this->get_uniqueid_for_user($userfrom->id));
3673     }
3675     /**
3676      * Notify student upon successful submission.
3677      *
3678      * @param stdClass $submission
3679      * @return void
3680      */
3681     protected function notify_student_submission_receipt(stdClass $submission) {
3682         global $DB, $USER;
3684         $adminconfig = $this->get_admin_config();
3685         if (empty($adminconfig->submissionreceipts)) {
3686             // No need to do anything.
3687             return;
3688         }
3689         if ($submission->userid) {
3690             $user = $DB->get_record('user', array('id'=>$submission->userid), '*', MUST_EXIST);
3691         } else {
3692             $user = $USER;
3693         }
3694         $this->send_notification($user,
3695                                  $user,
3696                                  'submissionreceipt',
3697                                  'assign_notification',
3698                                  $submission->timemodified);
3699     }
3701     /**
3702      * Send notifications to graders upon student submissions.
3703      *
3704      * @param stdClass $submission
3705      * @return void
3706      */
3707     protected function notify_graders(stdClass $submission) {
3708         global $DB, $USER;
3710         $instance = $this->get_instance();
3712         $late = $instance->duedate && ($instance->duedate < time());
3714         if (!$instance->sendnotifications && !($late && $instance->sendlatenotifications)) {
3715             // No need to do anything.
3716             return;
3717         }
3719         if ($submission->userid) {
3720             $user = $DB->get_record('user', array('id'=>$submission->userid), '*', MUST_EXIST);
3721         } else {
3722             $user = $USER;
3723         }
3724         if ($teachers = $this->get_graders($user->id)) {
3725             foreach ($teachers as $teacher) {
3726                 $this->send_notification($user,
3727                                          $teacher,
3728                                          'gradersubmissionupdated',
3729                                          'assign_notification',
3730                                          $submission->timemodified);
3731             }
3732         }
3733     }
3735     /**
3736      * Assignment submission is processed before grading.
3737      *
3738      * @param $mform If validation failed when submitting this form - this is the moodleform.