Merge branch 'MDL-66017_course_filter_rebase' of git://github.com/davosmith/moodle
[moodle.git] / mod / assign / lib.php
blobaf12729cfd9aeec82ee6a288893c65d33aaae466
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.
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 moodle hooks for the assign module.
20 * It delegates most functions to the assignment class.
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
26 defined('MOODLE_INTERNAL') || die();
28 /**
29 * Adds an assignment instance
31 * This is done by calling the add_instance() method of the assignment type class
32 * @param stdClass $data
33 * @param mod_assign_mod_form $form
34 * @return int The instance id of the new assignment
36 function assign_add_instance(stdClass $data, mod_assign_mod_form $form = null) {
37 global $CFG;
38 require_once($CFG->dirroot . '/mod/assign/locallib.php');
40 $assignment = new assign(context_module::instance($data->coursemodule), null, null);
41 return $assignment->add_instance($data, true);
44 /**
45 * delete an assignment instance
46 * @param int $id
47 * @return bool
49 function assign_delete_instance($id) {
50 global $CFG;
51 require_once($CFG->dirroot . '/mod/assign/locallib.php');
52 $cm = get_coursemodule_from_instance('assign', $id, 0, false, MUST_EXIST);
53 $context = context_module::instance($cm->id);
55 $assignment = new assign($context, null, null);
56 return $assignment->delete_instance();
59 /**
60 * This function is used by the reset_course_userdata function in moodlelib.
61 * This function will remove all assignment submissions and feedbacks in the database
62 * and clean up any related data.
64 * @param stdClass $data the data submitted from the reset course.
65 * @return array
67 function assign_reset_userdata($data) {
68 global $CFG, $DB;
69 require_once($CFG->dirroot . '/mod/assign/locallib.php');
71 $status = array();
72 $params = array('courseid'=>$data->courseid);
73 $sql = "SELECT a.id FROM {assign} a WHERE a.course=:courseid";
74 $course = $DB->get_record('course', array('id'=>$data->courseid), '*', MUST_EXIST);
75 if ($assigns = $DB->get_records_sql($sql, $params)) {
76 foreach ($assigns as $assign) {
77 $cm = get_coursemodule_from_instance('assign',
78 $assign->id,
79 $data->courseid,
80 false,
81 MUST_EXIST);
82 $context = context_module::instance($cm->id);
83 $assignment = new assign($context, $cm, $course);
84 $status = array_merge($status, $assignment->reset_userdata($data));
87 return $status;
90 /**
91 * This standard function will check all instances of this module
92 * and make sure there are up-to-date events created for each of them.
93 * If courseid = 0, then every assignment event in the site is checked, else
94 * only assignment events belonging to the course specified are checked.
96 * @param int $courseid
97 * @param int|stdClass $instance Assign module instance or ID.
98 * @param int|stdClass $cm Course module object or ID (not used in this module).
99 * @return bool
101 function assign_refresh_events($courseid = 0, $instance = null, $cm = null) {
102 global $CFG, $DB;
103 require_once($CFG->dirroot . '/mod/assign/locallib.php');
105 // If we have instance information then we can just update the one event instead of updating all events.
106 if (isset($instance)) {
107 if (!is_object($instance)) {
108 $instance = $DB->get_record('assign', array('id' => $instance), '*', MUST_EXIST);
110 if (isset($cm)) {
111 if (!is_object($cm)) {
112 assign_prepare_update_events($instance);
113 return true;
114 } else {
115 $course = get_course($instance->course);
116 assign_prepare_update_events($instance, $course, $cm);
117 return true;
122 if ($courseid) {
123 // Make sure that the course id is numeric.
124 if (!is_numeric($courseid)) {
125 return false;
127 if (!$assigns = $DB->get_records('assign', array('course' => $courseid))) {
128 return false;
130 // Get course from courseid parameter.
131 if (!$course = $DB->get_record('course', array('id' => $courseid), '*')) {
132 return false;
134 } else {
135 if (!$assigns = $DB->get_records('assign')) {
136 return false;
139 foreach ($assigns as $assign) {
140 assign_prepare_update_events($assign);
143 return true;
147 * This actually updates the normal and completion calendar events.
149 * @param stdClass $assign Assignment object (from DB).
150 * @param stdClass $course Course object.
151 * @param stdClass $cm Course module object.
153 function assign_prepare_update_events($assign, $course = null, $cm = null) {
154 global $DB;
155 if (!isset($course)) {
156 // Get course and course module for the assignment.
157 list($course, $cm) = get_course_and_cm_from_instance($assign->id, 'assign', $assign->course);
159 // Refresh the assignment's calendar events.
160 $context = context_module::instance($cm->id);
161 $assignment = new assign($context, $cm, $course);
162 $assignment->update_calendar($cm->id);
163 // Refresh the calendar events also for the assignment overrides.
164 $overrides = $DB->get_records('assign_overrides', ['assignid' => $assign->id], '',
165 'id, groupid, userid, duedate, sortorder');
166 foreach ($overrides as $override) {
167 if (empty($override->userid)) {
168 unset($override->userid);
170 if (empty($override->groupid)) {
171 unset($override->groupid);
173 assign_update_events($assignment, $override);
178 * Removes all grades from gradebook
180 * @param int $courseid The ID of the course to reset
181 * @param string $type Optional type of assignment to limit the reset to a particular assignment type
183 function assign_reset_gradebook($courseid, $type='') {
184 global $CFG, $DB;
186 $params = array('moduletype'=>'assign', 'courseid'=>$courseid);
187 $sql = 'SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
188 FROM {assign} a, {course_modules} cm, {modules} m
189 WHERE m.name=:moduletype AND m.id=cm.module AND cm.instance=a.id AND a.course=:courseid';
191 if ($assignments = $DB->get_records_sql($sql, $params)) {
192 foreach ($assignments as $assignment) {
193 assign_grade_item_update($assignment, 'reset');
199 * Implementation of the function for printing the form elements that control
200 * whether the course reset functionality affects the assignment.
201 * @param moodleform $mform form passed by reference
203 function assign_reset_course_form_definition(&$mform) {
204 $mform->addElement('header', 'assignheader', get_string('modulenameplural', 'assign'));
205 $name = get_string('deleteallsubmissions', 'assign');
206 $mform->addElement('advcheckbox', 'reset_assign_submissions', $name);
207 $mform->addElement('advcheckbox', 'reset_assign_user_overrides',
208 get_string('removealluseroverrides', 'assign'));
209 $mform->addElement('advcheckbox', 'reset_assign_group_overrides',
210 get_string('removeallgroupoverrides', 'assign'));
214 * Course reset form defaults.
215 * @param object $course
216 * @return array
218 function assign_reset_course_form_defaults($course) {
219 return array('reset_assign_submissions' => 1,
220 'reset_assign_group_overrides' => 1,
221 'reset_assign_user_overrides' => 1);
225 * Update an assignment instance
227 * This is done by calling the update_instance() method of the assignment type class
228 * @param stdClass $data
229 * @param stdClass $form - unused
230 * @return object
232 function assign_update_instance(stdClass $data, $form) {
233 global $CFG;
234 require_once($CFG->dirroot . '/mod/assign/locallib.php');
235 $context = context_module::instance($data->coursemodule);
236 $assignment = new assign($context, null, null);
237 return $assignment->update_instance($data);
241 * This function updates the events associated to the assign.
242 * If $override is non-zero, then it updates only the events
243 * associated with the specified override.
245 * @param assign $assign the assign object.
246 * @param object $override (optional) limit to a specific override
248 function assign_update_events($assign, $override = null) {
249 global $CFG, $DB;
251 require_once($CFG->dirroot . '/calendar/lib.php');
253 $assigninstance = $assign->get_instance();
255 // Load the old events relating to this assign.
256 $conds = array('modulename' => 'assign', 'instance' => $assigninstance->id);
257 if (!empty($override)) {
258 // Only load events for this override.
259 if (isset($override->userid)) {
260 $conds['userid'] = $override->userid;
261 } else if (isset($override->groupid)) {
262 $conds['groupid'] = $override->groupid;
263 } else {
264 // This is not a valid override, it may have been left from a bad import or restore.
265 $conds['groupid'] = $conds['userid'] = 0;
268 $oldevents = $DB->get_records('event', $conds, 'id ASC');
270 // Now make a to-do list of all that needs to be updated.
271 if (empty($override)) {
272 // We are updating the primary settings for the assignment, so we need to add all the overrides.
273 $overrides = $DB->get_records('assign_overrides', array('assignid' => $assigninstance->id), 'id ASC');
274 // It is necessary to add an empty stdClass to the beginning of the array as the $oldevents
275 // list contains the original (non-override) event for the module. If this is not included
276 // the logic below will end up updating the wrong row when we try to reconcile this $overrides
277 // list against the $oldevents list.
278 array_unshift($overrides, new stdClass());
279 } else {
280 // Just do the one override.
281 $overrides = array($override);
284 if (!empty($assign->get_course_module())) {
285 $cmid = $assign->get_course_module()->id;
286 } else {
287 $cmid = get_coursemodule_from_instance('assign', $assigninstance->id, $assigninstance->course)->id;
290 foreach ($overrides as $current) {
291 $groupid = isset($current->groupid) ? $current->groupid : 0;
292 $userid = isset($current->userid) ? $current->userid : 0;
293 $duedate = isset($current->duedate) ? $current->duedate : $assigninstance->duedate;
295 // Only add 'due' events for an override if they differ from the assign default.
296 $addclose = empty($current->id) || !empty($current->duedate);
298 $event = new stdClass();
299 $event->type = CALENDAR_EVENT_TYPE_ACTION;
300 $event->description = format_module_intro('assign', $assigninstance, $cmid);
301 // Events module won't show user events when the courseid is nonzero.
302 $event->courseid = ($userid) ? 0 : $assigninstance->course;
303 $event->groupid = $groupid;
304 $event->userid = $userid;
305 $event->modulename = 'assign';
306 $event->instance = $assigninstance->id;
307 $event->timestart = $duedate;
308 $event->timeduration = 0;
309 $event->timesort = $event->timestart + $event->timeduration;
310 $event->visible = instance_is_visible('assign', $assigninstance);
311 $event->eventtype = ASSIGN_EVENT_TYPE_DUE;
312 $event->priority = null;
314 // Determine the event name and priority.
315 if ($groupid) {
316 // Group override event.
317 $params = new stdClass();
318 $params->assign = $assigninstance->name;
319 $params->group = groups_get_group_name($groupid);
320 if ($params->group === false) {
321 // Group doesn't exist, just skip it.
322 continue;
324 $eventname = get_string('overridegroupeventname', 'assign', $params);
325 // Set group override priority.
326 if (isset($current->sortorder)) {
327 $event->priority = $current->sortorder;
329 } else if ($userid) {
330 // User override event.
331 $params = new stdClass();
332 $params->assign = $assigninstance->name;
333 $eventname = get_string('overrideusereventname', 'assign', $params);
334 // Set user override priority.
335 $event->priority = CALENDAR_EVENT_USER_OVERRIDE_PRIORITY;
336 } else {
337 // The parent event.
338 $eventname = $assigninstance->name;
341 if ($duedate && $addclose) {
342 if ($oldevent = array_shift($oldevents)) {
343 $event->id = $oldevent->id;
344 } else {
345 unset($event->id);
347 $event->name = $eventname.' ('.get_string('duedate', 'assign').')';
348 calendar_event::create($event, false);
352 // Delete any leftover events.
353 foreach ($oldevents as $badevent) {
354 $badevent = calendar_event::load($badevent);
355 $badevent->delete();
360 * Return the list if Moodle features this module supports
362 * @param string $feature FEATURE_xx constant for requested feature
363 * @return mixed True if module supports feature, null if doesn't know
365 function assign_supports($feature) {
366 switch($feature) {
367 case FEATURE_GROUPS:
368 return true;
369 case FEATURE_GROUPINGS:
370 return true;
371 case FEATURE_MOD_INTRO:
372 return true;
373 case FEATURE_COMPLETION_TRACKS_VIEWS:
374 return true;
375 case FEATURE_COMPLETION_HAS_RULES:
376 return true;
377 case FEATURE_GRADE_HAS_GRADE:
378 return true;
379 case FEATURE_GRADE_OUTCOMES:
380 return true;
381 case FEATURE_BACKUP_MOODLE2:
382 return true;
383 case FEATURE_SHOW_DESCRIPTION:
384 return true;
385 case FEATURE_ADVANCED_GRADING:
386 return true;
387 case FEATURE_PLAGIARISM:
388 return true;
389 case FEATURE_COMMENT:
390 return true;
392 default:
393 return null;
398 * Lists all gradable areas for the advanced grading methods gramework
400 * @return array('string'=>'string') An array with area names as keys and descriptions as values
402 function assign_grading_areas_list() {
403 return array('submissions'=>get_string('submissions', 'assign'));
408 * extend an assigment navigation settings
410 * @param settings_navigation $settings
411 * @param navigation_node $navref
412 * @return void
414 function assign_extend_settings_navigation(settings_navigation $settings, navigation_node $navref) {
415 global $PAGE, $DB;
417 // We want to add these new nodes after the Edit settings node, and before the
418 // Locally assigned roles node. Of course, both of those are controlled by capabilities.
419 $keys = $navref->get_children_key_list();
420 $beforekey = null;
421 $i = array_search('modedit', $keys);
422 if ($i === false and array_key_exists(0, $keys)) {
423 $beforekey = $keys[0];
424 } else if (array_key_exists($i + 1, $keys)) {
425 $beforekey = $keys[$i + 1];
428 $cm = $PAGE->cm;
429 if (!$cm) {
430 return;
433 $context = $cm->context;
434 $course = $PAGE->course;
436 if (!$course) {
437 return;
440 if (has_capability('mod/assign:manageoverrides', $PAGE->cm->context)) {
441 $url = new moodle_url('/mod/assign/overrides.php', array('cmid' => $PAGE->cm->id));
442 $node = navigation_node::create(get_string('groupoverrides', 'assign'),
443 new moodle_url($url, array('mode' => 'group')),
444 navigation_node::TYPE_SETTING, null, 'mod_assign_groupoverrides');
445 $navref->add_node($node, $beforekey);
447 $node = navigation_node::create(get_string('useroverrides', 'assign'),
448 new moodle_url($url, array('mode' => 'user')),
449 navigation_node::TYPE_SETTING, null, 'mod_assign_useroverrides');
450 $navref->add_node($node, $beforekey);
453 // Link to gradebook.
454 if (has_capability('gradereport/grader:view', $cm->context) &&
455 has_capability('moodle/grade:viewall', $cm->context)) {
456 $link = new moodle_url('/grade/report/grader/index.php', array('id' => $course->id));
457 $linkname = get_string('viewgradebook', 'assign');
458 $node = $navref->add($linkname, $link, navigation_node::TYPE_SETTING);
461 // Link to download all submissions.
462 if (has_any_capability(array('mod/assign:grade', 'mod/assign:viewgrades'), $context)) {
463 $link = new moodle_url('/mod/assign/view.php', array('id' => $cm->id, 'action'=>'grading'));
464 $node = $navref->add(get_string('viewgrading', 'assign'), $link, navigation_node::TYPE_SETTING);
466 $link = new moodle_url('/mod/assign/view.php', array('id' => $cm->id, 'action'=>'downloadall'));
467 $node = $navref->add(get_string('downloadall', 'assign'), $link, navigation_node::TYPE_SETTING);
470 if (has_capability('mod/assign:revealidentities', $context)) {
471 $dbparams = array('id'=>$cm->instance);
472 $assignment = $DB->get_record('assign', $dbparams, 'blindmarking, revealidentities');
474 if ($assignment && $assignment->blindmarking && !$assignment->revealidentities) {
475 $urlparams = array('id' => $cm->id, 'action'=>'revealidentities');
476 $url = new moodle_url('/mod/assign/view.php', $urlparams);
477 $linkname = get_string('revealidentities', 'assign');
478 $node = $navref->add($linkname, $url, navigation_node::TYPE_SETTING);
484 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
485 * for the course (see resource).
487 * Given a course_module object, this function returns any "extra" information that may be needed
488 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
490 * @param stdClass $coursemodule The coursemodule object (record).
491 * @return cached_cm_info An object on information that the courses
492 * will know about (most noticeably, an icon).
494 function assign_get_coursemodule_info($coursemodule) {
495 global $CFG, $DB;
497 $dbparams = array('id'=>$coursemodule->instance);
498 $fields = 'id, name, alwaysshowdescription, allowsubmissionsfromdate, intro, introformat, completionsubmit';
499 if (! $assignment = $DB->get_record('assign', $dbparams, $fields)) {
500 return false;
503 $result = new cached_cm_info();
504 $result->name = $assignment->name;
505 if ($coursemodule->showdescription) {
506 if ($assignment->alwaysshowdescription || time() > $assignment->allowsubmissionsfromdate) {
507 // Convert intro to html. Do not filter cached version, filters run at display time.
508 $result->content = format_module_intro('assign', $assignment, $coursemodule->id, false);
512 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
513 if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
514 $result->customdata['customcompletionrules']['completionsubmit'] = $assignment->completionsubmit;
517 return $result;
521 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
523 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
524 * @return array $descriptions the array of descriptions for the custom rules.
526 function mod_assign_get_completion_active_rule_descriptions($cm) {
527 // Values will be present in cm_info, and we assume these are up to date.
528 if (empty($cm->customdata['customcompletionrules'])
529 || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
530 return [];
533 $descriptions = [];
534 foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
535 switch ($key) {
536 case 'completionsubmit':
537 if (!empty($val)) {
538 $descriptions[] = get_string('completionsubmit', 'assign');
540 break;
541 default:
542 break;
545 return $descriptions;
549 * Return a list of page types
550 * @param string $pagetype current page type
551 * @param stdClass $parentcontext Block's parent context
552 * @param stdClass $currentcontext Current context of block
554 function assign_page_type_list($pagetype, $parentcontext, $currentcontext) {
555 $modulepagetype = array(
556 'mod-assign-*' => get_string('page-mod-assign-x', 'assign'),
557 'mod-assign-view' => get_string('page-mod-assign-view', 'assign'),
559 return $modulepagetype;
563 * @deprecated since Moodle 3.3, when the block_course_overview block was removed.
565 function assign_print_overview() {
566 throw new coding_exception('assign_print_overview() can not be used any more and is obsolete.');
570 * @deprecated since Moodle 3.3, when the block_course_overview block was removed.
572 function assign_get_mysubmission_details_for_print_overview() {
573 throw new coding_exception('assign_get_mysubmission_details_for_print_overview() can not be used any more and is obsolete.');
577 * @deprecated since Moodle 3.3, when the block_course_overview block was removed.
579 function assign_get_grade_details_for_print_overview() {
580 throw new coding_exception('assign_get_grade_details_for_print_overview() can not be used any more and is obsolete.');
584 * Print recent activity from all assignments in a given course
586 * This is used by the recent activity block
587 * @param mixed $course the course to print activity for
588 * @param bool $viewfullnames boolean to determine whether to show full names or not
589 * @param int $timestart the time the rendering started
590 * @return bool true if activity was printed, false otherwise.
592 function assign_print_recent_activity($course, $viewfullnames, $timestart) {
593 global $CFG, $USER, $DB, $OUTPUT;
594 require_once($CFG->dirroot . '/mod/assign/locallib.php');
596 // Do not use log table if possible, it may be huge.
598 $dbparams = array($timestart, $course->id, 'assign', ASSIGN_SUBMISSION_STATUS_SUBMITTED);
599 $namefields = user_picture::fields('u', null, 'userid');
600 if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, um.id as recordid,
601 $namefields
602 FROM {assign_submission} asb
603 JOIN {assign} a ON a.id = asb.assignment
604 JOIN {course_modules} cm ON cm.instance = a.id
605 JOIN {modules} md ON md.id = cm.module
606 JOIN {user} u ON u.id = asb.userid
607 LEFT JOIN {assign_user_mapping} um ON um.userid = u.id AND um.assignment = a.id
608 WHERE asb.timemodified > ? AND
609 asb.latest = 1 AND
610 a.course = ? AND
611 md.name = ? AND
612 asb.status = ?
613 ORDER BY asb.timemodified ASC", $dbparams)) {
614 return false;
617 $modinfo = get_fast_modinfo($course);
618 $show = array();
619 $grader = array();
621 $showrecentsubmissions = get_config('assign', 'showrecentsubmissions');
623 foreach ($submissions as $submission) {
624 if (!array_key_exists($submission->cmid, $modinfo->get_cms())) {
625 continue;
627 $cm = $modinfo->get_cm($submission->cmid);
628 if (!$cm->uservisible) {
629 continue;
631 if ($submission->userid == $USER->id) {
632 $show[] = $submission;
633 continue;
636 $context = context_module::instance($submission->cmid);
637 // The act of submitting of assignment may be considered private -
638 // only graders will see it if specified.
639 if (empty($showrecentsubmissions)) {
640 if (!array_key_exists($cm->id, $grader)) {
641 $grader[$cm->id] = has_capability('moodle/grade:viewall', $context);
643 if (!$grader[$cm->id]) {
644 continue;
648 $groupmode = groups_get_activity_groupmode($cm, $course);
650 if ($groupmode == SEPARATEGROUPS &&
651 !has_capability('moodle/site:accessallgroups', $context)) {
652 if (isguestuser()) {
653 // Shortcut - guest user does not belong into any group.
654 continue;
657 // This will be slow - show only users that share group with me in this cm.
658 if (!$modinfo->get_groups($cm->groupingid)) {
659 continue;
661 $usersgroups = groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
662 if (is_array($usersgroups)) {
663 $usersgroups = array_keys($usersgroups);
664 $intersect = array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid));
665 if (empty($intersect)) {
666 continue;
670 $show[] = $submission;
673 if (empty($show)) {
674 return false;
677 echo $OUTPUT->heading(get_string('newsubmissions', 'assign').':', 3);
679 foreach ($show as $submission) {
680 $cm = $modinfo->get_cm($submission->cmid);
681 $context = context_module::instance($submission->cmid);
682 $assign = new assign($context, $cm, $cm->course);
683 $link = $CFG->wwwroot.'/mod/assign/view.php?id='.$cm->id;
684 // Obscure first and last name if blind marking enabled.
685 if ($assign->is_blind_marking()) {
686 $submission->firstname = get_string('participant', 'mod_assign');
687 if (empty($submission->recordid)) {
688 $submission->recordid = $assign->get_uniqueid_for_user($submission->userid);
690 $submission->lastname = $submission->recordid;
692 print_recent_activity_note($submission->timemodified,
693 $submission,
694 $cm->name,
695 $link,
696 false,
697 $viewfullnames);
700 return true;
704 * Returns all assignments since a given time.
706 * @param array $activities The activity information is returned in this array
707 * @param int $index The current index in the activities array
708 * @param int $timestart The earliest activity to show
709 * @param int $courseid Limit the search to this course
710 * @param int $cmid The course module id
711 * @param int $userid Optional user id
712 * @param int $groupid Optional group id
713 * @return void
715 function assign_get_recent_mod_activity(&$activities,
716 &$index,
717 $timestart,
718 $courseid,
719 $cmid,
720 $userid=0,
721 $groupid=0) {
722 global $CFG, $COURSE, $USER, $DB;
724 require_once($CFG->dirroot . '/mod/assign/locallib.php');
726 if ($COURSE->id == $courseid) {
727 $course = $COURSE;
728 } else {
729 $course = $DB->get_record('course', array('id'=>$courseid));
732 $modinfo = get_fast_modinfo($course);
734 $cm = $modinfo->get_cm($cmid);
735 $params = array();
736 if ($userid) {
737 $userselect = 'AND u.id = :userid';
738 $params['userid'] = $userid;
739 } else {
740 $userselect = '';
743 if ($groupid) {
744 $groupselect = 'AND gm.groupid = :groupid';
745 $groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id';
746 $params['groupid'] = $groupid;
747 } else {
748 $groupselect = '';
749 $groupjoin = '';
752 $params['cminstance'] = $cm->instance;
753 $params['timestart'] = $timestart;
754 $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
756 $userfields = user_picture::fields('u', null, 'userid');
758 if (!$submissions = $DB->get_records_sql('SELECT asb.id, asb.timemodified, ' .
759 $userfields .
760 ' FROM {assign_submission} asb
761 JOIN {assign} a ON a.id = asb.assignment
762 JOIN {user} u ON u.id = asb.userid ' .
763 $groupjoin .
764 ' WHERE asb.timemodified > :timestart AND
765 asb.status = :submitted AND
766 a.id = :cminstance
767 ' . $userselect . ' ' . $groupselect .
768 ' ORDER BY asb.timemodified ASC', $params)) {
769 return;
772 $groupmode = groups_get_activity_groupmode($cm, $course);
773 $cmcontext = context_module::instance($cm->id);
774 $grader = has_capability('moodle/grade:viewall', $cmcontext);
775 $accessallgroups = has_capability('moodle/site:accessallgroups', $cmcontext);
776 $viewfullnames = has_capability('moodle/site:viewfullnames', $cmcontext);
779 $showrecentsubmissions = get_config('assign', 'showrecentsubmissions');
780 $show = array();
781 foreach ($submissions as $submission) {
782 if ($submission->userid == $USER->id) {
783 $show[] = $submission;
784 continue;
786 // The act of submitting of assignment may be considered private -
787 // only graders will see it if specified.
788 if (empty($showrecentsubmissions)) {
789 if (!$grader) {
790 continue;
794 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
795 if (isguestuser()) {
796 // Shortcut - guest user does not belong into any group.
797 continue;
800 // This will be slow - show only users that share group with me in this cm.
801 if (!$modinfo->get_groups($cm->groupingid)) {
802 continue;
804 $usersgroups = groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
805 if (is_array($usersgroups)) {
806 $usersgroups = array_keys($usersgroups);
807 $intersect = array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid));
808 if (empty($intersect)) {
809 continue;
813 $show[] = $submission;
816 if (empty($show)) {
817 return;
820 if ($grader) {
821 require_once($CFG->libdir.'/gradelib.php');
822 $userids = array();
823 foreach ($show as $id => $submission) {
824 $userids[] = $submission->userid;
826 $grades = grade_get_grades($courseid, 'mod', 'assign', $cm->instance, $userids);
829 $aname = format_string($cm->name, true);
830 foreach ($show as $submission) {
831 $activity = new stdClass();
833 $activity->type = 'assign';
834 $activity->cmid = $cm->id;
835 $activity->name = $aname;
836 $activity->sectionnum = $cm->sectionnum;
837 $activity->timestamp = $submission->timemodified;
838 $activity->user = new stdClass();
839 if ($grader) {
840 $activity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
843 $userfields = explode(',', user_picture::fields());
844 foreach ($userfields as $userfield) {
845 if ($userfield == 'id') {
846 // Aliased in SQL above.
847 $activity->user->{$userfield} = $submission->userid;
848 } else {
849 $activity->user->{$userfield} = $submission->{$userfield};
852 $activity->user->fullname = fullname($submission, $viewfullnames);
854 $activities[$index++] = $activity;
857 return;
861 * Print recent activity from all assignments in a given course
863 * This is used by course/recent.php
864 * @param stdClass $activity
865 * @param int $courseid
866 * @param bool $detail
867 * @param array $modnames
869 function assign_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
870 global $CFG, $OUTPUT;
872 echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
874 echo '<tr><td class="userpicture" valign="top">';
875 echo $OUTPUT->user_picture($activity->user);
876 echo '</td><td>';
878 if ($detail) {
879 $modname = $modnames[$activity->type];
880 echo '<div class="title">';
881 echo $OUTPUT->image_icon('icon', $modname, 'assign');
882 echo '<a href="' . $CFG->wwwroot . '/mod/assign/view.php?id=' . $activity->cmid . '">';
883 echo $activity->name;
884 echo '</a>';
885 echo '</div>';
888 if (isset($activity->grade)) {
889 echo '<div class="grade">';
890 echo get_string('grade').': ';
891 echo $activity->grade;
892 echo '</div>';
895 echo '<div class="user">';
896 echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->id}&amp;course=$courseid\">";
897 echo "{$activity->user->fullname}</a> - " . userdate($activity->timestamp);
898 echo '</div>';
900 echo '</td></tr></table>';
904 * @deprecated since Moodle 3.8
906 function assign_scale_used() {
907 throw new coding_exception('assign_scale_used() can not be used anymore. Plugins can implement ' .
908 '<modname>_scale_used_anywhere, all implementations of <modname>_scale_used are now ignored');
912 * Checks if scale is being used by any instance of assignment
914 * This is used to find out if scale used anywhere
915 * @param int $scaleid
916 * @return boolean True if the scale is used by any assignment
918 function assign_scale_used_anywhere($scaleid) {
919 global $DB;
921 if ($scaleid and $DB->record_exists('assign', array('grade'=>-$scaleid))) {
922 return true;
923 } else {
924 return false;
929 * List the actions that correspond to a view of this module.
930 * This is used by the participation report.
932 * Note: This is not used by new logging system. Event with
933 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
934 * be considered as view action.
936 * @return array
938 function assign_get_view_actions() {
939 return array('view submission', 'view feedback');
943 * List the actions that correspond to a post of this module.
944 * This is used by the participation report.
946 * Note: This is not used by new logging system. Event with
947 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
948 * will be considered as post action.
950 * @return array
952 function assign_get_post_actions() {
953 return array('upload', 'submit', 'submit for grading');
957 * Returns all other capabilities used by this module.
958 * @return array Array of capability strings
960 function assign_get_extra_capabilities() {
961 return ['gradereport/grader:view', 'moodle/grade:viewall'];
965 * Create grade item for given assignment.
967 * @param stdClass $assign record with extra cmidnumber
968 * @param array $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
969 * @return int 0 if ok, error code otherwise
971 function assign_grade_item_update($assign, $grades=null) {
972 global $CFG;
973 require_once($CFG->libdir.'/gradelib.php');
975 if (!isset($assign->courseid)) {
976 $assign->courseid = $assign->course;
979 $params = array('itemname'=>$assign->name, 'idnumber'=>$assign->cmidnumber);
981 // Check if feedback plugin for gradebook is enabled, if yes then
982 // gradetype = GRADE_TYPE_TEXT else GRADE_TYPE_NONE.
983 $gradefeedbackenabled = false;
985 if (isset($assign->gradefeedbackenabled)) {
986 $gradefeedbackenabled = $assign->gradefeedbackenabled;
987 } else if ($assign->grade == 0) { // Grade feedback is needed only when grade == 0.
988 require_once($CFG->dirroot . '/mod/assign/locallib.php');
989 $mod = get_coursemodule_from_instance('assign', $assign->id, $assign->courseid);
990 $cm = context_module::instance($mod->id);
991 $assignment = new assign($cm, null, null);
992 $gradefeedbackenabled = $assignment->is_gradebook_feedback_enabled();
995 if ($assign->grade > 0) {
996 $params['gradetype'] = GRADE_TYPE_VALUE;
997 $params['grademax'] = $assign->grade;
998 $params['grademin'] = 0;
1000 } else if ($assign->grade < 0) {
1001 $params['gradetype'] = GRADE_TYPE_SCALE;
1002 $params['scaleid'] = -$assign->grade;
1004 } else if ($gradefeedbackenabled) {
1005 // $assign->grade == 0 and feedback enabled.
1006 $params['gradetype'] = GRADE_TYPE_TEXT;
1007 } else {
1008 // $assign->grade == 0 and no feedback enabled.
1009 $params['gradetype'] = GRADE_TYPE_NONE;
1012 if ($grades === 'reset') {
1013 $params['reset'] = true;
1014 $grades = null;
1017 return grade_update('mod/assign',
1018 $assign->courseid,
1019 'mod',
1020 'assign',
1021 $assign->id,
1023 $grades,
1024 $params);
1028 * Return grade for given user or all users.
1030 * @param stdClass $assign record of assign with an additional cmidnumber
1031 * @param int $userid optional user id, 0 means all users
1032 * @return array array of grades, false if none
1034 function assign_get_user_grades($assign, $userid=0) {
1035 global $CFG;
1037 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1039 $cm = get_coursemodule_from_instance('assign', $assign->id, 0, false, MUST_EXIST);
1040 $context = context_module::instance($cm->id);
1041 $assignment = new assign($context, null, null);
1042 $assignment->set_instance($assign);
1043 return $assignment->get_user_grades_for_gradebook($userid);
1047 * Update activity grades.
1049 * @param stdClass $assign database record
1050 * @param int $userid specific user only, 0 means all
1051 * @param bool $nullifnone - not used
1053 function assign_update_grades($assign, $userid=0, $nullifnone=true) {
1054 global $CFG;
1055 require_once($CFG->libdir.'/gradelib.php');
1057 if ($assign->grade == 0) {
1058 assign_grade_item_update($assign);
1060 } else if ($grades = assign_get_user_grades($assign, $userid)) {
1061 foreach ($grades as $k => $v) {
1062 if ($v->rawgrade == -1) {
1063 $grades[$k]->rawgrade = null;
1066 assign_grade_item_update($assign, $grades);
1068 } else {
1069 assign_grade_item_update($assign);
1074 * List the file areas that can be browsed.
1076 * @param stdClass $course
1077 * @param stdClass $cm
1078 * @param stdClass $context
1079 * @return array
1081 function assign_get_file_areas($course, $cm, $context) {
1082 global $CFG;
1083 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1085 $areas = array(ASSIGN_INTROATTACHMENT_FILEAREA => get_string('introattachments', 'mod_assign'));
1087 $assignment = new assign($context, $cm, $course);
1088 foreach ($assignment->get_submission_plugins() as $plugin) {
1089 if ($plugin->is_visible()) {
1090 $pluginareas = $plugin->get_file_areas();
1092 if ($pluginareas) {
1093 $areas = array_merge($areas, $pluginareas);
1097 foreach ($assignment->get_feedback_plugins() as $plugin) {
1098 if ($plugin->is_visible()) {
1099 $pluginareas = $plugin->get_file_areas();
1101 if ($pluginareas) {
1102 $areas = array_merge($areas, $pluginareas);
1107 return $areas;
1111 * File browsing support for assign module.
1113 * @param file_browser $browser
1114 * @param object $areas
1115 * @param object $course
1116 * @param object $cm
1117 * @param object $context
1118 * @param string $filearea
1119 * @param int $itemid
1120 * @param string $filepath
1121 * @param string $filename
1122 * @return object file_info instance or null if not found
1124 function assign_get_file_info($browser,
1125 $areas,
1126 $course,
1127 $cm,
1128 $context,
1129 $filearea,
1130 $itemid,
1131 $filepath,
1132 $filename) {
1133 global $CFG;
1134 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1136 if ($context->contextlevel != CONTEXT_MODULE) {
1137 return null;
1140 $urlbase = $CFG->wwwroot.'/pluginfile.php';
1141 $fs = get_file_storage();
1142 $filepath = is_null($filepath) ? '/' : $filepath;
1143 $filename = is_null($filename) ? '.' : $filename;
1145 // Need to find where this belongs to.
1146 $assignment = new assign($context, $cm, $course);
1147 if ($filearea === ASSIGN_INTROATTACHMENT_FILEAREA) {
1148 if (!has_capability('moodle/course:managefiles', $context)) {
1149 // Students can not peak here!
1150 return null;
1152 if (!($storedfile = $fs->get_file($assignment->get_context()->id,
1153 'mod_assign', $filearea, 0, $filepath, $filename))) {
1154 return null;
1156 return new file_info_stored($browser,
1157 $assignment->get_context(),
1158 $storedfile,
1159 $urlbase,
1160 $filearea,
1161 $itemid,
1162 true,
1163 true,
1164 false);
1167 $pluginowner = null;
1168 foreach ($assignment->get_submission_plugins() as $plugin) {
1169 if ($plugin->is_visible()) {
1170 $pluginareas = $plugin->get_file_areas();
1172 if (array_key_exists($filearea, $pluginareas)) {
1173 $pluginowner = $plugin;
1174 break;
1178 if (!$pluginowner) {
1179 foreach ($assignment->get_feedback_plugins() as $plugin) {
1180 if ($plugin->is_visible()) {
1181 $pluginareas = $plugin->get_file_areas();
1183 if (array_key_exists($filearea, $pluginareas)) {
1184 $pluginowner = $plugin;
1185 break;
1191 if (!$pluginowner) {
1192 return null;
1195 $result = $pluginowner->get_file_info($browser, $filearea, $itemid, $filepath, $filename);
1196 return $result;
1200 * Prints the complete info about a user's interaction with an assignment.
1202 * @param stdClass $course
1203 * @param stdClass $user
1204 * @param stdClass $coursemodule
1205 * @param stdClass $assign the database assign record
1207 * This prints the submission summary and feedback summary for this student.
1209 function assign_user_complete($course, $user, $coursemodule, $assign) {
1210 global $CFG;
1211 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1213 $context = context_module::instance($coursemodule->id);
1215 $assignment = new assign($context, $coursemodule, $course);
1217 echo $assignment->view_student_summary($user, false);
1221 * Rescale all grades for this activity and push the new grades to the gradebook.
1223 * @param stdClass $course Course db record
1224 * @param stdClass $cm Course module db record
1225 * @param float $oldmin
1226 * @param float $oldmax
1227 * @param float $newmin
1228 * @param float $newmax
1230 function assign_rescale_activity_grades($course, $cm, $oldmin, $oldmax, $newmin, $newmax) {
1231 global $DB;
1233 if ($oldmax <= $oldmin) {
1234 // Grades cannot be scaled.
1235 return false;
1237 $scale = ($newmax - $newmin) / ($oldmax - $oldmin);
1238 if (($newmax - $newmin) <= 1) {
1239 // We would lose too much precision, lets bail.
1240 return false;
1243 $params = array(
1244 'p1' => $oldmin,
1245 'p2' => $scale,
1246 'p3' => $newmin,
1247 'a' => $cm->instance
1250 // Only rescale grades that are greater than or equal to 0. Anything else is a special value.
1251 $sql = 'UPDATE {assign_grades} set grade = (((grade - :p1) * :p2) + :p3) where assignment = :a and grade >= 0';
1252 $dbupdate = $DB->execute($sql, $params);
1253 if (!$dbupdate) {
1254 return false;
1257 // Now re-push all grades to the gradebook.
1258 $dbparams = array('id' => $cm->instance);
1259 $assign = $DB->get_record('assign', $dbparams);
1260 $assign->cmidnumber = $cm->idnumber;
1262 assign_update_grades($assign);
1264 return true;
1268 * Print the grade information for the assignment for this user.
1270 * @param stdClass $course
1271 * @param stdClass $user
1272 * @param stdClass $coursemodule
1273 * @param stdClass $assignment
1275 function assign_user_outline($course, $user, $coursemodule, $assignment) {
1276 global $CFG;
1277 require_once($CFG->libdir.'/gradelib.php');
1278 require_once($CFG->dirroot.'/grade/grading/lib.php');
1280 $gradinginfo = grade_get_grades($course->id,
1281 'mod',
1282 'assign',
1283 $assignment->id,
1284 $user->id);
1286 $gradingitem = $gradinginfo->items[0];
1287 $gradebookgrade = $gradingitem->grades[$user->id];
1289 if (empty($gradebookgrade->str_long_grade)) {
1290 return null;
1292 $result = new stdClass();
1293 if (!$gradingitem->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
1294 $result->info = get_string('outlinegrade', 'assign', $gradebookgrade->str_long_grade);
1295 } else {
1296 $result->info = get_string('grade') . ': ' . get_string('hidden', 'grades');
1298 $result->time = $gradebookgrade->dategraded;
1300 return $result;
1304 * Obtains the automatic completion state for this module based on any conditions
1305 * in assign settings.
1307 * @param object $course Course
1308 * @param object $cm Course-module
1309 * @param int $userid User ID
1310 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
1311 * @return bool True if completed, false if not, $type if conditions not set.
1313 function assign_get_completion_state($course, $cm, $userid, $type) {
1314 global $CFG, $DB;
1315 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1317 $assign = new assign(null, $cm, $course);
1319 // If completion option is enabled, evaluate it and return true/false.
1320 if ($assign->get_instance()->completionsubmit) {
1321 if ($assign->get_instance()->teamsubmission) {
1322 $submission = $assign->get_group_submission($userid, 0, false);
1323 } else {
1324 $submission = $assign->get_user_submission($userid, false);
1326 return $submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1327 } else {
1328 // Completion option is not enabled so just return $type.
1329 return $type;
1334 * Serves intro attachment files.
1336 * @param mixed $course course or id of the course
1337 * @param mixed $cm course module or id of the course module
1338 * @param context $context
1339 * @param string $filearea
1340 * @param array $args
1341 * @param bool $forcedownload
1342 * @param array $options additional options affecting the file serving
1343 * @return bool false if file not found, does not return if found - just send the file
1345 function assign_pluginfile($course,
1346 $cm,
1347 context $context,
1348 $filearea,
1349 $args,
1350 $forcedownload,
1351 array $options=array()) {
1352 global $CFG;
1354 if ($context->contextlevel != CONTEXT_MODULE) {
1355 return false;
1358 require_login($course, false, $cm);
1359 if (!has_capability('mod/assign:view', $context)) {
1360 return false;
1363 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1364 $assign = new assign($context, $cm, $course);
1366 if ($filearea !== ASSIGN_INTROATTACHMENT_FILEAREA) {
1367 return false;
1369 if (!$assign->show_intro()) {
1370 return false;
1373 $itemid = (int)array_shift($args);
1374 if ($itemid != 0) {
1375 return false;
1378 $relativepath = implode('/', $args);
1380 $fullpath = "/{$context->id}/mod_assign/$filearea/$itemid/$relativepath";
1382 $fs = get_file_storage();
1383 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1384 return false;
1386 send_stored_file($file, 0, 0, $forcedownload, $options);
1390 * Serve the grading panel as a fragment.
1392 * @param array $args List of named arguments for the fragment loader.
1393 * @return string
1395 function mod_assign_output_fragment_gradingpanel($args) {
1396 global $CFG;
1398 $context = $args['context'];
1400 if ($context->contextlevel != CONTEXT_MODULE) {
1401 return null;
1403 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1404 $assign = new assign($context, null, null);
1406 $userid = clean_param($args['userid'], PARAM_INT);
1407 $attemptnumber = clean_param($args['attemptnumber'], PARAM_INT);
1408 $formdata = array();
1409 if (!empty($args['jsonformdata'])) {
1410 $serialiseddata = json_decode($args['jsonformdata']);
1411 parse_str($serialiseddata, $formdata);
1413 $viewargs = array(
1414 'userid' => $userid,
1415 'attemptnumber' => $attemptnumber,
1416 'formdata' => $formdata
1419 return $assign->view('gradingpanel', $viewargs);
1423 * Check if the module has any update that affects the current user since a given time.
1425 * @param cm_info $cm course module data
1426 * @param int $from the time to check updates from
1427 * @param array $filter if we need to check only specific updates
1428 * @return stdClass an object with the different type of areas indicating if they were updated or not
1429 * @since Moodle 3.2
1431 function assign_check_updates_since(cm_info $cm, $from, $filter = array()) {
1432 global $DB, $USER, $CFG;
1433 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1435 $updates = new stdClass();
1436 $updates = course_check_module_updates_since($cm, $from, array(ASSIGN_INTROATTACHMENT_FILEAREA), $filter);
1438 // Check if there is a new submission by the user or new grades.
1439 $select = 'assignment = :id AND userid = :userid AND (timecreated > :since1 OR timemodified > :since2)';
1440 $params = array('id' => $cm->instance, 'userid' => $USER->id, 'since1' => $from, 'since2' => $from);
1441 $updates->submissions = (object) array('updated' => false);
1442 $submissions = $DB->get_records_select('assign_submission', $select, $params, '', 'id');
1443 if (!empty($submissions)) {
1444 $updates->submissions->updated = true;
1445 $updates->submissions->itemids = array_keys($submissions);
1448 $updates->grades = (object) array('updated' => false);
1449 $grades = $DB->get_records_select('assign_grades', $select, $params, '', 'id');
1450 if (!empty($grades)) {
1451 $updates->grades->updated = true;
1452 $updates->grades->itemids = array_keys($grades);
1455 // Now, teachers should see other students updates.
1456 if (has_capability('mod/assign:viewgrades', $cm->context)) {
1457 $params = array('id' => $cm->instance, 'since1' => $from, 'since2' => $from);
1458 $select = 'assignment = :id AND (timecreated > :since1 OR timemodified > :since2)';
1460 if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS) {
1461 $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
1462 if (empty($groupusers)) {
1463 return $updates;
1465 list($insql, $inparams) = $DB->get_in_or_equal($groupusers, SQL_PARAMS_NAMED);
1466 $select .= ' AND userid ' . $insql;
1467 $params = array_merge($params, $inparams);
1470 $updates->usersubmissions = (object) array('updated' => false);
1471 $submissions = $DB->get_records_select('assign_submission', $select, $params, '', 'id');
1472 if (!empty($submissions)) {
1473 $updates->usersubmissions->updated = true;
1474 $updates->usersubmissions->itemids = array_keys($submissions);
1477 $updates->usergrades = (object) array('updated' => false);
1478 $grades = $DB->get_records_select('assign_grades', $select, $params, '', 'id');
1479 if (!empty($grades)) {
1480 $updates->usergrades->updated = true;
1481 $updates->usergrades->itemids = array_keys($grades);
1485 return $updates;
1489 * Is the event visible?
1491 * This is used to determine global visibility of an event in all places throughout Moodle. For example,
1492 * the ASSIGN_EVENT_TYPE_GRADINGDUE event will not be shown to students on their calendar.
1494 * @param calendar_event $event
1495 * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
1496 * @return bool Returns true if the event is visible to the current user, false otherwise.
1498 function mod_assign_core_calendar_is_event_visible(calendar_event $event, $userid = 0) {
1499 global $CFG, $USER;
1501 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1503 if (empty($userid)) {
1504 $userid = $USER->id;
1507 $cm = get_fast_modinfo($event->courseid, $userid)->instances['assign'][$event->instance];
1508 $context = context_module::instance($cm->id);
1510 $assign = new assign($context, $cm, null);
1512 if ($event->eventtype == ASSIGN_EVENT_TYPE_GRADINGDUE) {
1513 return $assign->can_grade($userid);
1514 } else {
1515 return true;
1520 * This function receives a calendar event and returns the action associated with it, or null if there is none.
1522 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
1523 * is not displayed on the block.
1525 * @param calendar_event $event
1526 * @param \core_calendar\action_factory $factory
1527 * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
1528 * @return \core_calendar\local\event\entities\action_interface|null
1530 function mod_assign_core_calendar_provide_event_action(calendar_event $event,
1531 \core_calendar\action_factory $factory,
1532 $userid = 0) {
1534 global $CFG, $USER;
1536 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1538 if (empty($userid)) {
1539 $userid = $USER->id;
1542 $cm = get_fast_modinfo($event->courseid, $userid)->instances['assign'][$event->instance];
1543 $context = context_module::instance($cm->id);
1545 $completion = new \completion_info($cm->get_course());
1547 $completiondata = $completion->get_data($cm, false, $userid);
1549 if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
1550 return null;
1553 $assign = new assign($context, $cm, null);
1555 // Apply overrides.
1556 $assign->update_effective_access($userid);
1558 if ($event->eventtype == ASSIGN_EVENT_TYPE_GRADINGDUE) {
1559 $name = get_string('grade');
1560 $url = new \moodle_url('/mod/assign/view.php', [
1561 'id' => $cm->id,
1562 'action' => 'grader'
1564 $itemcount = $assign->count_submissions_need_grading();
1565 $actionable = $assign->can_grade($userid) && (time() >= $assign->get_instance()->allowsubmissionsfromdate);
1566 } else {
1567 $usersubmission = $assign->get_user_submission($userid, false);
1568 if ($usersubmission && $usersubmission->status === ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
1569 // The user has already submitted.
1570 // We do not want to change the text to edit the submission, we want to remove the event from the Dashboard entirely.
1571 return null;
1574 $participant = $assign->get_participant($userid);
1576 if (!$participant) {
1577 // If the user is not a participant in the assignment then they have
1578 // no action to take. This will filter out the events for teachers.
1579 return null;
1582 // The user has not yet submitted anything. Show the addsubmission link.
1583 $name = get_string('addsubmission', 'assign');
1584 $url = new \moodle_url('/mod/assign/view.php', [
1585 'id' => $cm->id,
1586 'action' => 'editsubmission'
1588 $itemcount = 1;
1589 $actionable = $assign->is_any_submission_plugin_enabled() && $assign->can_edit_submission($userid, $userid);
1592 return $factory->create_instance(
1593 $name,
1594 $url,
1595 $itemcount,
1596 $actionable
1601 * Callback function that determines whether an action event should be showing its item count
1602 * based on the event type and the item count.
1604 * @param calendar_event $event The calendar event.
1605 * @param int $itemcount The item count associated with the action event.
1606 * @return bool
1608 function mod_assign_core_calendar_event_action_shows_item_count(calendar_event $event, $itemcount = 0) {
1609 // List of event types where the action event's item count should be shown.
1610 $eventtypesshowingitemcount = [
1611 ASSIGN_EVENT_TYPE_GRADINGDUE
1613 // For mod_assign, item count should be shown if the event type is 'gradingdue' and there is one or more item count.
1614 return in_array($event->eventtype, $eventtypesshowingitemcount) && $itemcount > 0;
1618 * This function calculates the minimum and maximum cutoff values for the timestart of
1619 * the given event.
1621 * It will return an array with two values, the first being the minimum cutoff value and
1622 * the second being the maximum cutoff value. Either or both values can be null, which
1623 * indicates there is no minimum or maximum, respectively.
1625 * If a cutoff is required then the function must return an array containing the cutoff
1626 * timestamp and error string to display to the user if the cutoff value is violated.
1628 * A minimum and maximum cutoff return value will look like:
1630 * [1505704373, 'The due date must be after the sbumission start date'],
1631 * [1506741172, 'The due date must be before the cutoff date']
1634 * If the event does not have a valid timestart range then [false, false] will
1635 * be returned.
1637 * @param calendar_event $event The calendar event to get the time range for
1638 * @param stdClass $instance The module instance to get the range from
1639 * @return array
1641 function mod_assign_core_calendar_get_valid_event_timestart_range(\calendar_event $event, \stdClass $instance) {
1642 global $CFG;
1644 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1646 $courseid = $event->courseid;
1647 $modulename = $event->modulename;
1648 $instanceid = $event->instance;
1649 $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid];
1650 $context = context_module::instance($coursemodule->id);
1651 $assign = new assign($context, null, null);
1652 $assign->set_instance($instance);
1654 return $assign->get_valid_calendar_event_timestart_range($event);
1658 * This function will update the assign module according to the
1659 * event that has been modified.
1661 * @throws \moodle_exception
1662 * @param \calendar_event $event
1663 * @param stdClass $instance The module instance to get the range from
1665 function mod_assign_core_calendar_event_timestart_updated(\calendar_event $event, \stdClass $instance) {
1666 global $CFG, $DB;
1668 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1670 if (empty($event->instance) || $event->modulename != 'assign') {
1671 return;
1674 if ($instance->id != $event->instance) {
1675 return;
1678 if (!in_array($event->eventtype, [ASSIGN_EVENT_TYPE_DUE, ASSIGN_EVENT_TYPE_GRADINGDUE])) {
1679 return;
1682 $courseid = $event->courseid;
1683 $modulename = $event->modulename;
1684 $instanceid = $event->instance;
1685 $modified = false;
1686 $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid];
1687 $context = context_module::instance($coursemodule->id);
1689 // The user does not have the capability to modify this activity.
1690 if (!has_capability('moodle/course:manageactivities', $context)) {
1691 return;
1694 $assign = new assign($context, $coursemodule, null);
1695 $assign->set_instance($instance);
1697 if ($event->eventtype == ASSIGN_EVENT_TYPE_DUE) {
1698 // This check is in here because due date events are currently
1699 // the only events that can be overridden, so we can save a DB
1700 // query if we don't bother checking other events.
1701 if ($assign->is_override_calendar_event($event)) {
1702 // This is an override event so we should ignore it.
1703 return;
1706 $newduedate = $event->timestart;
1708 if ($newduedate != $instance->duedate) {
1709 $instance->duedate = $newduedate;
1710 $modified = true;
1712 } else if ($event->eventtype == ASSIGN_EVENT_TYPE_GRADINGDUE) {
1713 $newduedate = $event->timestart;
1715 if ($newduedate != $instance->gradingduedate) {
1716 $instance->gradingduedate = $newduedate;
1717 $modified = true;
1721 if ($modified) {
1722 $instance->timemodified = time();
1723 // Persist the assign instance changes.
1724 $DB->update_record('assign', $instance);
1725 $assign->update_calendar($coursemodule->id);
1726 $event = \core\event\course_module_updated::create_from_cm($coursemodule, $context);
1727 $event->trigger();
1732 * Return a list of all the user preferences used by mod_assign.
1734 * @return array
1736 function mod_assign_user_preferences() {
1737 $preferences = array();
1738 $preferences['assign_filter'] = array(
1739 'type' => PARAM_ALPHA,
1740 'null' => NULL_NOT_ALLOWED,
1741 'default' => ''
1743 $preferences['assign_workflowfilter'] = array(
1744 'type' => PARAM_ALPHA,
1745 'null' => NULL_NOT_ALLOWED,
1746 'default' => ''
1748 $preferences['assign_markerfilter'] = array(
1749 'type' => PARAM_ALPHANUMEXT,
1750 'null' => NULL_NOT_ALLOWED,
1751 'default' => ''
1754 return $preferences;